Beispiel #1
0
        public SearchResult <T> Search()
        {
            T        state = Problem.InitialState;
            Node <T> node  = new Node <T>(state);

            if (Problem.GoalTest(state))
            {
                return(new SearchResult <T>(node));
            }
            Frontier.Put(node);
            OpenList.Add(state);

            while (!Frontier.IsEmpty)
            {
                node  = Frontier.Take();
                state = node.State;
                ClosedList.Add(state);
                foreach (IAction <T> action in Problem.Actions(state))
                {
                    Node <T> childNode  = node.ChildNode(Problem, action);
                    T        childState = childNode.State;
                    if (!ClosedList.Contains(childState) && !OpenList.Contains(childState))
                    {
                        if (Problem.GoalTest(childState))
                        {
                            return(new SearchResult <T>(childNode));
                        }
                        Frontier.Put(childNode);
                        OpenList.Add(childState);
                    }
                }
            }
            return(new SearchResult <T>(null));
        }
        public bool FindTheShortesPath(Node Start, Node Target)
        {
            Node CurrentNode = Start;

            OpenList.Add(CurrentNode);

            for (; OpenList.Count > 0;)
            {
                CurrentNode = OpenList[0];

                if (CurrentNode.Equals(Target))
                {
                    VisitedNodes.Add(Target);

                    for (int Index = 0; Index < VisitedNodes.Count - 1; Index++)
                    {
                        ShortesPath.Add(InnerGraph.FindEdge(VisitedNodes[Index], VisitedNodes[Index + 1]));
                    }

                    return(true);
                }

                OpenList.Remove(CurrentNode);

                ClosedList.Add(CurrentNode);

                foreach (Node Inheritor in CurrentNode.Inheritors.Where(Node => Node != null && Node.Index != Node.Inheritors.Length - 1))
                {
                    if (!ClosedList.Contains(Inheritor))
                    {
                        if (!OpenList.Contains(Inheritor))
                        {
                            Inheritor[Inheritor.Index] = CurrentNode;

                            Inheritor.HeuristicPathWeight = CalculateHeuristic(Inheritor, Target);

                            Inheritor.GainedPathWeight = InnerGraph.FindEdge(CurrentNode, Inheritor).Weight;

                            Inheritor.TotalPathWeight = Inheritor.GainedPathWeight + Inheritor.HeuristicPathWeight;

                            OpenList.Add(Inheritor);

                            OpenList = OpenList.OrderBy(Node => Node.TotalPathWeight).ToList <Node>();
                        }
                    }
                }

                VisitedNodes.Add(CurrentNode);
            }

            return(true);
        }
Beispiel #3
0
    bool PushOpenList(int StandardPos, int OpenPos)
    {
        if (!ClosedList.Contains(OpenPos))
        {
            if (!OpenList.Contains(OpenPos))
            {
                OpenList.Add(OpenPos);

                ((Tile)Tiles[OpenPos]).Goal       = CalcuGoal(StandardPos, OpenPos);
                ((Tile)Tiles[OpenPos]).Heuristic  = CalcuHeuristic(OpenPos, EndPos);
                ((Tile)Tiles[OpenPos]).Fitness    = ((Tile)Tiles[OpenPos]).Goal + ((Tile)Tiles[OpenPos]).Heuristic;
                ((Tile)Tiles[OpenPos]).ParentTile = StandardPos;
                return(true);
            }
        }
        return(false);
    }
Beispiel #4
0
        public SearchResult <T> Search()
        {
            T state = Problem.InitialState;
            HeuristicNode <T> node = new HeuristicNode <T>(state, 1);

            if (Problem.GoalTest(state))
            {
                return(new SearchResult <T>(node));
            }
            PriorityQueue.Push(node);
            OpenList.Add(state);

            while (!PriorityQueue.IsEmpty)
            {
                node  = PriorityQueue.Pop();
                state = node.State;
                ClosedList.Add(state);
                foreach (IAction <T> action in Problem.Actions(state))
                {
                    HeuristicNode <T> childNode = node.ChildNode(Problem, action, Heuristic);
                    T childState = childNode.State;
                    if (ClosedList.Contains(childState) || OpenList.Contains(childState))
                    {
                        if (PriorityQueue.Contains(childNode) && childNode.HeuristicCost > node.HeuristicCost)
                        {
                            PriorityQueue.Push(childNode);
                            OpenList.Add(childState);
                        }
                    }

                    if (!ClosedList.Contains(childState) && !OpenList.Contains(childState))
                    {
                        if (Problem.GoalTest(childState))
                        {
                            return(new SearchResult <T>(childNode));
                        }
                        PriorityQueue.Push(childNode);
                        OpenList.Add(childState);
                    }
                }
            }
            return(new SearchResult <T>(null));
        }
Beispiel #5
0
        /// <summary>
        /// Searcher's abstract method overriding
        /// </summary>
        /// <param name="searchable"> to search on </param>
        /// <returns>the solution that BFS found</returns>
        public override Solution <T> Search(ISearchable <T> searchable)
        {
            lock (locker2)
            {
                AddToOpenList(searchable.GetInitialState());
            }
            HashSet <State <T> > closed = new HashSet <State <T> >();
            State <T>            goal   = searchable.GetGoalState();

            while (OpenListSize > 0)
            {
                State <T> state = PopOpenList();        // removes the best state
                closed.Add(state);                      // add it to the closed hash

                if (state.Equals(goal))
                {
                    return(BackTrace(goal));             // back traces through the parents
                }

                lock (locker)
                {
                    // returns a list of states with state as a parent
                    List <State <T> > succerssors = searchable.GetAllPossibleStates(state);
                    foreach (State <T> s in succerssors)
                    {
                        if (!closed.Contains(s) && !OpenList.Contains(s))
                        {
                            s.CameFrom = state;
                            AddToOpenList(s);
                        }
                        // the cost of the new way is better
                        else if (OpenList.Contains(s))
                        {
                            s.CameFrom = state;
                            UpdateStateIfPathBetter(s);
                        }
                    }
                }
            }
            return(null);
        }
Beispiel #6
0
        /// <summary>
        /// Searches the specified searchable.
        /// </summary>
        /// <param name="searchable">The searchable.</param>
        /// <returns></returns>
        public override Solution <T> Search(ISearchable <T> searchable)// Searcher's abstract method overriding
        {
            State <T> initialState = searchable.GetInitialState();

            OpenList.Enqueue(initialState);

            HashSet <State <T> > closed = new HashSet <State <T> >();

            while (OpenListSize > 0)
            {
                State <T> currentState = PopOpenList(); // inherited from Searcher, removes the best state
                closed.Add(currentState);
                if (currentState.Equals(searchable.GetGoalState()))
                {
                    return(Backtrace(searchable.GetGoalState(), GetNumberOfNodesEvaluated())); // private method, back traces through the parents
                }
                // calling the delegated method, returns a list of state
                List <State <T> > succerssors = searchable.GetAllPossibleStates(currentState);
                foreach (State <T> currentSuccessor in succerssors)
                {
                    if (!closed.Contains(currentSuccessor) && !OpenList.Contains(currentSuccessor))
                    {
                        currentSuccessor.CameFrom = currentState;
                        currentSuccessor.Cost     = currentState.Cost + searchable.GetStatesCost(currentState, currentSuccessor);
                        OpenList.Enqueue(currentSuccessor);
                    }
                    else
                    {
                        if (!closed.Contains(currentSuccessor))
                        {
                            AdjustPriorityForState(currentSuccessor, currentState,
                                                   currentState.Cost + searchable.GetStatesCost(currentState, currentSuccessor));
                        }
                    }
                }
            }
            return(null);
        }
Beispiel #7
0
        public static Path <SS, DS> AStarLookAhead(DS Start, SS ss,
                                                   int ComputationLimit, StateVisualizer <SS, DS> sv,
                                                   ref uint Expansions, ref uint Generations, bool Static,
                                                   Operator <SS, DS>[] Actions, Dictionary <string, Metric> HAdjusted,
                                                   Heuristic <SS, DS> Heuristic, Goal <SS, DS> Goal, Metric Weight, bool RTAStar)
        {
            if (ComputationLimit <= 0)
            {
                throw new ArgumentException("Computation Limit Invalid");
            }

            DS[] Neighbors           = Start.Expand(Actions, ss, Static).ToArray( );
            int  IterationExpansions = 1;

            Expansions++;

            Dictionary <DS, Metric>             GNeighs = new Dictionary <DS, Metric>( );
            Dictionary <DS, Metric>             HNeighs = new Dictionary <DS, Metric>( );
            Dictionary <DS, Operator <SS, DS> > OpNeighs
                = new Dictionary <DS, Operator <SS, DS> >( );

            LinkedList <DS> LookAheadNeighbors = new LinkedList <DS>( );

            foreach (DS Neighbor in Neighbors)
            {
                GNeighs.Add(Neighbor, Neighbor.Path( ).Cost);
                OpNeighs.Add(Neighbor, Neighbor.Path( ).Actions.First.Value);
                Neighbor.ResetPath( );
                Metric HNeigh = null;
                if (HAdjusted != null && HAdjusted.TryGetValue(Neighbor.ToString( ), out HNeigh))
                {
                    HNeighs.Add(Neighbor, HNeigh);
                }
                else
                {
                    LookAheadNeighbors.AddFirst(Neighbor);
                }
            }

            Dictionary <DS, PriorityQueue <Metric, DS> > OpenLists =
                new Dictionary <DS, PriorityQueue <Metric, DS> >( );

#if OpenGl
            HashSet <DS> OpenStates = new HashSet <DS>( );
#endif
            HashSet <DS> ClosedList = new HashSet <DS>( );
            ClosedList.Add(Start);
            foreach (DS Neighbor in LookAheadNeighbors)
            {
                var ol = new PriorityQueue <Metric, DS>( );
                ol.Enqueue(h(Neighbor, HAdjusted, Heuristic, Goal, Actions, ss), Neighbor);
                OpenLists.Add(Neighbor, ol);
#if OpenGl
                OpenStates.Add(Neighbor);
#endif
            }

            while (true)
            {
                LinkedList <DS> OpenNeighbors = new LinkedList <DS>(LookAheadNeighbors);
                foreach (DS Neighbor in LookAheadNeighbors)
                {
                    PriorityQueue <Metric, DS> OpenList;
                    OpenLists.TryGetValue(Neighbor, out OpenList);
#if OpenGl
                    if (sv != null)
                    {
                        sv.VisualizeAlg(ss, ss.InitialDynamicState, new OpenGLStateVisualizer.OpenGlVisulizationData( )
                        {
                            List      = OpenStates as HashSet <GenericGridWorldDynamicState>,
                            HAdjusted = HAdjusted,
                        });
                    }
#endif
                    if (OpenList.IsEmpty( ))
                    {
                        HNeighs.Add(Neighbor, new Metric(double.PositiveInfinity));
                        OpenNeighbors.Remove(Neighbor);
                        continue;
                    }
                    DS Cur = OpenList.Dequeue( );
#if OpenGl
                    OpenStates.Remove(Cur);
#endif

                    ClosedList.Add(Cur);
                    if (Goal.IsSatisfiedBy(ss, Cur))
                    {
                        HNeighs.Add(Neighbor, Cur.Path( ).Cost);
                        OpenNeighbors.Remove(Neighbor);
                        continue;
                    }
                    else
                    {
                        if (++IterationExpansions > ComputationLimit)
                        {
                            HNeighs.Add(Neighbor, Cur.Path( ).Cost
                                        + Weight * h(Cur, HAdjusted, Heuristic, Goal, Actions, ss));
                            OpenNeighbors.Remove(Neighbor);
                            break;
                        }
                        Expansions++;
                        foreach (DS e in Cur.Expand(Actions, ss, Static))
                        {
                            if (!ClosedList.Contains(e) && !OpenList.Contains(e))
                            {
                                OpenList.Enqueue(Weight * h(e, HAdjusted, Heuristic, Goal, Actions, ss)
                                                 + gComputer.G(ss, e, Goal), e);
#if OpenGl
                                OpenStates.Add(e);
#endif
                            }
                            Generations++;
                        }
                    }
                }
                LookAheadNeighbors = OpenNeighbors;
                if (IterationExpansions > ComputationLimit || LookAheadNeighbors.Count == 0)
                {
                    break;
                }
            }
            foreach (DS Neighbor in LookAheadNeighbors)
            {
                PriorityQueue <Metric, DS> OpenList;
                OpenLists.TryGetValue(Neighbor, out OpenList);
                if (OpenList.IsEmpty( ))
                {
                    HNeighs.Add(Neighbor, new Metric(double.PositiveInfinity));
                }
                else
                {
                    DS Cur = OpenList.Dequeue( );
                    HNeighs.Add(Neighbor, Cur.Path( ).Cost
                                + Weight * h(Cur, HAdjusted, Heuristic, Goal, Actions, ss));
                }
            }

            Metric            Best       = null;
            Operator <SS, DS> BestOp     = null;
            Metric            SecondBest = null;

            foreach (DS Neighbor in Neighbors)
            {
                Metric            HNeigh  = null;
                Metric            GNeigh  = null;
                Operator <SS, DS> OpNeigh = null;
                HNeighs.TryGetValue(Neighbor, out HNeigh);
                GNeighs.TryGetValue(Neighbor, out GNeigh);
                OpNeighs.TryGetValue(Neighbor, out OpNeigh);
                if (HNeigh != null)
                {
                    Metric FNeigh = GNeigh + HNeigh;
                    if (Best == null || Best > FNeigh)
                    {
                        BestOp = OpNeigh;
                        Best   = FNeigh;
                    }
                    else if (SecondBest == null || SecondBest > FNeigh)
                    {
                        SecondBest = FNeigh;
                    }
                }
            }
            if (RTAStar && SecondBest != null)
            {
                if (h(Start, HAdjusted, Heuristic, Goal, Actions, ss) < SecondBest)
                {
                    h(Start, SecondBest, HAdjusted);
                }
            }
            else if ((RTAStar && SecondBest == null) || Best == null)
            {
                h(Start, new Metric(double.PositiveInfinity), HAdjusted);
            }
            else if (Best != null)
            {
                if (h(Start, HAdjusted, Heuristic, Goal, Actions, ss) < Best)
                {
                    h(Start, Best, HAdjusted);
                }
            }
            if (BestOp == null)
            {
                return(null);
            }
            else
            {
                return(Operator <SS, DS> .MakePath(BestOp));
            }
        }