Dataset Viewer
query_id
stringlengths 32
32
| query
stringlengths 9
4.01k
| positive_passages
listlengths 1
1
| negative_passages
listlengths 88
101
|
---|---|---|---|
1ad8b2bda71c27dd30959fac0f57aaa8 | Finds the shortest path through a weighted graph using a heuristic. Used for planning & pathfinding in low dimension spaces. | [
{
"docid": "337086241106fd93d954e33e0b7111a4",
"score": "0.6438782",
"text": "def a_star(start_vertex, adjacent, cost, heuristic, goal, max_depth=None):\n if max_depth is not None and max_depth <= 0:\n raise ValueError(\"Argument max_depth must be greater than zero\")\n\n class InternalNode:\n '''\n value = User data\n parent = Parent's InternalNode (Or None if starting vertex)\n g = Total cost of getting to this node\n h = heuristic(vertex)\n f = g + h\n depth = Path length (in vertexes) to this node\n old = Has a shorter path to this node been found?\n '''\n # Try slots with performance tests, measure both time and memory\n # __slots__ = ('value', 'parent', 'old', 'h', 'g', 'f', 'depth')\n def __init__(self, vertex, parent):\n self.value = vertex\n self.parent = parent\n self.old = False\n if parent is None:\n self.depth = 1\n self.g = 0\n else:\n self.depth = parent.depth + 1\n edge_cost = cost(parent.value, vertex)\n self.g = parent.g + edge_cost\n self.h = heuristic(vertex)\n self.f = self.g + self.h\n\n def __lt__(self, other):\n return self.f < other.f\n\n start_node = InternalNode(start_vertex, None)\n\n frontier = [start_node]\n # visited contains all of frontier\n visited = {start_vertex: start_node}\n inconsistent_heuristic = False\n revisits = 0 # num-explore != len(visited) b/c revists overwrite previous entry in visited.\n\n while frontier:\n node = heapq.heappop(frontier)\n if node.old:\n continue\n\n if max_depth is not None and node.depth > max_depth:\n break\n\n vertex = node.value\n if goal(vertex):\n # Make the path\n path = []\n while node is not None:\n path.append(node)\n node = node.parent\n\n # Check for inadmissibile heuristics along the final path\n total_path_cost = path[0].g\n for vertex in path:\n remaining_path_cost = total_path_cost - vertex.g\n if vertex.h > remaining_path_cost:\n logger.warning(\"Detected inadmissible heuristic\")\n break\n\n calculate_EBF(len(visited) + revisits, len(path))\n\n return tuple(p.value for p in reversed(path))\n\n # Explore more of the graph\n for neighbor in adjacent(vertex):\n neighbor_node = InternalNode(neighbor, node)\n\n never_visited = neighbor not in visited\n shorter_path_found = False\n if not never_visited:\n previous_visit = visited[neighbor]\n if previous_visit.g > neighbor_node.g:\n shorter_path_found = True\n previous_visit.old = True\n revisits += 1\n # Detect Negative cost cycles.\n # TODO: Determine the time complexity of the following loop.\n cursor = neighbor_node.parent\n while cursor is not None:\n if cursor is previous_visit:\n raise CyclicGraphException(\"Negative Cost Cycle Detected\")\n cursor = cursor.parent\n\n if never_visited or shorter_path_found:\n # Visit this neighbor\n visited[neighbor] = neighbor_node\n heapq.heappush(frontier, neighbor_node)\n\n # Check for inconsistent heuristic (decreasing estimated total path cost)\n if node.f > neighbor_node.f:\n if not inconsistent_heuristic:\n inconsistent_heuristic = True\n logger.warning(\"Detected inconsistent heuristic\")\n\n raise NoPathException()",
"title": ""
}
] | [
{
"docid": "5478766196043feca0d87a016cf5f766",
"score": "0.7408174",
"text": "def shortest_path(graph, distances, visited_set, use_heuristic=False):\n n_list = []\n h = 0\n for name, dist in distances.items():\n if name not in visited_set and dist != float('inf'):\n if use_heuristic:\n h = heuristic(graph, graph.node_dict[name])\n n_list.append((dist + h, name))\n if len(n_list):\n return min(n_list)[1]\n return None",
"title": ""
},
{
"docid": "720f903b8371c1bf8325eb58c5632ae5",
"score": "0.7376161",
"text": "def get_shortest_path(weighted_graph, start, end):\r\n\r\n # We always need to visit the start\r\n nodes_to_visit = {start}\r\n #print(nodes_to_visit)\r\n visited_nodes = set()\r\n # Distance from start to start is 0\r\n distance_from_start = {start: 0}\r\n tentative_parents = {}\r\n\r\n while nodes_to_visit:\r\n # The next node should be the one with the smallest weight\r\n current = min(\r\n [(distance_from_start[node], node) for node in nodes_to_visit]\r\n )[1]\r\n #print(current)\r\n # The end was reached\r\n if current == end:\r\n break\r\n\r\n nodes_to_visit.discard(current)\r\n visited_nodes.add(current)\r\n\r\n edges = weighted_graph[current]#.get(current)\r\n #print(edges)\r\n unvisited_neighbours = set(edges).difference(visited_nodes)\r\n for neighbour in unvisited_neighbours:\r\n neighbour_distance = distance_from_start[current] + \\\r\n edges[neighbour]\r\n if neighbour_distance < distance_from_start.get(neighbour,\r\n float('inf')):\r\n distance_from_start[neighbour] = neighbour_distance\r\n tentative_parents[neighbour] = current\r\n nodes_to_visit.add(neighbour)\r\n\r\n return _deconstruct_path(tentative_parents, end)",
"title": ""
},
{
"docid": "ca4e53a8e77dc3f5268e6e4e87c5a55a",
"score": "0.7306786",
"text": "def astar_path(G, source, target, heuristic=None, weight='weight', search_space_nodes=False, search_space_size=False):\r\n if G.is_multigraph():\r\n raise NetworkXError(\"astar_path() not implemented for Multi(Di)Graphs\")\r\n\r\n if heuristic is None:\r\n # The default heuristic is h=0 - same as Dijkstra's algorithm\r\n def heuristic(u, v):\r\n return 0\r\n\r\n push = heapq.heappush\r\n pop = heapq.heappop\r\n\r\n # The queue stores priority, node, cost to reach, and parent.\r\n # Uses Python heapq to keep in priority order.\r\n # Add a counter to the queue to prevent the underlying heap from\r\n # attempting to compare the nodes themselves. The hash breaks ties in the\r\n # priority and is guarenteed unique for all nodes in the graph.\r\n c = heapq.count()\r\n queue = [(0, next(c), source, 0, None)]\r\n\r\n # Maps enqueued nodes to distance of discovered paths and the\r\n # computed heuristics to target. We avoid computing the heuristics\r\n # more than once and inserting the node into the queue too many times.\r\n enqueued = {}\r\n # Maps explored nodes to parent closest to the source.\r\n explored = {}\r\n i = 0\r\n while queue:\r\n i = i + 1\r\n # Pop the smallest item from queue.\r\n _, __, curnode, dist, parent = pop(queue)\r\n\r\n if curnode == target:\r\n path = [curnode]\r\n node = parent\r\n while node is not None:\r\n path.append(node)\r\n node = explored[node]\r\n path.reverse()\r\n if search_space_nodes:\r\n return path, explored.keys()\r\n elif search_space_size:\r\n return path, len(explored.keys())\r\n elif h:\r\n return path, i #len(explored.keys())\r\n\r\n return path\r\n\r\n if curnode in explored:\r\n continue\r\n\r\n explored[curnode] = parent\r\n\r\n for neighbor, w in G[curnode].items():\r\n if neighbor in explored:\r\n continue\r\n ncost = dist + w.get(weight, 1)\r\n if neighbor in enqueued:\r\n qcost, h = enqueued[neighbor]\r\n # if qcost < ncost, a longer path to neighbor remains\r\n # enqueued. Removing it would need to filter the whole\r\n # queue, it's better just to leave it there and ignore\r\n # it when we visit the node a second time.\r\n if qcost <= ncost:\r\n continue\r\n else:\r\n h = heuristic(neighbor, target)\r\n enqueued[neighbor] = ncost, h\r\n push(queue, (ncost + h, next(c), neighbor, ncost, curnode))\r\n\r\n raise nx.NetworkXNoPath(\"Node %s not reachable from %s\" % (source, target))",
"title": ""
},
{
"docid": "0813c601d9a353dd8c0684859f29d0bc",
"score": "0.71155983",
"text": "def astar_path_pathmax(G, source, target, heuristic=None, weight='weight', search_space_nodes=False, search_space_size=False):\r\n if G.is_multigraph():\r\n raise NetworkXError(\"astar_path() not implemented for Multi(Di)Graphs\")\r\n\r\n if heuristic is None:\r\n # The default heuristic is h=0 - same as Dijkstra's algorithm\r\n def heuristic(u, v):\r\n return 0\r\n\r\n push = heapq.heappush\r\n pop = heapq.heappop\r\n\r\n # The queue stores priority, node, cost to reach, and parent.\r\n # Uses Python heapq to keep in priority order.\r\n # Add a counter to the queue to prevent the underlying heap from\r\n # attempting to compare the nodes themselves. The hash breaks ties in the\r\n # priority and is guarenteed unique for all nodes in the graph.\r\n c = heapq.count()\r\n queue = [(0, next(c), source, 0, None)]\r\n\r\n # Maps enqueued nodes to distance of discovered paths and the\r\n # computed heuristics to target. We avoid computing the heuristics\r\n # more than once and inserting the node into the queue too many times.\r\n enqueued = {}\r\n # Maps explored nodes to parent closest to the source.\r\n explored = {}\r\n i = 0\r\n # For consistency, store the estimates\r\n estimates = {source:heuristic(source,target)}\r\n first = True\r\n while queue:\r\n i = i + 1\r\n # Pop the smallest item from queue.\r\n _, __, curnode, dist, parent = pop(queue)\r\n\r\n if curnode == target:\r\n path = [curnode]\r\n node = parent\r\n while node is not None:\r\n path.append(node)\r\n node = explored[node]\r\n path.reverse()\r\n if search_space_nodes:\r\n return path, explored.keys()\r\n elif search_space_size:\r\n return path, len(explored.keys())\r\n elif h:\r\n return path, i #len(explored.keys())\r\n\r\n return path\r\n\r\n if curnode in explored:\r\n continue\r\n\r\n explored[curnode] = parent\r\n\r\n for neighbor, w in G[curnode].items():\r\n if neighbor in explored:\r\n continue\r\n ncost = dist + w.get(weight, 1)\r\n if neighbor in enqueued:\r\n qcost, h = enqueued[neighbor]\r\n # if qcost < ncost, a longer path to neighbor remains\r\n # enqueued. Removing it would need to filter the whole\r\n # queue, it's better just to leave it there and ignore\r\n # it when we visit the node a second time.\r\n if qcost <= ncost:\r\n continue\r\n else:\r\n h = max(heuristic(neighbor, target), estimates[curnode]-w.get(weight,1))\r\n estimates[neighbor] = h\r\n enqueued[neighbor] = ncost, h\r\n push(queue, (ncost + h, next(c), neighbor, ncost, curnode))\r\n\r\n raise nx.NetworkXNoPath(\"Node %s not reachable from %s\" % (source, target))",
"title": ""
},
{
"docid": "b3ab440b7abd0616576d9bf38d039210",
"score": "0.7099636",
"text": "def compute_shortest_path(self) -> None:\n self.update_distance_of_all_edges_to(math.inf)\n self.distance_to[self.starting_node] = 0\n\n self.queue.insert(self.starting_node, 0)\n\n while self.queue.any:\n (node, _) = self.queue.remove_min()\n for neighbor, weight in node.neighbors.items():\n self.relax(node, neighbor, weight)",
"title": ""
},
{
"docid": "165c3191e44df0e16c827be8138e2799",
"score": "0.7020808",
"text": "def dijkstras_shortest_path(initial_position, destination, graph, adj):\n pass",
"title": ""
},
{
"docid": "2c007d6a98c9d0ffe754c6e1fff49e66",
"score": "0.7004128",
"text": "def shortest_path(self, s, t, weight=lambda e: 1):\n dist = {s: 0}\n prev = {s: None}\n Q = {s}\n while Q:\n u = min(Q, key=dist.get)\n Q.remove(u)\n if u == t:\n break\n for v in self.neighbors(u):\n alt = dist[u] + weight((u, v))\n if v not in dist or alt < dist[v]:\n Q.add(v)\n dist[v] = alt\n prev[v] = u\n if t not in prev:\n return None\n path = []\n while t is not None:\n path.append(t)\n t = prev[t]\n return reversed(path)",
"title": ""
},
{
"docid": "7ba1f9269864602e6c925c7812ae7fe5",
"score": "0.69155586",
"text": "def dijkstra_path(G, source, target, weight='weight'):\r\n (length,path)=single_source_dijkstra(G, source, target=target,\r\n weight=weight)\r\n try:\r\n #print \"Length to\", str(target) + \":\", str(path[target])\r\n return path[target]\r\n except KeyError:\r\n raise nx.NetworkXNoPath(\"node %s not reachable from %s\"%(source,target))",
"title": ""
},
{
"docid": "d03d39bfe0c88cb08ba9b016432557e1",
"score": "0.6905445",
"text": "def single_source_dijkstra(G,source,target=None,cutoff=None,weight='weight'):\r\n if source==target:\r\n return (0, [source])\r\n dist = {} # dictionary of final distances\r\n paths = {source:[source]} # dictionary of paths\r\n seen = {source:0}\r\n fringe=[] # use heapq with (distance,label) tuples\r\n heapq.heappush(fringe,(0,source))\r\n while fringe:\r\n (d,v)=heapq.heappop(fringe)\r\n if v in dist:\r\n continue # already searched this node.\r\n dist[v] = d\r\n if v == target:\r\n break\r\n #for ignore,w,edgedata in G.edges_iter(v,data=True):\r\n #is about 30% slower than the following\r\n if G.is_multigraph():\r\n edata=[]\r\n for w,keydata in G[v].items():\r\n minweight=min((dd.get(weight,1)\r\n for k,dd in keydata.items()))\r\n edata.append((w,{weight:minweight}))\r\n else:\r\n edata=iter(G[v].items())\r\n\r\n for w,edgedata in edata:\r\n vw_dist = dist[v] + edgedata.get(weight,1)\r\n\r\n if w in dist:\r\n if vw_dist < dist[w]:\r\n raise ValueError('Contradictory paths found:',\r\n 'negative weights?')\r\n elif w not in seen or vw_dist < seen[w]:\r\n seen[w] = vw_dist\r\n heapq.heappush(fringe,(vw_dist,w))\r\n paths[w] = paths[v]+[w]\r\n return (dist,paths)",
"title": ""
},
{
"docid": "2935ca57b952c5844593cf24873cabc0",
"score": "0.6892118",
"text": "def shortest_paths(self, u, by_weight=False, algorithm=None,\n weight_function=None, check_weight=True, cutoff=None):\n if weight_function is not None:\n by_weight = True\n elif by_weight:\n weight_function = lambda e:e[2]\n else:\n weight_function = lambda e:1\n\n if algorithm is None and not by_weight:\n algorithm = 'BFS'\n\n if by_weight and check_weight:\n self._check_weight_function(weight_function)\n\n if algorithm=='BFS':\n if by_weight:\n raise ValueError(\"The 'BFS' algorithm does not work on \" +\n \"weighted graphs.\")\n return self._backend.shortest_path_all_vertices(u, cutoff)\n\n elif algorithm=='Dijkstra_NetworkX':\n import networkx\n # If this is not present, an error might be raised by NetworkX\n if self.num_verts()==1 and self.vertices()[0]==u:\n return {u:[u]}\n if by_weight:\n if self.is_directed():\n G = networkx.DiGraph([(e[0], e[1], dict(weight=weight_function(e))) for e in self.edge_iterator()])\n else:\n G = networkx.Graph([(e[0], e[1], dict(weight=weight_function(e))) for e in self.edge_iterator()])\n else:\n # Needed to remove labels.\n if self.is_directed():\n G = networkx.DiGraph(self.edges(labels=False))\n else:\n G = networkx.Graph(self.edges(labels=False))\n G.add_nodes_from(self.vertices())\n return networkx.single_source_dijkstra_path(G, u)\n\n elif algorithm in ['Dijkstra_Boost','Bellman-Ford_Boost',None]:\n from sage.graphs.base.boost_graph import shortest_paths\n _,pred = shortest_paths(self, u, weight_function, algorithm)\n paths = {}\n for v in pred.keys():\n w = v\n path = [w]\n while w != u:\n w = pred[w]\n path.append(w)\n path.reverse()\n paths[v] = path\n return paths\n\n else:\n raise ValueError(\"Algorithm \" + algorithm + \" not yet \" +\n \"implemented. Please, contribute!\")",
"title": ""
},
{
"docid": "62b6f182269daf06fd638618f023f634",
"score": "0.688034",
"text": "def astar_graph_search(problem, h):\n def f(n):\n return n.path_cost + h(n)\n return best_first_graph_search(problem, f)",
"title": ""
},
{
"docid": "e93c91088fafa572a330d39a275caaa8",
"score": "0.68642414",
"text": "def single_source_dijkstra_path(G,source, cutoff=None, weight='weight'):\r\n (length,path)=single_source_dijkstra(G,source, weight = weight)\r\n return path",
"title": ""
},
{
"docid": "643935d6e525c0092a1ac0a8fd56a286",
"score": "0.6858446",
"text": "def shortest_path(self):\n print(\"Attempting to find shortest path from point A:{} to point B:{}\".format(self.start.node, self.goal.node))\n\n current = self.Nodes[self.start.node]\n current.score = self.f_score(current)\n\n self.frontier.put((current.score, current.node)) # Adding start node to the frontier\n\n bestGoalReached = False\n\n while not self.frontier.empty():\n\n current_node = self.frontier.get() # Picking the node with the lowest f-score\n current = self.Nodes[current_node[1]] # Using index 1 since f_score is stored at index 0\n\n for neighbour in current.neighbours: # Loop through all connecting nodes and add them to frontier\n\n if neighbour not in self.explored:\n self.Nodes[neighbour] = Node(neighbour, self.M)\n neighbour = self.Nodes[neighbour]\n neighbour.score = self.f_score(neighbour, current)\n\n self.frontier.put((neighbour.score, neighbour.node))\n\n # Break condition\n if current.node == self.goal.node:\n bestone = self.frontier.get()\n if bestone[0] >= current.score:\n bestGoalReached = True\n break\n self.frontier.put(bestone)\n\n self.explored.add(current.node)\n\n if bestGoalReached:\n print(\"Shortest path found!\")\n path = self.retrace_path(self.goal.node)\n else:\n print(\"No path found!\")\n path = None\n\n return path",
"title": ""
},
{
"docid": "84b2ca33a4dcba31823536327124dd9d",
"score": "0.6823071",
"text": "def shortest_path(graph, source, target):\n\n # instantiate queue and first node\n path = {}\n Q = []\n for node in graph.node_list():\n if node != source:\n # queue for minimizing distance\n Q.append((math.inf, node))\n # keep track of the current tentative distance and\n # neighbor of each node\n path[node] = (math.inf, None)\n\n # initialize source node\n Q.append((0, source))\n path[source] = (0, None)\n\n # iterate through queue based on next closest distance\n while len(Q) != 0:\n # sort queue and get next lowest neighbor\n Q.sort()\n dist, node = Q.pop(0)\n\n # get neighbors and distance to next node\n for neighbor, weight in graph.neighbors(node):\n # find this, if still in our queue\n queue_index = None\n for i,(w,n) in enumerate(Q):\n if n == neighbor:\n queue_index = i\n\n if queue_index is None:\n # neighbor not in queue, skip\n continue\n\n # check if it's shorter to proceed here via \n # the current node than our queue's estimate\n alt = dist + weight\n if alt < Q[queue_index][0]:\n # update variables\n path[neighbor] = (alt, node)\n Q[queue_index] = (alt, neighbor)\n\n # backtrack to get the shortest path and cumulative costs\n traj = []\n current = target\n while True:\n _, parent = path[current]\n traj.append(current)\n\n # stop condition\n if parent is None:\n break\n current = parent\n\n # reverse path\n traj.reverse()\n\n # return path, cost\n return traj, path[target][0]",
"title": ""
},
{
"docid": "4520892affda9b68e448ff745355752c",
"score": "0.6790623",
"text": "def solve(W):\n # setup dijkstra\n h, w = len(W), len(W[0])\n D, P = dijsktra(W, (0,0))\n print('Minimum Sum path cost: {}'.format(D[(h-1, w-1)]))",
"title": ""
},
{
"docid": "6d0f0d768d098e7ac4ac8ec5b5515bcd",
"score": "0.67847425",
"text": "def get_shortest_path(graph: nx.Graph, start: int, goal: int) -> list:\n paths = list()\n path_goal_min_val = float('inf')\n path_goal_min = None\n\n # Check for early termination if we're already at the goal.\n if start == goal:\n return [start]\n\n # Determine the intial distance from the start to the goal.\n goal_initial_distance = distance.euclidean(\n graph.intersections[start],\n graph.intersections[goal]\n )\n path = Path(\n cost=Cost(goal_initial_distance, 0, goal_initial_distance),\n intersections=[start],\n previous=start,\n frontier=start\n )\n heapq.heappush(paths, path)\n\n while len(paths) >= 1:\n nearest_frontier_path = heapq.heappop(paths)\n for neighbor_road in graph.roads[nearest_frontier_path.frontier]:\n\n # Ensure we don't go backwards.\n if neighbor_road == nearest_frontier_path.previous:\n continue\n else:\n new_path = update_path(\n graph=graph,\n path=nearest_frontier_path,\n new_frontier=neighbor_road,\n goal=goal\n )\n\n if neighbor_road == goal: # We've got to the goal....\n if new_path.cost.total < path_goal_min_val: # ...and it's cheaper than we've seen so far.\n path_goal_min_val = new_path.cost.total\n path_goal_min = new_path.intersections\n else: # ... and it's more expensive than we've seen so far.\n continue\n else:\n if path_goal_min is not None: # We have some kind of path to the goal...\n if new_path.cost.total >= path_goal_min_val: # ... and the current cost is too high.\n continue\n else: # ... it's not too high\n heapq.heappush(paths, new_path)\n else: # We havn't found the goal yet, keep going.\n heapq.heappush(paths, new_path)\n\n if path_goal_min is not None:\n return path_goal_min\n else:\n return -1",
"title": ""
},
{
"docid": "1f0cac23f2cafcc2c9218e4908fddecf",
"score": "0.6763409",
"text": "def bidirectional_dijkstra(G, source, target, weight = 'weight'):\r\n if source is None or target is None:\r\n raise nx.NetworkXException(\r\n \"Bidirectional Dijkstra called with no source or target\")\r\n if source == target: return (0, [source])\r\n #Init: Forward Backward\r\n dists = [{}, {}]# dictionary of final distances\r\n paths = [{source:[source]}, {target:[target]}] # dictionary of paths\r\n fringe = [[], []] #heap of (distance, node) tuples for extracting next node to expand\r\n seen = [{source:0}, {target:0} ]#dictionary of distances to nodes seen\r\n #initialize fringe heap\r\n heapq.heappush(fringe[0], (0, source))\r\n heapq.heappush(fringe[1], (0, target))\r\n #neighs for extracting correct neighbor information\r\n if G.is_directed():\r\n neighs = [G.successors_iter, G.predecessors_iter]\r\n else:\r\n neighs = [G.neighbors_iter, G.neighbors_iter]\r\n #variables to hold shortest discovered path\r\n #finaldist = 1e30000\r\n finalpath = []\r\n dir = 1\r\n while fringe[0] and fringe[1]:\r\n # choose direction\r\n # dir == 0 is forward direction and dir == 1 is back\r\n dir = 1-dir\r\n # extract closest to expand\r\n (dist, v )= heapq.heappop(fringe[dir])\r\n if v in dists[dir]:\r\n # Shortest path to v has already been found\r\n continue\r\n # update distance\r\n dists[dir][v] = dist #equal to seen[dir][v]\r\n if v in dists[1-dir]:\r\n # if we have scanned v in both directions we are done\r\n # we have now discovered the shortest path\r\n return (finaldist,finalpath)\r\n\r\n for w in neighs[dir](v):\r\n if(dir==0): #forward\r\n if G.is_multigraph():\r\n minweight=min((dd.get(weight,1)\r\n for k,dd in G[v][w].items()))\r\n else:\r\n minweight=G[v][w].get(weight,1)\r\n vwLength = dists[dir][v] + minweight #G[v][w].get(weight,1)\r\n else: #back, must remember to change v,w->w,v\r\n if G.is_multigraph():\r\n minweight=min((dd.get(weight,1)\r\n for k,dd in G[w][v].items()))\r\n else:\r\n minweight=G[w][v].get(weight,1)\r\n vwLength = dists[dir][v] + minweight #G[w][v].get(weight,1)\r\n\r\n if w in dists[dir]:\r\n if vwLength < dists[dir][w]:\r\n raise ValueError(\"Contradictory paths found: negative weights?\")\r\n elif w not in seen[dir] or vwLength < seen[dir][w]:\r\n # relaxing\r\n seen[dir][w] = vwLength\r\n heapq.heappush(fringe[dir], (vwLength,w))\r\n paths[dir][w] = paths[dir][v]+[w]\r\n if w in seen[0] and w in seen[1]:\r\n #see if this path is better than than the already\r\n #discovered shortest path\r\n totaldist = seen[0][w] + seen[1][w]\r\n if finalpath == [] or finaldist > totaldist:\r\n finaldist = totaldist\r\n revpath = paths[1][w][:]\r\n revpath.reverse()\r\n finalpath = paths[0][w] + revpath[1:]\r\n raise nx.NetworkXNoPath(\"No path between %s and %s.\" % (source, target))",
"title": ""
},
{
"docid": "6a74c5d9d643a1eec74ec24ecc402e7c",
"score": "0.6726148",
"text": "def vcg_cheapest_path(graph: nx.Graph, source, target):\n # first, find the shortest path between the source and the target\n main_path = nx.dijkstra_path(graph, source, target, \"weight\")\n # convert the main path to contain tuples that represents edges\n main_path = [tuple(main_path[i: i+2]) for i in range(len(main_path)-1)]\n # find it's cost\n main_cost = nx.dijkstra_path_length(graph, source, target, 'weight')\n\n # now calc every edge's cost\n for (s, t, w) in graph.edges.data('weight'):\n # the edge\n e = (s, t)\n # if the edge in the main path\n if e in main_path:\n # calc the shortest path without this edge\n # duplicate the graph\n temp_graph = nx.Graph.copy(graph)\n # remove the current edge\n temp_graph.remove_edges_from([(s, t), (t, s)])\n # calc the new shortest path\n current_cost = nx.dijkstra_path_length(temp_graph, source, target, 'weight')\n # the cost of the edge is: the main cost -(current cost + the edge's weight)\n cost = main_cost - (current_cost + w)\n print(\"(%s, %s) cost is %d\" % (s, t, cost))\n # else, the edge isn't in the main path\n else:\n # then its cost is 0\n print(\"(%s, %s) cost is 0\" % (s, t))",
"title": ""
},
{
"docid": "56cedf60aac09e43f1779c53594105d3",
"score": "0.6726049",
"text": "def a_star_search(problem, heuristic):\n \n smallState = problem.start.extractSmallState()\n n0 = Node(smallState, problem.start, None, None, problem,True, heuristic)\n if problem.is_goal_state(n0.state):\n return ['None']\n frontier = utils.PriorityQueue()\n frontier.push(n0, n0.cost)\n explored = set()\n while not frontier.is_empty():\n node = frontier.pop()\n path = node.get_path()\n explored.add(node.state)\n if problem.is_goal_state(node.state):\n return path\n next_states = problem.get_successors(node.fullState, node.state)\n frontier_costs = []\n frontier_states = []\n for n in frontier.heap:\n frontier_states.append(n[2].state)\n frontier_costs.append(n[2].cost)\n for next_state in next_states:\n next_node = Node(next_state[0], next_state[1], next_state[2], node, problem,True, heuristic)\n #print next_state[0]\n if (next_node.state not in explored and next_node.state not in frontier_states) or \\\n (next_node.state in frontier_states and frontier_costs[\n frontier_states.index(next_node.state)] > next_node.cost):\n frontier.push(next_node, next_node.cost)\n print \"no more frontiers...return path!!\"\n return path #node.getPath()",
"title": ""
},
{
"docid": "c291f9bdeb9f758c43fc0e06dc3fede8",
"score": "0.6661014",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n \"*** YOUR CODE HERE ***\"\n startNode = (problem.getStartState(), [], 0) # State of form: (node, path, pathcost)\n\n fringe = util.PriorityQueue() # Priority queue for fringe = selects nodes with lowest priority (Based on heuristic)\n fringe.push(startNode, 0) # Start node with initial priority of 0\n\n closed = set() # Contains all expanded nodes\n\n while not fringe.isEmpty():\n curState = fringe.pop() # Select node with lowest priority\n\n node = curState[0] # Store current node\n path = curState[1] # Get path to current node\n pathcost = curState[2] # Get cost of path to current node\n\n if problem.isGoalState(node): # If current node is the goal\n return path # Return path to current node\n\n if node not in closed: # If current node has not been expanded\n closed.add(node) # Add current node to closed set, since we will expand it\n\n # 'children' is a list of the form: [(successor, action, stepCost), (), ...]\n children = problem.getSuccessors(node) # Get children of current node (expand current node)\n\n for child,action,cost in children: # Iterate through each child \n if child in closed: # If child has already been expanded, then ignore it\n continue\n else:\n hn = heuristic(child, problem) # Heuristic: estimated cost from 'child' to goal node\n gn = pathcost + cost # Path cost from start node to 'child'\n newState = (child, path + [action], gn) # newState = (current node, updated path, updated cost)\n fringe.push(newState, hn + gn) # Add newState to fringe with priority : f(n) = h(n) + g(n)\n\n raise Exception(\"Failure\") # Did not find goal",
"title": ""
},
{
"docid": "7d8c4182777769140bf8ec32bbdfed85",
"score": "0.66590106",
"text": "def a_star(graph, h, start, goal):\n\n path = []\n path_cost = 0\n queue = PriorityQueue()\n queue.put((0, start))\n visited = set(start)\n\n branch = {}\n found = False\n \n while not queue.empty():\n item = queue.get()\n current_cost = item[0]\n current_node = item[1]\n \n if current_node == goal: \n print('Found a path.')\n found = True\n break\n else: \n for next_node in graph[current_node]:\n cost = graph.edges[current_node, next_node]['weight']\n new_cost = current_cost + cost + heuristic(next_node, goal)\n \n if next_node not in visited: \n visited.add(next_node) \n queue.put((new_cost, next_node))\n \n branch[next_node] = (new_cost, current_node)\n \n if found:\n # retrace steps\n n = goal\n path_cost = branch[n][0]\n path.append(goal)\n while branch[n][1] != start:\n path.append(branch[n][1])\n n = branch[n][1]\n path.append(branch[n][1])\n else:\n print('**********************')\n print('Failed to find a path!')\n print('**********************')\n \n return np.array(path[::-1]), path_cost",
"title": ""
},
{
"docid": "2debe06281955bda2de328501b390e8e",
"score": "0.6651053",
"text": "def astar_graph_search(problem, h=None):\n h = memoize(h or problem.h, slot='h')\n return best_first_graph_search(problem, lambda n: n.path_cost + h(n))",
"title": ""
},
{
"docid": "e88db77078ea8de978254b1e26e8430c",
"score": "0.66370904",
"text": "def dijkstra_shortest_path(grid_obs, source, dest):\n\n direction = [21, -1, -21, 1]\n outer_neighbors = [42, -2, -42, 2]\n vertexdict = dict()\n unvisited = []\n for i in range(len(grid_obs)):\n if grid_obs[i] != 'air': #<----------- Add things to avoid here\n vertexdict[i] = [1, 999, -999] #key = index, value = (cost, shortest dist from start, prev vert)\n unvisited.append(i) #add to unvisited list\n\n #set source vertex cost and shortest_dist_from_start to 0\n if source in vertexdict:\n vertexdict[source][0] = 0\n vertexdict[source][1] = 0\n else:\n return np.zeros(99)\n\n while len(unvisited) != 0:\n #find curVert - lowest shortest dist vertex\n lowestDist = float('inf')\n curVert = None\n for i in unvisited:\n if vertexdict[i][1] < lowestDist:\n curVert = i\n lowestDist = vertexdict[i][1]\n\n #examine neighbors of curVert\n for i in range(len(direction)):\n adjVert = curVert + direction[i]\n furtherVert = curVert + outer_neighbors[i]\n if adjVert in unvisited:\n #newcost = (cost of adjVert) + (shortest dist from curVert)\n newCost = vertexdict[adjVert][0] + vertexdict[curVert][1]\n if newCost < vertexdict[adjVert][1]:\n vertexdict[adjVert][1] = newCost\n vertexdict[adjVert][2] = curVert\n if furtherVert in unvisited:\n newCost = vertexdict[furtherVert][0] + vertexdict[curVert][1] + 1\n if newCost < vertexdict[furtherVert][1]:\n vertexdict[furtherVert][1] = newCost\n vertexdict[furtherVert][2] = curVert\n unvisited.remove(curVert)\n\n backtrack = dest\n path_list = []\n path_list.append(dest)\n while backtrack != source:\n path_list.insert(0, vertexdict[backtrack][2])\n backtrack = vertexdict[backtrack][2]\n return path_list",
"title": ""
},
{
"docid": "c4eea4a222c33c2db69f256a4c88261e",
"score": "0.66312426",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n startNode = (problem.getStartState(), [])\n frontier = util.PriorityQueue()\n \"Priority is g(n) + h(n), where g(n) is cost and h(n) the heuristic\"\n frontier.push(startNode, heuristic(startNode[0], problem))\n \"Expanded is a set for faster search. Insert only the state, to avoid visiting already visited nodes\"\n expanded = set()\n\n\n while not frontier.isEmpty():\n node = frontier.pop()\n if problem.isGoalState(node[0]):\n return node[1]\n if not (node[0] in expanded):\n expanded.add(node[0])\n children = problem.expand(node[0])\n for x in children:\n tempPath = list(node[1])\n tempPath.append(x[1])\n frontier.push((x[0], tempPath), problem.getCostOfActionSequence(tempPath) + heuristic(x[0], problem)) \n util.raiseNotDefined()",
"title": ""
},
{
"docid": "4d3a7ba3799d7ad21c3eff9f23ad29b6",
"score": "0.6625922",
"text": "def find_path(self, graph, start, end, heuristic_fn):\n \n # It starts off very similiar to Dijkstra. However, we will need to lookup\n # nodes in the _open list before. There can be thousands of nodes in the _open\n # list and any unordered search is too expensive, so we trade some memory usage for\n # more consistent performance by maintaining a dictionary (O(1) lookup) between\n # vertices and their nodes. \n _open_lookup = {}\n _open = []\n closed = set()\n \n # We require a bit more information on each node than Dijkstra\n # and we do slightly more calculation, so the heuristic must\n # prune enough nodes to offset those costs. In practice this\n # is almost always the case if their are any large _open areas\n # (nodes with many connected nodes).\n \n # Rather than simply expanding nodes that are on the _open list\n # based on how close they are to the start, we will expand based\n # on how much distance we predict is between the start and end \n # node IF we go through that parent. That is a combination of \n # the distance from the start to the node (which is certain) and\n # the distance from the node to the end (which is guessed).\n \n # We use the counter to enforce consistent ordering between nodes\n # with the same total predicted distance.\n \n counter = 0 \n heur = heuristic_fn(graph, start, end)\n _open_lookup[start] = {'vertex': start,\n 'dist_start_to_here': 0,\n 'pred_dist_here_to_end': heur,\n 'pred_total_dist': heur,\n 'parent': None}\n heapq.heappush(_open, (heur, counter, start))\n counter += 1\n \n while len(_open) > 0:\n current = heapq.heappop(_open)\n current_vertex = current[2]\n current_dict = _open_lookup[current_vertex]\n del _open_lookup[current_vertex]\n closed.update(current_vertex)\n \n if current_vertex == end:\n return self.reverse_path(current_dict)\n \n neighbors = graph.graph[current_vertex]\n for neighbor in neighbors:\n if neighbor in closed:\n # If we already expanded it it's definitely not better\n # to go through this node, or we would have expanded this\n # node first.\n continue\n \n cost_start_to_neighbor = current_dict['dist_start_to_here'] \\\n + graph.get_edge_weight(current_vertex, neighbor)\n # avoid searching twice\n neighbor_from_lookup = _open_lookup.get(neighbor, None)\n if neighbor_from_lookup is not None:\n # If our heuristic is NOT consistent or the grid is NOT uniform,\n # it is possible that there is a better path to a neighbor of a \n # previously expanded node. See above, ctrl+f \"river example neighbors\"\n \n # Note that the heuristic distance from here to end will be the same for\n # both, so the only difference will be in start->here through neighbor\n # and through the old neighbor.\n \n old_dist_start_to_neighbor = neighbor_from_lookup['dist_start_to_here']\n \n if cost_start_to_neighbor < old_dist_start_to_neighbor:\n pred_dist_neighbor_to_end = neighbor_from_lookup['pred_dist_here_to_end']\n pred_total_dist_through_neighbor_to_end = cost_start_to_neighbor + pred_dist_neighbor_to_end\n # Note, we've already shown that neighbor (the vector) is already in the _open list,\n # but unfortunately we don't know where and we have to do a slow lookup to fix the \n # key its sorting by to the new predicted total distance.\n \n # In case we're using a fancy debugger we want to search in user-code so when \n # this lookup freezes we can see how much longer its going to take.\n found = None\n for i in range(0, len(_open)):\n if _open[i][2] == neighbor:\n found = i\n break\n assert(found is not None)\n # TODO: I'm not certain about the performance characteristics of doing this with heapq, nor if\n # TODO: it would be better to delete heapify and push or rather than replace\n\n _open[found] = (pred_total_dist_through_neighbor_to_end, counter, neighbor)\n counter += 1\n heapq.heapify(_open)\n _open_lookup[neighbor] = {'vertex': neighbor,\n 'dist_start_to_here': cost_start_to_neighbor, \n 'pred_dist_here_to_end': pred_dist_neighbor_to_end, \n 'pred_total_dist': pred_total_dist_through_neighbor_to_end, \n 'parent': current_dict}\n continue\n\n # We've found the first possible way to the path!\n pred_dist_neighbor_to_end = heuristic_fn(graph, neighbor, end)\n pred_total_dist_through_neighbor_to_end = cost_start_to_neighbor + pred_dist_neighbor_to_end\n heapq.heappush(_open, (pred_total_dist_through_neighbor_to_end, counter, neighbor))\n _open_lookup[neighbor] = {'vertex': neighbor,\n 'dist_start_to_here': cost_start_to_neighbor,\n 'pred_dist_here_to_end': pred_dist_neighbor_to_end,\n 'pred_total_dist': pred_total_dist_through_neighbor_to_end,\n 'parent': current_dict}\n \n return None",
"title": ""
},
{
"docid": "79442350a3b6cf835ee6f223922bc889",
"score": "0.6611269",
"text": "def dijkstra(G, s):\n\n shortest_path = [INF for i in range(len(G))]\n shortest_path[s] = 0\n\n visited_nodes = set([s])\n\n while len(visited_nodes) < len(G):\n # choose an edge using dijkstra greedy score\n dgreedy_min = INF\n src = s\n dst = s\n need_break = True\n for i in visited_nodes:\n for edge in G[i]:\n if shortest_path[i] + edge[\"COST\"] < dgreedy_min and edge[\"DEST\"] not in visited_nodes:\n dgreedy_min = shortest_path[i] + edge[\"COST\"]\n src = i\n dst = edge[\"DEST\"]\n need_break = False\n\n if not need_break:\n # put shortest path cost for current node\n shortest_path[dst] = dgreedy_min\n visited_nodes.add(dst)\n else:\n break\n\n return shortest_path",
"title": ""
},
{
"docid": "d530ff25290ab928756e4c9d8698cc46",
"score": "0.6589445",
"text": "def graph_a_star(graph, h, start, goal):\n\n path = []\n path_cost = 0\n queue = PriorityQueue()\n queue.put((0, start))\n visited = set(start)\n\n branch = {}\n found = False\n\n while not queue.empty():\n item = queue.get()\n current_node = item[1]\n if current_node == start:\n current_cost = 0.0\n else:\n current_cost = branch[current_node][0]\n\n if current_node == goal:\n print('Found a path.')\n found = True\n break\n else:\n for next_node in graph[current_node]:\n cost = graph.edges[current_node, next_node]['weight']\n branch_cost = current_cost + cost\n queue_cost = branch_cost + h(next_node, goal)\n\n if next_node not in visited:\n visited.add(next_node)\n branch[next_node] = (branch_cost, current_node)\n queue.put((queue_cost, next_node))\n\n\n if found:\n # retrace steps\n n = goal\n path_cost = branch[n][0]\n path.append(goal)\n while branch[n][1] != start:\n path.append(branch[n][1])\n n = branch[n][1]\n path.append(branch[n][1])\n else:\n print('**********************')\n print('Failed to find a path!')\n print('**********************')\n return path[::-1], path_cost",
"title": ""
},
{
"docid": "3a208959306ede2e478a798128ef9323",
"score": "0.6522947",
"text": "def find_shortest_path(graph):\n comm = MPI.COMM_WORLD\n num_processes = comm.Get_size()\n rank = comm.Get_rank()\n\n if rank == 0:\n levels, nodes, distances, weights = parse_graph_repr(graph)\n start_time = MPI.Wtime()\n # How many nodes each process receives\n nodes_per_proc = math.ceil(nodes/(num_processes - 1))\n for level in range(2, levels + 2):\n node_index = 0\n destination = 1\n while(node_index < nodes):\n nodes_to_compute = range(node_index, node_index + nodes_per_proc)\n message = [distances[level -1], weights[level - 1], nodes_to_compute]\n comm.send(True, dest = destination, tag = SYNC_LEVEL)\n comm.send(message, dest = destination)\n destination += 1\n node_index += nodes_per_proc\n \n distances[level] = []\n for worker_process in range(1, destination):\n shortest_paths = comm.recv(source = worker_process)\n for key in shortest_paths:\n distances[level].append(shortest_paths[key])\n # Tells other processes to stop waiting for new tasks\n for node in range(1, num_processes):\n comm.send(False, dest = node, tag = SYNC_LEVEL)\n end_time = MPI.Wtime()\n print(end_time - start_time)\n else:\n # All process wait for requests from master process\n new_level = comm.recv(source = 0, tag = SYNC_LEVEL)\n while(new_level):\n # Receives from master process all data needed to find the shortest path\n # to node next_level_node\n message = comm.recv(source = 0)\n distances = message[0]\n weights = message[1]\n next_level_nodes = message[2]\n shortest_distances = {}\n for next_level_node in next_level_nodes:\n local_distances = []\n for node in range(0, len(weights[0])):\n dist = distances[node] + weights[node][next_level_node]\n local_distances.append(dist)\n shortest_distances[next_level_node] = min(local_distances)\n # Computes the shorstest path to next_level_node and sends it back\n comm.send(shortest_distances, dest = 0)\n new_level = comm.recv(source = 0, tag = SYNC_LEVEL)",
"title": ""
},
{
"docid": "78fb25e3a1f97bf0630d184ad0799ded",
"score": "0.6508275",
"text": "def dijkstras_shortest_path(initial_position, destination, graph, adj, visited_nodes):\n initial_box = find_box(initial_position, graph)\n destination_box = find_box(destination, graph)\n distances = {initial_box: 0} # Table of distances to cells \n previous_cell = {initial_box: None} # Back links from cells to predecessors\n queue = [(0, initial_box)] # The heap/priority queue used\n\n # Initial distance for starting position\n distances[initial_position] = 0\n \n while queue:\n # Continue with next min unvisited node\n current_distance, current_box = heappop(queue)\n print (current_distance == distances[current_box])\n #print (\"cur_node: \" +str(current_box))\n \n # Early termination check: if the destination is found, return the path\n if current_box == destination_box:\n node = destination_box\n path = []\n \n prev_point = initial_position\n while node is not None:\n line_end = (0,0)\n line_start = (0,0)\n #print (str(initial_box) + \" \" + str(destination_box) + \" \" + str(previous_cell[node]))\n if destination_box == initial_box:\n #print(\"single box\")\n line_start = initial_position\n line_end = destination\n elif previous_cell[node] != None or previous_cell[node] == initial_box:\n \n if node == destination_box:\n #print(\"destination box\")\n line_start = destination\n line_end = next_point(destination, node, previous_cell[node])\n else:\n #print(\"the rest\")\n line_start = prev_point\n line_end = next_point(prev_point, node, previous_cell[node])\n else:\n #print(\"initial box\")\n line_start = prev_point\n line_end = initial_position\n \n visited_nodes.append(node)\n path.append((line_start,line_end))\n prev_point = line_end \n node = previous_cell[node]\n #print (\"djtra: \" + str(path))\n #print(\"path: \" + str(path))\n return (path[::-1], visited_nodes) \n\n # Calculate tentative distances to adjacent cells\n for adjacent_node, edge_cost in adj(graph, current_box):\n new_distance = current_distance + heuristic(destination_box, adjacent_node)\n\n if adjacent_node not in distances or new_distance < distances[adjacent_node]:\n # Assign new distance and update link to previous cell\n distances[adjacent_node] = new_distance\n previous_cell[adjacent_node] = current_box\n heappush(queue, (new_distance, adjacent_node))\n \n # Failed to find a path\n print(\"Failed to find a path from\", initial_position, \"to\", destination)\n return None",
"title": ""
},
{
"docid": "caac5b76450ade4c94be9fcf520919ab",
"score": "0.64940196",
"text": "def run_dijkstra(argv_graph, argv_source, argv_target, argv_weight_edge):\n current_distance, current_path = networkx.single_source_dijkstra(\n G=argv_graph,\n source=argv_source,\n target=argv_target,\n weight=argv_weight_edge\n )\n return current_distance, current_path",
"title": ""
},
{
"docid": "abfd88b2b936217a32b399c74a72fc42",
"score": "0.64717966",
"text": "def shortestPath(self):\n\t\tdist = [float('inf')] * (self.size+1)\n\t\tdist[1] = 0\n\t\tfor v in range(1,self.size):\n\t\t\tfor u in self.graph[v]:\n\t\t\t\tif u == None:\n\t\t\t\t\tbreak\n\t\t\t\tif dist[u] > (dist[v] + 1):\n\t\t\t\t\tdist[u] = dist[v] + 1\n\t\treturn dist[self.size]",
"title": ""
},
{
"docid": "782e9b78d30ccd5a4d2f16eb033647fd",
"score": "0.64639467",
"text": "def single_source_dijkstra(G, source, target=None, cutoff=None, weight='weight',start_time='00:00:00'):\n if source == target:\n return ({source: 0}, {source: [(source,None,None,None)]})\n if cutoff is not None:\n cutoff = get_sec(cutoff)\n \n\n\n paths = {source: [(source,None,None,None)]} # dictionary of paths\n return _dijkstra(G, source, paths=paths, cutoff=cutoff,\n target=target,time_start=start_time)",
"title": ""
},
{
"docid": "6610334d1a66a457d334d9aac6dc20d4",
"score": "0.6456011",
"text": "def find_shortest_dijkstra_route(graph, journey):\n all_paths = dict(nx.all_pairs_dijkstra_path(graph))\n all_lengths = dict(nx.all_pairs_dijkstra_path_length(graph))\n\n if len(all_paths) != len(all_lengths):\n print(\"Path count is not equal to path length count, \"\n \"maybe some links are missing a weight?\")\n return False\n\n shortest_path = []\n \n for destination, path in all_paths[journey[0]].items():\n\n # If all nodes in our journey are in the current path being checked\n if all(node in path for node in journey):\n\n if (len(shortest_path) == 0) or (len(path) < len(shortest_path)):\n shortest_path = path\n\n\n total = 0\n for section in shortest_path:\n total += len(section) - 1\n\n print(\"\\nShortest dijkstra journey: {} connection(s)\".format(total))\n if len(shortest_path) < 1:\n print(\"No shortest dijkstra path found!\\n\")\n return False\n\n else:\n print(\"{} hop(s) {}\\n\".format(len(shortest_path) - 1, shortest_path))\n return shortest_path",
"title": ""
},
{
"docid": "218e1c83a7768b1b645b39769b47c692",
"score": "0.64454645",
"text": "def isPath(self, v, w): #O(n^2)\n if (v not in self.graph.keys()) or (w not in self.graph.keys()): #Raise ValueError it start node or target node isn't in the graph\n raise ValueError(\"One of the nodes was not found in the graph\")\n toVisit = deque([])\n visited = []\n toVisit.append(v)\n while len(toVisit) != 0:\n workingNode = toVisit.popleft()\n if w in self.graph[workingNode]: #If the target node is in the list of nodes the working node is connected to\n visited.append(workingNode) #Add working node to visited\n visited.append(w) #Add target node to visited\n break \n elif workingNode not in visited:\n visited.append(workingNode)\n for edge in self.graph[workingNode]:\n toVisit.append(edge)\n if w in visited:\n fileName = str(datetime.datetime.today()) + \"Shortest_Path.txt\"\n f = open(fileName, \"w+\")\n for i in visited:\n f.write(str(i) + \" \")\n f.close()\n return True\n else:\n return False",
"title": ""
},
{
"docid": "8193ce28132aa1bb72007c06c5ed4950",
"score": "0.64427286",
"text": "def shortest(visited, paths):\n shortest = float(\"inf\")\n index = -1\n for i, path in enumerate(paths):\n if not visited[i] and path < shortest:\n index = i\n shortest = path\n return index",
"title": ""
},
{
"docid": "9c04022b8084799a37db3c7e60a32cc2",
"score": "0.6425694",
"text": "def searchShortestPath(self,graph,start,to,path=[]):\n path=path+[start] # creates a new list by same name as path instead of appending to original\n if start==to:\n return path\n shortest=None\n if start not in graph:\n return None\n else:\n for node in graph[start]: \n if node not in path:\n #print(path)# to take care of already covered nodes/cycles using this if so have an if which searches\n\n val=self.searchShortestPath(graph,node,to,path) \n if val:\n if((shortest==None)):\n shortest=val\n elif(len(val)<len(shortest)):\n shortest=val\n return shortest",
"title": ""
},
{
"docid": "99f6f0fb6704387a03e56317400d920b",
"score": "0.64230776",
"text": "def heuristic(graph, curr_node):\n distances = [i[1] for i in graph.neighbors(curr_node)]\n try:\n return min(distances)\n except ValueError:\n return 0",
"title": ""
},
{
"docid": "9dc90a8a9a6a280e1b445b9f59f25131",
"score": "0.64035165",
"text": "def dijkstra_predecessor_and_distance(G,source, cutoff=None, weight='weight'):\r\n push=heapq.heappush\r\n pop=heapq.heappop\r\n dist = {} # dictionary of final distances\r\n pred = {source:[]} # dictionary of predecessors\r\n seen = {source:0}\r\n fringe=[] # use heapq with (distance,label) tuples\r\n push(fringe,(0,source))\r\n while fringe:\r\n (d,v)=pop(fringe)\r\n if v in dist: continue # already searched this node.\r\n dist[v] = d\r\n if G.is_multigraph():\r\n edata=[]\r\n for w,keydata in G[v].items():\r\n minweight=min((dd.get(weight,1)\r\n for k,dd in keydata.items()))\r\n edata.append((w,{weight:minweight}))\r\n else:\r\n edata=iter(G[v].items())\r\n for w,edgedata in edata:\r\n vw_dist = dist[v] + edgedata.get(weight,1)\r\n if cutoff is not None:\r\n if vw_dist>cutoff:\r\n continue\r\n if w in dist:\r\n if vw_dist < dist[w]:\r\n raise ValueError('Contradictory paths found:',\r\n 'negative weights?')\r\n elif w not in seen or vw_dist < seen[w]:\r\n seen[w] = vw_dist\r\n push(fringe,(vw_dist,w))\r\n pred[w] = [v]\r\n elif vw_dist==seen[w]:\r\n pred[w].append(v)\r\n return (pred,dist)",
"title": ""
},
{
"docid": "3a29bd57c3580ba7737f80dc53b9587a",
"score": "0.63937813",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n \"*** YOUR CODE HERE ***\"\n # Node: pos, g, h\n startNode = (problem.getStartState(), 0, 0)\n myList = util.PriorityQueue()\n visit = set()\n myList.push((startNode, [], []), 0) #position, visited, directions, f\n\n \n while not myList.isEmpty(): #If L = empty, then FAIL\n node, visit, path = myList.pop() # else pick a node n from L.\n if problem.isGoalState(node[0]): #If n is a goal node, STOP\n return path #return n and the path to it from an initial node.\n else: #Otherwise, remove n from OPEN\n if node[0] not in visit:\n visit += [node[0]] # put in in CLOSE\n children = problem.getSuccessors(node[0])\n for child in children: #and for all children x of n,\n if child[:][0] not in visit: #if x is not in CLOSE,\n # add x to OPEN and keep path information\n tempG = node[1] + child[2]\n tempH = heuristic(child[0], problem)\n tempF = tempG + tempH\n myList.push(((child[0], tempG, tempH), visit, path + [child[:][1]]), tempF)\n \n print \"ERROR: PATH NOT FOUND\"\n return []",
"title": ""
},
{
"docid": "7731233edd787c81c752d1695d1e40de",
"score": "0.638614",
"text": "def find_shortest_path(self):\n tree = Dijkstra(self.vertices, self.edges)\n matrix = tree.build_adj_matrix()\n short_path = [int(pnt) for pnt in tree.find_shortest_route(self.origin_id, self.destination_id, matrix)]\n all_path = self.path_to_xy(short_path, self.vertices)\n path_edges_xy = self.path_to_edge_xy(all_path)\n x_vertices_path = [x[0] for x in all_path]\n y_vertices_path = [x[1] for x in all_path]\n for path_line in path_edges_xy:\n self.main_subplot.plot([path_line[0][0], path_line[1][0]], [path_line[0][1], path_line[1][1]],\n color=\"#003D59\",\n linewidth=3)\n self.main_subplot.plot(x_vertices_path, y_vertices_path, \"o\", markersize=7, color=\"#FE6625\")\n self.fig_canvas = FigureCanvasTkAgg(self.mainFigure, self.root)\n self.fig_canvas.get_tk_widget().grid(row=3, column=1, rowspan=10, columnspan=10)",
"title": ""
},
{
"docid": "d640c89d78af039d58cc09622243e81e",
"score": "0.6367492",
"text": "def find_shortest_path(G, D, P, s, f):\n dijkstra(G, D, P, s)\n path = [f]\n v = P[f]\n while v is not None:\n path.append(v)\n v = P[v]\n path.reverse()\n return path",
"title": ""
},
{
"docid": "71fa290b7628d0a50b77530a41c34b31",
"score": "0.63570195",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n # priority queue to keep track of where our agent can move\n frontier = util.PriorityQueue()\n # start node contains the start state, an empty list representing the actions its taken thusfar\n startNode = (problem.getStartState(), [])\n # push node onto the stack with a prio of 0 (arbitrary bc start)\n frontier.push(startNode, 0)\n\n # holds the states visited so we dont end up in an infinite loop\n expanded = []\n\n while not frontier.isEmpty():\n node = frontier.pop()\n # the current state of our node\n currentState = node[0]\n # the path we took to get to our current state\n actionPath = node[1]\n # if we are at the goal, then return path to the goal\n if problem.isGoalState(currentState):\n return actionPath\n # ensure that we are not double visiting a node\n if currentState not in expanded:\n # add the current state to our expanded so we dont go over it more than once\n expanded.append(currentState)\n # children is a list of nodes connected to our currentState in format (child, action, stepCost)\n children = problem.expand(currentState)\n for child in children:\n # throw node on stack in form new state, newPath, stepCost\n newPath = actionPath + [child[1]]\n childState = child[0]\n childNode = (childState, newPath)\n\n # g(n) -- the observed cost from startState to the child state\n cost = problem.getCostOfActionSequence(newPath)\n # g(n) + h(n) -- take g(n) and add h(n) which is the heuristic estimate of child state to goal\n cost += heuristic(childState, problem)\n\n frontier.push(childNode, cost)\n # if we get through the entire search frontier without reaching the goal, return None\n return None",
"title": ""
},
{
"docid": "a89ca0b5e173339dfb98ccf8381be1e6",
"score": "0.6356788",
"text": "def FindPath(self, start, goal, path=[]):\n node, pathCost = start, 0\n frontier = util.Queue()\n visited = set()\n\n if start == goal:\n return path\n\n while node != goal:\n successors = [(edge.target, edge) for edge in self.GetEdges(node)]\n for successor, edge in successors:\n residual = edge.capacity - self.flow[edge]\n intPath = (edge, residual)\n if residual > 0 and not intPath in path and intPath not in visited:\n visited.add(intPath)\n frontier.push((successor, path + [(edge, residual)], pathCost + 1))\n\n if frontier.isEmpty():\n return None\n else:\n node, path, pathCost = frontier.pop()\n\n return path",
"title": ""
},
{
"docid": "37a61ca057ce0058d4b2316bd48f0f99",
"score": "0.6348699",
"text": "def shortestPath(graph, start, end, path=[]):\n\n path = path + [start]\n if start == end:\n return path\n if start not in graph:\n return None\n shortest = None\n for node in graph[start]:\n if node not in path:\n newpath = shortestPath(graph, node, end, path)\n if newpath:\n if not shortest or len(newpath) < len(shortest):\n shortest = newpath\n return shortest",
"title": ""
},
{
"docid": "e97c00d61d3e71c07a4d6bdcc1fd97bc",
"score": "0.6343977",
"text": "def test_get_shortest_paths_graph(self):\n shortest_path_graph = self.mapped_network.copy()\n shortest_path_graph.delete_vertices([2, 6, 7, 8])\n shortest_path_graph.simplify(combine_edges=max)\n shortest_path_graph.delete_vertices(\n shortest_path_graph.vs.select(_degree_eq=0))\n eid = shortest_path_graph.get_eid(\"0\", \"3\")\n shortest_path_graph.delete_edges(eid)\n weights = list(1 - np.array(shortest_path_graph.es['weight']))\n shortest_path_graph.es['weight'] = weights\n\n n = Network(\n self.interact_network,\n max_adj_p=0.05,\n max_l2fc=-1,\n min_l2fc=1,\n )\n n.set_up_network(self.protein_list)\n\n fn = FilteredNetwork(n)\n shortest_path_graph_to_test = fn.get_shortest_paths_graph()\n\n self.__check_for_graph_eq(shortest_path_graph,\n shortest_path_graph_to_test)",
"title": ""
},
{
"docid": "715930dda65138632ba9b60a613c3ebe",
"score": "0.6340343",
"text": "def ida_star_search(vertex, goal, discovered, bound, heuristic_function):\n f = heuristic_function(vertex)\n if f > bound:\n return f, None\n if vertex.current == goal:\n return True, vertex\n min = math.inf\n new = expand_fringe(vertex)\n for n in new:\n if n not in discovered:\n discovered.append(n)\n t, solving_n = ida_star_search(n, goal, discovered, bound, heuristic_function)\n if isinstance(t, bool) and t:\n return True, solving_n\n if t < min:\n min = t\n discovered.remove(n)\n return min, None",
"title": ""
},
{
"docid": "6af600252a08ccc7462cae8f82f48bdf",
"score": "0.6336181",
"text": "def aStar(start, goal, neighbor_func, distance_func, heuristic_func):\n pqueue = PriorityQueue()\n g_costs = {start : 1}\n parents = {start : start}\n \n pqueue.push(heuristic_func(start, goal), start)\n while not pqueue.isEmpty():\n next_cost, next_node = pqueue.pop()\n g_costs[next_node] = g_costs[parents[next_node]] \\\n + distance_func(next_node, parents[next_node])\n if next_node == goal: break\n children = neighbor_func(next_node)\n for child in children:\n updateChild(goal, distance_func, heuristic_func,\n child, next_node, parents, g_costs, pqueue)\n return getPathToGoal(start, goal, parents)",
"title": ""
},
{
"docid": "37702ff4d47e7b0f1adf3984b61d1f1a",
"score": "0.6333605",
"text": "def astar_search(problem, h=None):\n h = memoize(h or problem.h, 'h')\n return best_first_graph_search(problem, lambda n: n.path_cost + h(n))",
"title": ""
},
{
"docid": "1c44282a9e53a8eca15c9f998fedea5a",
"score": "0.63241047",
"text": "def AStar_search(problem, heuristic=nullHeuristic):\n\n frontier = util.PriorityQueue()\n startNode = Node(problem.getStartState(),None,0,None,0)\n frontier.push(startNode,heuristic(startNode.state,problem))\n explored_set = set()\n while True:\n Curr_node = frontier.pop()\n Curr_state = Curr_node.state\n if problem.isGoalState(Curr_state):\n path = []\n while Curr_node.depth != 0:\n path.insert(0,Curr_node.state)\n Curr_node = Curr_node.parent_node\n path.insert(0,startNode.state)\n return path\n elif Curr_state in explored_set:\n continue \n else:\n explored_set.add(Curr_state)\n new_frontiers = problem.getSuccessors(Curr_state)\n for transition in new_frontiers: \n if not transition[0] in explored_set:\n len(explored_set)\n new_node = Node(transition[0],transition[1],transition[2]+Curr_node.path_cost,Curr_node,Curr_node.depth+1)\n frontier.push(new_node,heuristic(new_node.state,problem)+new_node.path_cost)\n\n \n util.raiseNotDefined()",
"title": ""
},
{
"docid": "8caac4d8e858cc5cf2fb463d3d135032",
"score": "0.63137025",
"text": "def dijkstra(self, start, target): #O(n^2)\n if (start not in self.graph.keys()) or (target not in self.graph.keys()): #Checks that the starting node and target node are in the graph\n raise ValueError(\"One of the nodes was not found in the graph\")\n shortestPath = {} #Node and the weight of the shortest path to that node from the start node\n fromNode = {} #Node and the node before that the shortest path comes from\n toVisit = self.graph.copy() #Copy of the graph to keep a list of nodes that need visiting\n for i in toVisit:\n shortestPath[i] = math.inf #Initialise every nodes shortest path to infinity\n shortestPath[start] = 0 #Set the start node's shortest path to 0\n while toVisit:\n minNode = None\n for node in toVisit: #Iterates over all nodes in toVisit and selects one with the shortest weight in shortest path\n if minNode == None: #First case where node == None\n minNode = node\n elif shortestPath[node] < shortestPath[minNode]:\n minNode = node\n for toNode, weight in toVisit[minNode].items(): #Looks at all the nodes that the current node can get to \n if (weight + shortestPath[minNode]) < shortestPath[toNode]: #If the weight to the node + the weight to get to the current node is less than its current path\n shortestPath[toNode] = (weight + shortestPath[minNode]) #Update the shortest path to the weight to the node + the weight to get to the current node\n fromNode[toNode] = minNode #Update which node you came from to get to that node\n toVisit.pop(minNode) #Remove the current node from the list to visit\n path = []\n workingNode = target\n while workingNode != start: #Iterate over every node's path node to get path\n path.insert(0, workingNode) #Inserts current node at the start of the list\n workingNode = fromNode[workingNode] #Set the next node to the one before\n path.insert(0, start)\n cost = shortestPath[target]\n return path, cost",
"title": ""
},
{
"docid": "6eb8bc02bad0ec6638007d37f7327c2d",
"score": "0.6310573",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n \"*** YOUR CODE HERE ***\"\n start_state = problem.getStartState()\n if problem.isGoalState(start_state):\n return []\n class Node:\n def __init__(self, state, direction = None, total_cost = 0, parent_node = None):\n self.state = state\n self.direction = direction\n self.total_cost = total_cost\n self.parent_node = parent_node\n self._successor = None\n def successor_nodes(self, visited_states):\n if self._successor != None:\n self._successor = [x for x in self._successor if x.state not in visited_states]\n else: \n self._successor = [Node(x[0], direction=x[1], total_cost=self.total_cost + x[2], parent_node=self) \\\n for x in problem.getSuccessors(self.state) if x[0] not in visited_states]\n return self._successor\n def __str__(self):\n return f\"({self.state}, {self.direction}, {self.total_cost}, {self.parent_node != None})\"\n def __repr__(self):\n return str(self)\n\n visited_states = set()\n best_goal_node = None\n # the priority queue unlike uniform cost search uses the estimated cost to reach the goal\n # by adding the real cost needed to reach the node plus a heuristic estimate\n opened_que = util.PriorityQueueWithFunction(lambda x: x.total_cost + heuristic(x.state, problem)) \n opened_que.push(Node(start_state)) # start node is added\n \n while not opened_que.isEmpty(): # the entire graph will be searched until the cost of remaining nodes are too high\n node = opened_que.pop() # the node with the best estimate is popped\n if node.state in visited_states: # nodes already visited are skiped\n continue\n visited_states.add(node.state) # current node is visited\n # if current node has a worst estimate than the best path for the goal, then the search loop stops\n if best_goal_node != None and node.total_cost + heuristic(node.state, problem) >= best_goal_node.total_cost:\n break\n successor_nodes = node.successor_nodes(visited_states)\n\n for s_node in successor_nodes:\n # the goal state with the best cost is chosen if the node is a goal state\n if problem.isGoalState(s_node.state) and (best_goal_node == None or s_node.total_cost < best_goal_node.total_cost):\n best_goal_node = s_node\n else:\n opened_que.push(s_node) # non goal nodes added to the priority queue\n\n # unwind the path generated by the best_goal_node\n movements = []\n curr_node = best_goal_node\n while curr_node.parent_node != None:\n movements.append(curr_node.direction)\n curr_node = curr_node.parent_node\n movements.reverse()\n return movements\n # util.raiseNotDefined()",
"title": ""
},
{
"docid": "15b8f7000e4de51fd65445622ae13d10",
"score": "0.6299237",
"text": "def dijkstra(graph,src,dest,visited,distances,predecessors): \n # a few sanity checks\n if src not in graph:\n raise TypeError('the root of the shortest path tree cannot be found in the graph')\n if dest not in graph:\n raise TypeError('the target of the shortest path cannot be found in the graph') \n # ending condition\n if src == dest:\n # We build the shortest path and display it\n if dest not in distances:\n distances[dest] = 0\n path=[]\n pred=dest\n while pred != None:\n path.append(pred)\n pred=predecessors.get(pred,None)\n pathList = []\n pathList.append(str(path))\n pathList.append(distances[dest])\n return pathList\n\n else : \n # if it is the initial run, initializes the cost\n if not visited: \n distances[src]=0\n # visit the neighbors\n for neighbor in graph[src] :\n if neighbor not in visited:\n new_distance = distances[src] + graph[src][neighbor]\n if new_distance < distances.get(neighbor,float('inf')):\n distances[neighbor] = new_distance\n predecessors[neighbor] = src\n # mark as visited\n visited.append(src)\n # now that all neighbors have been visited: recurse \n # select the non visited node with lowest distance 'x'\n # run Dijskstra with src='x'\n unvisited={}\n for k in graph:\n if k not in visited:\n unvisited[k] = distances.get(k,float('inf')) \n x=min(unvisited, key=unvisited.get)\n return dijkstra(graph,x,dest,visited,distances,predecessors)",
"title": ""
},
{
"docid": "e6f3e458797785ccc5ab427ec1939a4f",
"score": "0.6289656",
"text": "def get_best_path(roadmap, start, end, restricted_roads, to_neighbor = False):\r\n\r\n \r\n # Write Dijkstra implementation here\r\n\r\n # PROBLEM 4c: Handle the to_neighbor = True case here\r\n\r\n #def get_best_path(roadmap, start, end, restricted_roads, to_neighbor = False):\r\n\r\n #if either start or end is not a valid node, return None\r\n if not roadmap.has_node(start) or not roadmap.has_node(end):\r\n return None\r\n #if start and end are the same node, return ([], 0) # Empty path with 0 travel time\r\n if start == end:\r\n return ([], 0)\r\n\r\n #Label every node as unvisited\r\n unvisited = roadmap.get_all_nodes()\r\n distanceTo = {node: float('inf') for node in roadmap.get_all_nodes()}\r\n distanceTo[start] = 0\r\n # Mark all nodes as not having found a predecessor node on path\r\n #from start\r\n predecessor = {node: None for node in roadmap.get_all_nodes()}\r\n\r\n while unvisited:\r\n # Select the unvisited node with the smallest distance from \r\n # start, it's current node now.\r\n current = min(unvisited, key=lambda node: distanceTo[node])\r\n\r\n # Stop, if the smallest distance \r\n # among the unvisited nodes is infinity.\r\n if distanceTo[current] == float('inf'):\r\n break\r\n\r\n # Find unvisited neighbors for the current node \r\n # and calculate their distances from start through the\r\n # current node.\r\n\r\n #iterate thru roads starting from current node\r\n for neighbour_road in roadmap.get_roads_for_node(current):\r\n\r\n #add road's time to total time\r\n alternativePathDist = distanceTo[current] + neighbour_road.get_total_time() #hops as distance\r\n\r\n # Compare the newly calculated distance to the assigned. \r\n # Save the smaller distance and update predecssor.\r\n if alternativePathDist < distanceTo[neighbour_road.get_destination()]:\r\n if neighbour_road.get_type() in restricted_roads:\r\n distanceTo[neighbour_road.get_destination()] = float('inf')\r\n else:\r\n distanceTo[neighbour_road.get_destination()] = alternativePathDist\r\n predecessor[neighbour_road.get_destination()] = current\r\n\r\n # Remove the current node from the unvisited set.\r\n unvisited.remove(current)\r\n \r\n #Attempt to be build a path working backwards from end\r\n path = []\r\n current = end\r\n while predecessor[current] != None:\r\n path.insert(0, current)\r\n current = predecessor[current]\r\n if path != []:\r\n path.insert(0, current)\r\n else:\r\n return None\r\n\r\n best_time = distanceTo[end]\r\n #get the road between two nodes and add the time of that\r\n #no method explicitly for that\r\n #but there is get_roads_for_node\r\n\r\n #return a tuple\r\n return (path, best_time)",
"title": ""
},
{
"docid": "ffedf68b0d5e82859ba894db78dd300b",
"score": "0.62883484",
"text": "def find_path(graph,\n start,\n end,\n cost = lambda pos: 1,\n passable = lambda pos: True,\n heuristic = helper.manhattan_dist):\n # tiles to check (tuples of (x, y), cost)\n todo = pqueue.PQueue()\n todo.update(start, 0)\n \n # tiles we've been to\n visited = set()\n \n # associated G and H costs for each tile (tuples of G, H)\n costs = { start: (0, heuristic(start, end)) }\n \n # parents for each tile\n parents = {}\n \n while todo and (end not in visited):\n todo.tie_breaker = lambda a,b: better_tile(a, b, start, end)\n \n cur, c = todo.pop_smallest()\n visited.add(cur)\n \n # check neighbours\n for n in graph.neighbours(cur):\n # skip it if we've already checked it, or if it isn't passable\n if ((n in visited) or\n (not passable(n))):\n continue\n \n if not (n in todo):\n # we haven't looked at this tile yet, so calculate its costs\n g = costs[cur][0] + cost(cur)\n h = heuristic(n, end)\n costs[n] = (g, h)\n parents[n] = cur\n todo.update(n, g + h)\n else:\n # if we've found a better path, update it\n g, h = costs[n]\n new_g = costs[cur][0] + cost(cur)\n if new_g < g:\n g = new_g\n todo.update(n, g + h)\n costs[n] = (g, h)\n parents[n] = cur\n \n # we didn't find a path\n if end not in visited:\n return []\n \n # build the path backward\n path = []\n while end != start:\n path.append(end)\n end = parents[end]\n path.append(start)\n path.reverse()\n \n return path",
"title": ""
},
{
"docid": "14281caf2bbe26c2a06c1ec2adc2edf6",
"score": "0.62715036",
"text": "def shortestPath(self, origin, destination, edgeCost=lambda src,dst: 1, \\\n\t\t\t\theuristic=lambda src,dst: 0):\n\t\tqueue = []\n\t\tvisited = set()\n\t\tpathCosts = {origin:0}\n\t\tparents = {origin:None}\n\t\theappush(queue, (0, origin))\n\t\twhile queue:\n\t\t\tpriority, node = heappop(queue)\n\t\t\tif node == destination:\n\t\t\t\tbreak\n\t\t\tif node in visited:\n\t\t\t\tcontinue\n\t\t\tvisited.add(node)\n\t\t\tfor neighbor in self.edges[node]:\n\t\t\t\tif neighbor in visited:\n\t\t\t\t\tcontinue\n\t\t\t\tnewPathCost = pathCosts[node] + edgeCost(node, neighbor)\n\t\t\t\tif neighbor in pathCosts:\n\t\t\t\t\tif pathCosts[neighbor] <= newPathCost:\n\t\t\t\t\t\tcontinue\n\t\t\t\tparents[neighbor] = node\n\t\t\t\tpathCosts[neighbor] = newPathCost\n\t\t\t\theappush(queue, (heuristic(neighbor, destination) + \\\n\t\t\t\t\t\tnewPathCost, neighbor))\n\t\tif node != destination:\n\t\t\traise PathError()\n\t\tpath = []\n\t\twhile node != None:\n\t\t\tpath = [node] + path\n\t\t\tnode = parents[node]\n\t\treturn path",
"title": ""
},
{
"docid": "e8fcf8fd04aa2c4d374ea9465c508052",
"score": "0.62714535",
"text": "def find_path(self):\n start = AstarNode(\n None,\n 0,\n self.h(\n self.start,\n self.goal),\n self.start,\n self.start_time)\n open_list = Q.PriorityQueue()\n open_hash = defaultdict()\n open_list.put(start)\n open_hash[(start.f, start.vertex.id)] = True\n closed_list = defaultdict()\n\n while not(open_list.empty()):\n\n # get the current best node\n best_node = open_list.get()\n open_hash.pop((best_node.f, best_node.vertex.id))\n # the following line expands the node and checks if the node is a\n # goal\n if self.is_goal(best_node):\n path = []\n node = best_node\n while node.parent is not None:\n path.append(node.vertex)\n node = node.parent\n path.append(node.vertex)\n return path[::-1]\n\n # expand the node if the node is not the goal and afterwards add to node\n # to closed_list\n self.expand_node(best_node, open_list, closed_list, open_hash)\n\n if open_list.empty():\n return None",
"title": ""
},
{
"docid": "33f187b852733fd2f0941109c9cae1d9",
"score": "0.6258173",
"text": "def heuristic_neighboors(G, idx_first_node = 0):\n\n num_nodes = G.order()\n dist = 0\n\n min_dist, opt_list_of_nodes = heuristic_shortest_edge(G)\n list_of_nodes = list(opt_list_of_nodes) #copy\n\n for i in range(1, num_nodes):\n for j in [x for x in range(1, num_nodes) if x != i]:\n list_of_nodes = swap(list_of_nodes, i,j)\n path_found = verify_path(G, list_of_nodes)\n\n if path_found is False:\n break\n\n dist = list_of_nodes_to_dist(G, list_of_nodes, min_dist)\n\n if dist < min_dist :\n min_dist = dist\n opt_list_of_nodes = list(list_of_nodes) #copy\n\n list_of_nodes = swap(list_of_nodes, i,j)\n\n return(min_dist, opt_list_of_nodes)",
"title": ""
},
{
"docid": "eeece756afb4771587d8b472616f4606",
"score": "0.6241078",
"text": "def a_star(start, goal, node_map, win):\n \"\"\"Works by minimising the heuristic score + cost of path from node to node \"\"\"\n start.g_score = 0\n open_set = [start] # records nodes with minimum A* score\n came_from = [] # Records nodes that are selected in the path\n\n while len(open_set) != 0:\n # Select node with lowest f_score\n f_score_list = list(map(lambda node: node.f_score, open_set))\n index = f_score_list.index(min(f_score_list))\n current = open_set[index]\n if current == goal:\n print(\"Success\")\n return reconstruct_path(current, node_map)\n del open_set[index]\n current.draw_node(win, (255, 255, 255))\n # pygame.time.wait(1)\n\n distance_current_neighbour = 8\n current_neighbours = get_neighbours(node_map, current)\n for neighbour in current_neighbours:\n tentative_gscore = current.g_score + distance_current_neighbour\n if tentative_gscore < neighbour.g_score:\n current_index = find_in_list_of_list(node_map, current)\n neighbour.came_from = current\n came_from.append(current_index)\n neighbour.g_score = tentative_gscore\n neighbour.f_score = neighbour.g_score + neighbour.h_value\n if neighbour not in open_set:\n open_set.append(neighbour)\n\n return 0",
"title": ""
},
{
"docid": "837fa049b4a4147b8f7106452716d1d4",
"score": "0.62349063",
"text": "def solve(self):\n for i in np.arange(1, self.graph.objects_number):\n for char in self.graph.mapping:\n char_width = self.graph.alphabet[self.graph.mapping[char]].shape[1]\n path_weights = self.graph.vertex_weights[i - char_width, :] + \\\n self.graph.edge_weights[i - char_width, i, :, char]\n\n self.graph.vertex_weights[i, char] = np.min(path_weights)\n\n self.labels[i, char] = np.argmin(path_weights)\n\n result = ''\n i = self.graph.objects_number - 1\n while i > 0:\n label = np.argmin(self.graph.vertex_weights[i, :])\n result = self.graph.mapping[label] + result\n i = i - self.graph.alphabet[self.graph.mapping[label]].shape[1]\n\n min_path_weight = np.min(self.graph.vertex_weights[-1, :])\n print('Minimum path weight: {}'.format(min_path_weight))\n print('Recognized string: {}'.format(result))\n return result, min_path_weight",
"title": ""
},
{
"docid": "94f9137f910dab03d7c4d807be21b237",
"score": "0.6232196",
"text": "def find_path(self, graph, start, end, heuristic_fn):\n \n # This algorithm is really just repeating unidirectional A* twice,\n # but unfortunately it's just different enough that it requires \n # even more work to try to make a single function that can be called \n # twice.\n \n \n # Note: The nodes in by_start will have heuristic distance to the end,\n # whereas the nodes in by_end will have heuristic distance to the start.\n # This means that the total predicted distance for the exact same node\n # might not match depending on which side we found it from. However, \n # it won't make a difference since as soon as we evaluate the same node\n # on both sides we've finished.\n #\n # This also means that we can use the same lookup table for both.\n \n open_by_start = []\n open_by_end = []\n open_lookup = {}\n \n closed = set()\n \n # used to avoid hashing the dict.\n counter_arr = [0]\n \n total_heur_distance = heuristic_fn(graph, start, end)\n heapq.heappush(open_by_start, (total_heur_distance, counter_arr[0], start))\n counter_arr[0] += 1\n open_lookup[start] = { 'vertex': start, \n 'parent': None, \n 'source': self.NodeSource.BY_START, \n 'dist_start_to_here': 0,\n 'pred_dist_here_to_end': total_heur_distance,\n 'pred_total_dist': total_heur_distance }\n \n heapq.heappush(open_by_end, (total_heur_distance, counter_arr, end))\n counter_arr[0] += 1\n open_lookup[end] = { 'vertex': end,\n 'parent': None,\n 'source': self.NodeSource.BY_END, \n 'dist_end_to_here': 0,\n 'pred_dist_here_to_start': total_heur_distance,\n 'pred_total_dist': total_heur_distance }\n \n # If the start runs out then the start is in a closed room,\n # if the end runs out then the end is in a closed room,\n # either way there is no path from start to end.\n while len(open_by_start) > 0 and len(open_by_end) > 0:\n result = self._evaluate_from_start(graph, start, end, heuristic_fn, open_by_start, open_by_end, open_lookup, closed, counter_arr)\n if result is not None:\n return result\n \n result = self._evaluate_from_end(graph, start, end, heuristic_fn, open_by_start, open_by_end, open_lookup, closed, counter_arr)\n if result is not None:\n return result\n \n return None",
"title": ""
},
{
"docid": "8c886729ed4bd3f688f1a1f52f8be4ed",
"score": "0.6219312",
"text": "def a_star_search(problem):\n # sets the intial goal state and initial state\n goal_state = problem.goal_states[0]\n state = problem.init_state\n\n # initializes all of the variables and data structures needed for the search\n node = Node(None,state,None,0)\n if goal_state == node.state:\n return [state], 0, 0\n frontier = queue.PriorityQueue() # intializes the frontier of the priority queue\n frontier.put((0,node)) # priority queue will store the path cost and the node as a tuple\n explored = {}\n explored[node.state] = 0 # initializes explored dictionary\n path = False\n max_frontier_size = 0\n num_nodes_expanded = 0\n \n while True:\n if frontier.qsize() == 0: # loops until the frontier is empty\n return [], num_nodes_expanded, max_frontier_size # if frontier is empty --> no solution to the problem\n max_frontier_size = max(max_frontier_size,frontier.qsize())\n node = (frontier.get())[1] # gets the node with the smallest cost\n if node.state == goal_state:\n break\n actions = problem.get_actions(node.state) # gets all of the actions associated with the node\n for action in actions:\n num_nodes_expanded += 1\n child = problem.get_child_node(node,action) # gets child associated with the actions\n if child.state not in explored or explored[child.state] > child.path_cost: # if the child has not been explored yet or if it has and has a higher path cost than what is already in the dictionary\n f = child.path_cost + problem.manhattan_heuristic(child.state,goal_state) # determines the path cost with the heuristic\n frontier.put((f,child))\n explored[child.state] = child.path_cost # updates the data structures accordingly\n\n final_path = [] # determines the final path by working backwards --> same process as breadth and bidirectional searches\n final_path.insert(0,goal_state)\n parent = node.parent\n while(True):\n final_path.insert(0,parent.state)\n if(parent.state == state):\n break\n parent = parent.parent\n\n return final_path, num_nodes_expanded, max_frontier_size",
"title": ""
},
{
"docid": "43512a3cc447caf54d9c297e504b75fb",
"score": "0.6216858",
"text": "def shortest_path(self, u, v, by_weight=False, algorithm=None,\n weight_function=None, check_weight=True,\n bidirectional=None): # TODO- multiple edges??\n if weight_function is not None:\n by_weight = True\n\n if algorithm is None:\n algorithm = 'Dijkstra_Bid' if by_weight else 'BFS_Bid'\n\n if algorithm in ['BFS', 'Dijkstra_NetworkX', 'Bellman-Ford_Boost']:\n return self.shortest_paths(u, by_weight, algorithm, weight_function, check_weight)[v]\n\n if weight_function is None and by_weight:\n weight_function = lambda e:e[2]\n\n if bidirectional is not None:\n deprecation(18938, \"Variable 'bidirectional' is deprecated and \" +\n \"replaced by 'algorithm'.\")\n\n if u == v: # to avoid a NetworkX bug\n return [u]\n\n\n if by_weight:\n if algorithm == 'BFS_Bid':\n raise ValueError(\"The 'BFS_Bid' algorithm does not \" +\n \"work on weighted graphs.\")\n if check_weight:\n self._check_weight_function(weight_function)\n else:\n weight_function = lambda e:1\n\n if algorithm==\"Dijkstra_Bid\":\n return self._backend.bidirectional_dijkstra(u, v, weight_function)\n elif algorithm==\"Dijkstra_Bid_NetworkX\":\n import networkx\n if self.is_directed():\n G = networkx.DiGraph([(e[0], e[1], dict(weight=weight_function(e))) for e in self.edge_iterator()])\n else:\n G = networkx.Graph([(e[0], e[1], dict(weight=weight_function(e))) for e in self.edge_iterator()])\n G.add_nodes_from(self.vertices())\n return networkx.bidirectional_dijkstra(G, u, v)[1]\n elif algorithm==\"BFS_Bid\":\n return self._backend.shortest_path(u,v)\n else:\n raise ValueError(\"Algorithm '\" + algorithm + \"' not yet implemented.\")",
"title": ""
},
{
"docid": "b0ac22fa1e1fe27cfde57abea68dfa1d",
"score": "0.6215874",
"text": "def dijkstra_shortest_path(graph, s):\n # Create a new sub-area of the graph\n x = Graph(s)\n # Keep track of distances\n A = {s.name: 0}\n while x != graph:\n # Take a subsection of the graph we have not explored\n x_v = graph - x\n assert all(node not in x_v.nodes for node in x.nodes)\n assert all(node not in x.nodes for node in x_v.nodes)\n # Find edges that cross between known and unknown\n edges = graph.find_edges(x.nodes.keys(), x_v.nodes.keys())\n if not edges:\n for node in graph.nodes.values():\n for edge in node.edges:\n if edge.start in x.nodes and edge.finish in x_v.nodes:\n logger.error(edge)\n\n logger.info(\"Found %s edges to unexplored areas\", len(edges))\n # Calculate Dijkstra's greedy criterion\n greedy = [A[edge.start] + edge.length for edge in edges]\n # Pick out the minimum based on the greedy criterion\n vw = edges[greedy.index(min(greedy))]\n assert vw.finish not in A\n assert vw.start in x.nodes and vw.finish in x_v.nodes\n logger.info(\"Found path of length %s to %s from %s\",\n vw.length, vw.finish, vw.start)\n # Add this new node to our graph, storing the path length\n x.add_node(graph.nodes[vw.finish])\n A[vw.finish] = A[vw.start] + vw.length\n logger.info(\"Total path from %s to %s is %s\",\n s.name, vw.finish, A[vw.finish])\n # Return the final distance\n return A",
"title": ""
},
{
"docid": "b15c9d1a26185055c5529945337e0703",
"score": "0.62136203",
"text": "def _dijkstra(G,source,time_start='00:00:00',pred=None, paths=None, cutoff=None,\n target=None):\n G_succ = G.succ if G.is_directed() else G.adj\n\n push = heappush\n pop = heappop\n dist = {} # dictionary of final distances\n #nb_walks = \n time_start = get_sec(time_start)\n seen = {source: time_start}\n prev = dict.fromkeys(list(G.nodes), (None, None, None,None)) # Pred node,pred_edge_id,pred_trip_id,pred_type\n c = count()\n fringe = [] # use heapq with (distance,label) tuples\n push(fringe, (time_start, next(c), source))\n while fringe:\n (d, _, v) = pop(fringe)\n if v in dist:\n continue # already searched this node.\n dist[v] = d\n if v == target:\n break\n current_time = dist[v]\n for u, e_group in G_succ[v].items():\n for id_,e in e_group.items():\n tmp = (v,id_,e['trip_id'],e['type'])\n cost = get_weight(e, current_time, prev[v]) \n if cost is None:\n continue\n vu_dist = dist[v] + cost\n if cutoff is not None:\n if vu_dist > cutoff:\n continue\n if u in dist:\n if vu_dist < dist[u]:\n raise ValueError('Contradictory paths found:',\n 'negative weights?')\n elif u not in seen or vu_dist < seen[u]:\n seen[u] = vu_dist\n prev[u] = tmp\n push(fringe, (vu_dist, next(c), u))\n if paths is not None:\n paths[u] = copy.deepcopy(paths[v]) + [tmp]\n if pred is not None:\n pred[u] = [v]\n elif vu_dist == seen[u]:\n if pred is not None:\n pred[u].append(v)\n\n if paths is not None:\n return (dist, paths)\n if pred is not None:\n return (dist, pred)\n return dist,None",
"title": ""
},
{
"docid": "f92e2bc852992d879710c7c6d29aedda",
"score": "0.6213613",
"text": "def astar_search(problem, h=None):\n h = h or problem.h\n h = memoize(h, 'h')\n def f(n):\n return max(getattr(n, 'f', -infinity), n.path_cost + h(n))\n return best_first_graph_search(problem, f)",
"title": ""
},
{
"docid": "4efcf71ccecc04b506c1a2983863a7d4",
"score": "0.6210283",
"text": "def astar(graph, start, goal, cost_heuristic=cost_heuristic_none, tie_heuristic=tie_heuristic_high_g):\n open_list = OpenList()\n\n # add start node to open list\n g = 0\n h = cost_heuristic(start)\n open_list.put(start, (g+h, tie_heuristic(g, h)))\n \n # set of nodes that have already been explored\n explored = set()\n\n # dict mapping children to parent\n predecessors = dict()\n\n # dict mapping nodes to cost from start\n costs = dict()\n costs[start] = 0\n\n path_found = False\n nodes_expanded = 0\n while not open_list.empty():\n node = open_list.get()\n nodes_expanded += 1\n\n # break if goal is found\n if node == goal:\n path_found = True\n break\n\n explored.add(node)\n\n # expand node\n for successor, cost in zip(*graph.get_successors(node)):\n # if we have already explored successor don't add to open list\n if successor in explored:\n continue\n\n g = costs[node] + cost\n h = cost_heuristic(successor)\n priority = (g+h, tie_heuristic(g, h))\n\n # if open_list already has successor,\n # and priority is lower than what is already there\n # update the priority, otherwise, skip\n if open_list.contains(successor):\n if priority < open_list.get_priority(successor):\n open_list.decrease_key(successor, priority)\n else:\n continue\n else:\n # if open_list doesn't have successor, add to open_list\n open_list.put(successor, priority)\n\n # update cost from start and predecessor\n costs[successor] = g\n predecessors[successor] = node\n\n if not path_found:\n return path_found, [], float('inf'), nodes_expanded\n\n # construct path\n path = []\n if path_found:\n node = goal\n path.append(goal)\n while node != start:\n node = predecessors[node]\n path.append(node)\n path = path[::-1] # reverse list\n\n return path_found, path, costs[goal], nodes_expanded",
"title": ""
},
{
"docid": "bb2d8cdc189ff1e5c760f9568d38234a",
"score": "0.62086135",
"text": "def aStarSearch(problem, heuristic):\n \"*** YOUR CODE HERE ***\"\n from game import Directions\n from util import PriorityQueue\n \n fringe = PriorityQueue()\n direction_to_goal = PriorityQueue()\n position_visited = []\n current_position = problem.getStartState()\n final_directions = [] \n while problem.isGoalState(current_position) == False:\n if current_position not in position_visited:\n position_visited.append(current_position) \n for temporary_position, temporary_direction, temporary_cost in problem.getSuccessors(current_position): \n totalcost = heuristic(temporary_position, problem, \"goal\")\n fringe.push(temporary_position, totalcost)\n direction_to_goal.push(final_directions + [temporary_direction], totalcost)\n current_position = fringe.pop()\n final_directions = direction_to_goal.pop()\n return final_directions",
"title": ""
},
{
"docid": "ee0b875e222cee2704cb80a4897864bc",
"score": "0.6206935",
"text": "def minimumCostPath(analyzer, destStation):\n return model.minimumCostPath(analyzer, destStation)",
"title": ""
},
{
"docid": "92267f3a2801c0d009cf59aae6233281",
"score": "0.6206013",
"text": "def greedyBestFirstSearch(problem, heuristic):\n startState = problem.getStartState()\n\n queue = util.PriorityQueue()\n parent = {}\n distance = {}\n\n queue.push(startState, 0 + heuristic(startState, problem))\n distance[startState] = 0\n\n while not queue.isEmpty():\n\n parentState = queue.pop()\n\n if problem.isGoalState(parentState):\n goalState = parentState\n break\n\n successorList = problem.getSuccessors(parentState)\n for currentStateInfo in successorList:\n currentState = currentStateInfo[0]\n currentStateCost = currentStateInfo[2]\n\n if currentState not in distance.keys():\n distance[currentState] = distance[parentState] + currentStateCost\n parent[currentState] = [parentState]\n parent[currentState] += currentStateInfo\n queue.push(currentState,heuristic(currentState, problem))\n\n\n moves = []\n while True:\n if goalState is startState:\n break\n\n parentState = parent[goalState]\n\n goalState = parentState[0]\n moves.append(parentState[2])\n\n moves.reverse()\n # print(moves)\n return moves",
"title": ""
},
{
"docid": "a6118e45a28f86e422f0c79011cec382",
"score": "0.62059385",
"text": "def test_weights_single_shortest_path(self): \n edges = self.context.frame.create(\n [(0,1,3), (0, 2, 2),\n (0, 3, 6), (0, 4, 4),\n (1, 3, 5), (1, 5, 5),\n (2, 4, 1), (3, 4, 2),\n (3, 5, 1), (4, 5, 4)],\n [\"src\", \"dst\", \"weights\"])\n vertices = self.context.frame.create([[0], [1], [2], [3], [4], [5]], [\"id\"])\n graph = self.context.graph.create(vertices, edges)\n\n #validate centrality values\n result_frame = graph.closeness_centrality(\"weights\", False)\n result = result_frame.to_pandas()\n expected_values = {0 : 0.238,\n 1: 0.176,\n 2: 0.333,\n 3: 0.667,\n 4: 0.25,\n 5: 0.0}\n self._validate_result(result, expected_values)",
"title": ""
},
{
"docid": "29c7707fbbb5287f01dfb6b2725a4191",
"score": "0.6202098",
"text": "def AStar_search(problem, heuristic=nullHeuristic):\n\n node=Node(problem.start_node, None, 0, None, 0)\n frontier = util.PriorityQueue()\n frontier.push(node, 0)\n explored = set([])\n while True:\n if frontier.isEmpty():\n return False\n node = frontier.pop()\n if (problem.isGoalState(node.state)):\n path = []\n n=node\n while True:\n path = [n.state]+path\n if n.state == problem.start_node:\n break\n n = n.parent_node\n return path\n if node.state in explored:\n continue\n explored.add(node.state)\n successors = problem.getSuccessors(node.state)\n for successor in successors:\n if(successor[0] not in explored):\n cnode=Node(successor[0], successor[1], node.path_cost+successor[2], node, node.depth+1)\n frontier.push(cnode , cnode.path_cost+ heuristic(cnode.state, problem))",
"title": ""
},
{
"docid": "b6829b8eb70b6dbac23cc1d19d6b9f44",
"score": "0.61849886",
"text": "def shortestPath(graph, start, end, _print = False):\n return DFS(graph, start, end, [], None, _print)",
"title": ""
},
{
"docid": "06767fb488c5b946410f383b352bf7e0",
"score": "0.6177424",
"text": "def astar_tree_search(problem, h):\n def f(n):\n return n.path_cost + h(n)\n return best_first_tree_search(problem, f)",
"title": ""
},
{
"docid": "67c53a6831bee8f2a94a0ef842031c15",
"score": "0.61762226",
"text": "def dijkstra(graph, s):\n\n def get_smallest_greedy(node):\n \"\"\"Given a starting node, return a 3-tuple containng the lowest\n greedy score, node, and the corresponding neighboring node among s's\n non-visited neighbors\n \"\"\"\n smallest_greedy = None\n for edge in (x for x in graph[node] if x[0] not in visited):\n neighbor, weight = edge\n greedy_score = A[node-1] + weight\n print(\"Edge {} has greedy score {}\".format(edge, greedy_score))\n if smallest_greedy is None or greedy_score < smallest_greedy[0]:\n smallest_greedy = (greedy_score, node, neighbor)\n return smallest_greedy\n\n def get_unvisited_neighbors(node):\n \"\"\"Given a node, return a list of the node's unvisited neighbors\"\"\"\n l = [\n edge[0]\n for edge in graph[node]\n if edge[0] not in visited\n ]\n print(\"In get_unvisited_neighbors: about to return {}\".format(l))\n return l\n\n A = [1000000 for _ in range(len(graph))] # Computed shortest distances\n A[s-1] = 0 # Distance from s to s is 0; subtract 1 for zero-based index\n B = [[] for _ in range(len(graph))]\n visited = set([s]) # Nodes processed so far\n heap = []\n\n # for neighbor in get_unvisited_neighbors(s):\n # smallest_greedy = get_smallest_greedy(neighbor)\n # if smallest_greedy:\n # h.heappush(heap, smallest_greedy)\n print(\"Value of B before while loop {}\".format(B))\n while heap:\n # Among all edges (v,w) with v member of x, w not a member of x,\n # pick one that minimizes a[v-1] + length from v to w\n # (Dijstra's greedy criterion)\n\n while True:\n print(\"Heap: {}\".format(heap))\n greedy_score, v, w = h.heappop(heap)\n if w in visited:\n # Recalculate greedy_score and put back in heap\n h.heappush(heap, get_smallest_greedy(v))\n else:\n break\n visited.add(w)\n A[w-1] = greedy_score\n for neighbor in get_unvisited_neighbors(w):\n smallest_greedy = get_smallest_greedy(neighbor)\n if smallest_greedy:\n h.heappush(heap, smallest_greedy)\n\n # print(\"Value of B before append: {}\".format(B))\n # print(\"Value of B[w-1]: {}\".format(B[w-1]))\n # print(\"Value of B[v-1]: {}\".format(B[v-1]))\n # print(\"Value of w: {}\".format(w))\n # print(\"Value of B[v-1].append(w): {}\".format(B[v-1].append(w)))\n B[w-1] = B[v-1] + [w]\n # print(\"Value of B after append: {}\".format(B))\n\n return A",
"title": ""
},
{
"docid": "7f19970b39dfc01593c8c29db02bf92a",
"score": "0.61660033",
"text": "def shortest_hamilton(paths: List[List[int]], adj_mat: List[List[float]]) -> Tuple[List[int], float, int]:\n shortest_time = math.inf\n shortest_path = None\n cpt=1\n \n def path_length(path: List[int]) -> float:\n \"\"\"\n Sub-function which returns the length of a path\n\n Parameters\n ----------\n path : List[int]\n the path described as a list of integers (representing the rooms).\n\n Returns\n -------\n float\n length in seconds/centimeters.\n\n \"\"\"\n length = 0\n for i in range(len(path)-1):\n length += adj_mat[path[i]][path[i+1]]\n return length\n \n for path in paths:\n path_len = path_length(path)\n if path_len < shortest_time:\n shortest_time = path_len\n shortest_path = path\n cpt=1\n if path_len == shortest_time:\n cpt+=1\n \n return shortest_path, shortest_time, cpt",
"title": ""
},
{
"docid": "e4efb5f0cb556b71e597af47c5c0d31a",
"score": "0.6165086",
"text": "def A_star(self, heuristic):\n # A list that store a object with the nodes and its heuristic weight\n to_visit_nodes = [\n {'weight': self.__head.depth, 'node': self.__head}\n ]\n # Node that solves the problem\n node = self.__head\n\n # Search in tree by node that solves the problem while there are nodes\n # to visit or the tree size is greater than maximum defined\n while len(to_visit_nodes) > 0 and self.size < self.MAX_SIZE:\n # Get the first node in the to_visit_nodes array\n current_node = to_visit_nodes.pop(0)['node']\n # Make copy of initial board\n board = copy.deepcopy(self.__initial_board)\n\n # Execute node movement in initial board\n for movement in current_node.value:\n board.move(movement)\n\n # Returs if the node commands achieves the goal\n if board.is_goal_achieved():\n node = current_node\n self.__initial_board = copy.deepcopy(board)\n break\n\n # If the node commands doesn't achieve the goal\n # add node available movements as it childrens\n # and add it to the begin of to_visit_nodes\n for movement in board.available_movements():\n if not self.__is_inverse(current_node, movement):\n new_node = self.insert_node(current_node, movement)\n heuristic_value = heuristic(board) + new_node.depth\n # Add object with node and it weight to to_visit_nodes list\n to_visit_nodes.insert(\n 0, {'weight': heuristic_value, 'node': new_node}\n )\n # Sort to_visit_nodes list to keep the minimum weight \n # as the first position list\n to_visit_nodes.sort(key=lambda x: x['weight'])\n\n return node.value",
"title": ""
},
{
"docid": "5090acbc869fc4c387f90538b8f3edb3",
"score": "0.6159175",
"text": "def single_source_dijkstra_path_length(G, source, weight= 'weight', target_cutoffs=[], only_targets=False):\r\n #print \"Target cutoffs:\", target_cutoffs\r\n dist = {} # dictionary of final distances\r\n\tfinal_dist ={}\r\n target_cutoffs = set(target_cutoffs)\r\n\r\n if source in target_cutoffs:\r\n target_cutoffs.remove(source)\r\n seen = {source:0}\r\n fringe=[] # use heapq with (distance,label) tuples\r\n heapq.heappush(fringe,(0,source))\r\n while fringe:\r\n (d,v)=heapq.heappop(fringe)\r\n\r\n if v in dist:\r\n continue # already searched this node.\r\n\r\n dist[v] = d\r\n if v in target_cutoffs:\r\n target_cutoffs.remove(v)\r\n\t\t\tfinal_dist[v] = d\r\n if not target_cutoffs:\r\n #print dist\r\n return final_dist if only_targets else dist\r\n\r\n #for ignore,w,edgedata in G.edges_iter(v,data=True):\r\n #is about 30% slower than the following\r\n edata=iter(G[v].items())\r\n\r\n for w,edgedata in edata:\r\n vw_dist = dist[v] + edgedata.get(weight,1)\r\n\r\n if w not in seen or vw_dist < seen[w]:\r\n seen[w] = vw_dist\r\n heapq.heappush(fringe,(vw_dist,w))\r\n if target_cutoffs:\r\n raise ValueError(\"There are still target cutoffs:\", str(target_cutoffs))\r\n return dist",
"title": ""
},
{
"docid": "865b40afa3cb91c1dbc352d15304310c",
"score": "0.61520076",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n \"*** YOUR CODE HERE ***\"\n \n aVisitar = util.PriorityQueue()\n visitats = []\n direccions = []\n costTotal = 0\n prediccio = 0+heuristic(problem.getStartState(), problem)\n # ((3,4), [west, south], 54) ()\n # (on soc, camí absolut, cost mínim per arribar)\n # Node = (Coordenades, Path, Prediction)\n startNode = (problem.getStartState(), direccions, costTotal) #a cada node guardem TOTA la llista de direccions i tots els pares dels que venim, aixi quan trobem el node de desti nomes hem de retornar les direccions del mateix node.\n \n aVisitar.push(startNode, prediccio)\n \n while not aVisitar.isEmpty():\n \n nodeCoord, direccions, costRecorregut = aVisitar.pop()\n \n if problem.isGoalState(nodeCoord):\n return direccions\n \n if nodeCoord in visitats: continue\n \n visitats.append(nodeCoord)\n \n for fillCoord, direccio, cost in problem.getSuccessors(nodeCoord):\n if fillCoord not in visitats:\n newNode = (fillCoord, direccions+[direccio],costRecorregut+cost) #es guarden dins de cada node\n aVisitar.push(newNode, costRecorregut + cost + heuristic(fillCoord,problem))",
"title": ""
},
{
"docid": "46d585b7188e237a79f068f17471e72a",
"score": "0.6150554",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n\n # class to represent SearchNode\n class SearchNode:\n \"\"\"\n Creates node: <state, action, f(s), g(s), h(s), parent_node>\n \"\"\"\n def __init__(self, state, action=None, g=None, h=None,\n parent=None):\n self.state = state\n self.action = action\n self.parent = parent\n # heuristic value\n self.h = h\n # combined cost\n if parent:\n self.g = g + parent.g\n else:\n self.g = 0\n # evaluation function value\n self.f = self.g + self.h\n\n def extract_solution(self):\n \"\"\" Gets complete path from goal state to parent node \"\"\"\n action_path = []\n search_node = self\n while search_node:\n if search_node.action:\n action_path.append(search_node.action)\n search_node = search_node.parent\n return list(reversed(action_path))\n\n\n # make search node function\n def make_search_node(state, action=None, cost=None, parent=None):\n if hasattr(problem, 'heuristicInfo'):\n if parent:\n # same parent - avoid re-calculation\n # for reducing computations in logic\n if parent == problem.heuristicInfo[\"parent\"]:\n problem.heuristicInfo[\"sameParent\"] = True\n else:\n problem.heuristicInfo[\"sameParent\"] = False\n # adding parent info for reducing computations\n problem.heuristicInfo[\"parent\"] = parent\n # get heuristic value\n h_value = heuristic(state, problem)\n return SearchNode(state, action, cost, h_value, parent)\n\n # create open list\n open = util.PriorityQueue()\n node = make_search_node(problem.getStartState())\n open.push(node, node.f)\n closed = set()\n best_g = {} # maps states to numbers\n\n # run until open list is empty\n while not open.isEmpty():\n node = open.pop() # pop-min\n\n if node.state not in closed or node.g < best_g[node.state]:\n closed.add(node.state)\n best_g[node.state] = node.g\n\n # goal-test\n if problem.isGoalState(node.state):\n return node.extract_solution()\n\n # expand node\n successors = problem.getSuccessors(node.state)\n for succ in successors:\n child_node = make_search_node(succ[0],succ[1],succ[2], node)\n if child_node.h < float(\"inf\"):\n open.push(child_node, child_node.f)\n\n # no solution\n util.raiseNotDefined()",
"title": ""
},
{
"docid": "3308af318d31d6a27abe770106d000eb",
"score": "0.61470634",
"text": "def shortestPath(graph, u, v, k):\n V = 4\n if k == 0 and u == v:\n return 0\n if k <= 0:\n return INF\n if k == 1 and graph[u][v] != INF:\n return graph[u][v]\n result = INF\n for i in range(0, V):\n if graph[u][i] != INF and u != i and v != i:\n rec_res = shortestPath(graph, i, v, k - 1)\n if rec_res != INF:\n result = min(result, graph[u][i] + rec_res)\n return result",
"title": ""
},
{
"docid": "4b40051a811f8d270806fa0c6a2a2420",
"score": "0.61315674",
"text": "def astar_search_graph(problem, h=None):\n h = memoize(h or problem.h, 'h')\n iterations, all_node_colors, node, all_node_f = best_first_graph_search_for_vis(problem,\n lambda n: n.path_cost + h(n))\n return(iterations, all_node_colors, node, all_node_f)",
"title": ""
},
{
"docid": "0f38a0f2989551d3760c1aaa8dbf0db6",
"score": "0.6129433",
"text": "def shortest_path(graph: Dict[str, List[str]], start_node: str, end_node: str\n ) -> List[str]:\n dest_src = shortest_path_bfs(graph, start_node, end_node)\n return build_path(dest_src, start_node, end_node)",
"title": ""
},
{
"docid": "e267a7932a21d5c8e55c11d00843b9d5",
"score": "0.6125924",
"text": "def shortest_path(S, neighbours, D_cond):\n Q = PriorityQueue()\n Q.put((0, S))\n seen = set()\n d = defaultdict(lambda: np.inf)\n d[S] = 0\n\n while not Q.empty():\n vd, v = Q.get()\n if D_cond(v):\n return vd\n seen.add(v)\n\n for neigh, cost in neighbours(v):\n if neigh in seen: continue\n nd = vd + cost\n if nd < d[neigh]:\n d[neigh] = nd\n Q.put((nd, neigh))\n\n return -1",
"title": ""
},
{
"docid": "f189fc4c18170af77b4c1bb7d2e4ff2c",
"score": "0.6122015",
"text": "def dijkstra(graph, src, dest, visited, distances, predecessors):\n # ending condition\n if src == dest:\n # We build the shortest path and display it\n path = []\n pred = dest\n while pred != None:\n path.append(pred)\n pred = predecessors.get(pred, None)\n # reverses the array, to display the path nicely\n path.pop()\n path.reverse()\n return path\n\n else:\n # if it is the initial run, initializes the cost\n if not visited:\n distances[src] = 0\n # visit the neighbors\n for neighbor in graph[src]:\n if neighbor not in visited:\n new_distance = distances[src] + graph[src][neighbor]\n if new_distance < distances.get(neighbor, float('inf')):\n distances[neighbor] = new_distance\n predecessors[neighbor] = src\n # mark as visited\n visited.append(src)\n # now that all neighbors have been visited: recurse\n # select the non visited node with lowest distance 'x'\n # run Dijskstra with src='x'\n unvisited = {}\n for k in graph:\n if k not in visited:\n unvisited[k] = distances.get(k, float('inf'))\n x = min(unvisited, key=unvisited.get)\n return dijkstra(graph, x, dest, visited, distances, predecessors)",
"title": ""
},
{
"docid": "8eb34bdbddd13c3491d571312d1531ec",
"score": "0.61158985",
"text": "def get_shortest_paths(self, node_i, node_j):\n try:\n node_i = self.node_labels_map[node_i]\n except:\n pass\n try:\n node_j = self.node_labels_map[node_j]\n except:\n pass\n # paths to self\n if node_i==node_j:\n return (0,1)\n # path to different nodes\n steps = 1\n a = b = self.adjacency_matrix.toarray()\n while steps<a.shape[0]:\n if b[node_i,node_j] > 0:\n return (steps, int(b[node_i,node_j]))\n b = b@a\n steps+=1\n\n return (np.Inf, 0)",
"title": ""
},
{
"docid": "9231aed3696f16fa5509e5d371266454",
"score": "0.61128074",
"text": "def ShortestPath(graphLosses: {int: {int}}, Armada: int) -> {int:int}:\n inTree, parent, distance = DijkstraTable(graphLosses, Armada)\n playersLeft = {k:v for k, v in distance.items()} # Players that not yet been choosen\n\n while True:\n # Determine next player arbitrarily\n nextPlayer = min(playersLeft, key = playersLeft.get)\n if playersLeft[nextPlayer] == float('inf'):\n break\n del playersLeft[nextPlayer]\n inTree[nextPlayer] = True\n \n for playerLosses in graphLosses[nextPlayer]:\n if (distance[nextPlayer] + 1) < distance[playerLosses]:\n distance[playerLosses] = distance[nextPlayer] + 1\n playersLeft[playerLosses] = distance[playerLosses]\n parent[playerLosses] = nextPlayer\n return parent, distance",
"title": ""
},
{
"docid": "2cc3b1f0edfcda7db8d49ddd21c9e1b2",
"score": "0.61109465",
"text": "def dag_longest_path(G, weight='weight', default_weight=1):\n dist = {} # stores {v : (length, u)}\n for v in networkx.topological_sort(G):\n us = [(dist[u][0] + data.get(weight, default_weight), u)\n for u, data in G.pred[v].items()]\n # Use the best predecessor if there is one and its distance is non-negative, otherwise terminate.\n maxu = max(us) if us else (0, v)\n dist[v] = maxu if maxu[0] >= 0 else (0, v)\n u = None\n v = max(dist, key=dist.get)\n path = []\n while u != v:\n path.append(v)\n u = v\n v = dist[v][1]\n path.reverse()\n return path",
"title": ""
},
{
"docid": "fecf9d48fb4f242cb4f7753fd7e01d35",
"score": "0.6110839",
"text": "def shortest_path( graph: Graph, startKey: str, endKey: str ) \\\r\n -> ( list, float ):\r\n remaining = PrioQ()\r\n for v in graph:\r\n if v.key == startKey:\r\n remaining.insert( v, 0 )\r\n else:\r\n remaining.insert( v )\r\n\r\n lowest = remaining.item()\r\n assert lowest.vtx.key == startKey\r\n\r\n while lowest.vtx.key != endKey:\r\n remaining.remove()\r\n if lowest.dist is None or remaining.is_empty(): # No way to get to end\r\n return [], -1\r\n thisDist = lowest.dist\r\n for u in lowest.vtx.get_connections():\r\n # Only do this if u is not final.\r\n u_ddata = remaining.get_ddata( u.key )\r\n if u_ddata is not None:\r\n newDist = thisDist + lowest.vtx.get_weight( u )\r\n if u_ddata.dist is None or newDist < u_ddata.dist:\r\n u_ddata.dist = newDist\r\n u_ddata.pred = lowest\r\n lowest = remaining.item()\r\n path = []\r\n if lowest.dist is None: # We found the end, but it never got connected.\r\n totalDistance = -1\r\n else:\r\n totalDistance = lowest.dist\r\n ddata = lowest\r\n while ddata is not None:\r\n path.insert( 0, ddata.vtx.key )\r\n ddata = ddata.pred\r\n\r\n return path, totalDistance",
"title": ""
},
{
"docid": "fb326a74d25cacce10cdbada622bece2",
"score": "0.61105686",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n #COMP90054 Task 1, Implement your A Star search algorithm here\n \"*** YOUR CODE HERE ***\"\n\n openList = util.PriorityQueue() # priority is f = g + h\n initialState = problem.getStartState()\n initialNode = (initialState, \"\", 0, [])\n openList.push(initialNode, initialNode[2] + heuristic(initialState, problem))\n closedList = set()\n bestG = dict() # maps each state to their corresponding best g\n\n while openList:\n node = openList.pop()\n state, action, cost, path = node\n\n # initiate an infinite g for unvisited states\n if state not in bestG:\n bestG[state] = INFINITY\n\n # when state is unvisited or re-open if there is a better g for state\n if state not in closedList or cost < bestG[state]:\n closedList.add(state)\n bestG[state] = cost # update state's best G\n\n # when goal is reached, break loop to return path\n if problem.isGoalState(state):\n path = path + [(state, action)]\n break\n\n # explore state's children\n succNodes = problem.expand(state)\n for succNode in succNodes:\n succState, succAction, succCost = succNode\n\n # if goal is reachable from succState, push to priority queue\n if heuristic(succState, problem) < INFINITY:\n newNode = (succState, succAction, cost + succCost, path + [(state, action)])\n openList.push(newNode, newNode[2] + heuristic(succState, problem))\n\n actions = [action[1] for action in path]\n del actions[0]\n\n return actions",
"title": ""
},
{
"docid": "96ad03c4a95b9d23c924079d86cd714a",
"score": "0.6107522",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n \"*** YOUR CODE HERE ***\"\n from util import PriorityQueue\n\n class Root:\n def __init__(self, position: tuple, path: list, cost: int) -> None:\n self.position = position\n self.path = path\n self.cost = cost\n\n def getPosition(self) -> tuple:\n return self.position\n\n def getPath(self) -> list:\n return self.path\n\n def getCost(self) -> int:\n return self.cost\n\n visited: set = set()\n rootsQueue: PriorityQueue = PriorityQueue()\n\n rootsQueue.push(Root(problem.getStartState(), [], 0),\n 0) # Push the initial root\n\n while not rootsQueue.isEmpty():\n currentNode: Root = rootsQueue.pop()\n\n if problem.isGoalState(currentNode.getPosition()):\n return currentNode.getPath().copy()\n\n if currentNode.getPosition() not in visited:\n visited.add(currentNode.getPosition())\n successors: list = problem.getSuccessors(currentNode.getPosition())\n for nextNode in successors:\n nextNodePostition: tuple = nextNode[0]\n if nextNodePostition not in visited:\n nextMove: str = nextNode[1]\n newPath: list = currentNode.getPath().copy()\n newPath.append(nextMove)\n newCost: int = problem.getCostOfActions(\n newPath) + heuristic(nextNodePostition, problem)\n if nextNodePostition not in visited:\n rootsQueue.push(\n Root(nextNodePostition, newPath, newCost), newCost)\n\n return []",
"title": ""
},
{
"docid": "d31f81a77eae673cbcf70cfe62eaf386",
"score": "0.61031836",
"text": "def dijkstra_search(graph, initial_node, dest_node):\r\n pass",
"title": ""
},
{
"docid": "1c2b4486fe21f653de48240e84e75c0d",
"score": "0.60928303",
"text": "def aStarSearch(problem, heuristic=nullHeuristic):\n # COMP90054 Task 1, Implement your A Star search algorithm here\n \"*** YOUR CODE HERE ***\"\n current = problem.getStartState()\n pq = util.PriorityQueue()\n pq.push((current, '', 0, []), 0)\n\n # we will reuse bestG as the closed set as well to save on memory\n bestG = dict()\n\n while not pq.isEmpty():\n state, action, cost, path = pq.pop()\n\n skip = state in bestG\n if skip:\n skip = cost >= bestG[state]\n\n if skip:\n continue\n\n bestG[state] = cost\n\n if problem.isGoalState(state):\n path = path + [(state, action)]\n break\n\n for succNode in problem.expand(state):\n succState, succAction, succCost = succNode\n newNode = (succState, succAction, cost +\n succCost, path + [(state, action)])\n h = heuristic(succState, problem)\n if h < float('inf'):\n pq.push(newNode, cost + succCost + h)\n\n actions = [action[1] for action in path]\n del actions[0]\n return actions",
"title": ""
},
{
"docid": "161109332002688b96f3ae44a9efb837",
"score": "0.6091422",
"text": "def shortest_path(digr, s):\r\n nodes_explored = [s]\r\n nodes_unexplored = DFS(digr, s)[1:] # all accessible nodes from s\r\n dist = {s:0}\r\n node_heap = []\r\n\r\n for n in nodes_unexplored:\r\n min = compute_min_dist(digr, n, nodes_explored, dist)\r\n heapq.heappush(node_heap, (min, n))\r\n\r\n while len(node_heap) > 0:\r\n min_dist, nearest_node = heapq.heappop(node_heap)\r\n dist[nearest_node] = min_dist\r\n nodes_explored.append(nearest_node)\r\n nodes_unexplored.remove(nearest_node)\r\n\r\n # recompute keys for just popped node\r\n for v in digr.neighbors(nearest_node):\r\n if v in nodes_unexplored:\r\n for i in range(len(node_heap)):\r\n if node_heap[i][1] == v:\r\n node_heap[i] = (compute_min_dist(digr, v, nodes_explored, dist), v)\r\n heapq.heapify(node_heap)\r\n\r\n return dist",
"title": ""
},
{
"docid": "2f94c299f446fd745834a866a2d4ee73",
"score": "0.60835236",
"text": "def dijkstra_search(graph, initial_node, dest_node):\n pass",
"title": ""
},
{
"docid": "921eab54db35be87dd92d8e57f5bfa55",
"score": "0.60811883",
"text": "def dijkstra_search_fill(graph, start):\n frontier = PriorityQueue()\n frontier.put(start, 0, 0, 0)\n came_from = {}\n cost_so_far = {}\n came_from[start] = None\n cost_so_far[start] = 0\n\n while not frontier.empty():\n current, current_priority = frontier.get()\n\n for next in graph.neighbors(current):\n new_cost = cost_so_far[current] + graph.cost(current, next)\n if next not in cost_so_far or new_cost < cost_so_far[next]:\n cost_so_far[next] = new_cost\n priority = new_cost\n frontier.put(next, priority, 0, priority)\n came_from[next] = current\n\n return came_from, cost_so_far",
"title": ""
},
{
"docid": "6f87af3030e787e478af19c93c7f84ca",
"score": "0.60807145",
"text": "def DFSJIT_KShortest(graph, start, target, K):\r\n def cost(u, v):\r\n return graph.edges[u,v][\"weight\"]\r\n\r\n def TS(u,v):\r\n return graph.edges[u, v][\"TS\"]\r\n\r\n lazyDijk = JITModifiedDijkstra(graph, start)\r\n\r\n def R(u,v,j,pre):\r\n if u == start:\r\n KPaths.append([(u,j),] + pre)\r\n\r\n for pred in graph.predecessors(u):\r\n ipred_upper = bisect_right(TS(pred, u), TS(u, v)[j]-cost(pred, u))-1\r\n ipred_lower = custom_bisect_left(TS(pred, u),pred,hi=ipred_upper+1, compare=lazyDijk.is_threshold_strictly_smaller_t_target)\r\n for i in range(ipred_lower,ipred_upper+1):\r\n R(pred, u, i, [(u,j),] + pre)\r\n\r\n if len(KPaths) == K: return #early stopping\r\n\r\n\r\n # gather candiates\r\n C = [(v,j) for v in graph.predecessors(target) for j in range(len(TS(v,target)))]\r\n\r\n # sort canidates\r\n C = sorted(C, key=lambda x: TS(x[0],target)[x[1]] + cost(x[0],target))\r\n # enumerate paths\r\n KPaths = []\r\n for x in C:\r\n if not lazyDijk.is_threshold_strictly_smaller_t_target(TS(x[0], target)[x[1]], x[0]):\r\n R(x[0], target, x[1], [])\r\n if len(KPaths) >= K: break\r\n\r\n return KPaths[:K], lazyDijk.Fin",
"title": ""
},
{
"docid": "dce74db7d61ebb158a4555c73f94750f",
"score": "0.6079356",
"text": "def dijkstra(self, initial):\n visited = {initial: 0}\n paths = {}\n\n nodes = set(self.nodes)\n\n while nodes:\n min_node = None\n for node in nodes:\n if node in visited:\n if min_node is None or visited[node] < visited[min_node]:\n min_node = node\n\n if min_node is None:\n break\n\n nodes.remove(min_node)\n current_weight = visited[min_node]\n\n for edge in self.edges[min_node]:\n try:\n weight = current_weight + self.distances[(min_node, edge)]\n except KeyError:\n continue\n if edge not in visited or weight < visited[edge]:\n visited[edge] = weight\n paths[edge] = min_node\n\n return visited, paths",
"title": ""
},
{
"docid": "be1c06f9aef5e133cf9c4513f74be225",
"score": "0.60782087",
"text": "def get_optimal_path(self, start: Tuple, goal: Tuple, distance_tolerance=.05) -> List[Tuple]:\n if self.display:\n print('Initializing Display')\n self.__init_display(start, goal)\n\n self.__build_tree(start)\n graph = self.__build_graph(self.vertices, self.edges)\n potential_goals = []\n for vertex in self.vertices: # find all vertices within 5m of goal\n if self.__euclidean_dist(vertex, goal) < distance_tolerance:\n potential_goals.append(vertex)\n\n path_queue = []\n for potential_goal in potential_goals: # find shortest path among potential goals\n path = networkx.shortest_path(graph, start, potential_goal, weight='weight')\n cost = networkx.path_weight(graph, path, weight='weight')\n heapq.heappush(path_queue, (cost, path))\n if len(path_queue) == 0:\n return []\n\n best_path = heapq.heappop(path_queue)[1]\n best_path = self.__add_heading_to_waypoints(best_path, start[2], goal[2])\n if self.display:\n self.__draw_optimal_path(best_path)\n return best_path",
"title": ""
},
{
"docid": "83436034572aba2c986140541cc86cd6",
"score": "0.60766315",
"text": "def a_star(self, heuristic):\n priority_queue = queue.PriorityQueue()\n visited = set()\n parent_cell = {}\n cost_so_far = {} # Cost from start to each cell\n\n # Put in que as tuple (priority, cell)\n priority_queue.put((0, self.start_position))\n visited.add(self.start_position)\n cost_so_far[self.start_position] = 0\n\n while not priority_queue.empty():\n current_cell = priority_queue.get()\n # Get the cell only, don't care about priority\n current_cell = current_cell[1]\n if current_cell == self.end_position:\n path = self.build_path(parent_cell)\n return {\"Status\": \"Found Path\", \"Visited cells\": visited,\n \"No of visited cells\": len(visited), \"Path\": path, \"Path length\": len(path)}\n\n for next_cell in self.a_map.connected_cells(current_cell):\n new_cost = cost_so_far[current_cell] + 1\n if next_cell not in visited:\n cost_so_far[next_cell] = new_cost\n parent_cell[next_cell] = current_cell\n visited.add(next_cell)\n\n priority = new_cost + self.find_heuristic(next_cell, heuristic)\n priority_queue.put((priority, next_cell))\n\n return {\"Status\": \"Path Not Found!!!\", \"Visited cells\": visited,\n \"No of visited cells\": len(visited), \"Path\": [], \"Path length\": \"N/A\"}",
"title": ""
},
{
"docid": "76e0282816b4404526a8218afd5b581d",
"score": "0.607352",
"text": "def shortest_path(self, start):\r\n dist = [sys.maxsize] * self.vertex_num\r\n dist[start] = 0\r\n pred = [None] * self.vertex_num\r\n q = []\r\n for v in range(self.vertex_num):\r\n heapq.heappush(q, (v, dist[v]))\r\n while not len(q) == 0:\r\n u = heapq.heappop(q)\r\n u = self.graph[u[0]].get_vertex()\r\n adjacent = self.graph[u].get_adjacent()\r\n for v in adjacent:\r\n if dist[u] + v[1] < dist[v[0]]:\r\n dist[v[0]] = dist[u] + v[1]\r\n for i in range(len(q)):\r\n if q[i][0] == v[0]:\r\n q[i] = (v[0], dist[u] + v[1])\r\n break\r\n pred[v[0]] = u\r\n # filter from dist\r\n return (dist, pred)",
"title": ""
}
] |
0de9fca772bfb65735c5d9615ad30b7f | store decoded instruction, prepare for next one | [{"docid":"32f9f6ffb70ceefd08ea42257e2ae3c0","score":"0.57765085","text":"def _save_instruction(self(...TRUNCATED) | [{"docid":"251672139dd55cedcb073d1046e8b9c9","score":"0.66286063","text":"def _decode(self):\n tr(...TRUNCATED) |
45a4339872939e50f1b9f5e7efc859c3 | Return the metadata of the requested table | [{"docid":"587eaf079abab28e435c2b2b70d0eb05","score":"0.67164326","text":"def table_info(request, na(...TRUNCATED) | [{"docid":"3fb576fc72d1a4763e97ad9a7ca78b31","score":"0.7701821","text":"def _metadata_table(self):\(...TRUNCATED) |
4a18047a82e15e9da2c85135e680c633 | Get the best ARIMA model. | [{"docid":"0282a9f33bdc11ac5c8b5843ba0d9963","score":"0.7164151","text":"def get_best_model(self):\n(...TRUNCATED) | [{"docid":"d8842cd0d2022b7bbda5c575f8abd437","score":"0.6984959","text":"def ARIMA_model(training_da(...TRUNCATED) |
ac4a70a179548769a54b4e8bcda2a33e | max Informationbased Nonparametric Exploration. | [{"docid":"e66a409de6378bd34be549f1e3ec9e89","score":"0.0","text":"def mic_test(self, inputs):\n (...TRUNCATED) | [{"docid":"b1786dfbdc9d9be4ed12f80d58b1acee","score":"0.6003945","text":"def _argmax(self, params, *(...TRUNCATED) |
e27c418436ca52894e43d72ed2eed4f1 | Computes the accuracy over the k top predictions for the specified values of k | [{"docid":"1fb344a00114e8ceae403851687e0b81","score":"0.7847017","text":"def accuracy(output, target(...TRUNCATED) | [{"docid":"092b204d6f194e96b85acc310eb7d8eb","score":"0.8249487","text":"def accuracy(output, target(...TRUNCATED) |
264d245dad9dd026a02a3524d8c95b3e | Kill the previously started Quixote server. | [{"docid":"ae941954f9eabbecaef43c4c42270d0b","score":"0.0","text":"def kill_server():\n global _s(...TRUNCATED) | [{"docid":"271d9573d0475ee33c60157648dadab6","score":"0.7437033","text":"def kill():\n return Ser(...TRUNCATED) |
870b64780dfa182edf12e4df39653c90 | Smooth the data with von Mises functions | [{"docid":"fdf5009c7e87693ef95b73de8a36878e","score":"0.632402","text":"def vonmises_smoothing(self,(...TRUNCATED) | [{"docid":"5babe5be0badb185409d0cd539883ea3","score":"0.5696802","text":"def smooth(values, dt, tau)(...TRUNCATED) |
e7b7cfb0d91468ec87cc607502d3d264 | Parse specification in the specification YAML file. | [{"docid":"1ddd55b5916bf21eab1a67ee8e2b71de","score":"0.7328811","text":"def read_specification(self(...TRUNCATED) | [{"docid":"427c032eef2b4c90af30cbfcb501e46f","score":"0.65131885","text":"def fileToSpec(file):\n\n (...TRUNCATED) |
cb0ddeca3dc7638e06e9b469917ee008 | Returns the string representation of the model | [{"docid":"0f283634439620e9ecd215d87804ec00","score":"0.0","text":"def to_str(self):\n return(...TRUNCATED) | [{"docid":"aa510b1d67cd504f00d31d7600881756","score":"0.8602374","text":"def _repr_model_(self):\n (...TRUNCATED) |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 100