Beispiel #1
0
        public void SolveInvalidClassicGivens()
        {
            foreach (var curBoard in Puzzles.uniqueClassics)
            {
                StringBuilder givens = new(curBoard.Item1);
                for (int i = 0; i < givens.Length; i++)
                {
                    if (givens[i] < '1' || givens[i] > '9')
                    {
                        for (char v = '1'; v <= '9'; v++)
                        {
                            if (curBoard.Item2[i] == v)
                            {
                                continue;
                            }

                            try
                            {
                                givens[i] = v;
                                Solver testSolver = SolverFactory.CreateFromGivens(givens.ToString());
                                goto do_test;
                            }
                            catch (ArgumentException)
                            {
                            }
                        }
                        break;
                    }
                }

do_test:
                Solver solver = SolverFactory.CreateFromGivens(givens.ToString());
                solver.TestInvalidSolution();
            }
        }
Beispiel #2
0
        public void CandidatesStringGenerateAndParse()
        {
            // When a board created from the CandidateString of another board is the same as that board we know the parser and generator for the CandidateString is symmetric.
            // Note that that means we're not testing correctness, just that we can read what we output.

            foreach (var board in Puzzles.uniqueClassics) // list of 9*9 puzzles
            {
                Solver solver = SolverFactory.CreateFromGivens(board.Item1);

                string candidatesBase = solver.CandidateString;

                // Since the solver disregards trivial masks we have to create the solver twice to weed out any "missing" candidates.
                Solver newSolver  = SolverFactory.CreateFromCandidates(candidatesBase);
                Solver newSolver2 = SolverFactory.CreateFromCandidates(newSolver.CandidateString);

                Assert.AreEqual(solver.HEIGHT, newSolver.HEIGHT);
                Assert.AreEqual(solver.HEIGHT, newSolver2.HEIGHT);
                Assert.AreEqual(newSolver.CandidateString, newSolver2.CandidateString);
            }

            foreach (var board in Puzzles.uniqueVariantFPuzzles) // Some of these aren't 9*9, atm this covers both <9*9 and >9*9
            {
                Solver solver = SolverFactory.CreateFromFPuzzles(board.Item1);

                string candidatesBase = solver.CandidateString;

                // Since the solver disregards trivial masks we have to create the solver twice to weed out any "missing" candidates.
                Solver newSolver  = SolverFactory.CreateFromCandidates(candidatesBase);
                Solver newSolver2 = SolverFactory.CreateFromCandidates(newSolver.CandidateString);

                Assert.AreEqual(solver.HEIGHT, newSolver.HEIGHT);
                Assert.AreEqual(solver.HEIGHT, newSolver2.HEIGHT);
                Assert.AreEqual(newSolver.CandidateString, newSolver2.CandidateString);
            }
        }
Beispiel #3
0
        private static SolverResult Solve(Config config, SolverConfig solverConfig, Instance instance)
        {
            var solver = new SolverFactory().Create(config.SolverName);

            Console.WriteLine($"Starting solver: {solver.GetType().Name}");
            var solverResult = solver.Solve(solverConfig, instance);

            Console.WriteLine($"Solver finished.");

            if (solverResult.Status == Status.Heuristic || solverResult.Status == Status.Optimal)
            {
                Console.WriteLine($"Solution found, checking its feasibility.");
                var feasibilityChecker     = new FeasibilityChecker();
                var feasibilityCheckStatus = feasibilityChecker.Check(
                    instance,
                    solverResult.StartTimes,
                    solverConfig,
                    solverResult.Objective);
                if (feasibilityCheckStatus != FeasibilityChecker.FeasibilityStatus.Feasible)
                {
                    throw new Exception($"Solution not feasible: {feasibilityCheckStatus}");
                }
                Console.WriteLine($"Solution feasible.");
            }
            else
            {
                Console.WriteLine($"No solution found.");
            }

            return(solverResult);
        }
Beispiel #4
0
        /// <summary>
        /// Complex and memory consuming resources may be prepared before the controller is started.
        /// </summary>
        public void PrepareForStart()
        {
            // Prepare the solver.
            if (mazeForm != null)
            {
                solver = SolverFactory.CreateSolver(mazeForm.StrategyName, this.Maze, mazePainter);
            }
            else
            {
                solver = SolverFactory.CreateSolver(null, this.Maze, mazePainter);
            }

            // Prepare the solution path.
            solutionPath = SolverFactory.SolutionPath(this.Maze);

            // If our Maze has embedded mazes, we need to supply them with embedded solvers.
            CreateEmbeddedSolvers();

            // Prepare embedded solvers.
            foreach (EmbeddedSolverController item in embeddedControllers)
            {
                item.PrepareForStart();
            }

            // After all controllers have been created, some resources need to be shared with the master controller.
            if (this.Maze.MazeId == MazeSquare.PrimaryMazeId)
            {
                CoordinateEmbeddedControllers(this);
            }
        }
Beispiel #5
0
 public void GetScattererType_ReturnsNonNull()
 {
     foreach (var sType in EnumHelper.GetValues <ScatteringType>())
     {
         var s = SolverFactory.GetScattererType(sType);
         Assert.IsNotNull(s, "The requested instance matching " + sType + " returned null from the call to GetScattererType().");
     }
 }
Beispiel #6
0
 protected XdgTimesteppingBase(
     Control.NonLinearSolverConfig nonlinconfig,
     Control.LinearSolverConfig linearconfig)
 {
     XdgSolverFactory = new SolverFactory(nonlinconfig, linearconfig);
     m_nonlinconfig   = nonlinconfig;
     m_linearconfig   = linearconfig;
 }
Beispiel #7
0
 public void GetForwardSolver_ReturnsNonNull()
 {
     foreach (var fsType in EnumHelper.GetValues <ForwardSolverType>())
     {
         var fs = SolverFactory.GetForwardSolver(fsType);
         Assert.IsNotNull(fs, "The requested instance matching " + fsType + " returned null from the call to GetForwardSolver().");
     }
 }
        private static void SolvePuzzle(Options options)
        {
            var solver = new SolverFactory().Create(options.Puzzle);

            var puzzleResult = solver.Solve(options.Input);

            Console.WriteLine($"The result for puzzle {options.Puzzle} is {puzzleResult.Result}.");
        }
Beispiel #9
0
 public void GetOptimizer_ReturnsNonNull()
 {
     foreach (var oType in EnumHelper.GetValues <OptimizerType>())
     {
         var o = SolverFactory.GetOptimizer(oType);
         Assert.IsNotNull(o, "The requested instance matching " + oType + " returned null from the call to GetOptimizer().");
     }
 }
Beispiel #10
0
 public void SolveUniqueClassicFPuzzles()
 {
     foreach (var curBoard in Puzzles.uniqueClassicFPuzzles)
     {
         Solver solver = SolverFactory.CreateFromFPuzzles(curBoard.Item1);
         solver.TestUniqueSolution(curBoard.Item2);
     }
 }
Beispiel #11
0
        public void SolvingSquareIsCompletedInLeastMoves(string squareString, int expectedMovesToSolve)
        {
            SolverFactory factory = new SolverFactory();

            var finishedSquare = factory.GetMostEfficientlySolvedSquare(squareString);

            finishedSquare.GetNumberOfChanges().Should().Be(expectedMovesToSolve);
        }
        public void CanCreateFactory_And_CreateASolver()
        {
            var sut = SolverFactory.CreateFactory();

            var solver = sut.TryCreateSolver("0");

            solver !.Should().NotBeNull();
            solver !.DayNumber.Should().Be(0);
        }
Beispiel #13
0
        public void SF_CreateSolverTest_01()
        {
            string testObject = "SWA.Ariadne.Logic.SolverFactory.CreateSolver";

            Maze        maze       = NewMaze();
            IMazeDrawer mazeDrawer = null;
            IMazeSolver actual     = SolverFactory.CreateSolver(null, maze, mazeDrawer);

            Assert.IsInstanceOfType(actual, typeof(IMazeSolver), testObject + " did not return an instanze of IMazeSolver");
        }
Beispiel #14
0
        public void SF_CreateDefaultSolverTest_01()
        {
            string testObject = "SWA.Ariadne.Logic.SolverFactory.CreateDefaultSolver";

            Maze        maze       = NewMaze();
            IMazeDrawer mazeDrawer = null;
            IMazeSolver actual     = SolverFactory.CreateDefaultSolver(maze, mazeDrawer);

            Assert.IsInstanceOfType(actual, SolverFactory.DefaultStrategy, testObject + " did not return an instance of the default strategy.");
        }
Beispiel #15
0
        public void MiracleCount()
        {
            Solver solver = SolverFactory.CreateFromGivens(Puzzles.blankGrid, new string[]
            {
                "king",
                "knight",
                "difference:neg1",
            });

            Assert.AreEqual(72ul, solver.CountSolutions(multiThread: true));
        }
Beispiel #16
0
        /// <summary>
        /// Continue after the designer generated code.
        /// </summary>
        private void InitializeComponent2()
        {
            this.mazeUserControl.MazeForm = this as IMazeForm;

            #region Fill the strategyComboBox with all known MazeSolvers

            SolverFactory.FillWithSolverTypes(strategyComboBox.Items);
            strategyComboBox.SelectedItem = SolverFactory.DefaultStrategy.Name;

            #endregion
        }
Beispiel #17
0
        public void SolveDiagonalNonconsecutive()
        {
            string solution = "572869431981432765634175829365781942819243657427956318246597183198324576753618294";
            Solver solver   = SolverFactory.CreateFromGivens("500000000000000000004000000000080000010200000000956000000000080008304000000000290", new string[]
            {
                "dnc",
            });

            Assert.AreEqual(LogicResult.PuzzleComplete, solver.ConsolidateBoard());
            Assert.AreEqual(solution, solver.ToGivenString());
        }
        private IEnumerable <double> ROfRho(ForwardSolverType forwardSolverType, OpticalProperties opticalProperties, DoubleRange rho, double noise)
        {
            var ops  = opticalProperties.AsEnumerable();
            var rhos = rho.AsEnumerable();
            var fs   = SolverFactory.GetForwardSolver(forwardSolverType);

            if (noise > 0.0)
            {
                return(fs.ROfRho(ops, rhos).AddNoise(noise));
            }
            return(fs.ROfRho(ops, rhos));
        }
        private IEnumerable <double> ROfFxAndTime(ForwardSolverType forwardSolverType, OpticalProperties opticalProperties, double fx, DoubleRange time, double noise)
        {
            var ops   = opticalProperties.AsEnumerable();
            var fxs   = fx.AsEnumerable();
            var times = time.AsEnumerable();
            var fs    = SolverFactory.GetForwardSolver(forwardSolverType);

            if (noise > 0.0)
            {
                return(fs.ROfFxAndTime(ops, fxs, times).AddNoise(noise));
            }
            return(fs.ROfFxAndTime(ops, fxs, times));
        }
Beispiel #20
0
        static int FromXMLFileInternal(string file, string name)
        {
            XmlDocument docu = new XmlDocument();

            docu.Load(file);

            XmlNode node = docu.SelectSingleNode("/SolverConfig/sparsesolver[@name='" + name + "']");

            var config = ilPSP.LinSolvers.SolverConfigurationParser.parseXMLConfigurationElements(node);
            var solver = SolverFactory.CreateSolver <ISparseSolver>(config);

            return(Infrastructure.RegisterObject(solver));
        }
Beispiel #21
0
        public static void RunTests(List <TestScenario> tests, int iterations)
        {
            StringBuilder     sb        = new StringBuilder();
            TextWriter        writer    = Console.Out;
            Stopwatch         stopwatch = new Stopwatch();
            List <TestResult> results   = new List <TestResult>();

            sb.Append("TestScenarioID,Iteration,ElapsedTime,SoC,Makespan\n");

            for (int testIdx = 0; testIdx < tests.Count; testIdx++)
            {
                var        test   = tests[testIdx];
                TestResult result = new TestResult();
                result.AddScenario(test);

                for (int i = 0; i < iterations; i++)
                {
                    WarehouseInstance instance = InstanceGenerator.GenerateInstance(test.description, 42 + i);
                    // TODO: Generate new items and orders without the need for whole new instance
                    Solver solver = SolverFactory.GetSolver(test.solver, instance);
                    stopwatch.Restart();

                    stopwatch.Start();
                    var tours = solver.FindTours();
                    stopwatch.Stop();

                    int makespan   = Tour.GetMakespan(tours);
                    int sumOfCosts = Tour.GetSumOfCosts(tours);
                    result.AddMeasurement((stopwatch.ElapsedMilliseconds, sumOfCosts, makespan, tours));
                    sb.Append($"{testIdx},{i},{stopwatch.ElapsedMilliseconds},{sumOfCosts},{makespan}\n");
                }

                result.Evaluate();
                results.Add(result);
            }
            Console.ReadKey();
            StreamWriter sw = new StreamWriter("./output.csv");

            sw.Write(sb.ToString());
            sw.Close();

            /*
             * void LogResults() {
             *  writer.WriteLine($"Time elapsed in {i}-th iteration: {stopwatch.ElapsedMilliseconds}");
             *
             *
             * Console.WriteLine("Agent {0} route has been found in {1}", i, sw.Elapsed);
             *  Console.WriteLine("   Items {0}\n    classes {1}", instance.agents[i].orders[0].vertices.Length, instance.agents[i].orders[0].classes[^1]);
             *  Console.WriteLine("   Constraint: {0}", constraints.Count);
             */
        }
Beispiel #22
0
        private static void Main(string[] args)
        {
            SolverLocator sl = new SolverLocator();

            sl.FindSolvers();

            string command = "";

            do
            {
                System.Console.BackgroundColor = ConsoleColor.Blue;
                System.Console.ForegroundColor = ConsoleColor.Yellow;
                System.Console.Clear();
                System.Console.WriteLine("*** Numbers Game Puzzle - Console Application ***\n");
                System.Console.WriteLine("\r\nRegistered solutions:");
                IEnumerable <string> descriptions = SolverFactory.GetSolverDescriptions();
                foreach (var d in descriptions)
                {
                    System.Console.WriteLine("{0}", d);
                }
                System.Console.WriteLine("\r\nMenu:\r\n");
                System.Console.WriteLine("S: Select Solver");
                System.Console.WriteLine("P: Play the game manually");
                System.Console.WriteLine("C: Run the competition");
                System.Console.WriteLine("Q: Quit the console");
                System.Console.Write(">");
                var input = System.Console.ReadLine();
                if (!string.IsNullOrEmpty(input))
                {
                    command = input.ToUpper().Substring(0, 1);
                    switch (command)
                    {
                    case "S":
                        SelectSolver();
                        break;

                    case "P":
                        PlayGame();
                        break;

                    case "C":
                        RunCompetition();
                        break;
                    }
                }
            } while (command != "Q");

            System.Console.WriteLine("Goodbye");
            System.Console.ReadLine();
        }
Beispiel #23
0
        private void FillMaze()
        {
            // Create a maze with fixed layout.
            mazeUserControl.Setup(5, 2, 3);

            // Draw the maze walls.
            mazeUserControl.MazePainter.PaintMaze(null);

            // Solve the maze.
            IMazeSolver solver = SolverFactory.CreateDefaultSolver(mazeUserControl.Maze, mazeUserControl.MazePainter);

            solver.Reset();
            solver.Solve();
        }
Beispiel #24
0
        public void SolvingSquareIsCompletedInLeastMovesUsingArray()
        {
            SolverFactory factory     = new SolverFactory();
            var           arraySquare = new[, ]
            {
                { 4, 8, 2 },
                { 4, 5, 7 },
                { 6, 1, 6 },
            };

            var finishedSquare = factory.GetMostEfficientlySolvedSquare(arraySquare);

            finishedSquare.GetNumberOfChanges().Should().Be(4);
        }
Beispiel #25
0
        // ReSharper disable UnusedMember.Global
        public static SimulationResults ExecuteModel(ModelInfo model, String solverName, double duration, int repeats, int samples)
        // ReSharper restore UnusedMember.Global
        {
            Console.WriteLine("Starting simulation...");

            ISolver solver = SolverFactory.CreateSolver(solverName, model, repeats, duration, samples);

            solver.Solve();
            var results = new SimulationResults(solver.GetTrajectoryLabels(), solver.GetTrajectoryData());

            Console.WriteLine("...finished simulation.");

            return(results);
        }
Beispiel #26
0
        // ReSharper disable MemberCanBePrivate.Global
        public static void RunModel(ModelInfo model, String solverName, double duration, int repeats, int samples)
        // ReSharper restore MemberCanBePrivate.Global
        {
            Console.WriteLine("Starting simulation...");

            ISolver solver = SolverFactory.CreateSolver(solverName, model, repeats, duration, samples);

            Console.WriteLine("Using solver {0}", solver);
            solver.Solve();
            string outputPrefix = Configuration.CurrentConfiguration.GetParameterWithDefault("output.prefix", "trajectories");

            solver.OutputData(outputPrefix);

            Console.WriteLine("...finished simulation.");
        }
Beispiel #27
0
        public ISolverFactory CreateSolverFactory()
        {
            ISolverFactory factory = null;

            try
            {
                factory = new SolverFactory();
            }
            catch (Exception exception)
            {
                this.Log.Error("Exception message: " + exception.Message + " and stacktrace " + exception.StackTrace);
            }

            return(factory);
        }
Beispiel #28
0
        public static void TestNonLinearSolverConfigurations()
        {
            //Arrange --- set configs
            var ACS = new AppControlSolver();
            NonLinearSolverConfig nlconfig = ACS.NonLinearSolver;
            LinearSolverConfig    lconfig  = ACS.LinearSolver;

            lconfig.verbose             = true;
            lconfig.NoOfMultigridLevels = 3;
            lconfig.TargetBlockSize     = 10;
            nlconfig.verbose            = true;
            var SF = new SolverFactory(nlconfig, lconfig);

            //Arrange --- get test multigrid operator stuff
            AggregationGridData[] seq;
            var MGO             = Utils.CreateTestMGOperator(out seq, Resolution: 10);
            var map             = MGO.Mapping;
            var changeofbasisis = Utils.GetAllMGConfig(MGO);
            var agggridbasisis  = Utils.GetAllAggGridBasis(MGO);

            //Arrange --- get nonlinear codes available
            var             nonlincodes = (NonLinearSolverCode[])Enum.GetValues(typeof(NonLinearSolverCode));
            NonlinearSolver NLsolver    = null;

            //Arrange --- get test linear Solver to set in NLsolver
            ISolverSmootherTemplate LinSolver = null;

            LinearSolverCode[] LinTestcandidates = { LinearSolverCode.classic_pardiso, LinearSolverCode.exp_gmres_levelpmg }; // in order to test the GMRES variants of the NL solver

            //Act and Assert
            foreach (var lincode in LinTestcandidates)
            {
                lconfig.SolverCode = lincode;
                TestDelegate nldlg = () => SF.GenerateNonLin(out NLsolver, out LinSolver, null, agggridbasisis, changeofbasisis, seq);
                SF.Clear();
                foreach (NonLinearSolverCode nlcode in nonlincodes)
                {
                    nlconfig.SolverCode = nlcode;
                    if (nlconfig.SolverCode == NonLinearSolverCode.selfmade)
                    {
                        SF.Selfmade_nonlinsolver = new Newton(null, agggridbasisis, changeofbasisis);
                    }
                    Assert.DoesNotThrow(nldlg, "", null);
                    Assert.IsNotNull(NLsolver);
                }
                Console.WriteLine("====");
            }
        }
Beispiel #29
0
        public void MiracleLogicalSolve()
        {
            string solution = "483726159726159483159483726837261594261594837594837261372615948615948372948372615";

            Solver solver = SolverFactory.CreateFromGivens(Puzzles.blankGrid, new string[]
            {
                "king",
                "knight",
                "difference:neg1",
            });

            Assert.IsTrue(solver.SetValue(4, 2, 1));
            Assert.IsTrue(solver.SetValue(5, 6, 2));
            Assert.AreEqual(LogicResult.PuzzleComplete, solver.ConsolidateBoard());
            Assert.AreEqual(solution, solver.ToGivenString());
        }
Beispiel #30
0
        public ISolverFactory CreateSolverFactory()
        {
            ISolverFactory factory = null;

            try
            {
                factory = new SolverFactory();
            }
            catch (Exception exception)
            {
                this.Log.Error(
                    exception.Message,
                    exception);
            }

            return(factory);
        }