public LRTAStarAgent(OnlineSearchProblem problem, PerceptToStateFunction ptsFunction, HeuristicFunction hf) { setProblem(problem); setPerceptToStateFunction(ptsFunction); setHeuristicFunction(hf); }
public void StartFindPath(Vector3 startPos, Vector3 targetPos, bool canFly, int unitPID, Heuristic desiredHeuristic) { switch (desiredHeuristic) { case Heuristic.EuclideanDistance: { hf = new HeuristicFunction(GetEuclideanDistance); break; } case Heuristic.TileDistance: { hf = new HeuristicFunction(GetDistance); break; } case Heuristic.Dijkstra: { hf = new HeuristicFunction(Dijkstra); break; } default: { hf = new HeuristicFunction(GetDistance); break; } } StartCoroutine(FindPath(startPos, targetPos, canFly, unitPID, hf)); //pass the function to use to calculate hCost //can pass boolean to determine flying or normal pathfinding }
/** * Constructs a LRTA* agent with the specified search problem, percept to * state function, and heuristic function. * * @param problem * an online search problem for this agent to solve. * @param ptsFunction * a function which returns the problem state associated with a * given Percept. * @param hf * heuristic function <em>h(n)</em>, which estimates the cost of * the cheapest path from the state at node <em>n</em> to a goal * state. */ public LRTAStarAgent(OnlineSearchProblem problem, PerceptToStateFunction ptsFunction, HeuristicFunction hf) { setProblem(problem); setPerceptToStateFunction(ptsFunction); setHeuristicFunction(hf); }
public Problem(Object initialState, SuccessorFunction successorFunction, GoalTest goalTest, StepCostFunction stepCostFunction, HeuristicFunction heuristicFunction) : this(initialState, successorFunction, goalTest, stepCostFunction) { this.heuristicFunction = heuristicFunction; }
public void setUp() { aMap = new ExtendableMap(); aMap.addBidirectionalLink("A", "B", 4.0); aMap.addBidirectionalLink("B", "C", 4.0); aMap.addBidirectionalLink("C", "D", 4.0); aMap.addBidirectionalLink("D", "E", 4.0); aMap.addBidirectionalLink("E", "F", 4.0); hf = new HeuristicFunction() {
public Problem(Object initialState, SuccessorFunction successorFunction, GoalTest goalTest) { this.initialState = initialState; this.successorFunction = successorFunction; this.goalTest = goalTest; this.stepCostFunction = new DefaultStepCostFunction(); this.heuristicFunction = new DefaultHeuristicFunction(); }
public HashSet <IGraphNode> FindNodesInCostRange(IGraphNode startNode, int cost) { var oldHeuristic = heuristic; heuristic = (a, b) => 0; var result = Run(startNode, null, cost).second; heuristic = oldHeuristic; return(result); }
// function LRTA*-COST(s, a, s', H) returns a cost estimate private double LRTACost(object s, IAction action, object sPrime) { // if s' is undefined then return h(s) if (null == sPrime) { return(HeuristicFunction.H(s)); } // else return c(s, a, s') + H[s'] return(Problem.StepCostFunction.C(s, action, sPrime) + this.h[sPrime]); }
public Problem(Object initialState, SuccessorFunction successorFunction, GoalTest goalTest) { this.initialState = initialState; this.successorFunction = successorFunction; this.goalTest = goalTest; this.stepCostFunction = new DefaultStepCostFunction(); this.heuristicFunction = new DefaultHeuristicFunction(); }
public SolutionSearchResult Solve(Board initialBoard, Algorithm algorithm, HeuristicFunction heuristicFunction, CancellationToken cancellationToken) { var problem = new EightPuzzleProblem(initialBoard); var search = CreateSearch(initialBoard, algorithm, heuristicFunction); var stopwatch = new Stopwatch(); stopwatch.Start(); var result = search.Search(problem, cancellationToken).ToList(); stopwatch.Stop(); return(new SolutionSearchResult(result.Any(), result, stopwatch.Elapsed)); }
public void Initialize(Point[,] inputPoints, float _heuristicMultiplayer = 0.5f, HeuristicFunction _heuristicFunction = HeuristicFunction.ClassicDistance) { heuristicMultiplayer = _heuristicMultiplayer; heuristicFunction = _heuristicFunction; int xLength = inputPoints.GetLength(0); int yLength = inputPoints.GetLength(1); Cells = new Node[xLength, yLength]; openSet = new HashSet <Node>(); closedSet = new HashSet <Node>(); for (int x = 0; x < xLength; x++) { for (int y = 0; y < yLength; y++) { Node node = new Node(inputPoints[x, y].cell, inputPoints[x, y].pointObject); if (x > 0) { CreateNeighborhood(node, Cells[x - 1, y]); } if (y > 0) { CreateNeighborhood(node, Cells[x, y - 1]); } Cells[x, y] = node; } } void CreateNeighborhood(Node first, Node second) { first.Neighbours.Add(second); second.Neighbours.Add(first); } }
private static optional <Vector3> closest_heuristic(HeuristicFunction distance_heuristic, Vector3 target) { List <Arc> arc_list = ArcUtility.get_all_arcs(); if (arc_list.Count > 0) { Vector3 closest_point = arc_list[0].begin(); float closest_distance_squared = Mathf.Infinity; foreach (Arc arc in arc_list) { Vector3 other_point = distance_heuristic(arc, target); float distance_squared = (other_point - target).sqrMagnitude; if (distance_squared < closest_distance_squared) { closest_distance_squared = distance_squared; closest_point = other_point; } } return(closest_point); } return(new optional <Vector3>()); }
public GreedyBestFirstStrategy(HeuristicFunction h) { this.h = h; }
public AStarEvaluationFunction(HeuristicFunction hf) { this.hf = hf; }
public AStarEvaluationFunction(HeuristicFunction hf) { this.hf = hf; }
public int CalculateHeuristic(GridSearchNode node) { return(HeuristicFunction.Calc_H(this, node)); }
public AStarSearch(QueueSearch search, HeuristicFunction hf) : base(search, new AStarEvaluationFunction(hf)) { }
public SimulatedAnnealingSearch(HeuristicFunction hf) { this.hf = hf; this.scheduler = new Scheduler(); }
public GreedyBestFirstEvaluationFunction(HeuristicFunction hf) { this.hf = hf; }
public void setHeuristicFunction(HeuristicFunction hf) { this.hf = hf; }
/// <summary> /// Tile-level (coarse) A* pathfinding. /// </summary> /// <param name="start"> Start Coords </param> /// <param name="end"> Target tile Coords </param> /// <param name="h"> Heuristic function </param> /// <returns> Route to goal, as a list of Directions </returns> public List<Direction> PathfinderAStarCoarse(Coords start, Coords end, HeuristicFunction h) { return this.PathfinderAStarCoarse(start, end, end, h); }
public IDA(State root, HeuristicFunction heuristic) : base(root) { this.heuristic = heuristic; }
public AStarGraphSearch(HeuristicFunction <TState> heuristic) { _heuristic = heuristic; }
public SimulatedAnnealingSearch(HeuristicFunction hf, Scheduler scheduler) { this.hf = hf; this.scheduler = scheduler; }
public SimulatedAnnealingSearch(HeuristicFunction hf) { this.hf = hf; this.scheduler = new Scheduler(); }
public static IEnumerable <GraphNode <TK, TV> > AStar <TK, TV>( this IReadableGraph <TK, TV> graph, TK from, TK to, HeuristicFunction <TK, TV> heuristicFunction ) where TK : IEquatable <TK> { var fromNode = graph[from]; var toNode = graph[to]; var closedSet = new HashSet <GraphNode <TK, TV> >(); var openSet = new HashSet <GraphNode <TK, TV> > { fromNode }; var cameFrom = new Dictionary <GraphNode <TK, TV>, GraphNode <TK, TV> >(); var gScore = new Dictionary <GraphNode <TK, TV>, double>(); var fScore = new Dictionary <GraphNode <TK, TV>, double>(); foreach (var node in graph.Nodes) { cameFrom[node] = null; gScore[node] = PositiveInfinity; fScore[node] = PositiveInfinity; } gScore[fromNode] = 0; fScore[fromNode] = heuristicFunction(graph, fromNode, toNode); while (openSet.Count > 0) { var current = openSet.First(x => x.Equals(fScore.MinBy(kv => kv.Value).Key)); if (current.Equals(toNode)) { return(ReconstructPath(cameFrom, current)); } openSet.Remove(current); closedSet.Add(current); foreach (var connection in graph.ConnectionsOf[current]) { if (closedSet.Contains(connection.Key)) { continue; } var tentativeGScore = gScore[current] + connection.Value; if (!openSet.Contains(connection.Key)) { openSet.Add(connection.Key); } else if (tentativeGScore >= gScore[connection.Key]) { continue; } cameFrom[connection.Key] = current; gScore[connection.Key] = tentativeGScore; fScore[connection.Key] = gScore[connection.Key] + heuristicFunction(graph, connection.Key, toNode); } } return(new GraphNode <TK, TV> [0]); }
public static Edge[] Solve(Graph g, Node start, Node goal, HeuristicFunction heuristic) { // setup sets (1) visited = new List <Node>(); unvisited = new List <Node> (g.getNodes()); // set all node tentative distance (2) status = new Dictionary <Node, NodeExtension> (); foreach (Node n in unvisited) { NodeExtension ne = new NodeExtension(); ne.distance = (n == start ? 0f : float.MaxValue); // infinite ne.estimate = (n == start ? heuristic(start, goal) : float.MaxValue); status [n] = ne; } // iterate until goal is reached with an optimal path (6) while (!CheckSearchComplete(goal, unvisited)) { // select net current node (3) Node current = GetNextNode(); if (status [current].distance == float.MaxValue) { break; // graph is partitioned } // assign weight and predecessor to all neighbors (4) foreach (Edge e in g.getConnections(current)) { if (status[current].distance + e.weight < status[e.to].distance) { NodeExtension ne = new NodeExtension(); ne.distance = status[current].distance + e.weight; ne.estimate = ne.distance + heuristic(start, e.to); ne.predecessor = e; status[e.to] = ne; // unlike Dijkstra's, we can now discover better paths if (visited.Contains(e.to)) { unvisited.Add(e.to); visited.Remove(e.to); } } } // mark current node as visited (5) visited.Add(current); unvisited.Remove(current); } if (status [goal].distance == float.MaxValue) { return(new Edge[0]); // goal is unreachable } // walk back and build the shortest path (7) List <Edge> result = new List <Edge> (); Node walker = goal; while (walker != start) { result.Add(status [walker].predecessor); walker = status [walker].predecessor.from; } result.Reverse(); return(result.ToArray()); }
public AStarSearch(QueueSearch search, HeuristicFunction hf) : base(search, new AStarEvaluationFunction(hf)) { }
public SimulatedAnnealingSearch(HeuristicFunction hf, Scheduler scheduler) { this.hf = hf; this.scheduler = scheduler; }
/// <summary> /// Sokoban map solver /// </summary> /// <param name="map">Map to analize</param> /// <param name="show">Print the intermediate states in the solution found</param> /// <param name="strategy">Search method to use</param> /// <param name="heuristic">Heuristic to use in informed search methods. Can be 1, 2 or 3</param> /// <param name="depth">Initial depth for IDDFS</param> static void Main(FileInfo map, bool show, Algorithms strategy, int heuristic = 1, int depth = 30) { var game = SokobanFactory.FromFile(map.FullName); HeuristicFunction heuristicFunction = heuristic switch { 1 => SokobanHeuristics.Heuristic1, 2 => SokobanHeuristics.Heuristic2, 3 => SokobanHeuristics.Heuristic3, _ => throw new ArgumentOutOfRangeException(nameof(heuristic)) }; SearchTree search = strategy switch { Algorithms.AStar => new AStar(game, heuristicFunction), Algorithms.BFS => new BFS(game), Algorithms.DFS => new DFS(game), Algorithms.GGS => new GGS(game, heuristicFunction), Algorithms.IDAStar => new IDA(game, heuristicFunction), Algorithms.IDDFS => new IDDFS(depth, game), _ => throw new ArgumentOutOfRangeException(nameof(strategy)) }; Console.WriteLine($"Strategy: {strategy}"); if (strategy >= Algorithms.GGS && strategy <= Algorithms.AStar) { Console.WriteLine($"Heuristic: {heuristic}"); } Console.WriteLine("Solving"); var sw = new Stopwatch(); sw.Start(); var solution = search.GetSolution(out int expanded, out int frontier); sw.Stop(); if (solution == null) { Console.WriteLine("No solution"); return; } List <SokobanState> states = new List <SokobanState>(); List <SokobanActions> actions = new List <SokobanActions>(); while (solution.Parent != null) { actions.Add((SokobanActions)solution.Action); states.Add((SokobanState)solution.State); solution = solution.Parent; } actions.Reverse(); states.Reverse(); Console.WriteLine($"Solved in {sw.ElapsedMilliseconds}ms"); Console.WriteLine($"Moves: {actions.Count}"); Console.WriteLine($"Nodes expanded: {expanded}"); Console.WriteLine($"Nodes in frontier: {frontier}"); Console.WriteLine("Solution:"); foreach (var action in actions) { Console.Write(action.ToString().PadRight(8)); } Console.Write('\n'); if (show) { Console.WriteLine("Steps:"); for (int i = 0; i < states.Count; i++) { Console.WriteLine($"{i}."); Console.Write(states[i]); Console.WriteLine(); } } } } }
/** * Sets the heuristic function of this agent. * * @param hf * heuristic function <em>h(n)</em>, which estimates the cost of * the cheapest path from the state at node <em>n</em> to a goal * state. */ public void setHeuristicFunction(HeuristicFunction hf) { this.hf = hf; }
public async Task <SolutionSearchResult> SolveAsync(Board initialBoard, Algorithm algorithm, HeuristicFunction heuristicFunction, CancellationToken cancellationToken) { return(await Task.Run(() => { return Solve(initialBoard, algorithm, heuristicFunction, cancellationToken); }, cancellationToken)); }
public GreedyBestFirstSearch(QueueSearch search, HeuristicFunction hf) : base(search, new GreedyBestFirstEvaluationFunction(hf)) { }
/// <summary> /// Tile-level (coarse) A* pathfinding. /// </summary> /// <param name="start"> Start Coords </param> /// <param name="endTopLeft"> Goal-box TopLeft Coords </param> /// <param name="endBottomRight"> Goal-box BottomRight Coords </param> /// <param name="h"> Heuristic function </param> /// <returns> Route to goal, as a list of Directions </returns> public List<Direction> PathfinderAStarCoarse(Coords start, Coords endTopLeft, Coords endBottomRight, HeuristicFunction h) { return this._PathfinderAStar(new Coords(CoordsType.General, start), new Coords(CoordsType.General, endTopLeft), new Coords(CoordsType.General, endBottomRight), this._passabilityMap, delegate(Coords c) { return h(c, StaticMathFunctions.CoordsAverage(endTopLeft, endBottomRight)); }); }
public aima.core.search.framework.Search GetSearch(Object owner, IContextLookup globalVars, HeuristicFunction objHeuristicFunction) { aima.core.search.framework.Search toReturn; QueueSearch objQueueSearch; switch (QueueSearchType) { case QueueSearchType.TreeSearch: objQueueSearch = new TreeSearch(); break; default: objQueueSearch = new GraphSearch(); break; } switch (AlgorithmType) { case SearchAlgorithmType.KnownInformed: switch (KnownInformedAlgorithm) { case KnownInformedSearch.GreedyBestFirst: toReturn = new GreedyBestFirstSearch(objQueueSearch, objHeuristicFunction); break; case KnownInformedSearch.RecursiveGreedyBestFirst: toReturn = new RecursiveBestFirstSearch(new GreedyBestFirstEvaluationFunction(objHeuristicFunction)); break; case KnownInformedSearch.RecursiveAStar: toReturn = new RecursiveBestFirstSearch(new AStarEvaluationFunction(objHeuristicFunction)); break; case KnownInformedSearch.HillClimbing: toReturn = new HillClimbingSearch(objHeuristicFunction); break; case KnownInformedSearch.SimulatedAnnealing: toReturn = new SimulatedAnnealingSearch(objHeuristicFunction); break; default: toReturn = new AStarSearch(objQueueSearch, objHeuristicFunction); break; } break; case SearchAlgorithmType.KnownUninformed: switch (KnownUninformedAlgorithm) { case KnownUninformedSearch.DepthFirst: toReturn = new DepthFirstSearch(objQueueSearch); break; case KnownUninformedSearch.DepthLimited: toReturn = new DepthLimitedSearch(DepthLimit); break; case KnownUninformedSearch.IterativeDeepening: toReturn = new IterativeDeepeningSearch(); break; case KnownUninformedSearch.UniformCost: toReturn = new UniformCostSearch(objQueueSearch); break; case KnownUninformedSearch.Bidirectional: toReturn = new BidirectionalSearch(); break; default: toReturn = new BreadthFirstSearch(objQueueSearch); break; } break; default: toReturn = CustomSearchAlgorithm.EvaluateTyped(owner, globalVars); break; } return(toReturn); }
public HillClimbingSearch(HeuristicFunction hf) { this.hf = hf; }
public GreedyBestFirstSearch(QueueSearch search, HeuristicFunction hf) : base(search, new GreedyBestFirstEvaluationFunction(hf)) { }
public GreedyBestFirstEvaluationFunction(HeuristicFunction hf) { this.hf = hf; }
private ISearch <EightPuzzleState> CreateSearch(Board initialBoard, Algorithm algorithm, HeuristicFunction heuristicFunction) { if (algorithm == Algorithm.AStar || algorithm == Algorithm.RecursiveBestFirstSearch) { IHeuristicFunction <EightPuzzleState> h; var goalBoard = Board.CreateGoalBoard(initialBoard.RowCount, initialBoard.ColumnCount); switch (heuristicFunction) { case HeuristicFunction.NoHeuristic: h = new NoHeuristicFunction <EightPuzzleState>(); break; case HeuristicFunction.ManhattanDistance: h = new ManhattanHeuristicFunction(goalBoard); break; case HeuristicFunction.NilssonHeuristic: h = new NilssonHeuristicFunction(goalBoard); break; case HeuristicFunction.RowColumnHeuristic: h = new RowColumnHeuristicFunction(goalBoard); break; default: throw new ArgumentOutOfRangeException(nameof(heuristicFunction), heuristicFunction, null); } switch (algorithm) { case Algorithm.AStar: return(new AStarSearch <EightPuzzleState>(h)); case Algorithm.RecursiveBestFirstSearch: return(new RecursiveBestFirstSearch <EightPuzzleState>(h)); default: throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm, null); } } switch (algorithm) { case Algorithm.IterativeDeepeningSearch: return(new IterativeDeepeningSearch <EightPuzzleState>()); default: throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm, null); } }
public AStar(State root, HeuristicFunction heuristic) : base(root) { Heuristic = heuristic; }
//for Ai public Node[] AIFindPath(Vector3 startPos, Vector3 targetPos, bool canFly, int unitPlayerID) { bool pathSuccess = false; HeuristicFunction heuristicFunction = new HeuristicFunction(GetDistance); Node startNode = gridRef.NodeFromWorldPoint(startPos); Node targetNode = gridRef.NodeFromWorldPoint(targetPos); Unit currentUnit = startNode.GetUnit(); if (startNode.canWalkHere && targetNode.canWalkHere) { Heap <Node> openSet = new Heap <Node>(gridRef.MaxSize); HashSet <Node> closedSet = new HashSet <Node>(); openSet.Add(startNode); while (openSet.Count > 0) { Node currentNode = openSet.RemoveFirst(); closedSet.Add(currentNode); if (currentNode == targetNode) { pathSuccess = true; break; } foreach (Node neighbour in gridRef.GetNeighbours(currentNode)) { bool checkHostile = false; if (neighbour.GetUnit() != null) { if (neighbour.GetUnit().GetUnitPlayerID() != unitPlayerID) { checkHostile = true; } } if ((!canFly && !neighbour.canWalkHere) || closedSet.Contains(neighbour) || checkHostile) { continue; //Skips unwalkable nodes when unit cannot fly, or if any node in closed set or if the unit in the node is hostile //considers unwalkable nodes if unit can fly, and ignores any node if in closed set } int newMovementCostToNeighbour = currentNode.gCost + GetDistance(currentNode, neighbour); if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains(neighbour)) { neighbour.gCost = newMovementCostToNeighbour; neighbour.hCost = heuristicFunction(neighbour, targetNode); neighbour.parent = currentNode; if (!openSet.Contains(neighbour)) { openSet.Add(neighbour); } } } } } if (pathSuccess) { Node[] waypoints = RetracePath(startNode, targetNode); currentUnit.SetMovementSpeedLeft(currentUnit.GetMovementSpeedLeft() - (waypoints.Length - 1)); return(waypoints); } return(new[] { startNode }); }
/// <summary> /// Tile-level (coarse) A* pathfinding. /// </summary> /// <param name="start"> Start Coords </param> /// <param name="endTopLeft"> Goal-box TopLeft Coords </param> /// <param name="endBottomRight"> Goal-box BottomRight Coords </param> /// <param name="h"> Heuristic function </param> /// <returns> Route to goal, as a list of Directions </returns> public List<Direction> PathfinderAStarCoarse(Coords start, Coords endTopLeft, Coords endBottomRight, HeuristicFunction h) { return this._PathfinderAStar(new Coords(CoordsType.General, start), new Coords(CoordsType.General, endTopLeft), new Coords(CoordsType.General, endBottomRight), this._passabilityMap, delegate(Coords c) { return h(c, StaticMathFunctions.CoordsAverage(endTopLeft, endBottomRight)); }); }
public AStar(HeuristicFunction heuristic, EdgeCostFunction edgeCost, NeighbourGetter neighbourGetter) { this.heuristic = heuristic; this.edgeCost = edgeCost; this.neighbourGetter = neighbourGetter; }
/// <summary> /// Tile-level (coarse) A* pathfinding. /// </summary> /// <param name="start"> Start Coords </param> /// <param name="end"> Target tile Coords </param> /// <param name="h"> Heuristic function </param> /// <returns> Route to goal, as a list of Directions </returns> public List<Direction> PathfinderAStarCoarse(Coords start, Coords end, HeuristicFunction h) { return this.PathfinderAStarCoarse(start, end, end, h); }