def findThickestPathLateral(self, skelImg, skelDia, xScale, yScale): print 'create skeleton graph' skelGraph, _ = self.makeGraphFast(skelImg, skelDia, xScale, yScale) rootVertex = self.findRootVertexLateral(skelGraph) epropW = skelGraph.edge_properties["w"] path = [] #remove all two-connected ones with 0 label print 'trace path of thickest diameter' #find thickest path pathDetect = True if skelGraph.num_vertices() > 0: pathDetect = True while pathDetect == True: lastVertex = self.findLastRootVertex(skelGraph) try: path, _ = gt.shortest_path(skelGraph, rootVertex, lastVertex, weights=epropW, pred_map=None) pathDetect = False except: raise if lastVertex <= 0: pathDetect = False else: skelGraph.remove_vertex(lastVertex) lastVertex = self.findLastRootVertex(skelGraph) return path, skelGraph
def get_shortest_path(self, start_key, end_key, key_field): """Returns the length of and the vertices involved in the shortest path in the network :param start_geoid: The string value of the starting GeoID for the shortest path analysis :param end_geoid: The string value of the ending GeoID for the shortest path analysis :return shortest_distance, vertex_list, edge_list: The length of the shortest path from the field weight_distance and the list of vertices and edges in the shortest path network """ start_vertex, end_vertex = None, None vertex_geoid = self._graph.vertex_properties[key_field] vertices = gutil.find_vertex(self._graph, vertex_geoid, start_key) if (len(vertices) > 0): start_vertex = vertices[0] vertices = gutil.find_vertex(self._graph, vertex_geoid, end_key) if (len(vertices) > 0): end_vertex = vertices[0] if (start_vertex is not None) and (end_vertex is not None): vertex_list, edge_list = gtopo.shortest_path(self._graph, start_vertex, end_vertex, self._graph.edge_properties["weight_dist"]) shortest_distance = gtopo.shortest_distance(self._graph, start_vertex, end_vertex, self._graph.edge_properties["weight_dist"]) return shortest_distance, vertex_list, edge_list else: return -1, "Could not find start or end vertex"
def get(self, args): source = int(args["source"]) target = int(args["target"]) vertex_list, edge_list = shortest_path(graph, graph.vertex(source), graph.vertex(target)) print(vertex_list) ret = [{"id": graph.vertex_index[v], "name": graph.vertex_properties["name"][v], "photo_filename": graph.vertex_properties["photo_filename"][v]} for v in vertex_list] return ret
def _compute_shortest_path(graph, source, target, distance=None, exclude_edge=False): """Compute the single shortest path from the source to the target. Parameters ---------- source : str Source node ID target : str Target node ID exclude_edge : bool, optional Flag indicating whether the direct edge from the source to the target should be excluded from the result (if exists). """ source_vertex = graph.vertex(_get_vertex_obj(graph, source)) target_vertex = graph.vertex(_get_vertex_obj(graph, target)) path, _ = shortest_path( graph, source_vertex, target_vertex, weights=graph.edge_properties[distance] if distance else None) return tuple([graph.vp["@id"][el] for el in path])
def findThickestPathLateral(self,skelImg,skelDia,xScale,yScale): print 'create skeleton graph' skelGraph,_=self.makeGraphFast(skelImg,skelDia,xScale,yScale) rootVertex=self.findRootVertexLateral(skelGraph) epropW=skelGraph.edge_properties["w"] path=[] #remove all two-connected ones with 0 label print 'trace path of thickest diameter' #find thickest path pathDetect=True if skelGraph.num_vertices() >0: pathDetect=True while pathDetect==True: lastVertex=self.findLastRootVertex(skelGraph) try: path,_=gt.shortest_path(skelGraph, rootVertex, lastVertex , weights=epropW, pred_map=None) pathDetect=False except: raise if lastVertex <=0: pathDetect=False else: skelGraph.remove_vertex(lastVertex) lastVertex=self.findLastRootVertex(skelGraph) return path,skelGraph
def simulation__shortest_redistribution(w): """ # objective function args: w: a vector contains imposed weights for edges """ #extract movements & frequencies movements = [m[0] for m in movements_frequency_autos] frequencies = np.array([m[1] for m in movements_frequency_autos]) #computing counts based on Ni and frequencies counts = frequencies * N #build movements and counts list movements_counts = list(zip(movements, counts)) # create edge property map edge_maxspeed = road_network.edge_properties["maxspeed"] edge_hdistance = road_network.edge_properties["hdistance"] # create new property map for total weights edge_weight = road_network.new_edge_property("double") #build a dictionary to store number cars on edges edges = list(road_network.edges()) for edge, wi in list(zip(edges, w)): edge_weight[edge] = max(wi + edge_hdistance[edge], 0) #to avoid negative weights dict_edge_cars = dict(zip(edges, [0] * len(edges))) #build a dictionary to store shortest path of movement #dict_movement_path = dict() for mc in movements_counts: m = mc[0] m_p = (dict_centroids_projected[m[0]], dict_centroids_projected[m[1]]) m_count = mc[1] #compute nodes and shortest path nodes, path = shortest_path(road_network, m_p[0], m_p[1], weights=edge_weight, negative_weights=False) #dict_movement_path[m] = path for edge in path: dict_edge_cars[edge] += m_count #build a dictionary to store the time of edges dict_edge_time = dict(list(zip(edges, [0] * len(edges)))) #compute time on edges t_tot = 0 for edge in edges: hdistance = edge_hdistance[edge] #haversine distance of the edge r_edge = dict_edge_cars[edge] / (hdistance * l) #density of edge if r_edge == 0: continue maxspeed = edge_maxspeed[edge] t_edge = compute_edgetime(r_edge, hdistance, maxspeed) dict_edge_time[edge] = t_edge t_tot += t_edge * dict_edge_cars[edge] #dict_movement_time = dict() #for m in movements: #path = dict_movement_path[m] #m_t = sum([dict_edge_time[e] for e in path]) #dict_movement_time[m] = m_t return t_tot,
def _compute_shortest_path(self, nodes: Tuple[Point, Point]) -> None: source_node, target_node = nodes source_node_wkt = source_node.wkt target_node_wkt = target_node.wkt if source_node_wkt != target_node_wkt: source_vertex = self._graph.find_vertex_from_name(source_node_wkt) target_vertex = self._graph.find_vertex_from_name(target_node_wkt) self.logger.info( f"Compute shortest path from {source_vertex} to {target_vertex}" ) # shortest path computing... _, path_edges = shortest_path( self._graph, source=source_vertex, target=target_vertex, weights=self._graph.edge_weights, # weights is based on line length ) gdf_copy = self._gdf.copy(deep=True) # # get path by using edge names osm_roads_features = gdf_copy[ gdf_copy[self._TOPO_FIELD].isin( [self._graph.edge_names[edge] for edge in path_edges] ) ] path_geoms = osm_roads_features[self._GEOMETRY_FIELD].to_list() path_osm_ids = filter( lambda x: isinstance(x, str), osm_roads_features[self._ID_OSM_FIELD].to_list(), ) path_osm_urls = filter( lambda x: isinstance(x, str), osm_roads_features[self._OSM_URL_FIELD].to_list(), ) # reorder linestring path_found = linemerge(path_geoms) if not Point(path_found.coords[0]).wkt == source_node_wkt: # we have to revert the coord order of the 1+ elements path_found = LineString(path_found.coords[::-1]) self._output_data.append( { "source_node": source_node.wkt, "target_node": target_node.wkt, "osm_ids": ", ".join(path_osm_ids), "osm_urls": ", ".join(path_osm_urls), "geometry": path_found, } ) else: self.logger.info( f"Path from {source_node_wkt} to {target_node_wkt} are equals: not proceed!" )
def find_shortest_path(source, destination): print "Finding the shortest path" vertices, edges=shortest_path(graph, mapping[source], mapping[destination]) print "Printing path" for station in vertices: print index_name[graph.vertex_index[station]] for edge in edges: print "Line: ", edge_map[graph.edge_index[edge]]
def essence(sequences, form_diagram, v_to_seq, probs): print(sequences[:4]) probs.a = -np.log(probs.a) size = form_diagram.num_vertices() start = form_diagram.vertex(size-2) end = form_diagram.vertex(size-1) vs, es = topology.shortest_path(form_diagram, start, end, probs) vs = np.array([int(v) for v in vs])[1:-1] print(v_to_seq[vs])
def shortest_paths(self, src_sid=None, dst_sid=None): nv = GraphData() if src_sid is None and dst_sid is None: raise Exception('src_sid or dst_sid must be set') elif src_sid is None and dst_sid is not None: dst = self.__resolve_sid_to_id(dst_sid) if dst is None: raise Exception('SID not found!') total = self.dbsession.query(func.count( EdgeLookup.id)).filter_by(ad_id=self.domain_id).filter( EdgeLookup.oid != self.domain_sid + '-513').scalar() q = self.dbsession.query( EdgeLookup.id).filter_by(ad_id=self.domain_id).filter( EdgeLookup.oid != self.domain_sid + '-513') for nodeid in tqdm(windowed_query(q, EdgeLookup.id, 1000), desc='running', total=total): for i, res in enumerate(shortest_path(self.graph, nodeid, dst)): if res == []: continue if i % 2 == 0: self.__result_path_add(nv, res) elif src_sid is not None and dst_sid is not None: dst = self.__resolve_sid_to_id(dst_sid) if dst is None: raise Exception('SID not found!') src = self.__resolve_sid_to_id(src_sid) if src is None: raise Exception('SID not found!') for i, res in enumerate(shortest_path(self.graph, src, dst)): if res == []: continue if i % 2 == 0: self.__result_path_add(nv, res) else: raise Exception('Not implemented!') return nv
def getRootTipPaths(self, thickestPath, G): print('Calculating Root-Tip Paths') CPVIDX = [] for i in thickestPath: CPVIDX.append(G.vertex_index[i]) vprop = G.vertex_properties["vp"] eprop = G.edge_properties["ep"] epropW = G.edge_properties["w"] if len(self.__RTP) == 0: tips = self.getTips(thickestPath, G) RTP = [] #print '***** TIPS VAR ******' #print tips if tips == -1: print 'ERROR: No tips found' return -1 try: tips.remove(G.vertex_index(thickestPath[0])) except: pass percentOld = 0 for idx, i in enumerate(tips): percent = (float(idx) / float(len(tips))) * 100 if percentOld + 5 < percent: print(str(np.round(percent, 1)) + '% '), percentOld = percent try: path, edges = gt.shortest_path(G, thickestPath[0], G.vertex(i), weights=epropW, pred_map=None) RTPTmp = [] for k in path: RTPTmp.append(G.vertex_index[k]) split = self.compareTwoOrderedLists(CPVIDX, RTPTmp) RTP.append(RTPTmp[split:]) for j in reversed(path): vprop[j]['nrOfPaths'] += 1 for j in edges: eprop[j]['RTP'] = True except: print 'ERROR: in def getRootTipPaths(self,thickestPath,G): no dijkstra path at ' + str( idx) + ' in tips' pass print 'Number of Root-Tip Paths: ' + str(len(RTP)) self.__RTP = RTP print 'RTP done!' return RTP, tips
def shortest_path(self, start_position, end_position): try: return [ int(v) for v in shortest_path( g=self._graph, source=self._graph.vertex(start_position), target=self._graph.vertex(end_position), )[0] ] except ValueError: return []
def getRootTipPaths(self, thickestPath, G): print ("Calculating Root-Tip Paths") CPVIDX = [] for i in thickestPath: CPVIDX.append(G.vertex_index[i]) vprop = G.vertex_properties["vp"] eprop = G.edge_properties["ep"] epropW = G.edge_properties["w"] if len(self.__RTP) == 0: tips = self.getTips(thickestPath, G) RTP = [] # print '***** TIPS VAR ******' # print tips if tips == -1: print "ERROR: No tips found" return -1 try: tips.remove(G.vertex_index(thickestPath[0])) except: pass percentOld = 0 for idx, i in enumerate(tips): percent = (float(idx) / float(len(tips))) * 100 if percentOld + 5 < percent: print (str(np.round(percent, 1)) + "% "), percentOld = percent try: path, edges = gt.shortest_path(G, thickestPath[0], G.vertex(i), weights=epropW, pred_map=None) RTPTmp = [] for k in path: RTPTmp.append(G.vertex_index[k]) split = self.compareTwoOrderedLists(CPVIDX, RTPTmp) RTP.append(RTPTmp[split:]) for j in reversed(path): vprop[j]["nrOfPaths"] += 1 for j in edges: eprop[j]["RTP"] = True except: print "ERROR: in def getRootTipPaths(self,thickestPath,G): no dijkstra path at " + str( idx ) + " in tips" pass print "Number of Root-Tip Paths: " + str(len(RTP)) self.__RTP = RTP print "RTP done!" return RTP, tips
def dijkstra_path(self, start_position, end_position): try: self.calculate_edge_weights() return [ int(v) for v in shortest_path( g=self._graph, source=self._graph.vertex(start_position), target=self._graph.vertex(end_position), weights=self._graph.ep.weight, )[0] ] except ValueError: return []
def parse_travel_path(path, v, joined_stops, g, vmr): path_nodes = [] path_edges = [] cur_node = v["cur_node"] for r, p_or_d in path: if p_or_d == 'p': o_or_d = r.road_o else: o_or_d = r.road_d nodes, edges = topology.shortest_path(g, vmr[cur_node], vmr[o_or_d]) path_nodes += [ g.vertex_properties['_graphml_vertex_id'][n] for n in nodes ] path_edges += edges cur_node = o_or_d return path_nodes, path_edges
def mockEventsGT(nx_map,gt_map,nx_index,t,n,w,nmid): events = [] for i in xrange(0,n): while True: b = gt_map.vertex( random.randint(0,gt_map.num_vertices()-1) ) e = gt_map.vertex( random.randint(0,gt_map.num_vertices()-1) ) b1 = nx_index[b] e1 = nx_index[e] if nx.has_path(nx_map,b1,e1) and b1!=e1: break start = random.randint(0,t) gt_path = map(lambda x: nx_index[x], gt_top.shortest_path(gt_map,b,e,weights=w)[0] ) events.append( te.TrafficEvent(b,e,gt_path, start) ) print i return events
def calc_path_radius(self, start, end): """ utile function for other function calc skeleton **mean** vertex radius along some segment """ if self.vert_radius == None: print 'please call calc_skel_radius function first' return None elif start in self.feature_node_index and end in self.feature_node_index: v_list, e_list = topology.shortest_path(self.skel_graph, self.skel_graph.vertex(start), self.skel_graph.vertex(end), weights=self.edge_length_map) v_idx_list = [] for v in v_list: v_idx_list.append(int(v)) v_radius = self.vert_radius[v_idx_list] return v_radius.mean() else: print 'input vertex index is not feature node index' return None
def mockEventsGT(nx_map, gt_map, nx_index, t, n, w, nmid): events = [] for i in xrange(0, n): while True: b = gt_map.vertex(random.randint(0, gt_map.num_vertices() - 1)) e = gt_map.vertex(random.randint(0, gt_map.num_vertices() - 1)) b1 = nx_index[b] e1 = nx_index[e] if nx.has_path(nx_map, b1, e1) and b1 != e1: break start = random.randint(0, t) gt_path = map(lambda x: nx_index[x], gt_top.shortest_path(gt_map, b, e, weights=w)[0]) events.append(te.TrafficEvent(b, e, gt_path, start)) print i return events
def shortest_path(self, from_sid, to_sid, pred_map=None): """ Computes the shortest path between stop `from_sid` and stop `to_sid` """ from_v = self.get_vertex(from_sid) to_v = self.get_vertex(to_sid) path_vs, _ = topology.shortest_path( self.gtG, from_v, to_v, weights=self.gtG.ep["duration"], pred_map=pred_map, ) if not path_vs: return [] return [self.gtG.vp["stop_id"][v] for v in path_vs]
def findThickestPath(self, skelImg, skelDia, xScale, yScale): print 'create skeleton graph' skelGraph, skelSize = self.makeGraphFast(skelImg, skelDia, xScale, yScale) rootVertex, _ = self.findRootVertex(skelGraph) epropW = skelGraph.edge_properties["w"] maxDia = np.max(skelDia) try: diaIdx = int(len(skelDia) * 0.1) except: print "Error line 234 in Segmentation.py" diaIdx = 1 maxDia10 = np.max(skelDia[0:diaIdx]) print 'max Diameter: ' + str(maxDia) path = [] #remove all two-connected ones with 0 label print 'trace path of thickest diameter' #find thickest path pathDetect = True if skelGraph.num_vertices() > 0: pathDetect = True while pathDetect == True: lastVertex = self.findLastRootVertex(skelGraph) try: path, _ = gt.shortest_path(skelGraph, rootVertex, lastVertex, weights=epropW, pred_map=None) pathDetect = False except: raise if lastVertex <= 0: pathDetect = False else: skelGraph.remove_vertex(lastVertex) lastVertex = self.findLastRootVertex(skelGraph) return path, skelGraph, maxDia10, skelSize
def findThickestPath(self,skelImg,skelDia,xScale,yScale): print 'create skeleton graph' skelGraph,skelSize=self.makeGraphFast(skelImg,skelDia,xScale,yScale) rootVertex,_=self.findRootVertex(skelGraph) epropW=skelGraph.edge_properties["w"] maxDia=np.max(skelDia) try: diaIdx=int(len(skelDia)*0.1) except: print "Error line 234 in Segmentation.py" diaIdx=1 maxDia10=np.max(skelDia[0:diaIdx]) print 'max Diameter: '+ str(maxDia) path=[] #remove all two-connected ones with 0 label print 'trace path of thickest diameter' #find thickest path pathDetect=True if skelGraph.num_vertices() >0: pathDetect=True while pathDetect==True: lastVertex=self.findLastRootVertex(skelGraph) try: path,_=gt.shortest_path(skelGraph, rootVertex, lastVertex , weights=epropW, pred_map=None) pathDetect=False except: raise if lastVertex <=0: pathDetect=False else: skelGraph.remove_vertex(lastVertex) lastVertex=self.findLastRootVertex(skelGraph) return path,skelGraph,maxDia10,skelSize
def path_exists(g: gt.Graph, source, target): vp, _ = gt_top.shortest_path(g, source, target) return len(vp) != 0
def path_from_income(self): """ :return: GeoDataFrame representing path of commuter to work """ # Get jobs within range of income of commuter streets = self.env.streets.copy().reset_index(drop=True) origins = self.env.origins.copy() destinations = self.env.destinations.copy() destinations = destinations[ (destinations['salary_n'] > self.income[0]) & (destinations['salary_n'] < self.income[1])] # Get shortest path to one random destination osm_g = Graph(directed=False) indices = {} if len(destinations) > 0: # Add vertices to graph for i, osm_id in enumerate( list(streets['from']) + list(streets['to'])): v = osm_g.add_vertex() v.index = int(i) indices[osm_id] = i # Add edges to graph for i in list(streets.index): o_osm = streets.at[i, 'from'] d_osm = streets.at[i, 'to'] osm_g.add_edge(indices[o_osm], indices[d_osm]) # Randomly choose destination destination = destinations.loc[ np.random.choice(list(destinations.index)), :] # Randomly choose origin parcel based on block id origins = origins[ (origins['Landuse'].isin(['MFH', 'MFL', 'SFA', 'SFD', 'MX'])) & (origins['index_block'] == self.block_id)].reset_index( drop=True) if len(origins) > 0: origin = origins.loc[np.random.choice(list(origins.index)), :] # Get closest street of origin and destination osm_origin = streets[streets.centroid == nearest_points( origin['geometry'], streets.centroid.unary_union)[1]] osm_destination = streets[streets.centroid == nearest_points( destination['geometry'], streets.centroid.unary_union)[1]] # Calculate shortest path def keys(dictA, value): return list(dictA.keys())[list( dictA.values()).index(value)] path = shortest_path( osm_g, indices[osm_origin['from'].values[0]], indices[osm_destination['to'].values[0]])[1] path_gdf = pd.concat([ streets[ (streets['from'] == keys(indices, int(edge.source()))) & (streets['to'] == keys(indices, int(edge.target())))] for edge in path ]) return path_gdf else: return None else: return None
def shortest_path(g, source, target, directed=None, weights=None, combine_weights="mean"): ''' Returns a shortest path between `source`and `target`. The algorithms returns an empty list if there is no path between the nodes. Parameters ---------- g : :class:`~nngt.Graph` Graph to analyze. source : int Node from which the path starts. target : int Node where the path ends. directed : bool, optional (default: ``g.is_directed()``) Whether the edges should be considered as directed or not (automatically set to False if `g` is undirected). weights : str or array, optional (default: binary) Whether to use weighted edges to compute the distances. By default, all edges are considered to have distance 1. combine_weights : str, optional (default: 'mean') How to combine the weights of reciprocal edges if the graph is directed but `directed` is set to False. It can be: * "sum": the sum of the edge attribute values will be used for the new edge. * "mean": the mean of the edge attribute values will be used for the new edge. * "min": the minimum of the edge attribute values will be used for the new edge. * "max": the maximum of the edge attribute values will be used for the new edge. Returns ------- path : array of ints Order of the nodes making up the path from `source` to `target`. References ---------- .. [gt-sp] :gtdoc:`topology.shortest_path` ''' # source == target case if source == target: return [source] # non-trivial cases g, graph, w = _get_gt_graph(g, directed, weights, combine_weights, return_all=True) w = _get_gt_weights(g, w) path, _ = gtt.shortest_path(graph, source, target, weights=w) return [int(v) for v in path]