public AStar(Game game, Grid grid, IHeuristic heuristic) : base(game) { this.grid = grid; Heuristic = heuristic; IsActive = false; }
public override bool Find(IMap grid, IHeuristic h) { Clear(); var sqrt2 = Sqrt(2); var cutOff = H(h, grid.StartNode, grid.EndNode); Dictionary <int, Node> route; Tuple <Node, double> t; OnStart(BuildArgs(0, grid)); var k = 0; for (k = 0; true; k++) { route = new Dictionary <int, Node>(); t = Search(h, grid, grid.StartNode, 0, cutOff, route, 0, grid.EndNode, k); if (t == null || t.Item2 == double.PositiveInfinity) { OnEnd(BuildArgs(k, grid, false)); return(false); } if (t.Item1 != null) { var lis = route.OrderByDescending(e => e.Key).Select(e => e.Value).ToList(); for (int i = 1; i < lis.Count; i++) { lis[i - 1].ParentNode = lis[i]; } OnEnd(BuildArgs(k, grid, true)); return(true); } cutOff = t.Item2; } // OnEnd(BuildArgs(0, false)); // return false; }
/// <summary> /// Gets the full search results of the planning search. /// </summary> /// <param name="includingSolutionPlan">Include the solution plan?</param> /// <returns>Search results.</returns> public SearchResults GetSearchResults(bool includingSolutionPlan = true) { IProblem problem = Problem as IProblem; IHeuristic heuristic = Heuristic as IHeuristic; SearchResults results = new SearchResults { ResultStatus = ResultStatus, DomainName = (problem != null) ? problem.GetDomainName() : "", ProblemName = Problem.GetProblemName(), Algorithm = GetName(), Heuristic = Heuristic.GetName(), SearchTime = GetSearchTime(), ClosedNodes = GetClosedNodesCount(), OpenNodes = GetOpenNodesCount(), MaxGValue = MaxGValue, BestHeuristicValue = heuristic?.GetStatistics().BestHeuristicValue ?? double.MaxValue, AverageHeuristicValue = heuristic?.GetStatistics().AverageHeuristicValue ?? double.MaxValue, SolutionPlan = null, SolutionCost = GetSolutionCost() }; if (includingSolutionPlan) { results.SolutionPlan = GetSolutionPlan(); } return(results); }
public Solver(Graph g, IHeuristic heuristic, IPriorityQueue <PriorityQueueItem> queue) { _heuristic = heuristic; graph = g; queue.Clear(); priorityQueue = queue; }
public Search_AStar(SparseGraph <TNode, TEdge> Graph, IHeuristic <SparseGraph <TNode, TEdge> > Heuristic, int Source, int Target) { this.Graph = Graph; this.bFound = false; this.Heuristic = Heuristic; SourceNodeIndex = Source; TargetNodeIndex = Target; int ActiveNodeCount = Graph.ActiveNodeCount(); int NodeCount = Graph.NodeCount(); ShortestPathTree = new List <TEdge>(NodeCount); SearchFrontier = new List <TEdge>(NodeCount); CostToThisNode = new List <double>(NodeCount); GCosts = new List <double>(NodeCount); FCosts = new List <double>(NodeCount); // not sure i need to initialize these...nt); for (int i = 0; i < NodeCount; i++) { ShortestPathTree.Insert(i, null); SearchFrontier.Insert(i, null); CostToThisNode.Insert(i, 0); FCosts.Insert(i, 0); GCosts.Insert(i, 0); } TimeSlicedQ = new IndexedPriorityQueueLow <double>(FCosts, Graph.NodeCount()); TimeSlicedQ.Insert(SourceNodeIndex); }
public NodeArrayAStarPathFinding(WorldModel WM, IHeuristic heuristic) : base(WM,null,null,heuristic) { this.NodeRecordArray = new NodeRecordArray(WM); this.lstars = new List<NodeRecord>(); this.Open = this.NodeRecordArray; this.Closed = this.NodeRecordArray; }
public MapNpc(IItemProvider?itemProvider, ILogger logger, IHeuristic distanceCalculator) { _itemProvider = itemProvider; _logger = logger; Requests = new Subject <RequestData>(); _distanceCalculator = distanceCalculator; }
public NodeArrayAStarPathFinding(WorldModel WM, IHeuristic heuristic) : base(WM, null, null, heuristic) { this.NodeRecordArray = new NodeRecordArray(WM); this.lstars = new List <NodeRecord>(); this.Open = this.NodeRecordArray; this.Closed = this.NodeRecordArray; }
// Permet de selectionner une heuristique pour un solver private void HeuristicButton_Click(object sender, EventArgs e) { // Enlève le focus du bouton précedent if (_selectedHeuristic.GetType() == typeof(Manhattan)) { ButtonUnsetFocus(heuristicThreeButton); } else if (_selectedHeuristic.GetType() == typeof(PLC)) { ButtonUnsetFocus(heuristicOneButton); } else { ButtonUnsetFocus(heuristicTwoButton); } // Ajoute l'heuristique choisie comme courante et met le bouton en Focus Button button = (Button)sender; if (button == heuristicOneButton) { _selectedHeuristic = new PLC(); } else if (button == heuristicTwoButton) { _selectedHeuristic = new PLCC(); } else { _selectedHeuristic = new Manhattan(); } ButtonSetFocus(button); }
public void CopyWithNewReferences_CreatesDeepCopy() { var puzzle = new PuzzleWithPossibleValues(new int?[][] { new int?[] { 1, null /* 4 */, null /* 3 */, 2 }, new int?[] { null /* 2 */, null /* 3 */, null /* 1 */, 4 }, new int?[] { null /* 4 */, null /* 1 */, null /* 2 */, 3 }, new int?[] { 3, 2, null /* 4 */, 1 } }); var ruleKeeper = new StandardRuleKeeper(); Assert.True(ruleKeeper.TryInit(puzzle)); var heuristic = new UniqueInColumnHeuristic( (IMissingColumnValuesTracker)ruleKeeper.GetRules()[0]); Assert.True(heuristic.TryInitFor(puzzle)); var puzzleCopy = new PuzzleWithPossibleValues(puzzle); var ruleKeeperCopy = (StandardRuleKeeper)ruleKeeper.CopyWithNewReferences( puzzleCopy); IHeuristic heuristicCopy = heuristic.CopyWithNewReferences( puzzleCopy, ruleKeeperCopy.GetRules()); var coord = new Coordinate(0, 1); BitVector originalPossibleValues = puzzle.GetPossibleValues(coord); Assert.Equal(originalPossibleValues, puzzleCopy.GetPossibleValues(coord)); heuristicCopy.UpdateAll(); Assert.Equal(originalPossibleValues, puzzle.GetPossibleValues(coord)); Assert.NotEqual(originalPossibleValues, puzzleCopy.GetPossibleValues(coord)); }
public AStarModified(IGraph graph, IEndPoints endPoints, IStepRule stepRule, IHeuristic function) : base(graph, endPoints, stepRule, function) { PercentOfFarthestVerticesToDelete = CalculatePercentOfFarthestVerticesToDelete; deletedVertices = new Queue <IVertex>(); }
public SearchResult GreedyBestFirstSearch(IHeuristic heuristic) { NodeComparator comparator = (node1, node2) => node1.HHat.CompareTo(node2.HHat); return(GenericSearch(_initialState, _goalState, "Greedy Best First Search", comparator, (state1, state2) => 1, heuristic)); }
public Node(Point point, Point endLocation, IHeuristic heuristic, int max) { Location = point; _heuristic = heuristic; H = _heuristic.GetTraversalCost(Location, endLocation); G = max; }
public SearchResult AStarSearch(IHeuristic heuristic) { NodeComparator comparator = (node1, node2) => node1.FHat.CompareTo(node2.FHat); return(GenericSearch(_initialState, _goalState, "AStar", comparator, (state1, state2) => 1, heuristic)); }
public PLCC() { // On utilise nos heuristiques P, LC et C prédéfini _h1 = new Manhattan(); _h2 = new LinearConflict(); _h3 = new CornerConflict(); }
public global::PathfindingAlgorithms.Algorithms.Astar.Astar ConstructorTest(IHeuristic heuristic, IAdjacement adjacement) { global::PathfindingAlgorithms.Algorithms.Astar.Astar target = new global::PathfindingAlgorithms.Algorithms.Astar.Astar (heuristic, adjacement); return target; // TODO: добавление проверочных утверждений в метод AstarTest.ConstructorTest(IHeuristic, IAdjacement) }
public AStarPathfinding(NavMeshPathGraph graph, IOpenSet open, IClosedSet closed, IHeuristic heuristic) { this.NavMeshGraph = graph; this.Open = open; this.Closed = closed; this.InProgress = false; this.Heuristic = heuristic; }
/// <summary> /// Gets the minimum-weight path to a goal using the A* algorithm. /// </summary> /// <typeparam name="TNode">The type of a node.</typeparam> /// <typeparam name="TKey">The type of a node key.</typeparam> /// <param name="sources">The set of nodes from which to start the search, weighted by their initial cost.</param> /// <param name="descriptor">The object describing how to navigate the weighted graph.</param> /// <param name="goal">The goal predicate.</param> /// <param name="heuristic">The heuristic function.</param> /// <returns>The minimum-weight path, or null if none exists.</returns> public static IWeighted <IEnumerable <TNode> > AStar <TNode, TKey>( this IEnumerable <IWeighted <TNode> > sources, IWeightedGraphDescriptor <TNode, TKey> descriptor, Func <TNode, bool> goal, IHeuristic <TNode> heuristic) { return(AStar(sources, descriptor.Key, descriptor.Next, goal, heuristic)); }
public AStarPathfinding(WorldModel WM, IOpenSet open, IClosedSet closed, IHeuristic heuristic) : base(WM) { this.Open = open; this.Closed = closed; this.NodesPerSearch = uint.MaxValue; //by default we process all nodes in a single request this.InProgress = false; this.Heuristic = heuristic; }
public NodeArrayAStarPathFinding(NavMeshPathGraph graph, IHeuristic heuristic) : base(graph, null, null, heuristic) { //do not change this var nodes = this.GetNodesHack(graph); this.NodeRecordArray = new NodeRecordArray(nodes); this.Open = this.NodeRecordArray; this.Closed = this.NodeRecordArray; }
public AStarPathfinding(NavMeshPathGraph graph, IOpenSet open, IClosedSet closed, IHeuristic heuristic) { this.NavMeshGraph = graph; this.Open = open; this.Closed = closed; this.NodesPerFrame = uint.MaxValue; //by default we process all nodes in a single request this.InProgress = false; this.Heuristic = heuristic; }
/// <summary> /// For the heuristic function h(n), returns the relaxed heuristic function h'(n) = (1 + amount) * h(n). /// </summary> /// <typeparam name="TNode">The type of a node.</typeparam> /// <param name="heuristic">The heuristic function.</param> /// <param name="amount">The amount to relax by.</param> /// <param name="maintainConsistency"> /// Should the consistency of the heuristic be maintained? /// Defaults to true since this is usually the desired behavior, even though theoretically this is not always the case. /// </param> /// <returns>The relaxed heuristic function.</returns> public static IHeuristic <TNode> Relax <TNode>(this IHeuristic <TNode> heuristic, double amount, bool maintainConsistency) { if (amount < 0) { throw new ArgumentOutOfRangeException("amount", "Must be nonnegative."); } amount += 1; return(Create <TNode>(x => amount * heuristic.Evaluate(x), maintainConsistency && heuristic.IsConsistent)); }
//maybe hold a list with all final operations- usefull for get next operation. public Strips(Board board) { this.board = board; var goalState = FindGoalStatePredicates(); stack.Push(goalState); heuristics = new Heuristic(); }
public GraphGroup(int size, IHeuristic heuristic) { Size = size; AllowedValues = Enumerable.Repeat(true, size).ToArray(); mutable = Enumerable.Repeat(true, size).ToArray(); Nodes = new List <GraphNode>(); Filled = Nodes.Count(a => a.Starting); ranker = heuristic; }
public AStarPathfinding(NavMeshPathGraph graph, IOpenSet open, IClosedSet closed, IHeuristic heuristic) { this.NavMeshGraph = graph; this.Open = open; this.Closed = closed; this.NodesPerSearch = uint.MaxValue; //by default we process all nodes in a single request this.InProgress = false; this.Heuristic = heuristic; }
static TestDomainData[] GenTest(IHeuristic heuristic, int numTasks = 100, int numSteps = Global.MAXSTEPS, bool writeCSV = true, bool computeCost = true) { TestDomainData[] data = new TestDomainData[numTasks]; string csvWritePath = string.Format(Global.ROOTPATH, Global.TESTTASKFN); CSVWriter csv = new CSVWriter(csvWritePath, ','); for (int i = 0; i < numTasks; i++) { DomainContainer domainContainer = new DomainContainer(heuristic, numSteps); ISearchDomain domain = domainContainer.Domain; IState initState = domain.Initial(); string initStateStr = string.Join(" ", initState.Arr); int cost = 0; long generated = 0; if (computeCost == true) { if (Global.DOMAINTYPE == typeof(BlocksWorld.BlocksWorld) && heuristic == null) { cost = PostBlocksWorld(initState, domain.Goal()); } else { IDAStar <ISearchDomain> planner = new IDAStar <ISearchDomain>(domain); List <IState> plan = planner.Search(initState); cost = (plan.Count - 1); generated = planner.Generated; } } data[i] = new TestDomainData(initState.Arr, cost, generated); csv.Add(initStateStr); csv.Add(cost.ToString()); csv.Add(generated.ToString()); csv.EndLine(); } if (writeCSV == true) { csv.Write(); } return(data); }
public MapNpc(IItemGenerationService?itemProvider, ILogger logger, IHeuristic distanceCalculator) { _itemProvider = itemProvider; _logger = logger; Requests = new Dictionary <Type, Subject <RequestData> >() { [typeof(INrunEventHandler)] = new Subject <RequestData>() }; _distanceCalculator = distanceCalculator; }
public SecureNodeArrayAStarPathFinding(AutonomousCharacter character, NavMeshPathGraph graph, IHeuristic heuristic) : base(graph, null, null, heuristic) { //do not change this var nodes = this.GetNodesHack(graph); this.NodeRecordArray = new NodeRecordArray(nodes); this.Open = this.NodeRecordArray; this.Closed = this.NodeRecordArray; this.character = character; }
public Solver(uint[,] board, IHeuristic heuristic, Func <int, uint[, ]> generateTarget, bool useGreedy = false) { Heuristic = heuristic; GenerateTarget = generateTarget; UseGreedy = useGreedy; Solution = new List <Board>(); StopWatch = new Stopwatch(); Solve(board); }
public Astar(IHeuristic heuristic, IAdjacement adjacement) { if (heuristic == null) throw new ArgumentNullException("heuristic"); if (adjacement == null) throw new ArgumentNullException("adjacement"); this.heuristic = heuristic; this.adjacement = adjacement; }
public override bool Find(IMap grid, IHeuristic heuristic) { Clear(); var sqrt2 = Sqrt(2); grid.StartNode.Cost = 0; grid.EndNode.Cost = 0; grid.AddInOpenList(grid.StartNode); var step = 0; OnStart(BuildArgs(step, grid)); while (grid.OpenListCount() != 0) { var node = grid.PopOpenList(); grid.AddInClosedList(node); if (node == grid.EndNode) { //_endNode = node; OnEnd(BuildArgs(step, grid, true)); return(true); } var neighbors = grid.GetNeighbors(node); for (var i = 0; i < neighbors.Count; ++i) { var neighbor = neighbors[i]; if (grid.IsClosed(neighbor)) { continue; } var x = neighbor.X; var y = neighbor.Y; // get the distance between current node and the neighbor // and calculate the next g score var ng = node.G + ((x - node.X == 0 || y - node.Y == 0) ? 1 : sqrt2); // check if the neighbor has not been inspected yet, or // can be reached with smaller cost from the current node if (!grid.IsOpen(neighbor) || ng < neighbor.G) { neighbor.G = ng; neighbor.H = Weight * CalcH(heuristic, Abs(x - grid.EndNode.X), Abs(y - grid.EndNode.Y)); neighbor.Cost = neighbor.G + neighbor.H; neighbor.ParentNode = node; if (!grid.IsOpen(neighbor)) { grid.PushInOpenList(neighbor); } } } grid.OrderOpenList(e => e.Cost); OnStep(BuildArgs(step++, grid)); } OnEnd(BuildArgs(step, grid, false)); return(false); }
public SearchResult(Node resultNode, int nodesGen, int nodesPrevGen, int nodesOnFrontier, int nodesOnExplored, string algName, IHeuristic heuristic) { ResultNode = resultNode; NodesGen = nodesGen; NodesPrevGen = nodesPrevGen; NodesOnFrontier = nodesOnFrontier; NodesOnExplored = nodesOnExplored; AlgName = algName; HeuristicName = heuristic?.Name; }
public SearchResult(SearchNode solution, int nodesGen, int nodesPrevGen, int nodesOnOpen, int nodesOnClosed, string algName, IHeuristic heuristic) { Solution = solution; NodesGenerated = nodesGen; NodesPrevGenerated = nodesPrevGen; NodesOnOpenList = nodesOnOpen; NodesOnClosedList = nodesOnClosed; AlgorithmName = algName; HeuristicName = heuristic == null ? null : heuristic.Name; }
public Problem( StateType startState, List <Operator <StateType> > operators, IGoalStateChecker <StateType> goalStateChecker, IHeuristic <StateType> heuristic = null) { this.StartState = startState; this.Operators = operators; this.GoalStateChecker = goalStateChecker; this.Heuristic = heuristic; }
public AStar(Graph <TModel> graph, int source, int target, IHeuristic <TModel> heuristic) { this.graph = graph; this.ShortestPathTree = new Edge[graph.Count()]; this.searchEdges = new Edge[graph.Count()]; this.gCosts = new double[graph.Count()]; this.fCosts = new double[graph.Count()]; this.source = source; this.target = target; this.Search(heuristic); }
static int _runFinder(IFinder finder, IHeuristic h, IMap map, bool window, bool noshow, int blocksize, int sleep) { if (!noshow) { if (sleep > 0) { finder.SleepUITimeInMs = sleep; } var viewer = window ? ViewerFactory.GetOpenGlViewerImplementation(blocksize) : ViewerFactory.GetConsoleViewerImplementation(); viewer.SetFinder(finder); viewer.Run(map, h); } else { if (finder.Find(map, h)) { var path = map.GetPath(); AbstractViewer.ShowEndLog(finder, path, new Pathfinder.Abstraction.FinderEventArgs { Finded = true, GridMap = map, ExpandedNodesCount = map.GetMaxExpandedNodes(), PassedTimeInMs = finder.GetProcessedTime(), Step = 0 }); var result = FileTool.GetTextRepresentation(map, false, path); if (!window) { Console.WriteLine(result); } else { MapViewWindow.OpenGlWindow(result, blocksize); } } else { Console.WriteLine("Cant find a path"); } } return(0); }
public Agent(LogarithmicGrid startingGrid, ISearcherFactory searcherFactory, IHeuristic heuristic) { this.searcherFactory = searcherFactory; this.searchTree = new SearchTree(heuristic, startingGrid); this.Timings.Add(1, Duration.Zero); if (startingGrid.Flatten().Any(i => i == 2)) { this.Timings.Add(2, Duration.Zero); } }
public static global::PathfindingAlgorithms.Algorithms.Astar.Astar Create(IHeuristic heuristic_iHeuristic, IAdjacement adjacement_iAdjacement) { global::PathfindingAlgorithms.Algorithms.Astar.Astar astar = new global::PathfindingAlgorithms.Algorithms.Astar.Astar (heuristic_iHeuristic, adjacement_iAdjacement); return astar; // TODO: Edit factory method of Astar // This method should be able to configure the object in all possible ways. // Add as many parameters as needed, // and assign their values to each field by using the API. }
public NodeArrayAStarPathFinding(NavMeshPathGraph graph, IHeuristic heuristic, bool usingGoalBounding) : base(graph, null, null, heuristic) { //do not change this var nodes = this.GetNodesHack(graph); this.NodeRecordArray = new NodeRecordArray(nodes, new BoundingBox()); this.Open = this.NodeRecordArray; this.Closed = this.NodeRecordArray; this.UsingGoalBounding = usingGoalBounding; this.fileReader = new FileReader(); if (usingGoalBounding) { fileReader.fileName = "goalBoundingInfo.xml"; NodeRecordArray = fileReader.readFile(this.NodeRecordArray); } }
/** * Create a path finder * * @param heuristic The heuristic used to determine the search order of the map * @param map The map to be searched * @param maxSearchDistance The maximum depth we'll search before giving up * @param allowDiagMovement True if the search should try diagonal movement */ public PathFinder(Quinoa quinoa, IHeuristic heuristic) { this.heuristic = heuristic; this.quinoa = quinoa; }
public GoalBoundingNodeArrayAStarPathFinding(NavMeshPathGraph graph, IHeuristic heuristic) : base(graph, heuristic) { }
public InfluenceMapAStarPathfinding(NavMeshPathGraph graph, IHeuristic heuristic, InfluenceMap redMap, InfluenceMap greenMap) : base(graph,heuristic) { this.RedMap = redMap; this.GreenMap = greenMap; }
public SearchTree(IHeuristic heuristic, LogarithmicGrid startingGrid) { this.Heuristic = heuristic; this.rootNode = new PlayerNode(startingGrid, this, startingGrid.Sum()); }
/// <summary> /// Generic search algorithm /// </summary> private static SearchResult GenericSearch(StateBase initialState, StateBase goalState, string algName, OpenListComparator comparator, CostFunc cost, IHeuristic heuristic, int? depthLimit = null) { var openList = new OpenList(comparator); var closedList = new ClosedList(); var cache = new HeuristicCache(goalState, heuristic); var nodesGenerated = 0; var nodesPrevGenerated = 0; // add initial node to open list openList.Push(new SearchNode(cost, initialState, null, null, cache.Evaluate)); while (true) { // if nothing on open list, fail if (openList.Count == 0) { return new SearchResult(null, nodesGenerated, nodesPrevGenerated, openList.Count, closedList.Count, algName, heuristic); } // get next node to expand var node = openList.Pop(); closedList.Push(node); // if at goal state, success if (node.State.Equals(goalState)) { return new SearchResult(node, nodesGenerated, nodesPrevGenerated, openList.Count, closedList.Count, algName, heuristic); } // if at depth limit, don't generate successors if (depthLimit != null && node.Depth == depthLimit) { continue; } var daughters = node.Successors(cost, cache.Evaluate); foreach (var daughter in daughters) { nodesGenerated++; // if this state is already in open list, replace old node with new node if g-hat is better var foundInOpen = openList.Find(daughter.State); if (foundInOpen != null) { nodesPrevGenerated++; if (daughter.Ghat < foundInOpen.Ghat) { openList.Replace(foundInOpen, daughter); } } else { // else if this state is already in closed list, move from closed to open if g-hat is better var foundInClosed = closedList.Find(daughter.State); if (foundInClosed != null) { nodesPrevGenerated++; if (daughter.Ghat < foundInClosed.Ghat) { openList.Push(daughter); closedList.Remove(foundInClosed); } } else { // else didn't find in open or closed, add to open openList.Push(daughter); } } } } }
/// <summary> /// Compares H-hat values for open list /// </summary> public SearchResult GreedySearch(CostFunc cost, IHeuristic heuristic) { OpenListComparator compareNodes = (node1, node2) => node1.Hhat.CompareTo(node2.Hhat); return GenericSearch(_initialState, _goalState, "Greedy", compareNodes, cost, heuristic); }