示例#1
0
        public PuzzleState Evalute(Puzzle current)
        {
            var crateMap = current.ToMap(current.Definition.AllCrates);

            return(new PuzzleState(Static,
                                   new StateMaps(crateMap,
                                                 SolverHelper.FloodFillUsingWallAndCrates(Static.WallMap, crateMap, current.Player.Position))
                                   ));
        }
示例#2
0
            public void Evalulate(Node node, IStragetgyItterator <Node> itterator)
            {
                var free = Static.FloorMap.Subtract(node.Maps.CrateMap);

                foreach (var move in node.Maps.MoveMap.TruePositions())
                {
                    var dir = node.CrateTarget - move;
                    if (dir == VectorInt2.Up || dir == VectorInt2.Down || dir == VectorInt2.Left ||
                        dir == VectorInt2.Right) // Next to each other
                    {
                        var p   = move;
                        var pp  = node.CrateTarget;
                        var ppp = node.CrateTarget + dir;

                        if (free.Contains(ppp) && free[ppp])
                        {
                            var newCrate = new Bitmap(node.Maps.CrateMap);
                            newCrate[pp]  = false;
                            newCrate[ppp] = true;

                            var newMove = SolverHelper.FloodFillUsingWallAndCrates(Static.WallMap, newCrate, pp);

                            var newNode = new Node
                            {
                                PlayerBefore = p,
                                PlayerAfter  = pp,
                                CrateTarget  = ppp,

                                Maps = new StateMaps(newCrate, newMove)
                            };

                            // Does this already exist
                            if (!CrateMap[ppp])
                            {
                                // New crate position
                                node.Add(newNode);
                                itterator.Add(newNode);
                                CrateMap[ppp] = true;
                            }
                            else
                            {
                                // the crate may exist, but we have a new move map
                                var match = node.Root().FirstOrDefault(x => x.Maps.Equals(newNode.Maps));
                                if (match == null)
                                {
                                    node.Add(newNode);
                                    itterator.Add(newNode);
                                }
                            }
                        }
                    }
                }
            }
        private SolverState PerformStandardTest(Puzzle puzzle, ExitConditions exit = null)
        {
            exit = exit ?? new ExitConditions
            {
                Duration       = TimeSpan.FromSeconds(60),
                StopOnSolution = true,
                TotalNodes     = int.MaxValue,
                TotalDead      = int.MaxValue
            };
            // arrange
            var solver  = new SingleThreadedReverseSolver(new SolverNodeFactoryTrivial());
            var command = new SolverCommand
            {
                Puzzle         = puzzle.Clone(),
                Report         = new XUnitOutput(outp),
                ExitConditions = exit,
                Inspector      = node =>
                {
                    if (node.GetHashCode() == 929793)
                    {
                        outp.WriteLine(node.ToString());
                        return(true);
                    }

                    return(false);
                }
            };

            // act
            var result = solver.Init(command);

            solver.Solve(result);
            // Console.WriteLine(result.ExitDescription);
            // Console.WriteLine(SolverHelper.GenerateSummary(result));
            result.ThrowErrors();

            // assert
            Assert.NotNull(result);

            foreach (var solution in result.SolutionsNodes)
            {
                var p = solution.PathToRoot().ToList();
                p.Reverse();
            }

            foreach (var sol in result.Solutions)
            {
                Assert.True(SolverHelper.CheckSolution(command.Puzzle, sol, out var error), "Solution is INVALID! " + error);
            }

            return(result);
        }
示例#4
0
        /// <summary>
        /// Solves a system of linear equations, <c>A'x = b</c>.
        /// </summary>
        /// <param name="input">The right hand side vector, <c>b</c>.</param>
        /// <param name="result">The left hand side vector, <c>x</c>.</param>
        public void SolveTranspose(Complex[] input, Complex[] result)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            int m2 = S.m2;

            var x = new Complex[m2];

            if (m >= n)
            {
                // x(q(0:m-1)) = b(0:m-1)
                Permutation.Apply(S.q, input, x, n);

                SolverHelper.SolveUpperTranspose(R, x); // x = R'\x

                // Apply Householder reflection to x.
                for (int k = n - 1; k >= 0; k--)
                {
                    ApplyHouseholder(Q, k, beta[k], x);
                }

                // b(0:n-1) = x(p(0:n-1))
                Permutation.Apply(S.pinv, x, result, m);
            }
            else
            {
                // x(0:m-1) = b(p(0:m-1)
                Permutation.ApplyInverse(S.pinv, input, x, n);

                // Apply Householder reflection to x.
                for (int k = 0; k < m; k++)
                {
                    ApplyHouseholder(Q, k, beta[k], x);
                }

                SolverHelper.SolveUpper(R, x); // x = R\x

                // b(q(0:n-1)) = x(0:n-1)
                Permutation.ApplyInverse(S.q, x, result, m);
            }
        }
        public void R001_Regression_CheckPath()
        {
            var puzzle = Puzzle.Builder.FromLines(new[]
            {
                "##########",
                "#O...X...#",
                "#O..XPX.O#",
                "##########"
            });

            string desc = null;

            SolverHelper.CheckSolution(puzzle, new Path("RRLLLLLRRRRULLLL"), out desc);
            Assert.Null(desc);
        }
        private SolverState PerformStandardTest(
            Puzzle puzzle,
            ExitConditions exit = null,
            Func <SolverNode, bool>?inspector = null
            )
        {
            exit = exit ?? new ExitConditions
            {
                Duration       = TimeSpan.FromSeconds(60),
                StopOnSolution = true,
                TotalNodes     = int.MaxValue,
                TotalDead      = int.MaxValue
            };
            // arrange
            var solver  = new SingleThreadedForwardReverseSolver(new SolverNodeFactoryTrivial());
            var command = new SolverCommand
            {
                Puzzle         = puzzle.Clone(),
                Report         = new XUnitOutput(outp),
                ExitConditions = exit,
                Inspector      = inspector
            };

            // act
            var result = solver.Init(command);

            solver.Solve(result);
            Console.WriteLine(result.ExitDescription);
            Console.WriteLine(SolverHelper.GenerateSummary(result));
            result.ThrowErrors();

            // assert
            Assert.NotNull(result);

            Assert.True(result.HasSolution);
            Assert.NotNull(result.Solutions);
            Assert.NotEmpty(result.Solutions);

            foreach (var sol in result.Solutions)
            {
                Console.WriteLine("Path: {0}", sol);
                string error = null;
                Assert.True(SolverHelper.CheckSolution(command.Puzzle, sol, out error),
                            "Solution is INVALID! " + error);
            }

            return(result);
        }
示例#7
0
        /// <summary>
        /// Solves a system of linear equations, <c>Ax = b</c>.
        /// </summary>
        /// <param name="input">The right hand side vector, <c>b</c>.</param>
        /// <param name="result">The left hand side vector, <c>x</c>.</param>
        /// <remarks>
        /// Let A be a m-by-n matrix. If m >= n a least-squares problem (min |Ax-b|)
        /// is solved. If m &lt; n the underdetermined system is solved.
        /// </remarks>
        public override void Solve(double[] input, double[] result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            var x = new double[S.m2];

            if (m >= n)
            {
                // x(0:m-1) = b(p(0:m-1)
                Permutation.ApplyInverse(S.pinv, input, x, m);

                // Apply Householder reflection to x.
                for (int k = 0; k < n; k++)
                {
                    ApplyHouseholder(Q, k, beta[k], x);
                }

                SolverHelper.SolveUpper(R, x); // x = R\x

                // b(q(0:n-1)) = x(0:n-1)
                Permutation.ApplyInverse(S.q, x, result, n);
            }
            else
            {
                // x(q(0:m-1)) = b(0:m-1)
                Permutation.Apply(S.q, input, x, m);

                SolverHelper.SolveUpperTranspose(R, x); // x = R'\x

                // Apply Householder reflection to x.
                for (int k = m - 1; k >= 0; k--)
                {
                    ApplyHouseholder(Q, k, beta[k], x);
                }

                // b(0:n-1) = x(p(0:n-1))
                Permutation.Apply(S.pinv, x, result, n);
            }
        }
示例#8
0
        private void PuzzleShouldHaveSolution(ISolver solver, Puzzle puzzle, ExitConditions exit = null,
                                              bool verbose = false)
        {
            if (exit == null)
            {
                exit = new ExitConditions
                {
                    Duration       = TimeSpan.FromSeconds(60),
                    StopOnSolution = true,
                    TotalNodes     = int.MaxValue,
                    TotalDead      = int.MaxValue
                }
            }
            ;
            var command = new SolverCommand
            {
                Puzzle         = puzzle,
                Report         = new XUnitOutput(outp),
                ExitConditions = exit
            };

            // act
            var result = solver.Init(command);

            solver.Solve(result);
            Console.WriteLine(result.ExitDescription);
            Console.WriteLine(SolverHelper.GenerateSummary(result));
            result.ThrowErrors();

            // assert
            Assert.NotNull(result);
            Assert.NotNull(result.Solutions);
            Assert.True(result.HasSolution);


            foreach (var sol in result.Solutions)
            {
                string error = null;
                Assert.True(SolverHelper.CheckSolution(command.Puzzle, sol, out error),
                            "Solution is INVALID! " + error);
            }
        }
示例#9
0
        /// <summary>
        /// Solves a system of linear equations, <c>Ax = b</c>.
        /// </summary>
        /// <param name="input">The right hand side vector, <c>b</c>.</param>
        /// <param name="result">The left hand side vector, <c>x</c>.</param>
        public void Solve(Complex[] input, Complex[] result)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var x = this.temp;

            Permutation.ApplyInverse(S.pinv, input, x, n); // x = P*b

            SolverHelper.SolveLower(L, x);                 // x = L\x

            SolverHelper.SolveLowerTranspose(L, x);        // x = L'\x

            Permutation.Apply(S.pinv, x, result, n);       // b = P'*x
        }
示例#10
0
        /// <summary>
        /// Solves a system of linear equations, <c>Ax = b</c>.
        /// </summary>
        /// <param name="input">The right hand side vector, <c>b</c>.</param>
        /// <param name="result">The left hand side vector, <c>x</c>.</param>
        public void Solve(Complex[] input, Complex[] result)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var x = this.temp;

            Permutation.ApplyInverse(pinv, input, x, n); // x = b(p)

            SolverHelper.SolveLower(L, x);               // x = L\x.

            SolverHelper.SolveUpper(U, x);               // x = U\x.

            Permutation.ApplyInverse(S.q, x, result, n); // b(q) = x
        }
示例#11
0
        /// <summary>
        /// Solves a system of linear equations, <c>A'x = b</c>.
        /// </summary>
        /// <param name="input">The right hand side vector, <c>b</c>.</param>
        /// <param name="result">The left hand side vector, <c>x</c>.</param>
        public void SolveTranspose(Complex[] input, Complex[] result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            var x = this.temp;

            Permutation.Apply(S.q, input, x, n);    // x = Q'*b

            SolverHelper.SolveUpperTranspose(U, x); // x = U'\x.

            SolverHelper.SolveLowerTranspose(L, x); // x = L'\x.

            Permutation.Apply(pinv, x, result, n);  // b = P'*x
        }
示例#12
0
        private void SolveRankings(int competitionId)
        {
            new Thread(() =>
            {
                UtilsNotification.StartLoadingAnimation();

                TeamSolver solverData = new TeamSolver();

                //Get Competition Teams
                var teams = teamService.GetCompetitionTeams(competitionId);

                if (teams != null && teams != null? teams.Count() > 0 : false)
                {
                    //Load teams into model
                    foreach (var t in teams)
                    {
                        solverData.Dados.Add(new TeamSolverData()
                        {
                            TeamId       = t.TeamId,
                            TeamName     = t.Name,
                            TeamDecision = new Decision(solverData.InputDomain, Utils.RemoveSpecialChars(t.Name))
                        });
                    }


                    //get Competition Matches
                    var matches = matchService.GetMatchesByCompetitionId(competitionId);

                    if (matches != null && matches != null ? matches.Count() > 0 : false)
                    {
                        //Load teams into model
                        foreach (var m in matches)
                        {
                            solverData.Jogos.Add(m);
                        }

                        //Calculate rankings using Microsoft.Solver
                        solverData = SolverHelper.SolverProblem(solverData);

                        //load model with data
                        ObservableCollection <RankingsModel> classificacoes = new ObservableCollection <RankingsModel>();

                        foreach (var cls in solverData.Dados)
                        {
                            classificacoes.Add(new RankingsModel()
                            {
                                TeamName        = cls.TeamName,
                                TeamRatingValue = Math.Round(cls.TeamDecision.ToDouble(), 2),
                                TeamRating      = Math.Round(cls.TeamDecision.ToDouble(), 2).ToString()
                            });
                        }

                        //checkRanks
                        int rnk = 1;
                        foreach (var r in classificacoes.OrderByDescending(x => x.TeamRatingValue))
                        {
                            r.TeamRankValue = rnk;
                            r.TeamRank      = rnk.ToString();
                            rnk++;
                        }

                        DataGridRankings.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.ItemsSource = null; }));
                        DataGridRankings.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.ItemsSource = classificacoes.OrderBy(x => x.TeamRankValue); }));
                        LabelHomeAdvantageValue.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantageValue.Text = Math.Round(solverData.HomeAdvantage.ToDouble(), 2).ToString(); }));

                        DataGridRankings.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.Visibility = Visibility.Visible; }));
                        LabelHomeAdvantage.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.Visibility = Visibility.Visible; }));
                        LabelHomeAdvantage.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantage.Visibility = Visibility.Visible; }));
                        LabelHomeAdvantageValue.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantageValue.Visibility = Visibility.Visible; }));

                        UtilsNotification.StopLoadingAnimation();
                    }
                    else
                    {
                        DataGridRankings.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.Visibility = Visibility.Collapsed; }));
                        LabelHomeAdvantage.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.Visibility = Visibility.Collapsed; }));
                        LabelHomeAdvantage.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantage.Visibility = Visibility.Collapsed; }));
                        LabelHomeAdvantageValue.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantageValue.Visibility = Visibility.Collapsed; }));

                        NotificationHelper.notifier.ShowCustomMessage("Não existem jogos registados na competição");
                        UtilsNotification.StopLoadingAnimation();
                    }
                }
                else
                {
                    DataGridRankings.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.Visibility = Visibility.Collapsed; }));
                    LabelHomeAdvantage.Dispatcher.BeginInvoke((Action)(() => { DataGridRankings.Visibility = Visibility.Collapsed; }));
                    LabelHomeAdvantage.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantage.Visibility = Visibility.Collapsed; }));
                    LabelHomeAdvantageValue.Dispatcher.BeginInvoke((Action)(() => { LabelHomeAdvantageValue.Visibility = Visibility.Collapsed; }));

                    NotificationHelper.notifier.ShowCustomMessage("Não existem equipas associadas à competição");
                    UtilsNotification.StopLoadingAnimation();
                }
            }).Start();
        }
示例#13
0
        public static void Run(string file, string report)
        {
            System.Console.WriteLine($"<file> {file} --report {report}");


            var ser = new BinaryNodeSerializer();

            if (report == "depth")
            {
                using (var f = System.IO.File.OpenRead(file))
                {
                    using (var br = new BinaryReader(f))
                    {
                        System.Console.WriteLine($"Reading File...");
                        var root = ser.AssembleTree(br);



                        var repDepth = MapToReporting.Create <SolverHelper.DepthLineItem>()
                                       .AddColumn("Depth", x => x.Depth)
                                       .AddColumn("Total", x => x.Total)
                                       .AddColumn("Growth Rate", x => x.GrowthRate)
                                       .AddColumn("UnEval", x => x.UnEval)
                                       .AddColumn("Complete", x => (x.Total - x.UnEval) * 100 / x.Total, c => c.ColumnInfo.AsPercentage());
                        repDepth.RenderTo(SolverHelper.ReportDepth(root), new MapToReportingRendererText(), System.Console.Out);
                    }
                }
            }
            else if (report == "clash")
            {
                using (var f = File.OpenRead(file))
                {
                    var writer = new BinaryNodeSerializer();
                    var nodes  = writer.ReadAll(new BinaryReader(f));

                    Dictionary <int, ClashLineItem> hash = new Dictionary <int, ClashLineItem>();
                    foreach (var n in nodes)
                    {
                        if (hash.TryGetValue(n.HashCode, out var c))
                        {
                            c.Count++;

                            if (c.First.CrateMap.Equals(n.CrateMap) && c.First.MoveMap.Equals(n.MoveMap))
                            {
                                c.Dups++;
                            }
                        }
                        else
                        {
                            hash[n.HashCode] = new ClashLineItem()
                            {
                                Hash  = n.HashCode,
                                Count = 1,
                                First = n
                            };
                        }
                    }

                    var items = hash.Where(x => x.Value.Count > 1).OrderByDescending(x => x.Value.Dups).ThenByDescending(x => x.Value.Count).Take(50).Select(x => x.Value);
                    MapToReporting.Create <ClashLineItem>()
                    .AddColumn("Hash", x => x.Hash)
                    .AddColumn("Count", x => x.Count)
                    .AddColumn("Dups", x => x.Dups)
                    .RenderTo(items, new MapToReportingRendererText(), System.Console.Out);


                    System.Console.WriteLine($"Total Dups: {hash.Values.Sum(x=>x.Dups)}");
                }
            }
            else if (report == "dump")
            {
                using (var f = File.OpenRead(file))
                {
                    var writer = new BinaryNodeSerializer();
                    using (var br = new BinaryReader(f))
                    {
                        foreach (var node in writer.ReadAll(br).OrderBy(x => x.SolverNodeId).Take(20))
                        {
                            System.Console.WriteLine(node);
                        }
                    }
                }
            }
            else
            {
                throw new Exception($"Unknown Report: {report}");
            }
        }