public override ISolverResult Solve(IAlgorithm tspSolvingAlgorithm) { var context = SolvingTimeContext.Instance; Statistics = new BasicSolverStatistics(); var resultAccumulator = new SolverResult(); var bestPath = new Path(new List <int>(), new ConstCostCalculationStrategy(int.MaxValue)); for (var i = 0; i < MslsRepeatAmount; i++) { using (context) { for (var j = 0; j < InsideAlgorithmRepeatAmount; j++) { var startNode = _randomGenerator.Next(0, CompleteGraph.NodesCount - 1); var pathAccumulator = _internalSolver.Solve(_internalAlgorithm, startNode); var localPath = pathAccumulator.Paths[0]; localPath = tspSolvingAlgorithm.Solve(localPath.Nodes.First(), CompleteGraph, localPath); if (localPath.Cost < bestPath.Cost) { bestPath = localPath; } } Statistics.UpdateSolvingResults(bestPath, context.Elapsed); resultAccumulator.AddPath(bestPath); } } return(resultAccumulator); }
public void Execute(object parameter) { SolverResult result = _runner.Run(); _runnerBarVM.LastRunsResult = result; _runnerBarVM.AllResults.Add(result); }
/// <summary> /// Solves the system for <paramref name="Unknowns"/>. /// </summary> /// <param name="Unknowns">The unknowns to be solved for.</param> /// <param name="dt">time step size</param> /// <param name="SpatialComponent">Spatial component - this parameter is optional.</param> public virtual void Solve(IList <double> Unknowns, double dt, int SpatialComponent = -1) { using (new FuncTrace()) { //Define and set matrix - can be called only once during lifetime of this object. if (!MatrixIsDefined) { m_SolverMatrix = DefineMatrix(dt); m_Solver.DefineMatrix(m_SolverMatrix); MatrixIsDefined = true; } //Define and set Rhs m_Rhs = DefineRhs(dt, SpatialComponent); //Some checks if ((m_SolverMatrix.RowPartitioning.LocalLength != Unknowns.Count) || (m_SolverMatrix.RowPartitioning.LocalLength != m_Rhs.Count)) { throw new ArgumentException("Mismatch of dimensions!"); } //Solve SolverResult res = m_Solver.Solve(Unknowns, m_Rhs); if (m_solverConf.Control.PrintLinerSolverResults && (m_solverConf.MPIRank == 0)) { Console.WriteLine("Linear solver results:"); Console.WriteLine("Converged: {0}, NoOfIterations: {1}, Runtime: {2} sec", res.Converged.ToString(), res.NoOfIterations, res.RunTime.TotalSeconds); } } }
public override ISolverResult Solve(IAlgorithm tspSolvingAlgorithm, ISolverResult solverResult) { Statistics = new BasicSolverStatistics(); ISet <Path> initialPopulation = new HashSet <Path>(solverResult.Paths); var optimalChilderens = new SolverResult(); _solverStopwatch.Start(); var localStopwatch = new Stopwatch(); while (_solverStopwatch.ElapsedMilliseconds < _solvingTime) { var parents = _selector.Select(initialPopulation); var child = _recombinator.Recombine(parents.Item1, parents.Item2); localStopwatch.Start(); var optimalChild = tspSolvingAlgorithm.Solve(StartNode(child), CompleteGraph, child); localStopwatch.Stop(); optimalChilderens.AddPath(optimalChild); initialPopulation = EnhancePopulation(optimalChild, initialPopulation); Statistics.UpdateSolvingResults(optimalChild, localStopwatch.Elapsed); localStopwatch.Reset(); } _solverStopwatch.Reset(); return(optimalChilderens); }
public override ISolverResult Solve(IAlgorithm tspSolvingAlgorithm) { var bestPath = InitialBestPath; var solverResult = new SolverResult(); for (var j = 0; j < _generatedPaths; j++) { var localSolverResult = _initializationSolver.Solve(StartNode); var localPath = localSolverResult.Paths[0]; localPath = tspSolvingAlgorithm.Solve(localPath.Nodes.First(), CompleteGraph, localPath); solverResult.AddPath(localPath); if (localPath.Cost < bestPath.Cost) { bestPath = localPath; } } CalculateSimilarities(solverResult, new ForEachSimilarityCalculator()); CalculateSimilarities(solverResult, new WithBestSimilarityCalculator(bestPath)); return(solverResult); }
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { timer.Stop(); if (e.Cancelled) { if (Solver_.Solutions.Count > 0 && MessageBox.Show("Calculation aborted!\nWould you like to use the solutions found so far?", "Find Solutions", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { Result_ = SolverResult.Complete; } else { Result_ = SolverResult.UserCancel; } } else { Result_ = (SolverResult)e.Result; if (Result_ == SolverResult.NoTimetable) { MessageBox.Show("No timetable loaded.", "Find Solutions", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else if (Result_ == SolverResult.Clash) { // TODO: be more helpful here (maybe move this back to main form?) MessageBox.Show("Couldn't find any solutions, there's an inherent clash.", "Find Solutions", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } Close(); }
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { timer.Stop(); if (e.Cancelled) { if (Solver_.Solutions.Count > 0 && MessageBox.Show("Calculation aborted!\nWould you like to use the solutions found so far?", "Find Solutions", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Result_ = SolverResult.Complete; else Result_ = SolverResult.UserCancel; } else { Result_ = (SolverResult)e.Result; if (Result_ == SolverResult.NoTimetable) { MessageBox.Show("No timetable loaded.", "Find Solutions", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else if (Result_ == SolverResult.Clash) { // TODO: be more helpful here (maybe move this back to main form?) MessageBox.Show("Couldn't find any solutions, there's an inherent clash.", "Find Solutions", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } Close(); }
public SolverResult Solve(SolverParameters parameters) { MplsAllocationSolverImpl solver = new MplsAllocationSolverImpl(parameters); SolverResult solution = solver.Solve(); return(solution); }
/// <summary> /// internal function to setting solver /// </summary> /// <param name="tspsolver"></param> private void SetSolver(TSPSolver tspsolver) { this.solver = tspsolver; this.solverResult = this.solver.SolveTSP(this.ShowProgressOnProgressBar); if (this.solverResult != null && this.solverResult.CityQueue != null && this.solverResult.CityQueue.Count > 0) { this.labelTourLen.Text = this.solverResult.TotalDistance.ToString("0.##"); this.labelTime.Text = this.solverResult.TimeToSolve.TotalMilliseconds.ToString("0.##") + @" ms"; this.FlushCanvas(); this.DrawCityOnCanvas(); foreach (CityResult cityResult in this.solverResult.CityQueue) { Coordinates coor1 = cityResult.StartCity.CityCoordinates; Coordinates coor2 = cityResult.EndCity.CityCoordinates; this.DrawLineOnCanvas(coor1, coor2, this.lineColor); } } }
private PVTEntry GetEntryAtPressureAndProperty( double pressure, double targetPropVal, Func <PVTEntry, double> propGetter) { PVTEntry liqEntry = GetEntryAtSatPressure(pressure, SaturationRegion.Liquid); PVTEntry vapEntry = GetEntryAtSatPressure(pressure, SaturationRegion.Vapor); if (vapEntry != null && liqEntry != null && propGetter(vapEntry) >= targetPropVal && propGetter(liqEntry) <= targetPropVal) { double liqFac = (propGetter(vapEntry) - targetPropVal) / (propGetter(vapEntry) - propGetter(liqEntry)); LiquidVaporEntryFactory fac = new LiquidVaporEntryFactory(vapEntry, liqEntry, liqFac); return(fac.BuildThermoEntry()); } double fx(double x) { PVTEntry entry = GetEntryAtTemperatureAndPressure(x, pressure); return(entry != null?propGetter(entry) - targetPropVal : double.NaN); } Range tempRange = GetTemperatureRange(pressure); SolverResult temperature = NewtonsMethod.Solve(fx, tempRange); return(temperature.ReachedMaxGuesses ? null : GetEntryAtTemperatureAndPressure(temperature.Value, pressure)); }
/// <summary> /// Исследование характеристик работы решателя одномерных задач /// </summary> private static void SolverTask1DTests() { // Задаём дифференциальный оператор var op = new DerivativeOperator1D3P(); op.Kim1 = -1m / (2m * 0.5m); op.Ki = 2m; op.Kip1 = 1m / (2m * 0.5m); // Создаём одномерную расчетную область var raschOblast1D = new Grid1D(1.5m, 11, AxisEnum.X); // Создаём исследуемый объект var lineSegment = new GeometryPrimitive1DLineSegment(new Coordinate1D(0m), 0.5m); var raschObjectGeometry1D = new Geometry1D(); var geometryElement = new GeometryElement1D(new Coordinate1D(0.5m)); geometryElement.AddGeometryPrimitive(lineSegment); raschObjectGeometry1D.AddGeometryElement(geometryElement); var gridWithGeometryPrecalculated1D = new GridWithGeometryPreCalculated1D(raschOblast1D, raschObjectGeometry1D); var nodeSet1D = gridWithGeometryPrecalculated1D.NodeSet1D; // Создаём задачу var task = new SolverTask1D(); task.NodeSet1D = nodeSet1D; SolverResult result = Solver.Calculate(task); }
public static void SimpleAllocationCase <T>() where T : IAllocationSolver, new() { Console.WriteLine($"Allocating with Solver: {typeof(T).Name}"); MachineBuilder machineBuilder = new MachineBuilder(); Machine[] machines = machineBuilder.WithCpu(20).WithMemory(20).BuildMany(93).Union( machineBuilder.WithCpu(5).WithMemory(5).BuildMany(51) ).Union( machineBuilder.WithCpu(1).WithMemory(1).BuildMany(84) ).ToArray(); ContainerBuilder containerBuilder = new ContainerBuilder(); ContainerSpec[] containers = containerBuilder.WithCpu(1).WithMemory(1).WithInstanceCount(24).BuildMany(1); SolverParameters parameters = new SolverParameters { Machines = machines, ContainerSpecs = containers, FullScanIterations = 2, InitialRandomGuessIterations = 2 }; IAllocationSolver solver = new T(); SolverResult solution = solver.Solve(parameters); Console.WriteLine($"Solution Quality: {solution.SolutionQuality.ToString()}"); var allocatedMachines = solution.NewAllocations.Select(c => new { c.Machine.Name }).ToArray(); foreach (var allocation in solution.Allocations) { Console.WriteLine($"{allocation.Machine.Name} <- {allocation.ContainerSpec.Name}"); } }
private void FormProgress_Load(object sender, EventArgs e) { progressBar.Value = 0; txtProgress.Text = "Calculating: 0%\r\nTime Elapsed: 0s"; Result_ = SolverResult.Clash; backgroundWorker.RunWorkerAsync(); timer.Start(); }
private void FormProgress_Load(object sender, EventArgs e) { progressBar.Value = 0; txtProgress.Text = "Calculating: 0%\r\nTime Elapsed: 0s"; Result_ = SolverResult.Clash; backgroundWorker.RunWorkerAsync(); timer.Start(); }
public SolverResult Solve <Tunknowns, Trhs>(Tunknowns _x, Trhs _rhs) where Tunknowns : IList <double> where Trhs : IList <double> { Init(); if (_x.Count != this.Matrix.RowPartitioning.LocalLength) { throw new ArgumentException("Mismatch in length of X vector."); } if (_rhs.Count != this.Matrix.RowPartitioning.LocalLength) { throw new ArgumentException("Mismatch in lenght of RHS vector."); } double[] x = _x as double[]; if (x == null) { x = _x.ToArray(); } double[] rhs = _rhs as double[]; if (x == null) { rhs = _rhs.ToArray(); } SolverResult R = new SolverResult(); Stopwatch stw = new Stopwatch(); stw.Start(); int ktype = (int)this.m_KrylovType; int maxI = this.m_MaxIterations; int ierr = 0; int Nrows = this.Matrix.RowPartitioning.LocalLength; int NoIter; Wrappers.ALMOND_UseSolver_d(ref Nrows, ref ktype, ref maxI, ref this.m_Tolerance, ref this.SolverHandle, x, rhs, out NoIter, out ierr); CheckErr(ierr); stw.Stop(); R.RunTime = stw.Elapsed; R.Converged = NoIter >= 0; R.NoOfIterations = Math.Abs(NoIter); if (!object.ReferenceEquals(x, _x)) { _x.SetV(x); } if (!object.ReferenceEquals(rhs, _rhs)) { _rhs.SetV(rhs); } return(R); }
public override ISolverResult Solve(IAlgorithm tspSolvingAlgorithm) { Statistics = new BasicSolverStatistics(); var solverResult = new SolverResult(); for (var startNode = 0; startNode < CompleteGraph.NodesCount; startNode++) { Solve(tspSolvingAlgorithm, startNode, solverResult); } return(solverResult); }
private static void OutputResults(SolverResult solverResult, TimeSpan elapsed) { var n = solverResult.NumberOfEquations <= 1001 ? solverResult.NumberOfEquations : 100; Console.WriteLine($"At t = {solverResult.EndTime:N2}\n Total = {solverResult.X.Sum()}"); Console.WriteLine($"{string.Join("\n", solverResult.X.Take(n).Select((e, i) => $" y[{i}] = {e}"))}"); Console.WriteLine( $"No. steps = {(solverResult.Steps > 0 ? $"{solverResult.Steps:N0}" : "<unknown>")}, " + $"No. f-s = {solverResult.FuncCalls:N0}, No. J-s = {solverResult.JacobianCalls:N0}"); Console.WriteLine($"Elapsed: {elapsed}\n\n"); }
public SolverResult TryToSolveOneCell(Grid grid, PencilMarks pencilMarks) { foreach (var solver in solvers) { var result = solver.TryToSolveOneCell(grid, pencilMarks); if (result.ProgressMade) { return(result); } } return(SolverResult.Failed(grid)); }
private List <SolverResult> Solve_EquationSulotion_V(Vector3 startVelocity, float duration, float sampleStp) { List <SolverResult> resultList = new List <SolverResult>(); float time = sampleStp; while (time <= duration) { SolverResult result = Solve_EquationSulotion_V(startVelocity, time); resultList.Add(result); time += sampleStp; } return(resultList); }
static SolverResult SolveMath(SolverInput input) { SolverResult necessaryResult = SolveNecessaryCondition(input); if (necessaryResult != null) { SolverResult necessaryFilteredResult = CorrectResultInterval(necessaryResult, 0.0, 1.0); if (necessaryFilteredResult != null) { return(GetSufficientCondition(input, necessaryFilteredResult)); } } return(null); }
static SolverResult GetSufficientCondition(SolverInput input, SolverResult resultIn) { Debug.Assert(resultIn != null); if (resultIn.root1 != null && !IsSufficientCondition(input, resultIn.root1.Value)) resultIn.root1 = null; if (resultIn.root2 != null && !IsSufficientCondition(input, resultIn.root2.Value)) resultIn.root2 = null; if (resultIn.root1 == null && resultIn.root2 == null) return null; else if (resultIn.root1 == null && resultIn.root2 != null) return new SolverResult(resultIn.root2, null); else return resultIn; }
/// <summary> /// solves the equation system; /// there is no solution output, /// the solution is written to the fields in <see cref="Mapping"/>; /// </summary> /// <param name="rhs">optional right-hand-side, can be null;</param> /// <returns>the basic statistics of the sparse solver</returns> /// <remarks> /// If an right-hand-side operator has been specified, i.e. /// <see cref="RhsEvaluator"/> is not null, it is evaluated prior /// to the sparse solver call; /// The result of this right-hand-side operator, added to <paramref name="rhs"/>, /// can be monitored by consuming the <see cref="RHSEvaluated"/>-event. /// </remarks> virtual public SolverResult Solve(IList <double> rhs) { // initial stuff // ============= using (var tr = new ilPSP.Tracing.FuncTrace()) { // prepare right-hand-side // ======================= // clone or allocate memory double[] _rhs; GetTotalRHS(rhs, out _rhs); //// testcode //{ // Field f = new SinglePhaseField(m_Context, new Basis(m_Context, 2)); // int J = f.Coordinates.NoOfRows; // int N = f.Coordinates.NoOfCols; // int cnt = 0; // for( int j = 0; j < J; j++) // for (int nn = 0; nn < N; nn++) { // f.Coordinates[j, nn] = _rhs[cnt]; // cnt++; // } // double InfNrm = f.LinfNorm(); // double TwoNorm = f.L2Norm(); // Console.WriteLine("rhs L2: " + TwoNorm + " inf: " + InfNrm); // //Array.Copy(_rhs, f.Coordinates.C, _rhs.Length); // BoSSS.Solution.Tecplot.Tecplot.PlotFields(new Field[] { f }, null, m_Context, "rhs", "---", 0, 0); //} // call solver // =========== tr.Info("entering linear solver:"); SolverResult ret = m_Solver.Solve <CoordinateVector, double[]>(m_DGCoordinates, (double[])_rhs.Clone()); tr.Info("no. of iterations: " + ret.NoOfIterations); tr.Info("converged? : " + ret.Converged); tr.Info("Pure solver runtime: " + ret.RunTime.TotalSeconds + " sec."); // finalize // ======== return(ret); } }
static SolverResult CorrectResultInterval(SolverResult resultIn, double leftRange, double rightRange) { Debug.Assert(resultIn != null); if (resultIn.root1 != null && (resultIn.root1.Value < leftRange || resultIn.root1.Value > rightRange)) resultIn.root1 = null; if (resultIn.root2 != null && (resultIn.root2.Value < leftRange || resultIn.root2.Value > rightRange)) resultIn.root2 = null; if (resultIn.root1 == null && resultIn.root2 == null) return null; else if (resultIn.root1 == null && resultIn.root2 != null) return new SolverResult(resultIn.root2, null); else return resultIn; }
public static Result FromSolverResult(SolverResult solverResult) { return(new Result { Status = solverResult.Status, TimeLimitReached = solverResult.TimeLimitReached, RunningTime = solverResult.RunningTime, StartTimes = solverResult.StartTimes?.ToIndexedStartTimes(), LowerBound = solverResult.LowerBound, Objective = solverResult.Objective, TimeToBest = solverResult.TimeToBest, Metadata = solverResult.Metadata, AdditionalInfo = solverResult.AdditionalInfo }); }
private static void AssertSolverResultIsEquivalent <T>( int[][] expectedComposition, SolverResult actualResult, Func <SolverParticipant, T> identifierPropertyResolver) { foreach (var course in actualResult.Courses) { var aggregatedEquivalentToConstraint = expectedComposition .Skip(1) .Aggregate( Is.EquivalentTo(expectedComposition.First()), (constraint, ints) => constraint.Or.EquivalentTo(ints) ); Assert.That(course.Participants.Select(identifierPropertyResolver), aggregatedEquivalentToConstraint); } }
/* * /// <summary> * /// Solves the linear system (diag(1/<paramref name="dt"/>) + * /// <em>M</em>) * x = * /// <see cref=" SubgridMapping.subgridCoordinates"/> / * /// <paramref name="dt"/> - * /// <see cref="ImplicitTimeStepper.m_AffineOffset1"/> and writes the * /// result to <see cref=" SubgridMapping.subgridCoordinates"/>. * /// </summary> * /// <param name="dt">The lenght of the timestep</param> * protected override void PerformTimeStep(double dt) { * using (var tr = new ilPSP.Tracing.FuncTrace()) { * * int n = SubgridMapping.SubgridNUpdate * SubgridMapping.MaxTotalNoOfCoordinatesPerCell; * * double[] rhs = (double[])m_CompressedAffine.Clone(); * BLAS.dscal(rhs.Length, -1.0, rhs, 1); * * for (int i = 0; i < n; i++) { * rhs[i] += 1.0 / dt * SubgridDGCoordinates[i]; * } * * tr.Info("Calling solver"); * * LastSolverResult = m_Solver.Solve<double[], double[]>(SubgridDGCoordinates, rhs); * //Console.WriteLine(LastSolverResult.NoOfIterations); * SubgridMapping.subgridCoordinates = SubgridDGCoordinates; * * } * }*/ protected override void PerformTimeStep(double dt) { using (var tr = new ilPSP.Tracing.FuncTrace()) { int[] cells = m_Subgrid.SubgridIndex2LocalCellIndex; // int n = SubgridMapping.SubgridNUpdate * SubgridMapping.MaxTotalNoOfCoordinatesPerCell; int CoordinateOffset = 0; double[] rhs = (double[])m_CompressedAffine.Clone(); // BLAS.dscal(rhs.Length, -1.0, rhs, 1); /* for (int j = 0; j < cells.Length; j++) { * CoordinateOffset = 0; * for (int g = 0; g < temporalOp.Length; g++) { * * if (temporalOp[g]) {*/ for (int g = 0; g < temporalOp.Length; g++) { if (temporalOp[g]) { for (int j = 0; j < cells.Length; j++) { int loc = j * m_SubgridMapping.MaxTotalNoOfCoordinatesPerCell + CoordinateOffset; for (int i = 0; i < m_SubgridMapping.Fields[g].Basis.MaximalLength; i++) { rhs[loc] += 1.0 / dt * SubgridDGCoordinates[loc]; loc++; } } } CoordinateOffset += m_SubgridMapping.Fields[g].Basis.MaximalLength; } tr.Info("Calling solver"); LastSolverResult = m_Solver.Solve <double[], double[]>(SubgridDGCoordinates, rhs); SubgridMapping.subgridCoordinates = SubgridDGCoordinates; Console.WriteLine("Solver" + LastSolverResult.NoOfIterations); if (LastSolverResult.Converged) { Console.WriteLine("SolverConverged?:Yes"); } else { Console.WriteLine("SolverConverged?:No"); } } }
public override ISolverResult Solve(IAlgorithm tspSolvingAlgorithm) { var context = SolvingTimeContext.Instance; Statistics = new BasicSolverStatistics(); var resultPathAccumulator = new SolverResult(); for (var i = 0; i < IlsRepeatAmount; i++) { Path bestPath; using (context) { var pathAccumulator = _initializationSolver.Solve(_initializationAlgorithm, StartNode); bestPath = pathAccumulator.Paths[0]; var timer = new Stopwatch(); timer.Start(); var newPath = bestPath; while (timer.ElapsedMilliseconds < AlgorithmSolveTimeMs) { for (var j = 0; j < PerturbanceLength; j++) { var move = GetRandomMove(newPath, CompleteGraph); newPath = move.Move(bestPath); } var solvedPath = tspSolvingAlgorithm.Solve(bestPath.Nodes.First(), CompleteGraph, bestPath); if (solvedPath.Cost >= bestPath.Cost) { continue; } bestPath = newPath; } } resultPathAccumulator.AddPath(bestPath); Statistics.UpdateSolvingResults(bestPath, context.Elapsed); Console.WriteLine(i + " / 10"); } return(resultPathAccumulator); }
/// <summary> /// /// </summary> /// <param name="temperature">in K</param> /// <param name="pressure">in Pa</param> /// <param name="maxTemperature">in K</param> public Region3Factory(double temperature, double pressure, Range temperatureRange) { Props = new Region3Properties() { Pressure = pressure, Temperature = temperature }; SolverResult result = NewtonsMethod.Solve((x) => DensitySolver(Props.Temperature, x), temperatureRange); if (result.ReachedMaxGuesses) { throw new ArgumentOutOfRangeException("Could find a point in region3 at the given temperature and pressure"); } Props.Density = result.Value; }
public void Run_WhenNoExceptionThrown_ThenTheErrorStringIsNullAndWasThereAnErrorIsFalse() { RubiksCube cube = new RubiksCube(); Mock <ICubeSolvingAlgorithm> algMock = new Mock <ICubeSolvingAlgorithm>(); algMock.Setup(alg => alg.Solve(cube)).Callback(new Action(() => { cube.TurnUp(TurningDirection.NineoClock); })); CubeRunner runner = new CubeRunner(cube, algMock.Object); SolverResult result = runner.Run(); Assert.IsFalse(result.WasThereAnError); Assert.IsNull(result.ErrorMessage); }
public void Run_WhenAlgorithmTurnsCubeTwice_ThenMovesToCompletionIsTwo() { RubiksCube cube = new RubiksCube(); Mock <ICubeSolvingAlgorithm> algMock = new Mock <ICubeSolvingAlgorithm>(); algMock.Setup(alg => alg.Solve(cube)).Callback(new Action(() => { cube.TurnUp(TurningDirection.NineoClock); cube.TurnLeft(TurningDirection.NineoClock); })); CubeRunner runner = new CubeRunner(cube, algMock.Object); SolverResult result = runner.Run(); Assert.AreEqual <int>(2, result.MovesToCompletion); }
public void Run_WhenAlgorithmRunsForOneSecond_ThenTimeToCompletionIsOneSecondPlusOrMinusPointTwoSeconds() { RubiksCube cube = new RubiksCube(); Mock <ICubeSolvingAlgorithm> algMock = new Mock <ICubeSolvingAlgorithm>(); algMock.Setup(alg => alg.Solve(cube)).Callback(new Action(() => { System.Threading.Thread.Sleep(1000); })); CubeRunner runner = new CubeRunner(cube, algMock.Object); SolverResult result = runner.Run(); Assert.IsTrue(TimeSpan.FromSeconds(1) + TimeSpan.FromSeconds(.2) > result.TimeToCompletion || TimeSpan.FromSeconds(1) - TimeSpan.FromSeconds(.2) < result.TimeToCompletion, string.Format("Actual time to completion {0}", result.TimeToCompletion)); }
public void Run_WhenAlgorithmFailsToSolveCube_ThenResultShowThatTheCubeWasSolved() { RubiksCube cube = new RubiksCube(); cube.TurnLeft(); cube.TurnUp(); Mock <ICubeSolvingAlgorithm> algMock = new Mock <ICubeSolvingAlgorithm>(); algMock.Setup(alg => alg.Solve(cube)).Callback(new Action(() => { cube.TurnUp(TurningDirection.NineoClock); })); CubeRunner runner = new CubeRunner(cube, algMock.Object); SolverResult result = runner.Run(); Assert.IsFalse(result.WasCubeSolved); }
static void RunAlgLib(int numberOfEquations) { if (numberOfEquations > 51) { Console.WriteLine($"NOT calling OdeSolverSolve because the number of equations is too large: {numberOfEquations}."); return; } Console.WriteLine("Calling OdeSolverSolve."); Start = DateTime.Now; var stepSize = 0.0; var x = new[] { StartTime, EndTime, }; alglib.odesolverrkck(GetInitialValues(numberOfEquations), x, SolverParams.DefaultAbsoluteTolerance, stepSize, out var s); var sw = new Stopwatch(); sw.Start(); alglib.odesolversolve(s, FImpl2, null); alglib.odesolverresults(s, out var m, out var xTbl, out var yTbl, out var rep); var elapsed = sw.Elapsed; var solverResult = new SolverResult { ResultState = ResultState.Success, StartTime = StartTime, EndTime = xTbl[1], X = Enumerable.Range(0, numberOfEquations).Select(i => yTbl[1, i]).ToArray(), Steps = -1, FuncCalls = CallCount, JacobianCalls = 0, RequiredLRW = 0, RequiredLIW = 0, }; OutputResults(solverResult, elapsed); }
public SudokuField Process(SudokuField sudoku) { CheckCollision(sudoku); _ = _solverUnique.Process(sudoku); if (_solverUnique.Process(sudoku) != Result.FullFilled) { SolverResult solverResult = _solverBackTrack.Process(sudoku); if (solverResult.Result == Result.Error) { throw new SudokuUnsolvableException("There is no solution for this Sudoku."); } else { sudoku = solverResult.Sudoku; } } return(sudoku); }
private void BenchButton_Click(object sender, RoutedEventArgs e) { SolverResult s = new SolverResult(); //存储游戏结果 s.Solver = SolverList.SelectedItem as ISudokuSolver; //解题器为列表中所选 int?[,] arr = Board.GameBoard.ToArray(); //将迷局存储到数组 BenchButton.IsEnabled = false; //按钮禁用 InfoPanel.Visibility = Visibility.Hidden; WaitPanel.Visibility = Visibility.Visible; long tick = DateTime.Now.Ticks; solverWorker = new BackgroundWorker(); //在单独的线程上执行操作 solverWorker.DoWork += new DoWorkEventHandler(delegate(object dwsender, DoWorkEventArgs dwe) { s.Failed = !s.Solver.Solve(ref arr); //调用解题器解题 s.TimeTaken = TimeSpan.FromTicks((DateTime.Now.Ticks - tick)); //计算时间 }); solverWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object rwcsender, RunWorkerCompletedEventArgs rwce) //计算出来后 { Graph.Items.Add(s); //将答案以图像显示 InfoPanel.Visibility = Visibility.Visible; WaitPanel.Visibility = Visibility.Hidden; BenchButton.IsEnabled = true; }); solverWorker.RunWorkerAsync(); }