def GetItemPath(self, item): path = [] while item.IsOk(): path.append(self._tree.GetPyData(item)) item = self._tree.GetItemParent(item) path.reverse() return path
def run_a_star(start,goal): #start and goal are in grid coordinates #Create the start node start_node = SearchNode(start, None, 0) #Compute it's heuristic value start_node_h = euclidean_distance_grid(start,goal) #Create Fringe fringe = Queue.PriorityQueue() #Insert start node into fringe priority = start_node.cost + start_node_h # Compute it's f-value fringe.put((priority, start_node)) # Add it to the fringe print 'Starting A* search from grid cell ', start_node.state, ' to goal cell ', goal print 'Starting f-value is ', start_node_h + start_node.cost #Run the A* search goal_node = a_star(fringe,goal) #Extract path from the goal_node and return it path = [] if goal_node is not None: print 'Found a solution!' cur_node = goal_node while cur_node is not None: path.append(cur_node.state) cur_node = cur_node.parent path.reverse() return path
def traverseContainer(self, container=None, path=None, url=None, queryDict=None): "used for the dynamic menu system" queryDict = queryDict or {} if path is None: path = self.getFixedUpPath() path.reverse() try: selected = path.pop() except IndexError: selected = None if url is None: url = self.absolute_url_path() if container is None: container = self.getOrigin() temp = [] if container is not None: containers = container.objectItems() containers = sorted((name, object) for name, object in containers if self.isOkay(name, object)) for name, object in containers: if name == selected: temp.append((os.path.join(url, name), name, 1, '', queryDict, '')) temp.append(self.traverseContainer(object, path, url=os.path.join(url, selected), queryDict=queryDict)) else: temp.append((os.path.join(url, name), name, 0, '', queryDict, '')) return temp
def _find_path(self, src, tgt): visited = set() to_visit = [src] came_from = {} while len(to_visit) > 0: elem = to_visit[0] del to_visit[0] if elem in visited: continue # if path found, redo path and return if elem is tgt and src in visited: # elem in visited for the case where src = tgt path = [] prev_elem = elem while prev_elem is not src: path.append(prev_elem) prev_elem = came_from[prev_elem] path.append(src) path.reverse() return path visited.add(elem) for outelem in elem.outset: came_from[outelem] = elem to_visit.append(outelem) return [] # if no path found, return an empty path
def reconstruct_path(came_from, start, goal): current = goal path = [current] while current != start: current = came_from[current] path.append(current) path.reverse() # optional return path
def addNodeByPath(self, path, name): path.reverse() root = self.getRoot() child = root.childNodes[path[0] + 1] print child for index in path[1:-1]: child = child.childNodes[index] print child
def addNodeByPath(self, path, name): path.reverse() root = self.getRoot() child = root.childNodes[path[0]+1] print child for index in path[1:-1]: child = child.childNodes[index] print child
def getPath(c, p): path = [ i.h[6:] for i in p.self_and_parents() if i.h[:6] in ('@path ', '@text ') ] path.append(g.getBaseDirectory(c)) path.reverse() return os.path.join(*path)
def _path(self, path): path.append(self) if self.parent is None: path.reverse() return path else: return self.parent._path(path)
def solve(grid, distances, keys, positions): best_length, _, _, path = find_shortest(distances, keys, positions, set(), []) print(best_length) path.reverse() for pos in path: print(grid[pos], end='') print()
def doCaseThree(): global a global q global destination destu = list() dicta = dict() nop = list() print( "\nSelect the destination router to find the shortes path from Source to Destnation:\n" ) #it checks the input, it should be an integer while True: try: destination = int( input("Please enter a valid router and an integer value \n")) except ValueError: print("Not an integer! Please enter a valid router ID") continue else: break #the input should be an existing router. q = len(dictionary_values) if destination < 1 or destination > q: print("Enter a valid router again by pressing the command 3") takeaction = { "3": doCaseThree, "5": doCaseFivepointone, "6": doCaseSix } command = input("Please Enter the command, choices -> 3 or 5 or 6: \n") takeaction.get(command, errtwohandler)() #Finding the minimum cost to the destination. destination1 = destination b = destination c = visitedNode[destination] print( "\nThe minimum cost from the source %s to the detination %s is equal to %s" % (a, b, c)) #Finding the shortest path to the destination. path = list() while 1: path.append(destination) if destination == a: break destination = nodeBefore[destination] path.reverse() destination = destination1 print( "\nThe shortest Path from the source %s to the detination %s is equal to %s" % (a, b, path)) #Once case3 is done, the available options are 4,5,6 takeaction = {"4": doCaseFour, "5": doCaseFivepointone, "6": doCaseSix} command = input("Please Enter the command: \n") takeaction.get(command, errS3handler)()
def getTreePath(item : QTreeWidgetItem, root : str): path = [] while item is not None: path.append(item.text(0)) item = item.parent() path.reverse() for f in path: root = os.path.join(root, f) return root
def get_path(self, sep=u'/', root=False): path = [] this = self while this is not None: path.append(this.get_name()) this = this.get_parent() if not root and len(path)>0: del path[-1] path.reverse() return sep + sep.join(path)
def getSolvePath(self, came_from): current = (self.endRow, self.endCol) start = (self.startRow, self.startCol) path = [] while not self.isSameGridElement(current, start): path.append(current) current = came_from[current] path.append(start) path.reverse() return path
def build_path(v, A): path = [v] n = A[v] while n != None: path.append(n) n = A[n] path.reverse() return path
def path(self, from_vertex, to_vertex): path = [] i = to_vertex path.append(i) while i in self.parents and i is not from_vertex: i = self.parents[i] path.append(i) if i is not from_vertex: raise NoDependencyPathFound(from_vertex, to_vertex) path.reverse() return path
def set_dirty(self, path): """Marks the requested leaf node as "dirty". Path is an iterable of integers representing the path to the leaf node that is requested to be marked as dirty. """ path = list(path) assert len(path) == self.depth path.reverse() self._set_dirty_helper(path)
def update_decision(self): print 'Evidence: ', self.evidence if self.AUItoggleButton.isChecked(): path = nx.shortest_path(self.hid, 'gui', self.node) parent = path.pop() path.reverse() for p in path: if self.key in self.hid.node[p]['evidence']: parent = p self.node = self.hid_decision(parent) self.decision.emit(self.node)
def shortest_path(self, x, y): d = self.dijkstra(x) path = [] i = y while i != x: path.append(i) i = d[i][1] path.append(x) path.reverse() return path, d[y][0]
def get_kppy_entry_path(cls, entry): """ Generate a full "path" for a keepass entry that includes titles for it and its parent group(s) :param entry: Which entry to process :return: String like {group}/{subgroup}/{entry} """ path = [entry.title] g = entry.group while (g): if g.title: path.append(g.title) g = g.parent path.reverse() return "/".join(path)
def get_layer_path(root,layer_id): path = [] for node in root.children(): if isinstance(node,QgsLayerTreeGroup): check = False (check,path) = UniumPlugin.rec_get_layer_path(node,layer_id,path) if check: path.append(root.name()) break elif isinstance(node,QgsLayerTreeLayer): if node.layerId() == layer_id: path.append(root.name()) path.reverse() return chr(92).join([p for p in path if len(p) > 0])
def _get_tree_path(self, item): """ Get item of parents. :param item: pytest.Item :return list of parents """ path = [item] parent = item.parent while parent is not None and not isinstance(parent, Session): if not isinstance(parent, Instance): path.append(parent) parent = parent.parent path.reverse() return path
def list(path=None): if path is None: path = dfltpath() path = [p for p in path] # because list() taken :-( path.reverse() ss = {} for base in path: try: names = os.listdir(base) except OSError: continue for name in names: if len(name) > 0 and name[0] != '.': ss[name] = base ks = ss.keys() ks.sort() return ks
def find_sub_tree(tree, basedir): """Return a subtree of the given tree Keyword arguments: tree -- the git.Tree root in which we look for the subtree basedir -- the path where the subtree is located """ path = basedir.split('/') if len(path) > 0: path.reverse() dirname = path.pop() path.reverse() for subtree in tree.trees: if subtree.name == dirname: return find_sub_tree(subtree, '/'.join(path)) logging.info("Using " + tree.name + " subdirectory") return tree
def _path_to_node(self, path): node = self.root path = filter(len, path.split('/')) path.reverse() if len(path) and path[-1] == '~trash': node = self.trash path.pop() try: while path: part = path.pop() node = node[part] except KeyError: return None return node
def create_output(current_node, path): out_file = "output{}-MINE.txt".format(TEST_NUMBER) file_output = open(out_file, 'w') if path == ['FAIL']: file_output.write('FAIL') else: path.pop(len(path) - 1) path.reverse() path.append(current_node) file_output.write(str(current_node[1])) file_output.write('\n' + str(len(path))) prev_cost = 0 for i in path: file_output.write( '\n' + str(i[0][0]) + ' ' + str(i[0][1]) + ' ' + str(i[0][2]) + ' ' + str(i[1] - prev_cost)) prev_cost = i[1] file_output.close()
def find_path(self, start, goal): for tile in MAP.tiles: tile.node.cost_so_far = 0 tile.node.in_path = 0 start.estimated_total_cost = start.cost_heuristic(goal) open = [start] closed = [] count = 0 while len(open) > 0: count += 1 current = open[0] if current == goal: break for neighbor in current.neighbors(): if neighbor in closed: if neighbor.cost_so_far <= current.cost_so_far + 1: continue #skip, we've already got a better path else: closed.remove( neighbor) #reopen the node, we can do better elif neighbor in open: if neighbor.cost_so_far <= current.cost_so_far + 1: continue #skip, we've already got a better path neighbor.cost_so_far = current.cost_so_far + 1 neighbor.estimated_total_cost = neighbor.cost_so_far + neighbor.cost_heuristic( goal) neighbor.parent = current if not neighbor in open: heappush(open, neighbor) heappop(open) #we're done with current, remove it from top of heap closed.append(current) #when we have exausted the open list, we've got the goal path = [] while not current == start: #This breaks if I do while current != start. Weird path.append(current) current.in_path = True current = current.parent path.reverse() return path
def mysearch2(self, start, goal): # finds shortest path between nodes path = [] visited = [] predecessor = {} length = 0 visit_queue = collections.deque() visit_queue.appendleft(start) length += 1 next = visit_queue.pop() length -= 1 while next != goal and length > -1: visited.append(next) successors = [ x for x in self.get_first_degree_relatives(next) if x not in visited + list(collections.deque(visit_queue)) ] visit_queue.extendleft(successors) length += len(successors) for s in successors: predecessor[s] = next if length > 0: next = visit_queue.pop() else: return [] length -= 1 path.append(next) found = copy.deepcopy(next) while next in predecessor: path.append(predecessor[next]) next = predecessor[next] path.reverse() return path
def path(self): path = [self.filename] parent = self.parent while parent: path.append(parent.filename) parent = parent.parent path.reverse() if len(path) > 1: full_path = os.path.join(*path) else: full_path = path[0] if not full_path.startswith("/"): full_path = "/" + full_path return full_path
def locate(tag): ''' Locate the DO in the tree. Return absolute path as tuple. ''' try: # Get from cache return _cached_path[tag] except KeyError: # Not cached yet path = search_in_tree(DOtree, tag) if path: # The last result is in reversed order path.reverse() # No more manipulation on the list, change to tuple to save memory. path = tuple(path) # Add to cache _cached_path[tag] = path return path else: return False
def find_path(self, start, goal): for tile in MAP.tiles: tile.node.cost_so_far = 0 tile.node.in_path = 0 start.estimated_total_cost = start.cost_heuristic(goal) open = [start] closed = [] count = 0 while len(open) > 0: count += 1 current = open[0] if current == goal: break for neighbor in current.neighbors(): if neighbor in closed: if neighbor.cost_so_far <= current.cost_so_far + 1: continue #skip, we've already got a better path else: closed.remove(neighbor) #reopen the node, we can do better elif neighbor in open: if neighbor.cost_so_far <= current.cost_so_far + 1: continue #skip, we've already got a better path neighbor.cost_so_far = current.cost_so_far + 1 neighbor.estimated_total_cost = neighbor.cost_so_far + neighbor.cost_heuristic(goal) neighbor.parent = current if not neighbor in open: heappush(open, neighbor) heappop(open) #we're done with current, remove it from top of heap closed.append(current) #when we have exausted the open list, we've got the goal path = [] while not current == start: #This breaks if I do while current != start. Weird path.append(current) current.in_path = True current = current.parent path.reverse() return path
def finish_suites(self): """ Finish all suites in run with status calculations. If an execution passes in multiprocessing mode we don't know which and how many items will be passed to our process. Because of that we don't finish suites until the very last step. And after that we finish them at once. """ # Ensure there is no running items while len(self._get_items(ExecStatus.IN_PROGRESS)) > 0: sleep(0.1) skipped_items = self._get_items(ExecStatus.CREATED) for item in skipped_items: path = list(self._tree_path[item]) path.reverse() for leaf in path[1:-1]: if leaf['exec'] == ExecStatus.IN_PROGRESS: self._lock(leaf, lambda p: self._proceed_suite_finish(p))
def findPath(self, start, finish): """ Uses A* algorithm to find the shortest path from start to finish Code was copied from: https://www.redblobgames.com/pathfinding/a-star/introduction.html""" frontier = PriorityQueue() frontier.put(start, 0) came_from = {} cost_so_far = {} came_from[start] = None cost_so_far[start] = 0 while not frontier.empty(): current = frontier.get() if current == finish: break for nextCell in self.neighbours(current): new_cost = cost_so_far[current] + nextCell.cost if nextCell not in cost_so_far or new_cost < cost_so_far[nextCell]: cost_so_far[nextCell] = new_cost priority = new_cost + heuristic(finish, nextCell) frontier.put(nextCell, priority) came_from[nextCell] = current # reconstruct the path current = finish path = [] try: while current != start: path.append(current) current = came_from[current] except KeyError: # if there is no path found, just return the start return Path([start]) path.append(start) path.reverse() return Path(path)
def LC(n, s, t, C): # process data get the node without inf children = [[] for i in range(n)] g = [] for i in range(n): g.append((np.inf, i)) for j in range(n): if C[i, j] < np.inf: children[i].append(j) # start node and OPEN g[s] = (0, s) OPEN = Queue() OPEN.put((0, s)) parent = [0] * n g_cost = [0] * n node = [0] * n # LC while not OPEN.empty(): i = OPEN.get() for j in children[i]: if g[i][0] + C[i, j] < g[j][0] and g[i][0] + C[i, j] < g[t][0]: g[j] = (g[i][0] + C[i, j], j) parent[j] = i g_cost[j] = g[i][0] + C[i, j] node[j] = j if j != t: OPEN.put(g[j]) path = [] cost = [] current = t while current != s: path.append(node[current]) cost.append(g_cost[current]) current = parent[current] path.append(s) cost.append(0.0) path.reverse() return [path, cost]
def traverseContainer(self, container=None, path=None, url=None, queryDict=None): "used for the dynamic menu system" queryDict = queryDict or {} if path is None: path = self.getFixedUpPath() path.reverse() try: selected = path.pop() except IndexError: selected = None if url is None: url = self.absolute_url_path() if container is None: container = self.getOrigin() temp = [] if container is not None: containers = container.objectItems() containers = sorted((name, object) for name, object in containers if self.isOkay(name, object)) for name, object in containers: if name == selected: temp.append( (os.path.join(url, name), name, 1, '', queryDict, '')) temp.append( self.traverseContainer(object, path, url=os.path.join(url, selected), queryDict=queryDict)) else: temp.append( (os.path.join(url, name), name, 0, '', queryDict, '')) return temp
def gw_path(mesh, start, end): for node in mesh.nodes(): node.parent = None queue = Queue() queue.put(start) start.parent = start while not queue.empty(): node = queue.get() if node == end: eprint('{} reached'.format(node.hostname)) path = [ node ] while node.parent != node: path.append(node.parent) node = node.parent path.reverse() return path for neighbour in node.neighbours(): if not neighbour.parent: neighbour.parent = node queue.put(neighbour) return None
def A_star(start, goal, MyWorld): # frontier of points that havent been searched frontier = PriorityQueue() # put a point in frontier frontier.put(start, 0) # dictionary of squares that other squares came from came_from = {} came_from[start] = None cost_so_far = {} cost_so_far[start] = 0 while not frontier.empty(): current = frontier.get() print("Searching {0}".format(current)) # If the place we are at is the goal end the search if current == goal: break # Search for each point that is next to current for next in MyWorld.neighbors(current): new_cost = cost_so_far[current] + distance( current, next) + angle_cost(came_from[current], current, next) if new_cost < cost_so_far.get(next, math.inf): cost_so_far[next] = new_cost priority = new_cost + distance(next, goal) frontier.put(next, priority) came_from[next] = current # Find the path from the start to end current = goal path = [] while current != start: print("Current: {0}".format(current)) path.append(current) current = came_from[current] path.append(start) path.reverse() return path
def doCaseFour(): global notVisited global a global destination global q global newlis qrt = list() newton = 0 rajton = 0 print("\nPlease, select a Router to be Removed.") #the input should be an integer while True: try: down_router = int( input("Please enter a valid router - an integer value\n")) except ValueError: print("Not an integer! Please enter a valid router ID") continue else: break #The router should be a valid and existing router. q = len(dictionary_values) if down_router < 1 or down_router > q: print("Enter valid Router") takeaction = {"4": doCaseFour, "5": doCaseFivepointone, "6": doCaseSix} command = input("Please Enter the command, choice -> 4 or 5 or 6: \n") takeaction.get(command, errS3handler)() #downs the router downminusone = down_router - 1 for i in range(len(graphical_representaion)): matrix = {} for j in range(len(graphical_representaion)): if i != j != downminusone and i != j and graphical_representaion[ i][j] != -1: matrix[j + 1] = graphical_representaion[i][j] dictionary_values[i + 1] = matrix del dictionary_values[down_router] del node_edge[downminusone] #a case if deleting router was the start node. We will perform doSteptwo again. if down_router == a: while True: try: a = int( input( "Enter new start node again as removed node was the start node \n" )) except ValueError: print("Not an integer! Enter a valid router ID") else: break dijkstra(a) print("\nRouter %s Connection Table:" % a) print("\n\tDestination \tInterface") print("==================================") for key in nodes_dict: print(key, "\t\t", nodes_dict[key]) #if the deleted node is the destination node. path = [] destination2 = destination if down_router == destination: print("\nSelect the destination router:") while True: try: destination = int( input( "Enter a new destination node again as removed node was the destination node \n" )) destination2 = destination except ValueError: print("Not an integer! Enter a valid router ID") else: break while 1: path.append(destination) if destination == a: break destination = nodeBefore[destination] path.reverse() destination = destination2 print("The new shortest distance to destination is ", visitedNode[destination]) print("The new shortest path is ", path) newlis = list() #available options for key, value in dictionary_values.items(): newlis.append(key) takeaction = {"5": doCaseFivepointtwo, "6": doCaseSix} command = input("Please Enter the command: \n") takeaction.get(command, err5handler)()
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # # main if __name__ == "__main__": # re-create the PYTHONPATH at 'configure' time import os.path, sys, site path = '@PYTHONPATH@'.split(':') path.reverse() for directory in path: if directory: directory = os.path.abspath(directory) sys.path.insert(1, directory) site.addsitedir(directory) # if we are embedding, insert the extension module in the # 'lithomop3d' package try: import builtin_lithomop3d sys.modules['lithomop3d.lithomop3d'] = builtin_lithomop3d except ImportError: pass from lithomop3d.Application import Application
def _reverse(path): path = strip_ext(path).split(os.path.sep) path.reverse() return path
def search(goal, init, map_array): grid = np.asarray(map_array) grid = grid.transpose() grid = list(grid) heuristic = [[[0 for x in range(len(grid[0][0]))] for y in range(len(grid[0]))] for z in range(len(grid))] delta = [[-1, 0, 0], # zuruck [ 0,-1, 0], # links [ 1, 0, 0], # vor [ 0, 1, 0], # rechts [ 0, 0,-1], # unten [ 0, 0, 1]] # oben cost = 1 start = time.clock() heuristic = calcheuristic(grid,goal,heuristic) print('Calcheuristic: %0.3fs' % (time.clock() - start)) closed = [[[0 for x in range(len(grid[0][0]))] for y in range(len(grid[0]))] for z in range(len(grid))] closed[init[0]][init[1]][init[2]] = 1 expand = [[[-1 for x in range(len(grid[0][0]))] for y in range(len(grid[0]))] for z in range(len(grid))] action = [[[-1 for x in range(len(grid[0][0]))] for y in range(len(grid[0]))] for z in range(len(grid))] x = init[0] y = init[1] z = init[2] g = 0 h = heuristic[z][y][x] f = g+h open = [[f, g, x, y, z]] found = False # flag that is set when search is complete resign = False # flag set if we can't find expand count = 0 while not found and not resign: if len(open) == 0: resign = True return "Fail" else: open.sort() open.reverse() next = open.pop() x = next[2] y = next[3] z = next[4] g = next[1] f = next[0] expand[z][y][x] = count count += 1 if x == goal[0] and y == goal[1] and z == goal[2]: found = True else: for i in range(len(delta)): x2 = x + delta[i][0] y2 = y + delta[i][1] z2 = z + delta[i][2] if z2 >= 0 and z2 < len(grid) and \ y2 >=0 and y2 < len(grid[0]) and \ x2 >=0 and x2 < len(grid[0][0]): if closed[z2][y2][x2] == 0 and grid[z2][y2][x2] == 0: g2 = g + cost f2 = g2 + heuristic[z2][y2][x2] open.append([f2, g2, x2, y2, z2]) closed[z2][y2][x2] = 1 # Memorize the sucessfull action for path planning action[z2][y2][x2] = i path=[] path.append([goal[0], goal[1], goal[2]]) while x != init[0] or y != init[1] or z != init[2]: x2 = x-delta[action[z][y][x]][0] y2 = y-delta[action[z][y][x]][1] z2 = z-delta[action[z][y][x]][2] #policy[x2][y2][z2]=delta_name[action[x][y][z]] x = x2 y = y2 z = z2 # Path path.append([x2, y2, z2]) #print('\nCoordinates for Path smoothing=') path.reverse() spath=smooth(path) return path
def getPath(c,p): path = [i.headString()[6:] for i in p.self_and_parents_iter() if i.headString()[:6] in ('@path ', '@text ')] path.append(g.getBaseDirectory(c)) path.reverse() return os.path.join(*path)
def getPath(c, p): path = [i.h[6:] for i in p.self_and_parents() if i.h[:6] in ("@path ", "@text ")] path.append(g.getBaseDirectory(c)) path.reverse() return os.path.join(*path)