Example #1
0
        public Node <State> TreeSearchMethod <State>(IProblem <State> problem, IFringe <Node <State> > fringe)
        {
            fringe.Add(new Node <State>(problem.InitialState, null, problem.Compare()));
            while (!fringe.IsEmpty)
            {
                Node <State> node = fringe.Pop();

                if (problem.IsGoal(node.StateOfNode))
                {
                    Console.Write("\n\nFinalne ustawienie:\n");
                    return(node);
                }

                Console.WriteLine("\n");
                problem.PrintState(node.StateOfNode);
                Console.Write(" --- Distance: ");
                Console.Write(problem.CheckDistance(node.StateOfNode));

                foreach (State state in problem.Expand(node.StateOfNode))
                {
                    if (!node.OnPathToRoot(state))
                    {
                        fringe.Add(new Node <State>(state, node, problem.Compare()));
                    }
                }
            }
            return(null);
        }
        public static Node <State> Search(IProblem <State> problem, IFringe <Node <State> > fringe)
        {
            Func <Node <State>, Node <State>, int> compareStatesPriority = (node1, node2) =>
            {
                return(problem.CompareStatesPriority(node1.NodeState, node2.NodeState));
            };

            Func <Node <State>, Node <State>, int> compareStatesPriorityWithPathCost = (node1, node2) =>
            {
                return(problem.CompareStatesPriorityWithPathCost(node1.NodeState, node2.NodeState, node1.PathCost, node2.PathCost));
            };

            fringe.SetPriorityMethod(compareStatesPriority, compareStatesPriorityWithPathCost);
            fringe.Add(new Node <State>(problem.InitialState, null, 0.0));
            while (!fringe.IsEmpty)
            {
                var node = fringe.Pop();

                if (problem.IsGoal(node.NodeState))
                {
                    return(node);
                }
                foreach (var state in problem.Expand(node.NodeState))
                {
                    if (!node.OnPathToRoot(state, problem.AreStatesTheSame))
                    {
                        var newNode = new Node <State>(state, node, node.PathCost + problem.CalculateCostToNextState(node.NodeState, state));
                        fringe.Add(newNode);
                    }
                }
            }
            return(null);
        }
Example #3
0
        public Summary <TCustomData> SolveProblem(Fringe <TCustomData> fringe, IProblem <TCustomData> problem, Config config = null)
        {
            var summary = new Summary <TCustomData>();

            if (config == null)
            {
                config = new Config();
            }

            var initialState = new State <TCustomData> {
                Data = config.DataForInitialState == null ? problem.DataForInitialState : (TCustomData)config.DataForInitialState
            };

            fringe.Add(initialState);

            while (!fringe.IsEmpty)
            {
                summary.MaxNumberOfStates = Math.Max(summary.MaxNumberOfStates, fringe.Count);

                var next = fringe.Next;

                if (problem.IsFinalState(next))
                {
                    summary.Results.Add(GetSolution(next, config));

                    if (config.MaxNumberOfResults != 0 && summary.Results.Count >= config.MaxNumberOfResults)
                    {
                        break;
                    }
                }
                else
                {
                    var children = problem.Expand(next);

                    if (children.Count == 0)
                    {
                        next.Parent = null;
                        continue;
                    }

                    if (config.PreserveHierarchy)
                    {
                        next.Children = children;

                        foreach (var child in next.Children)
                        {
                            child.Parent = next;
                        }
                    }

                    summary.TotalNumberOfStates += children.Count;
                    fringe.AddRange(children);
                }
            }

            return(summary);
        }
Example #4
0
        public static Node <State> TreeSearchMethod(IProblem <State> problem, IFringe <Node <State> > fringe, Enum method)
        {
            Func <Node <State>, int> calculatePriorityForBestFirstSearch = newState =>
                                                                           problem.CountOfConflicts(newState.StateOfNode);

            Func <Node <State>, int> calculatePriorityForAStar = newstate =>
                                                                 problem.CountDistancesToGoal(newstate.StateOfNode);


            fringe.SetCompareMethod(ComparePriority);

            var initNode = new Node <State>(problem.InitialState, null);

            initNode.Priority = CalculatePriorityMethod(method,
                                                        calculatePriorityForBestFirstSearch,
                                                        calculatePriorityForAStar, initNode);

            fringe.Add(initNode); ///tworzy root na stosie

            while (!fringe.IsEmpty)
            {
                var node = fringe.Pop();              //zdjecie ze stosu
                if (problem.IsGoal(node.StateOfNode)) //sprawdzenie zdjetego elementu ze stosu
                {
                    return(node);
                }

                problem.CountOfSteps++;

                foreach (var actualState in problem.Expand(node.StateOfNode))
                {
                    //foreach-a z możliwymy stanami, to tam sprawdzam czy dany stan z IListy
                    // już nie wystąpił, wywołując OnPathToRoot,
                    if (!node.OnPathToRoot(node.StateOfNode, actualState, problem.Compare))
                    //Wykonuje sie gdy nie ma znalezionego identycznego stanu
                    {
                        var nodeToAdd = new Node <State>(actualState, node);
                        nodeToAdd.Priority = CalculatePriorityMethod(method,
                                                                     calculatePriorityForBestFirstSearch,
                                                                     calculatePriorityForAStar, nodeToAdd);

                        fringe.Add(nodeToAdd);
                    }
                }
            }

            return(null);
        }
Example #5
0
        public IProblemAction[] Solve(IProblem <TState> problem)
        {
            StatesEvaluated  = 0UL;
            MaxCostEvaulated = 0;

            var openSet   = new OpenSet <double, StateCost <TState> >();
            var closedSet = new HashSet <TState>();
            var cameFrom  = new Dictionary <TState, (TState parent, IProblemAction move)>();

            var initialState = problem.GetInitialState();

            openSet.PushOrImprove(0, new StateCost <TState>(initialState, 0));
            cameFrom.Add(initialState, (default(TState), null));

            while (!openSet.IsEmpty)
            {
                var next  = openSet.PopMin();
                var state = next.State;
                var cost  = next.Cost;
                closedSet.Add(state);
                StatesEvaluated++;
                MaxCostEvaulated = Math.Max(MaxCostEvaulated, cost);
                if (problem.IsGoal(state))
                {
                    return(RebuildSolution(cameFrom, state));
                }
                foreach (var move in problem.Expand(state))
                {
                    var(successor, stepCost) = problem.ApplyAction(state, move);
                    if (closedSet.Contains(successor))
                    {
                        continue;
                    }
                    var wasImprovement =
                        openSet.PushOrImprove(
                            cost + stepCost + heuristic(successor),
                            new StateCost <TState>(successor, cost + stepCost)
                            );
                    if (wasImprovement)
                    {
                        cameFrom[successor] = (state, move);
                    }
                }
            }
            return(null);
        }
        public static Node <State> TreeSearchMetod(IProblem <State> problem, IFringe <Node <State> > fringe, Enum method)
        {
            Func <State, double> calculatePriorityForBestFirstSearch = newState =>
                                                                       problem.CalculateDistanceToDestinyCity(newState);
            //odleglosc w lini prostej

            Func <Node <State>, State, double> calculatePriorityForAStar = (parent, newState) =>
                                                                           problem.CalculatePriorityForAStar(parent.StateOfNode, newState);

            //Linia prosta + odleglosc krawedziowa, pozniej dodana jest
            //droga juz pokonana


            fringe.SetCompareMethod(ComparePriority);
            fringe.Add(new Node <State>(problem.InitialState, null, 1, double.MaxValue)); //tworzy root na stosie

            while (!fringe.IsEmpty)
            {
                var node = fringe.Pop();              //zdjecie ze stosu
                if (problem.IsGoal(node.StateOfNode)) //sprawdzenie zdjetego elementu ze stosu
                {
                    return(node);
                }

                foreach (var actualState in problem.Expand(node.StateOfNode))
                {
                    //foreach-a z możliwymy stanami, to tam sprawdzam czy dany stan z IListy
                    // już nie wystąpił, wywołując OnPathToRoot,
                    if (!node.OnPathToRoot(node.StateOfNode, actualState, problem.Compare))
                    //Wykonuje sie gdy nie ma znalezionego identycznego stanu
                    {
                        var nodeToAdd = new Node <State>(actualState, node, node.StepsForSolution++,
                                                         CalculatePriorityMethod(method, calculatePriorityForBestFirstSearch,
                                                                                 calculatePriorityForAStar, node, actualState));

                        nodeToAdd.TotalRoad = node.TotalRoad +
                                              problem.GetDistanceToCity(node.StateOfNode, nodeToAdd.StateOfNode);
                        fringe.Add(nodeToAdd);
                        CountOfSteps++;
                    }
                }
            }

            return(null);
        }
Example #7
0
 public static Node <State> TreeSearch <State>(IProblem <State> problem, IFringe <Node <State> > queue)
 {
     queue.Add(new Node <State>(problem.InitialState, null));
     while (!queue.Empty())
     {
         Node <State> node = queue.Remove();
         if (problem.IsGoal(node.State))
         {
             return(node);
         }
         IList <State> successors = problem.Expand(node.State);
         foreach (State st in successors)
         {
             queue.Add(new Node <State>(st, node));
         }
     }
     return(null);
 }
        public IProblemAction[] Solve(IProblem <TState> problem)
        {
            StatesEvaluated  = 0UL;
            MaxCostEvaulated = 0;

            var openSet   = new OpenSet <double, StateCost <TState> >();
            var closedSet = new HashSet <TState>();
            var cameFrom  = new Dictionary <TState, (TState parent, IProblemAction move)>();

            var initialState = problem.GetInitialState();

            openSet.PushOrImprove(0, new StateCost <TState>(initialState, 0));
            cameFrom.Add(initialState, (default(TState), null));

            while (!openSet.IsEmpty)
            {
                var stateCost = openSet.PopMin();
                var state     = stateCost.State;
                var cost      = stateCost.Cost;
                closedSet.Add(state);
                StatesEvaluated++;
                MaxCostEvaulated = Math.Max(MaxCostEvaulated, cost);
                if (problem.IsGoal(state))
                {
                    return(RebuildSolution(cameFrom, state));
                }
                foreach (var move in problem.Expand(state))
                {
                    var(successor, stepCost) = problem.ApplyAction(state, move);
                    if (closedSet.Contains(successor))
                    {
                        continue;
                    }
                    // why is this 1 and not step cost? because that's how we enforce
                    // the BFS property of exploring on level fully before starting the next
                    var wasImprovement = openSet.PushOrImprove(cost + 1, new StateCost <TState>(successor, cost + 1));
                    if (wasImprovement)
                    {
                        cameFrom[successor] = (state, move);
                    }
                }
            }
            return(null);
        }
        public static Node <State> TreeSearchWithQueue <State> (IProblem <State> problem, IFringe <Node <State> > fringe, bool enableAStarMethod = false)
        {
            if (enableAStarMethod)
            {
                fringe.GetCost = (Node <State> node) => { return(problem.EstimatedCostToGoal(node.state) + problem.GetCurrentCost(node.state, node.node.state, node.CurrentCost)); };
            }
            else
            {
                fringe.GetCost = (Node <State> node) => { return(problem.EstimatedCostToGoal(node.state)); };
            }

            fringe.Add(new Node <State>(problem.InitialState, null));

            int a = 1;

            while (!fringe.IsEmpty)
            {
                Node <State> node = fringe.Pop();

                if (problem.IsGoal(node.state))
                {
                    return(node);
                }

                foreach (State state in problem.Expand(node.state))
                {
                    if (!node.OnPathToRoot(state, problem.StateCompare))
                    {
                        fringe.Add(new Node <State>(state, node, problem.GetCurrentCost(state, node.state, node.CurrentCost)));
                        if (rownyRzad(a))
                        {
                            problem.Print(state);
                        }
                        a++;
                    }
                }
            }
            return(null);
        }
Example #10
0
        public Node <State> TreeSearchMethodMap <State>(IProblem <State> problem, IFringe <Node <State> > fringe) //w programie głownym jest przegladanie drogi
        {
            fringe.Add(new Node <State>(problem.InitialState, null, problem.Compare()));
            while (!fringe.IsEmpty)
            {
                Node <State> node = fringe.Pop();
                if (problem.IsGoal(node.StateOfNode))
                {
                    return(node);
                }

                foreach (State state in problem.Expand(node.StateOfNode))
                {
                    if (!node.OnPathToRoot(state))
                    {
                        node.currentDistance = problem.CheckDistance(node.StateOfNode);
                        fringe.Add(new Node <State>(state, node, problem.Compare()));
                    }
                }
            }

            return(null);
        }
Example #11
0
        private double Search(TState state, TState parent, double pathCost, Stack <IProblemAction> path, double bound)
        {
            var f = pathCost + heuristic(state);

            StatesEvaluated++;
            if (f > bound)
            {
                return(f);
            }
            if (problem.IsGoal(state))
            {
                return(FOUND);
            }
            var min     = double.MaxValue;
            var actions = problem.Expand(state);

            foreach (var action in actions)
            {
                var(successor, stepCost) = problem.ApplyAction(state, action);
                var successorPathCost = pathCost + stepCost;
                // TODO: so many assumptions here
                if (successor.Equals(parent))
                {
                    continue;
                }
                path.Push(action);
                var result = Search(successor, state, successorPathCost, path, bound);
                if (result == FOUND)
                {
                    return(FOUND);
                }
                min = Math.Min(min, result);
                path.Pop();
            }
            return(min);
        }