示例#1
0
        /// <summary>
        /// Strong constuctor, also 'registers' all available stats
        /// </summary>
        /// <param name="controller"></param>
        public SolverStats(SolverController controller)
        {
            this.controller = controller;

            // Register all stats, for easy of use
            stats = new List<Statistic>();
            stats.Add(CurrentEvalSecs);
            stats.Add(EvaluationTime);
            stats.Add(EvaluationItterations);
            stats.Add(Nodes);
            stats.Add(NodesPerSecond);
            stats.Add(NodesFwd);
            stats.Add(NodesRev);

            stats.Add(Duplicates);
            stats.Add(DeadNodes);
            stats.Add(AvgEvalList);
            stats.Add(WeightingMin);
            stats.Add(WeightingMax);
            stats.Add(WeightingAvg);
            stats.Add(HintsUsed);
            stats.Add(MaxDepth);

            BestNodesFwd = new LinkedList<SolverNode>();
            BestNodesRev = new LinkedList<SolverNode>();
        }
示例#2
0
        public void Init(SolverController controller)
        {
            treeRenderer = new TreeVisualisation(controller.Strategy.EvaluationTree, new RectangleInt(0, 0, 1800, 1800), new SizeInt(8, 8));
            treeRenderer.Controller = controller;

            treeVis.Visualisation = treeRenderer;
        }
        public void TestRoom()
        {
            string[] puzzle = new string[]
                {
                    "~~###########",
                    "~##.....#..P#",
                    "###.X.XX#...#",
                    "#.##X....XX.#",
                    "#..#..X.#...#",
                    "######.######",
                    "#OO.OOX.#$##~",
                    "#.OO....###~~",
                    "#..OO#####~~~",
                    "#########~~~~"
                };

            SokobanMap map = new SokobanMap();
            map.SetFromStrings(puzzle);

            PuzzleMap pMap = new PuzzleMap((Puzzle)null);
            pMap.Map = map;

            SolverController solver = new SolverController(pMap);
            solver.Init();
        }
示例#4
0
        public void Build(SolverController controller)
        {
            AppendHeadingOne("SokoSolve Sokoban Solver Report");
            AppendLabel("Generated", DateTime.Now.ToLongDateString());

            Append(controller.Stats.GetDisplayData().ToHTML());
        }
        /// <summary>
        /// Strong constructor
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="cellSize"></param>
        public NodeListVisualisation(SolverController controller, List<SolverNode> nodes, SizeInt cellSize)
        {
            Display = new CommonDisplay(controller);
            this.nodes = nodes;
            this.cellSize = cellSize;

            int maxH = ((nodes.Count + 1)/maxCellWidth+1)*cellSize.Height;
            renderCanvas = new RectangleInt(0,0, cellSize.Width*maxCellWidth, maxH);
            windowRegion = renderCanvas;
        }
示例#6
0
        public void TestSolverReport()
        {
            XmlProvider xmlHelper = new XmlProvider();
            Library lib = xmlHelper.Load(MakePathUIContent("Libraries\\Sasquatch.ssx"));

            List<SolverResult> results = new List<SolverResult>();

            SolverController one = new SolverController(lib.Puzzles[0].MasterMap);
            results.Add(one.Solve());

            SolverController two = new SolverController(lib.Puzzles[1].MasterMap);
            results.Add(two.Solve());

            SolverResultHTML rpt = new SolverResultHTML(results, null);
            rpt.BuildReport();
            rpt.Save(@"solver.html");
        }
        protected SolverResult Solve(SokobanMap puzzle)
        {
            using (CodeTimer timer = new CodeTimer("TestSolver.Solve(...)"))
            {
                SolverController controller = new SolverController(puzzle);
                try
                {
                    System.Console.WriteLine(puzzle.ToString());

                    SolverResult results = controller.Solve();
                    if (results.Exception != null)
                    {
                        // Bubble up
                        throw new Exception("Solver Failed Iternally", results.Exception);
                    }

                    if (results.Status == SolverResult.CalculationResult.SolutionFound)
                    {
                        // Check that
                        Assert.IsTrue(results.HasSolution, "State says a solution was found, but none are listed in solutions list");
                    }

                    if (results.HasSolution)
                    {
                        int cc = 0;
                        foreach (Solution solution in results.Solutions)
                        {
                            string testRes = "Error";
                            Assert.IsTrue(solution.Test(puzzle, out testRes), testRes);
                            Console.WriteLine("Testing solution: {0} - {1}", cc, testRes);
                            cc++;
                        }
                    }

                    return results;
                }
                finally
                {
                    timer.Stop();
                    Console.WriteLine(controller.DebugReport.ToString(new DebugReportFormatter()));
                    System.Console.WriteLine("Total Time: " + timer.Duration(1));
                    System.Console.WriteLine("---");
                }
            }
        }
        public void TestReverseStrategyCoreSimple()
        {
            CodeTimer timer = new CodeTimer("");
            timer.Start();

            try
            {
                SokobanMap map = new SokobanMap();
                map.SetFromStrings(new string[]
                                   {
             "~##~#####",
              "##.##.O.#",
              "#.##.XO.#",
              "~##.X...#",
              "##.XP.###",
              "#.X..##~~",
              "#OO.##.##",
              "#...#~##~",
              "#####~#~~"
                                   });

                PuzzleMap pMap = new PuzzleMap((Puzzle)null);
                pMap.Map = map;

                SolverController controller = new SolverController(pMap);
                controller.Init();
                controller.State = SolverController.States.Running; // Manually set state, as we are not using the controller; but the strategy uses the controller to check if it should exit

                ReverseStrategy rev = new ReverseStrategy(controller);

                Evaluator<SolverNode> eval = new Evaluator<SolverNode>();
                EvalStatus result =  eval.Evaluate(rev);

                Assert.AreEqual(EvalStatus.CompleteSolution, result, "Should find a solution");
            }
            finally
            {
                timer.Stop();
                System.Console.WriteLine("Total Time: " + timer.Duration(1));
            }
        }
示例#9
0
        /// <summary>
        /// Build the result from the completed solver
        /// </summary>
        /// <param name="controller"></param>
        public void Build(SolverController controller)
        {
            map = controller.Map;

            // Build type strong info class
            info = new SolverResultInfo();
            info.TotalNodes = (int) controller.Stats.Nodes.ValueTotal;
            info.TotalSeconds = controller.Stats.EvaluationTime.ValueTotal;
            info.Machine = DebugHelper.GetCPUDescription();
            info.RatingScore = PuzzleAnalysis.CalcRating(map);
            foreach (Statistic stat in controller.Stats.Stats)
            {
                SolverLabel lb = stat.GetDisplayData();

                info.InfoValues.Add(new NameValuePair() {Name = lb.Name, Value = lb.Value});
            }

            // Build the exit status and summary
            if (HasSolution)
            {
                // General Sucess
                status = CalculationResult.SolutionFound;
                StringBuilder sb = new StringBuilder();
                if (solutions.Count == 1)
                {
                    sb.Append("Solution");
                }
                else
                {
                    sb.AppendFormat("{0} solutions", solutions.Count);
                }

                sb.AppendFormat(" in {0} and {1} nodes at {2:0} nodes/s (puzzle score {3})",
                                StringHelper.ToString(TimeSpan.FromSeconds(info.TotalSeconds)),
                                info.TotalNodes,
                                info.TotalNodes/info.TotalSeconds,
                                info.RatingScore);
                summary = sb.ToString();
            }
            else
            {
                if (exception != null)
                {
                    status = CalculationResult.Error;
                    summary = string.Format("Error ({0})", exception.Message);
                }
                else
                {
                    if (controllerResult == SolverController.States.Cancelled)
                    {
                        status = CalculationResult.Cancelled;
                        summary =
                            string.Format(" Cancelled after {0} sec and {1} nodes at {2:0} nodes/s (puzzle score {3})",
                                          StringHelper.ToString(TimeSpan.FromSeconds(info.TotalSeconds)),
                                          info.TotalNodes,
                                          info.TotalNodes/info.TotalSeconds,
                                          info.RatingScore);
                    }
                    else if (controllerResult == SolverController.States.CompleteNoSolution)
                    {
                        status = CalculationResult.NoSolution;
                        summary = "The puzzle does not have a solution";
                    }
                    else
                    {
                        status = CalculationResult.GaveUp;
                        summary = string.Format(
                                "The solver could not find a within the given constraints. Tried for {0} sec and {1} nodes at {2:0} nodes/s (puzzle score {3})",
                                StringHelper.ToString(TimeSpan.FromSeconds(info.TotalSeconds)),
                                info.TotalNodes,
                                info.TotalNodes/info.TotalSeconds,
                                info.RatingScore);
                    }
                }
            }
        }
示例#10
0
 /// <summary>
 /// Strong Construction
 /// </summary>
 /// <param name="controller"></param>
 public StaticAnalysis(SolverController controller)
 {
     this.controller = controller;
 }
 public RootPathVisualisation(SizeInt cellSize, SolverController controller)
 {
     this.cellSize = cellSize;
     this.controller = controller;
 }
示例#12
0
 public CommonDisplay(SolverController controller)
 {
     this.controller = controller;
 }
示例#13
0
 private void SolverSection_Disposed(object sender, EventArgs e)
 {
     if (worker != null)
     {
         StopWorker(worker);
     }
     worker = null;
     solver = null;
 }
示例#14
0
        /// <summary>
        /// Start the solver (this will always to run with a non UI worker thread)
        /// </summary>
        private void Solve()
        {
            try
            {
                complete = false;
                solverEvalStatus = EvalStatus.InProgress;
                solver = new SolverController(map);

                solver.ExitConditions.StopOnSolution = exitConditions.cbStopOnSolution.Checked;
                solver.ExitConditions.MaxDepth = (int)exitConditions.upMaxDepth.Value;
                solver.ExitConditions.MaxNodes = (int)exitConditions.upMaxNodes.Value;
                solver.ExitConditions.MaxItterations = (int)exitConditions.upMaxItter.Value;
                solver.ExitConditions.MaxTimeSecs = (int)(exitConditions.upMaxTime.Value * 60);

                solverEvalStatus = solver.Solve();
                complete = true;
            }
            catch (Exception ex)
            {
                lastException = ex;
            }

            Invoke(OnComplete); // Set to SolverComplete
        }
示例#15
0
        public override ReturnCodes Execute(ConsoleCommandController controller)
        {
            if (ArgReport != null)
            {
                reportFile = File.CreateText(ArgReport);
            }

            if (!string.IsNullOrEmpty(ArgSolverLibrary))
            {
                DateTime start = DateTime.Now;

                // MODE: Progress + Library
                ProgressComponent comp = new ProgressComponent();
                Library lib = null;

                // It is exists load...
                if (File.Exists(ArgSolverLibrary))
                {
                    comp.Load(ArgSolverLibrary);
                }

                // If a library is specified, merge/add it...
                if (!string.IsNullOrEmpty(ArgLibrary))
                {
                    XmlProvider xml = new XmlProvider();
                    lib = xml.Load(ArgLibrary);
                    comp.Add(lib);
                }

                int cc = 0;
                foreach (SolverPuzzle item in comp.Items)
                {
                    if (ArgNonSolutionOnly && item.HasSolution)
                    {
                        controller.DisplayLable("Skipping solution", item.Name);
                        cc++;
                        continue;
                    }

                    TimeSpan left = TimeSpan.FromSeconds((double) (comp.Items.Count - cc)*ArgMaxTime);
                    controller.DisplayLable("Est. Time Left", left.ToString());
                    controller.DisplayLable("Time Elapsed", (DateTime.Now-start).ToString());
                    controller.Display("==========================================================================");
                    controller.Display("");
                    controller.DisplayLable("Attempt", string.Format("{0}/{1} {2}%, maxtime={3}", cc, comp.Items.Count, cc*100/comp.Items.Count, TimeSpan.FromSeconds(ArgMaxTime)));
                    controller.DisplayLable("Name", item.Name);
                    controller.DisplayLable("Rating", string.Format("{0}, size=({1}, {2})", item.Rating, item.Width, item.Height));

                    controller.Display(StringHelper.Join(item.NormalisedMap, null, Environment.NewLine));

                    SokobanMap map = new SokobanMap();
                    map.SetFromStrings(item.NormalisedMap);
                    using (SolverController ctrl = new SolverController(map))
                    {
                        ctrl.ExitConditions.MaxDepth = 1000;
                        ctrl.ExitConditions.MaxItterations = 10000000;
                        ctrl.ExitConditions.MaxTimeSecs = (float) ArgMaxTime;

                        SolverResult res = ctrl.Solve();
                        if (res.Exception != null)
                        {
                            controller.Display(res.Exception);
                        }
                        controller.DisplayLable("Result", res.Summary);

                        comp.Update(res);
                    }

                    CheckForceGC();
                    controller.Display("---------------------------------------------------------------------------");

                    if (System.Console.KeyAvailable && System.Console.ReadKey().KeyChar == 'Q')
                    {
                        controller.Display("BREAK REQUESTED... Exiting");
                        break;
                    }

                    cc++;
                }

                comp.Save(ArgSolverLibrary);

            }
            else if (!string.IsNullOrEmpty(ArgLibrary))
            {
                // MODE: Only Library
                XmlProvider xml = new XmlProvider();
                Library lib = xml.Load(ArgLibrary);

                if (ArgPuzzle == "*")
                {
                    int cc = 0;
                    foreach (Puzzle puzzle in lib.Puzzles)
                    {
                        cc++;
                        controller.Display("");
                        controller.DisplayLable("Attempting", string.Format("{0:000} of {1:000}", cc, lib.Puzzles.Count));

                        SolvePuzzle(puzzle.MasterMap, puzzle.GetDetails().Name);

                        CheckForceGC();

                        if (System.Console.KeyAvailable && System.Console.ReadKey().KeyChar == 'Q')
                        {
                            controller.Display("BREAK REQUESTED... Exiting");
                            break;
                        }

                    }
                }
                else
                {
                    Puzzle pux = lib.GetPuzzleByID(ArgPuzzle);
                    SolvePuzzle(pux.MasterMap, pux.GetDetails().Name);
                }
            }

            if (reportFile != null)
            {
                reportFile.Close();
                reportFile.Dispose();
            }

            return ReturnCodes.OK;
        }
示例#16
0
        private void SolvePuzzle(PuzzleMap puz, string Name)
        {
            using (SolverController ctrl = new SolverController(puz))
            {
                ctrl.ExitConditions.MaxDepth = 1000;
                ctrl.ExitConditions.MaxItterations = 10000000;
                ctrl.ExitConditions.MaxTimeSecs = (float) ArgMaxTime;

                SolverResult res = ctrl.Solve();
                if (res.Exception != null)
                {
                    controller.Display(res.Exception);
                }

                controller.DisplayLable("Name", Name);
                controller.DisplayLable("Result", res.StatusString);
                controller.DisplayLable("Summary", res.Summary);
                controller.DisplayLable("Exit Conditions", ctrl.ExitConditions.ToString());

                if (res.HasSolution)
                {
                    controller.DisplayLable("Solution", res.Solutions[0].Steps);
                }

                if (reportFile != null)
                {
                    reportFile.WriteLine("###########################################################################");
                    reportFile.WriteLine(string.Format("{0} ===> {1}", Name, res.Summary));
                    reportFile.WriteLine("###########################################################################");
                    reportFile.WriteLine(res.Info.ToString());
                    reportFile.WriteLine(res.DebugReport.ToString(new DebugReportFormatter()));
                    reportFile.WriteLine("---------------------------------------------------------------------------");
                    reportFile.WriteLine("");
                }
            }
        }
 /// <summary>
 /// Strong constuctor
 /// </summary>
 /// <param name="cellSize"></param>
 /// <param name="controller"></param>
 public RootPathVisualisation(SizeInt cellSize, SolverController controller)
 {
     this.cellSize = cellSize;
     this.controller = controller;
     this.Display = new CommonDisplay(controller);
 }
示例#18
0
        /// <summary>
        /// Exit click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbExit_Click(object sender, EventArgs e)
        {
            // Stop anything that has started
            tsbStop_Click(sender, e);

            if (worker != null)
            {
                StopWorker(worker);
            }

            solver = null;
            worker = null;

            // Set the library
            FormMain main = FindForm() as FormMain;
            main.Mode = FormMain.Modes.Library;
        }
示例#19
0
 public void Init(SolverController controller)
 {
     treeRenderer = new TreeVisualisation(controller);
     treeRenderer.RenderCanvas = new RectangleInt(0, 0, 1800, 1800);
     treeVis.Visualisation = treeRenderer;
 }
 public TreeVisualisation(SolverController controller)
 {
     this.controller = controller;
     this.tree = controller.Strategy.EvaluationTree;
 }