def getGhostPath(self): try: path = nx.dijkstra_path(self.graph, self.node_ghost, self.node_pacman) return (nx.dijkstra_path(self.graph, self.node_ghost, self.node_pacman)) except nx.NetworkXError: print("error") return self.graph.neighbors(self.node_ghost)
def test_feasible(self, new_sites = []): #considering deviation sites = new_sites temp_route = [] temp_time = 0 if len(sites) == 1: ori_route = networkx.dijkstra_path(self.graph, self.origin, sites[-1]) if route_distance(ori_route) > driving_range/2: return False else: des_route = networkx.dijkstra_path(self.graph, sites[-1], self.destination) if route_distance(des_route) > driving_range/2: return False else: return True else: ind = True for i in range(len(sites)): if i == 0: temp_route = networkx.dijkstra_path(self.graph, self.origin, sites[i]) if route_distance(temp_route) > driving_range/2: ind = False break elif i == len(sites): temp_route = networkx.dijkstra_path(self.graph, sites[i], self.destination) if route_distance(temp_route) > driving_range/2: ind = False break else: temp_route = networkx.dijkstra_path(self.graph, sites[i], sites[i+1]) if route_distance(temp_route) > driving_range: ind = False break return ind
def checkConnection(network, from_node_id, to_node_id): try: nx.dijkstra_path(\ network, \ from_node_id,\ to_node_id\ ) except nx.exception.NetworkXNoPath, e: return False
def cost_nsplit(G,cur,tremdstlist): #*print "Entering cnsplit" cnsplit=[] next=[] next2=[] tremdstlist2=list(tremdstlist) tablensplit=[[] for i in xrange(len(tremdstlist))] max_len=0 result=[] max_len_path_list=[] num=0 for j in tremdstlist: tablensplit[num]=nx.dijkstra_path(G,cur,tremdstlist[num]) # make a list of all paths if (tablensplit[num][1] not in next2): next2.append(tablensplit[num][1]) # make a list of unique next hops if len(tablensplit[num])>max_len: max_len=len(tablensplit[num]) max_len_path_list=[] max_len_path_list.append(tablensplit[num]) if len(tablensplit[num])==max_len: max_len_path_list.append(tablensplit[num]) num=num+1 back_flag=0 for path in max_len_path_list: for j in tremdstlist: if path[1]!=j and cur in nx.dijkstra_path(G,path[1],j): back_flag=1 break if back_flag==0: result=[path[1],G.edge[cur][path[1]]['weight']+cost_split(G,path[1],tremdstlist)] break # Filter if result==[]: to_del=[] for i in next2: # Remove those next hops that would possibly send pkt back to cur node for j in tremdstlist: if i==j: continue path=nx.dijkstra_path(G,i,j) # Ignoring those next hops that are end destinations if cur in path: to_del.append(i) break for elem in to_del: next2.remove(elem) if (len(next2)!=0): cmin=G.edge[cur][next2[0]]['weight']+cost_split(G,next2[0],tremdstlist) best_next=next2[0] else: cmin=99999 best_next=0 result=[best_next,cmin] return result
def LabelFeature(self, graph): # for each graph # pick a random source and a random target # run each of the networkx src tgt shortest path algorithms one by one # time how long they each take # repeat for N different srcs/tgts # find the average time for each algorithm # make the label for that graph the one with the shortest time # feature key: 0 = dijkstra, 1 = bidijkstra 2 = astar numIters = 10 n = networkx.number_of_nodes(graph) dijkstraTimes = np.zeros(numIters) biDijkstraTimes = np.zeros(numIters) aStarTimes = np.zeros(numIters) for i in xrange(numIters): # pick a random source and target src = np.random.randint(0, n) + 1 tgt = np.random.randint(0, n) + 1 while tgt == src: tgt = np.random.randint(0, n) + 1 dijkstraTime = time.time() try: networkx.dijkstra_path(graph, src, tgt) except: # no path found i -= 1 continue dijkstraTime = time.time() - dijkstraTime dijkstraTimes[i] = dijkstraTime biDijkstraTime = time.time() networkx.bidirectional_dijkstra(graph, src, tgt) biDijkstraTime = time.time() - biDijkstraTime biDijkstraTimes[i] = biDijkstraTime aStarTime = time.time() networkx.astar_path(graph, src, tgt) aStarTime = time.time() - aStarTime aStarTimes[i] = aStarTime meanDijkstra = np.mean(dijkstraTimes) meanBiDijkstra = np.mean(biDijkstraTimes) meanAStar = np.mean(aStarTimes) minTime = min(meanDijkstra, meanBiDijkstra, meanAStar) if meanDijkstra == minTime: label = 0 elif meanBiDijkstra == minTime: label = 1 else: label = 2 return label
def get_laziest_path(self, start='Cover', \ end='THE END FOR REAL THIS TIME'): # calculated the shortest number of passages # turned through from starting passage spl = nx.dijkstra_path(self.G, start, end) # nx.set_node_attributes(self.G, 'lazy_{}_length'.format(start.lower()), spl) sp = nx.dijkstra_path(self.G, 'Cover', end) # nx.set_node_attributes(self.G, 'lazy_{}_path'.format(start.lower()), sp) return spl, sp
def fish_distance(point1,point2): """ Returns the shortest distance around land (see the Land model) between the two points. Returns the distance in miles and the geos linestring that represents the path. NOTE: I'm assuming that the native units of the points and line is meters. This is true for the MLPA project but may not be true for other processes. """ # This is the straight line between the two points line = geos.LineString(point1,point2) # See if the straight line crosses land if line_crosses_land(line): # The straight line cut across land so we have to do it the hard way. G = PickledGraph.objects.all()[0].graph G = add_points_to_graph([point1,point2],G) # G.add_nodes_from([point1,point2]) # G = add_ocean_edges_for_node(G,get_node_from_point(G,point1)) # G = add_ocean_edges_for_node(G,get_node_from_point(G,point2)) # Replace the straight line with the shortest path around land line = geos.LineString( nx.dijkstra_path(G,get_node_from_point(G,point1),get_node_from_point(G,point2)) ) line.srid = settings.GEOMETRY_DB_SRID # Figure out the distance of the line (straight or otherwise) in miles distance = length_in_display_units(line) return distance, line
def __init__(self,graph,links): #Try to get all the combination of switches and destination hosts. self.switches = [] self.hosts = [] self.srcSwitchdstIPportNumMac = {} self.NextHopIP_PortNum = {} self.HipMac = {} self.graph = graph self.links = links temp = self.graph.nodes() temp.sort() for node in temp: if 'h' in node: self.hosts.append(node) elif 's' in node: self.switches.append(node) for key in temp: if key == 'h1': self.HipMac[key] = "00:00:00:00:00:01" if key == 'h2': self.HipMac[key] = "00:00:00:00:00:02" if key == 'h3': self.HipMac[key] = "00:00:00:00:00:03" if key == 'h4': self.HipMac[key] = "00:00:00:00:00:04" if key == 'h5': self.HipMac[key] = "00:00:00:00:00:05" if key == 'h6': self.HipMac[key] = "00:00:00:00:00:06" for switch in self.switches: for host in self.hosts: ipSeries = nx.dijkstra_path(graph,switch,host) nextHop = ipSeries[1] #print self.links.getNextHopPort((switch,nextHop)) self.srcSwitchdstIPportNumMac[(switch,host)] = (self.links.getNextHopPort((switch,nextHop)), self.HipMac[host])
def shortestWalk(g,line,mode): # Get index of closest nodes to line endpoints nPts = [g.node[n]["point"] for n in g] nPts = rc.Collections.Point3dList(nPts) start = nPts.ClosestIndex(line.From) end = nPts.ClosestIndex(line.To) # Check that start and are not the same node if start == end: print "Start and end node is the same" else: # Check that a path exist between the two nodes if hasPath(g,start,end): # Calculate shortest path if mode == "dijkstra_path": sp = nx.dijkstra_path(g,start,end,weight = "weight") elif mode == "shortest_path": sp = nx.shortest_path(g,start,end,weight = "weight") # Make polyline through path pts = [g.node[i]["point"] for i in sp] pl = rc.Geometry.PolylineCurve(pts) return pl
def get_closest_parking_section(self, dstNodeId, tolerance=5): paths = [] for i in self.find_entrances(): path = nx.dijkstra_path(self.g, i, dstNodeId) while (self.g.node[path[-1]]['type'].upper() != 'PARKING'): path.pop() paths.append(path) destinations = [] for i in xrange(0, len(paths)): destinations.append(paths[i][-1]) for i in xrange(0,len(destinations)): section = self.g.node[destinations[i]]['section'] free = float(section['capacity']) / section['max'] * 100 prevFound = [destinations[i]] while (free < tolerance): destinations[i] = self.find_neighbor_with_parking_spots(destinations[i], exclude=prevFound) prevFound.append(destinations[i]) section = self.g.node[destinations[i]]['section'] free = float(section['capacity']) / section['max'] * 100 if len(destinations) == 1: destinations = destinations[0] return destinations
def cost_split(G,cur,tremdstlist): csplit=0 tablesplit=[[] for i in xrange(len(tremdstlist))] num=0 for j in tremdstlist: if (cur!=tremdstlist[num]): tablesplit[num]=nx.dijkstra_path(G,cur,tremdstlist[num]) num=num+1 csplit=nx.dijkstra_path_length(G,cur,tremdstlist[0]) #print "CSPLIT added cost from :",cur, "to ",tremdstlist[0],"as ",length[cur][tremdstlist[0]] #*print "tablesplit[0]=",tablesplit[0] for x in xrange(1,num): curpath=tablesplit[x] for y in xrange(len(curpath)): if (y!=len(curpath)-1): if ((curpath[y+1] in tablesplit[0]) !=True): curwt=G.edge[curpath[y]][curpath[y+1]]['weight'] #print "CSPLIT : Adding [",curpath[y],"][",curpath[y+1],"]" csplit=csplit+curwt return csplit
def generateNextPill(self): list_nodes_temp = self.aStar(self.node_pacman, self.node_ghost,self.graph) list_nodes = [] array_nodes = [] manhattan = {'node':[], 'distance': 0} possible_options = self.graph.neighbors(self.node_pacman) for node in possible_options: path_total = nx.dijkstra_path(self.graph, self.node_ghost, self.node_pacman) len_path = len(path_total) if(self.manhattan(node,self.node_ghost) > manhattan['distance'] -10 and len_path>4): manhattan['node'].append(node) manhattan['distance'] = self.manhattan(node,self.node_ghost) random.shuffle(manhattan['node']) for node in manhattan['node'] : if(node.graph_node.has_image ==True): return node if(len(manhattan['node']) == 0): possible_options = self.graph.neighbors(self.node_pacman) best = {'node': None, 'distance': 0} for node in possible_options: if(self.manhattan(node, self.node_ghost)> best['distance']): best['node'] = node best['distance'] = self.manhattan(node, self.node_ghost) return best['node'] return manhattan['node'][0]
def label_url(self, loc1, loc2): # Connection string replaced with "" for security conn_str = "" # Connect to db conn = psycopg2.connect(conn_str) # Determine the path using Dijkstra's algorithm self.d_path = networkx.dijkstra_path(self.graph, loc1, loc2) # Add markers to the url count = 0 alpha_list = list(string.ascii_uppercase) for city in self.d_path: lat, lng = self.get_coords(conn,city) self.url = self.url + "&markers=color:yellow%7Clabel:" +\ alpha_list[count] + "%7C" +\ str(lat) + "," + str(lng) count = count + 1 # Add a path to the url path = "&path=color:blue" for city in self.d_path: lat, lng = self.get_coords(conn,city) path = path + "|" +\ str(lat) + "," + str(lng) self.url = self.url + path
def find_path(self, source_id, target_id): if source_id == target_id: shortest_path = [source_id] else: shortest_path = nx.dijkstra_path(self.graph, source_id, target_id, 'cost') return shortest_path
def experiment_4(): G = nx.Graph() G.add_edge(0, 11, weight=91) G.add_edge(1, 11, weight=72) G.add_edge(1, 13, weight=96) G.add_edge(2, 13, weight=49) G.add_edge(2, 6, weight=63) G.add_edge(2, 3, weight=31) G.add_edge(3, 9, weight=98) G.add_edge(3, 7, weight=1) G.add_edge(3, 12, weight=59) G.add_edge(4, 7, weight=6) G.add_edge(4, 9, weight=6) G.add_edge(4, 8, weight=95) G.add_edge(5, 11, weight=44) G.add_edge(6, 11, weight=53) G.add_edge(8, 10, weight=2) G.add_edge(8, 12, weight=48) G.add_edge(9, 12, weight=32) G.add_edge(10, 14, weight=16) G.add_edge(11, 13, weight=86) G = nx.read_gpickle('G.gpickle') path_nx = nx.dijkstra_path(G, 0, 14) path = dijkstra(G, 0, 14, True) if path_cost(G, path) > path_cost(G, path_nx): print 'Error' else: print 'Correct' return locals()
def getShortestPath(self, source_switch_id, target_switch_id): self.setTopologyGraph() try: path = nx.dijkstra_path(self.topology, source_switch_id, target_switch_id, self.WEIGHT_PROPERTY_NAME) except nx.NetworkXNoPath: path = None return path
def optimize(self, gs): comps = self._find_components() self._zdd = { 'B': Node('B %d B B ' % (len(self.switches) + 1)), 'T': Node('T %d T T ' % (len(self.switches) + 1)) } for line in gs.dumps().split('\n'): if line.startswith('.'): break n = Node(line) self._zdd[n.n] = n self.search_space.start = n.n entries = set([self.search_space.start]) for comp in comps: entries = self._rebuild(entries, comp) self.search_space.end = 'T' path = nx.dijkstra_path(self.search_space.graph, self.search_space.start, self.search_space.end) closed_switches = [] for i in range(len(path) - 1): x, y = path[i], path[i + 1] closed_switches.extend(list(self.search_space.graph[x][y]['config'])) return sorted(list(set(closed_switches)))
def get_patterns_a(self): leaves = [] root_name = "%s//%s" %(root, root.data) for n in G.nodes(): if not nx.has_path(G, root_name, n): G.remove_node(n) # for n in nx.descendants(G, root_name): elif G.successors(n) == []: leaves.append(n) if leaves == []: print '\n******No Pattern******\n' else: print '\n******Patterns******\n' print '\nExtracted Pattern <%i>' %len(leaves) i = 0 for n in leaves: pattern = [] if nx.has_path(G, root_name, n): for p in nx.dijkstra_path(G, root_name, n): if G.node[p].has_key('fontcolor'): pattern.append(G.node[p]['label'].split(r'\n')[1]) elif G.node[p] == {}: pass else: label = G.node[p]['label'].split(r'\n')[:-1] pattern.append('<%s>:{%s}' %(label[0].split('(')[0], ', '.join(label[1:]))) print '%d:' %i, u'//'.join(pattern) i += 1
def get_patterns_b(self): roots = [] for n in G.nodes(): if not nx.has_path(G, n, '1'): G.remove_node(n) # for n in nx.ancestors(G, '1'): elif G.predecessors(n) == []: roots.append(n) if roots == []: print '\n******No Pattern******\n' else: print '\n******Patterns******\n' print '\nExtracted Pattern <%i>' %len(roots) i = 0 for n in roots: pattern = [] if nx.has_path(G, n, '1'): for p in nx.dijkstra_path(G, n, '1')[:-1]: if G.node[p].has_key('fontcolor'): pattern.append(G.node[p]['label'].split(r'\n')[1]) else: label = G.node[p]['label'].split(r'\n')[:-1] pattern.append('%s:{%s}' %(label[0].split('(')[0], ', '.join(label[1:]))) print '%d:' %i, u' '.join(pattern) i += 1
def getFindedIndexes(str_len,e_list,delta): G = nx.Graph() G.add_node(0) G.add_node(str_len) # Добавление обычных переходов for elem in e_list: G.add_edge(elem[0], elem[1], weight=elem[1] - elem[0] - delta) # Добавление "нулевых" переходов for (u1,v1) in G.nodes(data='weight'): for (u2,v2) in G.nodes(data='weight'): if u1!=u2: if not(G.has_edge(u1,u2)): w = 2+abs(u1-u2)**2 G.add_edge(u1,u2, weight=w) path_ = nx.dijkstra_path(G, 0, str_len) len_path = len(path_) findedIndexes = [] for i in range(len_path): if i+1<len_path: for ind,x in enumerate(e_list): if x[0]==path_[i] and x[1]==path_[i+1]: findedIndexes.append(ind) return findedIndexes
def get_patterns_a(self, snts, query): leaves = [] root_name = "%s//%s" %(root, root.data) for n in G.nodes(): if not nx.has_path(G, root_name, n): G.remove_node(n) # for n in nx.descendants(G, root_name): elif G.successors(n) == []: leaves.append(n) # if leaves == []: # print '\n******No Pattern******\n' # else: # print '\n******Patterns******\n' # print '\nExtracted Pattern <%i>' %len(leaves) #入力文章を振り分ける snt_divide = defaultdict(list) for s in snts: before_t = sum([s[:i] for i, x in enumerate(s) if x[0] == query], []) after_t = sum([s[i+1:] for i, x in enumerate(s) if x[0] == query], []) if after_t == [] or before_t == []: pass else: for i, n in enumerate(leaves): if nx.dijkstra_path(G, root_name, n)[1].split(u'//')[1][:-3] == after_t[0][1]: snt_divide[i].append(before_t) # print pp(snt_divide) i = 0 Ext_Patterns = [] for n in leaves: pattern = [] if nx.has_path(G, root_name, n): for p in nx.dijkstra_path(G, root_name, n): if G.node[p].has_key('fontcolor'): pattern.append(G.node[p]['label'].split(r'\n')[1]) elif G.node[p] == {}: pass else: label = G.node[p]['label'].split(r'\n')[:-1] pattern.append('<%s>:{%s}' %(label[0].split('(')[0], ', '.join(label[1:]))) # print '%d:' %i, u'//'.join(pattern) Ext_Patterns.append(u'//'.join(pattern)) i += 1 return snt_divide, Ext_Patterns
def getWeightPath(self, src, dst): try: nodeList = nx.dijkstra_path(self.topo, src, dst) except: nodeList = [] return nodeList
def findPathbyWeight(self, fo, to, time=1, flow=3): key = fo + to if key not in self.path_dic: path = nx.dijkstra_path(self.G, fo, to, weight='weight') Path(self.G, self.path_dic, self.path_flow_dic, path, time, flow).start() # sleep 5s, 消耗一个带宽 else: path = self.path_dic[key] return path
import networkx as nx MG = nx.MultiGraph() #MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)]) MG.add_edge(1, 2, key='lambda_0', weight=4) MG.add_edge(1, 2, key='lambda_1', weight=9) MG.add_edge(1, 2, key='lambda_2', weight=7) MG.add_edge(2, 3, key='lambda_0', weight=4) MG.add_edge(2, 3, key='lambda_1', weight=3) MG.add_edge(2, 3, key='lambda_2', weight=4) print(nx.dijkstra_path(MG, 1, 3)) print(nx.dijkstra_path_length(MG, 1, 3)) MG.remove_edge(1, 2, key='lambda_0') print(nx.dijkstra_path(MG, 1, 3)) print(nx.dijkstra_path_length(MG, 1, 3))
label_pos=0.3, font_size=3) nx.draw(G, pos, alpha=0.5, node_size=3, node_color='r', font_size=5, width=[float(v['weight'] * 0.05) for (r, c, v) in G.edges(data=True)], cmap=plt.get_cmap('jet'), with_labels=True) plt.savefig('3_4_all_path.jpg', dpi=300) plt.show() ###use method of dijkstra to get shortest path and distance path = nx.dijkstra_path(G, source='Colombia', target='Mexico') print('M到C的路径:', path) distance = nx.dijkstra_path_length(G, source='Colombia', target='Mexico') print('M到C的距离为:', distance) path = nx.dijkstra_path(G, source='Mexico', target='Colombia') print('C到M的路径:', path) distance = nx.dijkstra_path_length(G, source='Mexico', target='Colombia') print('C到M的距离为:', distance) ###do circulation to get all efficient distance for index, row in df1.iterrows(): #print(row['H1N1country']) df1.loc[index, 'new_effdis'] = nx.dijkstra_path_length(G,
"b": 4, "d": 8, "e": 2 }, "d": { "e": 7 }, "e": { "d": 9 } } G.add_weighted_edges_from(edges) #shortest path shortestPath = nx.dijkstra_path(G, "a", "d") print(f"Shortest path -> {shortestPath}") #shortest distance shortest_distance = nx.dijkstra_path_length(G, "a", "d") print(shortest_distance) # number of nodes and edges print(G.number_of_edges(), G.number_of_nodes()) #visualize graph #Position of nodes using Fruchterman-Reingold force-directed algorithm. pos = nx.spring_layout(G) weight = nx.get_edge_attributes(G, "weight") nx.draw_networkx(G, pos, arrows=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=weight)
# if value equals 'Mr. Hi' append a blue node if value == 'Mr. Hi': color_map.append('blue') # else if value equals 'Officer' append a blue node elif value == 'Officer': color_map.append('green') # else if value is anything else append a gray node else: color_map.append('gray') # draw the graph, since the colors where applied in the same order as the nodes are ordered # the correct color will be applied to the corresponding node nx.draw(G, node_color=color_map, with_labels=True) # Task 1.3 shortest_path = nx.dijkstra_path(G, 24, 16) print('Shortest path is:', shortest_path) # Task 1.4 # nx.get_node_attributes returns a dict, so I iterate the keys of the dict for value in node_dict.keys(): # if the key is one of the values in shortest_path it will override that nodes color to red if shortest_path.__contains__(value): color_map[value] = 'red' # draw the graph, since the colors where applied in the same order as the nodes are ordered # the correct color will be applied to the corresponding node nx.draw(G, node_color=color_map, with_labels=True)
def create_merge_splits(i_patch): image = i_patch['image'] prob = i_patch['prob'] seg = i_patch['seg'] patches = [] #g_image = mh.gaussian_filter(image, 3.5) g_image = image grad_x = np.gradient(g_image)[0] grad_y = np.gradient(g_image)[1] grad = np.sqrt(np.add(grad_x * grad_x, grad_y * grad_y)) grad -= grad.min() grad /= (grad.max() - grad.min()) grad *= 255 grad = grad.astype(np.uint8) G = nx.Graph() for y in range(grad.shape[0]): for x in range(grad.shape[1]): vertex_name = str(y) + '-' + str(x) left_vertex_name = str(y) + '-' + str(x - 1) top_vertex_name = str(y - 1) + '-' + str(x) G.add_node(vertex_name) if x > 0: G.add_edge(left_vertex_name, vertex_name, weight=int(grad[y, x])) if y > 0: G.add_edge(top_vertex_name, vertex_name, weight=int(grad[y, x])) starts = range(0, 75, 10) starts.append(74) ends = list(reversed(range(0, 75, 10))) ends = [74] + ends out = np.array(seg) for i in range(len(starts)): start = starts[i] end = ends[i] for sw in range(0, 2): if sw == 0: start_v = str(start) + '-0' end_v = str(end) + '-74' else: start_v = '0-' + str(start) end_v = '74-' + str(end) if i == 0 and sw > 0: # calculate first border only once continue if i == len(starts) - 1 and sw > 0: # and last one only once continue out = np.zeros(grad.shape) # fig = plt.figure() sp = nx.dijkstra_path(G, start_v, '37-37') sp2 = nx.dijkstra_path(G, '37-37', end_v) border = [] for s in sp: y, x = s.split('-') out[int(y), int(x)] = 1 border.append((int(y), int(x))) for s in sp2: y, x = s.split('-') out[int(y), int(x)] = 1 border.append((int(y), int(x))) # plt.imshow(out) # # create label images for our patch # patch_new_labeled = skimage.measure.label(out) patch_new_labeled[out == 1] = 1 patch_new_labeled[seg == 0] = 0 patch_new_labeled = mh.labeled.relabel(patch_new_labeled)[0] array1 = _metrics.Util.threshold(patch_new_labeled, 1) array2 = _metrics.Util.threshold(patch_new_labeled, 2) merged_array = array1 + array2 dilated_array1 = np.array(array1) dilated_array2 = np.array(array2) for o in range(10): dilated_array1 = mh.dilate(dilated_array1.astype(np.uint64)) dilated_array2 = mh.dilate(dilated_array2.astype(np.uint64)) overlap = np.logical_and(dilated_array1, dilated_array2) overlap[merged_array == 0] = 0 patch = {} patch['image'] = image patch['prob'] = prob patch['binary1'] = array1.astype(np.bool) patch['binary2'] = array2.astype(np.bool) patch['overlap'] = overlap.astype(np.bool) patch['border'] = border patch['bbox'] = i_patch['bbox'] patch['border_center'] = i_patch['border_center'] patches.append(patch) return patches
def createConvexPath_FD(pair): #For F_D pair only #return demand_id if ESP distance to target demand is less than fd_delivery print pair[1] odPointsList = ((pair[0][0].x, pair[0][0].y), (pair[0][1].x, pair[0][1].y)) st_line = LineString(odPointsList) labeledObstaclePoly = [] totalConvexPathList = {} if st_line.length > fd_delivery * 5280: return 0 dealtArcList = {} totalConvexPathList[odPointsList] = LineString(odPointsList) LineString terminate = 0 idx_loop1 = 0 time_loop1 = 0 time_contain2 = 0 time_crossingDict = 0 time_convexLoop = 0 time_impedingArcs = 0 time_spatialFiltering = 0 time_loop1_crossingDict = 0 time_buildConvexHulls = 0 no_obs = False while terminate == 0: t1s = time.time() idx_loop1 += 1 t6s = time.time() #w = shapefile.Writer(shapefile.POLYLINE) #w.field('nem') #for line in totalConvexPathList: #w.line(parts=[[ list(x) for x in line ]]) #w.record('ff') #w.save(path + "graph_" + str(idx_loop1) + version_name) totalGrpah = createGraph(totalConvexPathList.keys()) spatial_filter_n = networkx.dijkstra_path(totalGrpah, odPointsList[0], odPointsList[1]) spatial_filter = [] for i in xrange(len(spatial_filter_n) - 1): spatial_filter.append( [spatial_filter_n[i], spatial_filter_n[i + 1]]) #w = shapefile.Writer(shapefile.POLYLINE) #w.field('nem') #for line in spatial_filter: #w.line(parts=[[ list(x) for x in line ]]) #w.record('ff') #w.save(self.path + "spatial Filter_" + str(idx_loop1) + self.version_name) #sp_length = 0 #for j in spatial_filter: #sp_length += LineString(j).length #sp_l_set.append(sp_length) crossingDict = defaultdict(list) for line in spatial_filter: Line = LineString(line) for obs in obstaclesPolygons: if Line.crosses(obs): if obs not in labeledObstaclePoly: labeledObstaclePoly.append(obs) crossingDict[tuple(line)].append(obs) t6e = time.time() time_spatialFiltering += t6e - t6s if len(crossingDict.keys()) == 0: terminate = 1 no_obs = True continue else: t7s = time.time() for tLine in crossingDict.keys(): #cLine = list(tLine) if dealtArcList.has_key(tLine): try: del totalConvexPathList[tLine] except: del totalConvexPathList[(tLine[1], tLine[0])] continue else: dealtArcList[tLine] = LineString(list(tLine)) try: del totalConvexPathList[tLine] except: del totalConvexPathList[(tLine[1], tLine[0])] containingObs = [] for obs in crossingDict[tLine]: convexHull = createConvexhull(obs, tLine) splitBoundary(totalConvexPathList, convexHull) convexHull = createConvexhull(obs, odPointsList) splitBoundary(totalConvexPathList, convexHull) convexHull2 = createConvexhull(obs) if convexHull2.contains(Point(tLine[0])): containingObs.append(obs) elif convexHull2.contains(Point(tLine[1])): containingObs.append(obs) if len(containingObs) != 0: #SPLIT subConvexPathList = {} vi_obs = MultiPolygon([x for x in containingObs]) containedLineCoords = list(tLine) fromX = containedLineCoords[0][0] fromY = containedLineCoords[0][1] toX = containedLineCoords[1][0] toY = containedLineCoords[1][1] fxA = (fromY - toY) / (fromX - toX) fxB = fromY - (fxA * fromX) minX = vi_obs.bounds[0] maxX = vi_obs.bounds[2] split_line = LineString([ (min(minX, fromX, toX), fxA * min(minX, fromX, toX) + fxB), (max(maxX, fromX, toX), fxA * max(maxX, fromX, toX) + fxB) ]) for obs in containingObs: s1, s2 = splitPolygon(split_line, obs) dividedObsPoly = [] #to deal with multipolygon a = s1.intersection(obs) b = s2.intersection(obs) if a.type == "Polygon": dividedObsPoly.append(a) else: for o in a.geoms: if o.type == "Polygon": dividedObsPoly.append(o) if b.type == "Polygon": dividedObsPoly.append(b) else: for o2 in b.geoms: if o2.type == "Polygon": dividedObsPoly.append(o2) for obs2 in dividedObsPoly: for pt in tLine: convexHull = createConvexhull(obs2, [pt]) splitBoundary(subConvexPathList, convexHull) subVertices = [] for line in subConvexPathList: subVertices.extend(line) subVertices = list(set(subVertices)) containingObsVertices = [] for obs in containingObs: containingObsVertices.extend( list(obs.exterior.coords)) subVertices = [ x for x in subVertices if x in containingObsVertices ] deleteList = [] for line in subConvexPathList: chk_cross = 0 for obs in containingObs: if subConvexPathList[line].crosses(obs): chk_cross = 1 if chk_cross == 1: deleteList.append(line) for line in deleteList: del subConvexPathList[line] #subConvexPathList.remove(line) pairList = [] for i in range(len(subVertices)): for j in range(i + 1, len(subVertices)): pairList.append( (subVertices[i], subVertices[j])) for i in pairList: Line = LineString(i) chk_cross = 0 for obs in containingObs: if Line.crosses(obs): chk_cross = 1 elif Line.within(obs): chk_cross = 1 if chk_cross == 0: subConvexPathList[i] = Line #subConvexPathList.append(i) buffer_st_line = split_line.buffer(0.1) deleteList = [] for line in subConvexPathList: if buffer_st_line.contains( subConvexPathList[line]): deleteList.append(line) for line in deleteList: if subConvexPathList.has_key(line): del subConvexPathList[line] #subConvexPathList = [x for x in subConvexPathList if x not in deleteList] for line in subConvexPathList: if not totalConvexPathList.has_key(line): if not totalConvexPathList.has_key( (line[1], line[0])): totalConvexPathList[ line] = subConvexPathList[ line] #if line not in totalConvexPathList: #if [line[1], line[0]] not in totalConvexPathList: #totalConvexPathList.append(line) #w = shapefile.Writer(shapefile.POLYLINE) #w.field('nem') #for line in totalConvexPathList: #w.line(parts=[[ list(x) for x in line ]]) #w.record('ff') #w.save(self.path + "graph2_" + str(idx_loop1) + self.version_name) t7e = time.time() time_loop1_crossingDict += t7e - t7s #new lines labeled_multyPoly = MultiPolygon([x for x in labeledObstaclePoly]) convexHull = createConvexhull(labeled_multyPoly, odPointsList) splitBoundary(totalConvexPathList, convexHull) #new lines end #impededPathList t5s = time.time() impededPathList = {} for line in totalConvexPathList: for obs in labeledObstaclePoly: if totalConvexPathList[line].crosses(obs): impededPathList[line] = totalConvexPathList[line] break t5e = time.time() time_impedingArcs += t5e - t5s for line in impededPathList: del totalConvexPathList[line] terminate2 = 0 idx_loop2 = 0 t1e = time.time() time_loop1 += t1e - t1s while terminate2 == 0: idx_loop2 += 1 deleteList = [] crossingDict = defaultdict(list) for line in dealtArcList: if impededPathList.has_key(line): del impededPathList[line] elif impededPathList.has_key((line[1], line[0])): del impededPathList[(line[1], line[0])] t3s = time.time() #pr.enable() for line in impededPathList: for obs in labeledObstaclePoly: if impededPathList[line].crosses(obs): crossingDict[line].append(obs) t3e = time.time() time_crossingDict += t3e - t3s #at this point, impededArcList should be emptied, as it only contains crossing arcs, and all of them #should be replaced by convex hulls. for line in crossingDict: del impededPathList[line] for line in impededPathList: if not totalConvexPathList.has_key(line): totalConvexPathList[line] = impededPathList[line] impededPathList = {} if len(crossingDict.keys()) == 0: terminate2 = 1 continue else: #w = shapefile.Writer(shapefile.POLYLINE) #w.field('nem') #for line in crossingDict: #w.line(parts=[[ list(x) for x in line ]]) #w.record('ff') #w.save(self.path + "crossingDict_" + str(idx_loop1) + "_"+ str(idx_loop2) +"_"+ self.version_name) t4s = time.time() for tLine in crossingDict.keys(): dealtArcList[tLine] = crossingDict[tLine] containingObs = [] for obs in crossingDict[tLine]: chk_contain = 0 convexHull2 = createConvexhull(obs) if convexHull2.contains(Point(tLine[0])): containingObs.append(obs) chk_contain = 1 elif convexHull2.contains(Point(tLine[1])): containingObs.append(obs) chk_contain = 1 if chk_contain == 0: t10s = time.time() convexHull = createConvexhull(obs, tLine) splitBoundary(impededPathList, convexHull) t10e = time.time() time_buildConvexHulls += t10e - t10s if len(containingObs) != 0: #SPLIT #print "SPLIT" t2s = time.time() subConvexPathList = {} vi_obs = MultiPolygon([x for x in containingObs]) containedLineCoords = tLine fromX = containedLineCoords[0][0] fromY = containedLineCoords[0][1] toX = containedLineCoords[1][0] toY = containedLineCoords[1][1] fxA = (fromY - toY) / (fromX - toX) fxB = fromY - (fxA * fromX) minX = vi_obs.bounds[0] maxX = vi_obs.bounds[2] split_line = LineString([ (min(minX, fromX, toX), fxA * min(minX, fromX, toX) + fxB), (max(maxX, fromX, toX), fxA * max(maxX, fromX, toX) + fxB) ]) for obs in containingObs: s1, s2 = splitPolygon(split_line, obs) dividedObsPoly = [] #to deal with multipolygon a = s1.intersection(obs) b = s2.intersection(obs) if a.type == "Polygon": dividedObsPoly.append(a) else: for o in a.geoms: if o.type == "Polygon": dividedObsPoly.append(o) if b.type == "Polygon": dividedObsPoly.append(b) else: for o2 in b.geoms: if o2.type == "Polygon": dividedObsPoly.append(o2) for obs2 in dividedObsPoly: for pt in tLine: convexHull = createConvexhull( obs2, [pt]) splitBoundary(subConvexPathList, convexHull) subVertices = [] for line in subConvexPathList: subVertices.extend(line) subVertices = list(set(subVertices)) containingObsVertices = [] for obs in containingObs: containingObsVertices.extend( list(obs.exterior.coords)) subVertices = [ x for x in subVertices if x in containingObsVertices ] deleteList = [] for line in subConvexPathList: chk_cross = 0 for obs in containingObs: if subConvexPathList[line].crosses(obs): chk_cross = 1 if chk_cross == 1: deleteList.append(line) for line in deleteList: del subConvexPathList[line] pairList = [] for i in range(len(subVertices)): for j in range(i + 1, len(subVertices)): pairList.append( (subVertices[i], subVertices[j])) for i in pairList: Line = LineString(list(i)) chk_cross = 0 for obs in containingObs: if Line.crosses(obs): chk_cross = 1 elif Line.within(obs): chk_cross = 1 if chk_cross == 0: subConvexPathList[i] = Line buffer_st_line = split_line.buffer(0.1) deleteList = [] for line in subConvexPathList: if buffer_st_line.contains( subConvexPathList[line]): deleteList.append(line) for line in deleteList: del subConvexPathList[line] for line in subConvexPathList: if not impededPathList.has_key(line): if not impededPathList.has_key( (line[1], line[0])): impededPathList[ line] = subConvexPathList[line] t2e = time.time() time_contain2 += t2e - t2s #pr.disable() for line in dealtArcList: if impededPathList.has_key(line): del impededPathList[line] #impededPathList = [x for x in impededPathList if x not in dealtArcList] t4e = time.time() time_convexLoop += t4e - t4s #end of else #w = shapefile.Writer(shapefile.POLYLINE) #w.field('nem') #for line in impededPathList: #w.line(parts=[[ list(x) for x in line ]]) #w.record('ff') #w.save(path + "After_graph_" + str(idx_loop1) + "_"+ str(idx_loop2) +"_"+ version_name) #end of while2 for line in impededPathList: if not totalConvexPathList.has_key(line): totalConvexPathList[line] = impededPathList[line] #totalConvexPathList.extend(impededPathList) #no obstruction if no_obs == True: return 1 totalGraph = createGraph(totalConvexPathList.keys()) esp_n = networkx.dijkstra_path(totalGraph, odPointsList[0], odPointsList[1]) esp = [] for i in range(len(esp_n) - 1): esp.append([esp_n[i], esp_n[i + 1]]) #w = shapefile.Writer(shapefile.POLYLINE) #w.field('nem') #no_edges = 0 #for line in totalConvexPathList.keys(): #no_edges += 1 #w.line(parts=[[ list(x) for x in line ]]) #w.record('ff') #w.save(path + "totalpath" + version_name + "%d" % pair[1] ) w = shapefile.Writer(shapefile.POLYLINE) w.field('nem') for line in esp: w.line(parts=[[list(x) for x in line]]) w.record('ff') w.save(path + "ESP_" + version_name + "%d" % pair[1]) targetPysal = pysal.IOHandlers.pyShpIO.shp_file(path + "ESP_" + version_name + "%d" % pair[1]) targetShp = generateGeometry(targetPysal) total_length = 0 for line in targetShp: total_length += line.length if total_length <= fd_delivery: return 1 else: return 0
def updateNodeBusinessAmountByRing(ringName): import networkx as nx import copy import json import re from django.db.models import Q, F linkList = hw_ipran_link.objects.filter(Q(ring=ringName)&Q(isDelete=False)).values_list('source','dest') # 'ValuesListQuerySet' object has no attribute 'extend',所以得转为list linkList = list(linkList) nodeTuple = reduce(lambda x,y:x+y, linkList) #[(1,2),(2,3)]-->(1,2,2,3) nodeTuple = tuple(set(nodeTuple)) #(1,2,2,3)-->{1,2,3}-->(1,2,3) rootNodeTuple = tuple(a for a in nodeTuple if re.search(r'J\d{3,4}',a)) #过滤带环节点,不加tuple是一个生成器,无法计算长度 rootLinkList = zip(*[iter(rootNodeTuple[i:]) for i in range(2)]) #(1,2,3,4)-->[(1,2),(2,3),(3,4)] (1,)-->[] ()-->[] if len(rootNodeTuple)==0 or len(rootNodeTuple)>2: #ToDo:raise error print u"{0}环带环点大于2或等于0" # return None linkList.extend(rootLinkList) G = nx.Graph() G.add_edges_from(linkList) try: CycleNode = nx.cycle_basis(G)[0] #环的所有节点 CycleNodeNum = len(CycleNode)-len(rootNodeTuple) ChainNodeNum = len(nodeTuple)-len(CycleNode) except: CycleNode = [] #无法生成环,则设环为空列表 CycleNodeNum = 0 ChainNodeNum = len(nodeTuple)-len(rootNodeTuple) ring.objects.update_or_create( name = ringName, defaults = { 'topoStruct':json.dumps(linkList, ensure_ascii=False), #这样才是显示中文 'ringNodeNum':CycleNodeNum, 'chainNodeNum':ChainNodeNum } ) for NodeName in nodeTuple: I = G.copy() #得用一个临时变量来存G,不然每次循环都会改变G(G是不会改变的),得用copy CycleNodeCopy = copy.deepcopy(CycleNode) #得复制列表,不然remove会改变主列表情况 if NodeName in rootNodeTuple: #如果节点为带环节点,则跳出本次循环 continue elif NodeName in CycleNodeCopy: #如果想要查询的节点为环上节点,则移除其它环节点(不包括支链节点) CycleNodeCopy.remove(NodeName) I.remove_nodes_from(CycleNodeCopy) else: #如果想要查询的节点不为环上节点,则计算带环节点至该节点的最短路径经过的节点,并移除。 try: ShortestNode = nx.dijkstra_path(I,rootNodeTuple[0],NodeName) except: print u'无法计算环路节点{0}至带环点的最短路径,可能带环点有误'.format(NodeName) continue ShortestNode.remove(NodeName) I.remove_nodes_from(ShortestNode) H = nx.dfs_tree(I,NodeName) #最后即可通过生成树协议获得节点及其所下带的节点 TreeNodeList = H.nodes() #最终得到所有下带节点 #TreeNodeList.remove(NodeName) #为什么需要移除本节点? #print NodeName try: NodeObj = hw_ipran_node.objects.get(name=NodeName) except: #print NodeName #根据链接关系的节点名称,无法在节点表查到相应的节点。华为的原因,得问清楚 print u'无法更新{0}环"{1}"节点的下挂业务数,因为在节点表中未查到改点'.format(ring, NodeName) BusinessAmount = 0 for TreeNodeName in TreeNodeList: TreeNodeObj = hw_ipran_node.objects.get(name=TreeNodeName) BusinessAmount += TreeNodeObj.SelfBusinessAmount NodeObj.BusinessAmount = BusinessAmount NodeObj.save()
def decide_support_move(current_node, coalition, game_map, max_infantry_in_node): if coalition != "red" and coalition != "blue": logger.error( "Cannot decide support move: Coalition must be either 'red' or 'blue'; was: '%s'" % coalition) return None # We prefer to fill nodes that are at the shortest possible distance from base, that still require support and don't # have enemy units. Note that we ignore anything on the reinforcements path. for distance in range( 1, game_map.get_longest_distance(coalition, include_reinforcement=False) + 1): nodes = game_map.get_nodes_by_distance(coalition, distance, include_reinforcement=False) if nodes is not None: random.shuffle(nodes) for node_id in nodes: if node_id == current_node: continue num_infantry_in_node = 0 infantry_dict = game_map.get_infantry_in_node(node_id) if infantry_dict is not None: # Note that we don't need to check here WHOSE infantry it is - the condition above already will have # rejected the node if it's enemy infantry. Hence, if we get past the condition, it must be ours. num_infantry_in_node = infantry_dict["number"] # Target nodes (but not detour nodes) are rejected with extreme prejudice, if they have enemy units or # they have less than half the max infantry. For a detour to a worthy target node, we WILL consider # nodes that are merely slightly lacking, though we give priority to nodes less than half-full. if game_map.is_enemy_activity_in_node(coalition, node_id) is False and \ num_infantry_in_node <= max_infantry_in_node / 2.0: # Node: this is the neighbors-dictionary. We check if current node is this node's neighbor. if current_node in game_map.graph[node_id]: # The absolute optimal situation. Target node needs support and is next to us. Choose that. # Note that the original list was shuffled, so we can just take the first instance that we come # across. It's still random. logger.debug( "Support unit for %s in node %d is able to make optimal move to node %d" % (coalition, int(current_node), int(node_id))) return int(node_id) # Ok, we're here, so we found no optimal choices. What about a detour of exactly one node, such that # would take us to our target in two moves? Note: This is a bit special case. If we find even one such # target node, we immediately make the decision, only randomizing what detour we take. I mean, how likely # is it that there are several legitimate target nodes, exactly at this distance from base, and exactly one # node removed from us? for node_id in nodes: if node_id == current_node: continue options = [] num_infantry_in_node = 0 infantry_dict = game_map.get_infantry_in_node(node_id) if infantry_dict is not None: num_infantry_in_node = infantry_dict["number"] if game_map.is_enemy_activity_in_node(coalition, node_id) is False and \ num_infantry_in_node <= max_infantry_in_node / 2.0: for neighbor in game_map.graph[current_node]: num_infantry_in_node = 0 infantry_dict = game_map.get_infantry_in_node(neighbor) if infantry_dict is not None: # Note that we don't need to check here WHOSE infantry it is - the condition above # already will have rejected the node if it's enemy infantry. Hence, if we get past the # condition, it must be ours. num_infantry_in_node = infantry_dict["number"] if node_id in game_map.graph[neighbor] and \ game_map.is_enemy_activity_in_node(coalition, neighbor) is False and \ num_infantry_in_node <= max_infantry_in_node / 2.0: options.append(neighbor) if len(options) > 0: # Now we have to actually use the choice function because we are choosing from the neighbors # list, which is not shuffled. node_num = int(np.random.choice(options)) logger.debug( "Support unit for %s in node %d is able to make almost optimal move to node %d; " "advancing towards goal through support needing detour." % (coalition, int(current_node), node_num)) return node_num # Getting more desperate. Is there any neighbor that needs support AT ALL? for neighbor in game_map.graph[current_node]: num_infantry_in_node = 0 infantry_dict = game_map.get_infantry_in_node(neighbor) if infantry_dict is not None: # Note that we don't need to check here WHOSE infantry it is - the condition above # already will have rejected the node if it's enemy infantry. Hence, if we get past the # condition, it must be ours. num_infantry_in_node = infantry_dict["number"] if node_id in game_map.graph[neighbor] and \ game_map.is_enemy_activity_in_node(coalition, neighbor) is False and \ num_infantry_in_node < max_infantry_in_node: options.append(neighbor) if len(options) > 0: node_num = int(np.random.choice(options)) logger.debug( "Support unit for %s in node %d is able to make almost optimal move to node %d; " "advancing towards goal through support needing detour." % (coalition, int(current_node), node_num)) return node_num # Now we're getting REALLY desperate about this particular distance. Are there any nodes whatsoever at it, # such that need support? If so, we choose between the nodes (if more than one) that are at the smallest # distance from our current position. distance_dict = {} for node_id in nodes: if node_id == current_node: continue num_infantry_in_node = 0 infantry_dict = game_map.get_infantry_in_node(node_id) if infantry_dict is not None: num_infantry_in_node = infantry_dict["number"] if game_map.is_enemy_activity_in_node(coalition, node_id) is False and \ num_infantry_in_node <= max_infantry_in_node / 2.0: try: path = nx.dijkstra_path(game_map.graph, current_node, node_id) except nx.NetworkXNoPath: continue this_distance = len(path) - 1 if this_distance not in distance_dict: distance_dict[this_distance] = [] distance_dict[this_distance].append(node_id) if bool(distance_dict) is False: # Empty dictionary. In other words, we didn't find any nodes at all worth visiting at this distance from # base. We skip all the way to the beginning of the outermost loop, in which we try a greater distance # from base. continue # We have finally found a node worth visiting. What are the node(s) at the smallest possible distance from # our current position? smallest_distance = min(list(distance_dict.keys())) # Between those (or if just one, we pick that) we take first node (remember, original list was shuffled, so # this is the same as choosing randomly target_node = distance_dict[smallest_distance][0] try: path = nx.dijkstra_path(game_map.graph, current_node, target_node) except nx.NetworkXNoPath: continue if len(path) < 2: # Just extreme paranoia - trying to avoid an exception in some pathological circumstance. continue node_num = int(path[1]) # In this one case we are completely deterministic and just take the shortest path to our target node. # Remember: The randomness was already involved in CHOOSING the target, so this is still unpredictable. logger.debug( "Support unit for %s in node %d needs to make a bad move to node %d: Follow shortest path to " "target" % (coalition, int(current_node), node_num)) return node_num # If here, we try the next greatest distance from base # All nodes either occupied, or don't require assistance return None
if TAZ.node[node]['ID_TAZ12A'] in tazlist: print TAZ.node[node]['ID_TAZ12A'], "in current TAZ list" tazlistC[TAZ.node[node]['ID_TAZ12A']] = tazlist[TAZ.node[node] ['ID_TAZ12A']] count += 1 print count # TAZs currently in arcGIS version f = open(inSpace + 'TAZlist_current_json.txt', 'wb') f.write(json.dumps(tazlistC, sort_keys=True)) f.close() # HINT: IMPORTANT: TEST ROUTING IS ALRIGHT # USE NETWORKX Dijkstra algo for now path = nx.dijkstra_path(newG, tazlistC[22415000], tazlistC[22018000], weight='cost') # extract edges totalcost = 0 hwyroute = [] for i in range(1, len(path)): thisedge = newG.edge[path[i - 1]][path[i]] totalcost += thisedge['cost'] if thisedge['id_stn'] > 0: hwyroute.append(thisedge['id_stn']) print "total cost:", totalcost print "hwy stations:", hwyroute import cPickle as pickle
def test(): ''' Some test code for developing Not needed for the generator code ''' fac_num = 8 cli_num = 92 N = fac_num + cli_num world_size = np.array([100, 100]) #generate facilities facilities = np.random.rand(fac_num, 2) * world_size[None, :] #generate clients clients = np.random.rand(cli_num, 2) * world_size[None, :] #combine nodes nodes = np.concatenate((facilities, clients), axis=0) G, T, TG = graph_generation(facilities, clients) #G,_,_ = graph_generation(facilities,clients) dict_TG = save_graph(TG, fac_num, cli_num) TGr = load_adj(dict_TG, N) fig = plt.figure(figsize=(16, 8)) fig.add_subplot(1, 2, 1) # nx.draw(TG,pos_TG,with_labels=False, node_color=color_map, edge_color='red', node_size=30, alpha=0.5,width=0.5) vis_graph(nodes, TG, fac_num, cli_num) fig.add_subplot(1, 2, 2) # nx.draw(TG,pos_TG,with_labels=False, node_color=color_map, edge_color='red', node_size=30, alpha=0.5,width=0.5) vis_graph(nodes, TGr, fac_num, cli_num) fig.show() input('any key to continue') # color map for graph color_map = [] for node in G: if node < fac_num: color_map.append('blue') else: color_map.append('green') # Apply fixed position layout for graph fixed_positions = {i: tuple(nodes[i]) for i in range(N)} fixed_nodes = fixed_positions.keys() # Generate layout pos_G = nx.spring_layout(G, pos=fixed_positions, fixed=fixed_nodes) pos_T = nx.spring_layout(T, pos=fixed_positions, fixed=fixed_nodes) pos_TG = nx.spring_layout(TG, pos=fixed_positions, fixed=fixed_nodes) print('draw graph') fig = plt.figure(figsize=(16, 16)) # fig.patch.set_facecolor('xkcd:mint green') # draw graph fig.add_subplot(2, 2, 1) nx.draw(G, pos_G, with_labels=True, node_color=color_map, edge_color='red', node_size=200, alpha=0.5, fontsize=8) plt.title('Full Graph', fontsize=15) fig.add_subplot(2, 2, 2) nx.draw(T, pos_T, with_labels=True, node_color=color_map, edge_color='red', node_size=100, alpha=0.5, fontsize=4) plt.title('Minimum Spanning Tree', fontsize=15) fig.add_subplot(2, 2, 3) # nx.draw(TG,pos_TG,with_labels=False, node_color=color_map, edge_color='red', node_size=30, alpha=0.5,width=0.5) vis_graph(nodes, TG, fac_num, cli_num) plt.title('Add more edges', fontsize=15) fig.add_subplot(2, 2, 4) plt.scatter(clients[:, 0], clients[:, 1], c='b') plt.scatter(facilities[:, 0], facilities[:, 1], c='r') plt.title('Scatters', fontsize=15) fig.show() input('any key to continue') # ''' # Shortest Path with dijkstra_path # ''' print('shortest part with dijkstra algorithm') path = nx.dijkstra_path(T, source=0, target=10) print('path from node 0 to node 10 in T', path) path = nx.dijkstra_path(TG, source=0, target=10) print('path from node 0 to node 10 in TG', path)
def cost(steps): s = 0 for j in range(1, len(steps)): s += distances[steps[j - 1] + ':' + steps[j]] return s lijn1 = ['odz','hglo','hgl','hglg','ddn','go','lc','zp'] expand(lijn1) lijn2 = ['es', 'esk', 'hgl', 'bn', 'amri', 'aml', 'wdn', 'nvd', 'rat', 'hno', 'zl'] expand(lijn2) lijn3 = ['kpn', 'zlsh', 'zl'] expand(lijn3) lijn4 = ['aml', 'vz', 'da', 'vhp', 'mrb', 'hdb'] expand(lijn4) lijn5 = ['zl', 'dl', 'omn', 'mrb', 'hdb', 'gbg', 'co', 'dln', 'na', 'emnz', 'emn'] expand(lijn5) pairs = set(lijn1 + lijn2 + lijn3 + lijn4 + lijn5) print('startplaceref,endplaceref,distance,operatorref,fareref') for x in pairs: for y in pairs: if x != y: steps = nx.dijkstra_path(G, x, y, weight='weight') print('NL:S:%s,NL:S:%s,%d,%s,%s' % (x, y, cost(steps), 'IFF:BN', 'IFF:BN'))
key = op.itemgetter(1), reverse=True) all_pairs_2 = [] for i in graph2.nodes(): for j in graph2.nodes(): if (i != j): all_pairs_2.append((i,j)) # Compute and store the sum of all dijkstra shortest paths # divided by the number of node pairs shortest_paths_w = {} shortest_path_lengths_w = {} cost_w_2 = 0 for k in all_pairs_2: sp = nx.dijkstra_path(graph2, k[0], k[1], weight = 'cost') spl = nx.dijkstra_path_length(graph2, k[0], k[1], weight = 'cost') cost_w_2 += spl shortest_paths_w[k] = sp shortest_path_lengths_w[k] = spl cost_w_bef = cost_w_2/len(all_pairs_2) #------------------------------------------------------------------ # Compute the change in cost as a function of centraity of # removed edge edge_number_w = 0 change_in_path_w = {} xw = []
g = nx.read_edgelist("data/graph1.txt") print("Noeuds du graphe g:", g.nodes()) print("Liens du graphe g:", g.edges()) # Manip 2 for n in g.nodes(): print("Noeud %r, degré: %d, voisins: %r" % (n, g.degree(n), g.neighbors(n))) # Manip 3 list_nodes = g.nodes() for i in range(len(list_nodes)): for j in range(i + 1, len(list_nodes)): if nx.has_path(g, list_nodes[i], list_nodes[j]): print(list_nodes[i], list_nodes[j], nx.dijkstra_path(g, list_nodes[i], list_nodes[j])) plt.figure() nx.draw(g, with_labels=True) plt.title("graph1.txt") plt.show() # Manip 4 g_directed = nx.read_edgelist("data/graphM2.txt", create_using=nx.DiGraph()) print("Noeuds du graphe orienté g_directed:", g_directed.nodes()) print("Liens du graphe orienté g_directed:", g_directed.edges()) for n in g_directed.nodes_iter(): print( "Noeud %r, degré: %d, voisins: %r, degré entrant: %d, degré sortant: %d" % (n, g_directed.degree(n), g_directed.neighbors(n), g_directed.in_degree(n), g_directed.out_degree(n)))
def test_basic_simulation(): ## CREATION OF GRAPH Node = type( 'Site', (core.Identifiable, core.Log, core.Locatable, core.HasResource), {}) nodes = [] path = [] distances = [550, 500, 300, 500, 150, 150, 500, 300, 500, 550] coords = [] coords.append([0, 0]) for d in range(len(distances)): coords.append([ pyproj.Geod(ellps="WGS84").fwd(coords[d][0], coords[d][1], 90, distances[d])[0], 0 ]) for d in range(len(coords)): data_node = { "env": [], "name": "Node " + str(d + 1), "geometry": shapely.geometry.Point(coords[d][0], coords[d][1]) } node = Node(**data_node) nodes.append(node) for i in range(2): if i == 0: for j in range(len(nodes) - 1): path.append([nodes[j], nodes[j + 1]]) if i == 1: for j in range(len(nodes) - 1): path.append([nodes[j + 1], nodes[j]]) FG = nx.DiGraph() positions = {} for node in nodes: positions[node.name] = (node.geometry.x, node.geometry.y) FG.add_node(node.name, geometry=node.geometry) for edge in path: FG.add_edge(edge[0].name, edge[1].name, weight=1) ## SIMULATION SET-UP simulation_start = datetime.datetime.now() env = simpy.Environment( initial_time=time.mktime(simulation_start.timetuple())) ## CREATION OF VESSELS Vessel = type('Vessel', (core.Identifiable, core.Movable, core.HasContainer, core.HasResource, core.Routeable, core.VesselProperties), {}) start_point = 'Node 11' end_point = 'Node 1' data_vessel_one = { "env": env, "name": "Vessel", "route": nx.dijkstra_path(FG, start_point, end_point, weight='length'), "geometry": FG.nodes[start_point]['geometry'], "capacity": 1_000, "v": 4, "type": 'CEMT - Va', "B": 10, "L": 155.0 } env.FG = FG vessels = [] for v in range(2): vessel = Vessel(**data_vessel_one) vessels.append(vessel) ## SYSTEM PARAMETERS # water level difference wlev_dif = [np.linspace(0, 45000, 1000), np.zeros(1000)] for i in range(len(wlev_dif[0])): wlev_dif[1][i] = 2 # lock area parameters waiting_area_1 = core.IsLockWaitingArea(env=env, nr_resources=1, priority=True, name='Volkeraksluizen_1', node="Node 2") lineup_area_1 = core.IsLockLineUpArea(env=env, nr_resources=1, priority=True, name='Volkeraksluizen_1', node="Node 3", lineup_length=300) lock_1 = core.IsLock(env=env, nr_resources=100, priority=True, name='Volkeraksluizen_1', node_1="Node 5", node_2="Node 6", node_3="Node 7", lock_length=300, lock_width=24, lock_depth=4.5, doors_open=10 * 60, doors_close=10 * 60, wlev_dif=wlev_dif, disch_coeff=0.8, grav_acc=9.81, opening_area=4.0, opening_depth=5.0, simulation_start=simulation_start, operating_time=25 * 60) waiting_area_2 = core.IsLockWaitingArea(env=env, nr_resources=1, priority=True, name="Volkeraksluizen_1", node="Node 10") lineup_area_2 = core.IsLockLineUpArea(env=env, nr_resources=1, priority=True, name="Volkeraksluizen_1", node="Node 9", lineup_length=300) lock_1.water_level = "Node 5" #location of lock areas in graph FG.nodes["Node 6"]["Lock"] = [lock_1] FG.nodes["Node 2"]["Waiting area"] = [waiting_area_1] FG.nodes["Node 3"]["Line-up area"] = [lineup_area_1] FG.nodes["Node 10"]["Waiting area"] = [waiting_area_2] FG.nodes["Node 9"]["Line-up area"] = [lineup_area_2] ## INITIATE VESSELS for vessel in vessels: vessel.env = env env.process(vessel.move()) ## RUN MODEL env.FG = FG env.run() ## OUTPUT ANALYSIS lock_cycle_start = np.zeros(len(vessels)) lock_cycle_duration = np.zeros(len(vessels)) waiting_in_lineup_start = np.zeros(len(vessels)) waiting_in_lineup_duration = np.zeros(len(vessels)) waiting_in_waiting_start = np.zeros(len(vessels)) waiting_in_waiting_duration = np.zeros(len(vessels)) for v in range(len(vessels)): for t in range(0, len(vessels[v].log["Message"]) - 1): if vessels[v].log["Message"][t] == "Passing lock start": lock_cycle_start[v] = vessels[v].log["Timestamp"][t].timestamp( ) - simulation_start.timestamp() lock_cycle_duration[v] = vessels[v].log["Value"][t + 1] break for t in range(0, len(vessels[v].log["Message"]) - 1): if vessels[v].log["Message"][t] == "Waiting in line-up area start": waiting_in_lineup_start[v] = vessels[v].log["Timestamp"][ t].timestamp() - simulation_start.timestamp() waiting_in_lineup_duration[v] = vessels[v].log["Value"][t + 1] break for t in range(0, len(vessels[v].log["Message"]) - 1): if vessels[v].log["Message"][t] == "Waiting in waiting area start": waiting_in_waiting_start[v] = vessels[v].log["Timestamp"][ t].timestamp() - simulation_start.timestamp() waiting_in_waiting_duration[v] = vessels[v].log["Value"][t + 1] break ## TESTS # start times vessel 1 np.testing.assert_almost_equal( lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth)) + 550 / 4 + 500 / 2 + (300 - 0.5 * 155) / 2 + (0.5 * 155 + 500) / 1 + (300 - 0.5 * 155) / 1, lock_cycle_start[0], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal(550 / 4 + 500 / 2 + (300 - 0.5 * 155) / 2, waiting_in_lineup_start[0], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal(0, waiting_in_waiting_start[0], decimal=0, err_msg='', verbose=True) # durations vessel 1 np.testing.assert_almost_equal( lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth)), lock_cycle_duration[0], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal( lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth)), waiting_in_lineup_duration[0], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal(0, waiting_in_waiting_duration[0], decimal=0, err_msg='', verbose=True) # start times vessel 2 np.testing.assert_almost_equal( 3 * (lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth))) + 2 * (0.5 * 155 + (500 + 300 - 0.5 * 155)) + 550 / 4 + 0.5 * 155 + 800 / 4 + (500 + 300 - 0.5 * 155) / 2, lock_cycle_start[1], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal( (lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth))) + 550 / 4 + (500 + 300 - 0.5 * 155) / 2 + 500 + 0.5 * 155 + 300 - 0.5 * 155, waiting_in_lineup_start[1], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal(550 / 4, waiting_in_waiting_start[1], decimal=0, err_msg='', verbose=True) # durations vessel 2 np.testing.assert_almost_equal( lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth)), lock_cycle_duration[1], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal( 2 * (lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth))) + 0.5 * 155 + 500 / 4 + 300 / 4, waiting_in_lineup_duration[1], decimal=0, err_msg='', verbose=True) np.testing.assert_almost_equal( lock_1.doors_open + lock_1.doors_close + 2 * lock_1.lock_width * lock_1.lock_length * wlev_dif[1][0] / (lock_1.disch_coeff * lock_1.opening_area * math.sqrt(2 * lock_1.grav_acc * lock_1.opening_depth)) + (300 - 0.5 * 155) / 2 + 500 / 2 + 0.5 * 155, waiting_in_waiting_duration[1], decimal=0, err_msg='', verbose=True)
def longest_path_and_length(graph, s, t, weight='weight'): i_w_graph = inverse_weight(graph, weight) path = nx.dijkstra_path(i_w_graph, s, t) length = nx.dijkstra_path_length(i_w_graph, s, t) return path, length
def delivery_network(in_solution, s_file, in_name="temp_graph"): arc_list = [] arc_shp_list = [] connectivity = True resultingGraph = networkx.Graph() for i in range(len(in_solution) - 1): sites = F_Fdict[in_solution[i]].keys() for j in range(i + 1, len(in_solution)): if in_solution[j] in sites: resultingGraph.add_edge( (facil_shp[in_solution[i]].x, facil_shp[in_solution[i]].y), (facil_shp[in_solution[j]].x, facil_shp[in_solution[j]].y), weight=F_Fdict[in_solution[i]][in_solution[j]][0]) if F_Fdict[in_solution[i]][in_solution[j]][1] == "straight": arc_list.append((in_solution[i], in_solution[j])) else: arc_list.append("ESP_" + str(in_solution[i]) + "_" + str(in_solution[j]) + ".shp") for i in range(len(warehouse_coords) - 1): for j in range(i + 1, len(warehouse_coords)): try: route = networkx.dijkstra_path(resultingGraph, warehouse_coords[i], warehouse_coords[j]) except: connectivity = False break if connectivity == False: break for site in in_solution: for whouse in warehouse_coords: try: route = networkx.dijkstra_path( resultingGraph, (facil_shp[site].x, facil_shp[site].y), whouse) except: connectivity = False break if connectivity == False: break if connectivity == True: if s_file == True: for i in arc_list: if type(i) == tuple: arc_shp_list.append( LineString([ list(facil_shp[i[0]].coords)[0], list(facil_shp[i[1]].coords)[0] ])) else: arc_pysal = pysal.IOHandlers.pyShpIO.shp_file(path + i) arc_shp = generateGeometry(arc_pysal) arc_shp_list.extend(arc_shp) w = shapefile.Writer(shapefile.POLYLINE) w.field('nem') for line in arc_shp_list: w.line(parts=[[list(x) for x in list(line.coords)]]) w.record('chu') w.save(path + in_name) return resultingGraph else: return None
f = open("distances2.txt", "r") distances2 = json.load(f) f.close() ''' for i in range(len(distances)): distances[i][target_no]=8 distances[source_no][target_no]=50 ''' a_path = [] distances[source_no - 1][target_no - 1] = 50 A = numpy.array(distances) G = networkx.from_numpy_matrix(A, create_using=networkx.DiGraph()) #print (list(networkx.all_simple_paths(G,source_no,target_no,3))) #print networkx.dijkstra_path_length(G,3,45) a_path = networkx.dijkstra_path(G, source_no - 1, target_no - 1) index_link = [] #print a_path index_link.append(a_path[0]) for i in range(len(a_path) - 1): temp = [] distances[a_path[i]][a_path[i + 1]] = 50 distances[a_path[i + 1]][a_path[i]] = 50 V = numpy.array(distances) G2 = networkx.from_numpy_matrix(V, create_using=networkx.DiGraph()) temp = networkx.dijkstra_path(G2, a_path[i], a_path[i + 1]) for j in range(len(temp)): if temp[j] != a_path[i]: index_link.append(temp[j]) l = len(index_link)
import networkx as nx import numpy as np G = nx.DiGraph() v = np.loadtxt('node.txt', dtype=int) v_num = v.shape[0] for i in range(v_num): G.add_node(v[i][0], X=v[i][1], Y=v[i][2]) e = np.loadtxt('edge.txt', dtype=int) e_num = e.shape[0] data = [] for i in range(e_num): temp = (e[i][0], e[i][1], e[i][2]) data.append(temp) G.add_weighted_edges_from(data) print(nx.dijkstra_path(G, 101, 1)) print(nx.dijkstra_path_length(G, 101, 1))
city1 = rd.choice(G3.nodes()) city2 = rd.choice(G3.nodes()) #selecting random costs wt = rd.randint(20, 2000) if city1 != city2 and G3.has_edge(city1, city2) == 0: G3.add_edge(city1, city2, weight=wt) pos = nx.circular_layout(G3) nx.draw(G3, pos, with_labels=1) nx.draw_networkx_edge_labels(G3, pos) plt.show() # In[23]: # Getting the shortest path print nx.dijkstra_path(G3, 'Mumbai', 'Tuticorin') # ## 3.3. Generating Interest Graph # # The interest graph is generated by making connections to the object which people are interested in. Here objects are the repositories. As I already stated let us build a star graph by making edges to the repository "AwesomeDataScience" with the people who starred it. Its schema is displayed below. # # <img src="gs_1.png" alt="Graph Schema 1"/> # In[1]: # Finding the people who followed the "awesome-datascience" repository from github import Github ACCESS_TOKEN = 'cfda794b26e8ab9ec9c28fca61cce08c76417d7a' gh = Github(ACCESS_TOKEN, per_page=100) user = gh.get_user('bulutyazilim')
print(" - link_capacity is in Gbit/s") sys.exit(2) graph, demands = solve(sys.argv[1], int(sys.argv[2])) demands.sort(key=lambda x: x[2], reverse=True) tunnels = [] for d in demands: tmpgraph = graph.copy() edges_to_remove = [] for v1, v2, attr in tmpgraph.edges(data=True): if attr["capacity_left"] < d[2]: edges_to_remove.append((v1, v2)) tmpgraph.remove_edges_from(edges_to_remove) try: p = nx.dijkstra_path(tmpgraph, d[0], d[1]) except nx.exception.NetworkXNoPath: minedge = None for vt1 in tmpgraph.nodes: for vt2 in tmpgraph.nodes: tmpgraph2 = tmpgraph.copy() tmpgraph2.add_edge(vt1, vt2) tmpgraph2.add_edge(vt2, vt1) cost = link_cost(tmpgraph2.nodes[vt2], tmpgraph2.nodes[vt2]) if not minedge or cost < minedge[2]: try: p = nx.dijkstra_path(tmpgraph2, d[0], d[1]) except nx.exception.NetworkXNoPath: continue minedge = (vt1, vt2, cost, p)
elevation_difference = get_elevation(pt.x, pt.y) - elevation_start pt_start = pt if elevation_difference > 0: Time.append( pt.distance(pt_start) / 5000 + elevation_difference / 600) else: Time.append(pt.distance(pt_start) / 5000) g.add_edge(road_links[link]['start'], road_links[link]['end'], fid=link, weight=Time) #nx.draw(g, node_size=1) path = nx.dijkstra_path(g, source=(450000, 85000), target=(460000, 92500), weight="weight") def color_path(g, path, color="blue"): res = g.copy() first = path[0] for node in path[1:]: res.edges[first, node]["color"] = color first = node return res def obtain_colors(graph, default_node="blue", default_edge="black"): node_colors = [] for node in graph.nodes:
def getShortestPathDijkstra(self, a, b): out_node_list = nx.dijkstra_path(self.G, a, b) return out_node_list
def modify_path(infile, outfile="newpath.dat", mindist=1.0): """try to get a inter-point distance of mindist or more if needed""" p = bornprofiler.io.readPoints(infile) # inplace sort by z (col=2): # http://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column p[:] = p[p[:, 2].argsort()] d = distance_array(p.astype(float32), p.astype(float32)) G = NX.Graph(d < 20) # cutoff 20 is sufficient to connect points for (n, nbrdict) in G.adjacency_iter(): for k, eattr in nbrdict.items(): eattr['weight'] = d[n, k]**3 # favours nearest neighbours (mostly...) dij3 = NX.dijkstra_path(G, 0, G.nodes()[-1]) newp = p[dij3] savetxt(outfile, newp, "%8.3f %8.3f %8.3f") # newp is ordered in traversal order; # get the distances between adjacent nodes deltas = map(linalg.norm, newp[1:] - newp[:-1]) # build new linear graph with distances between nodes as edge attribute G2 = NX.Graph() G2.add_path(arange(0, len(newp)), weight=0) for ((n, nbrdict), delta) in zip(G2.adjacency_iter(), deltas): for k, eattr in nbrdict.items(): eattr['weight'] = delta # remove points so that distance is the shortest distance larger than mindist pruned = NX.Graph() n = m = k = 0 while (n < len(G2) - 1): dist = 0 while (k < len(G2) and dist < mindist): m = k # move along the chain k += 1 dist += G2.edge[m][k]['weight'] #print "segment: ", (m,k,dist) pruned.add_edge(n, k, weight=dist) #print "edge:", (n,k,dist) n = k # sort nodes so that the output pdb is also in linear order # (nodes() returns node numbers in arbirary order but by construction # we know that the linear graph goes from 0 -> last) pruned_coords = newp[sort(pruned.nodes())] import os.path root, ext = os.path.splitext(outfile) new_outfile = (root + "_dq%.1f" + ext) % mindist new_pdb = (root + "_dq%.1f.pdb") % mindist savetxt(new_outfile, pruned_coords, "%8.3f %8.3f %8.3f") print "Wrote pruned path to %(new_outfile)r" % locals() # write pdb with open(new_pdb, "w") as pdb: for i, (x, y, z) in enumerate(pruned_coords): atomnr = i + 1 pdb.write( "ATOM%(atomnr)7i C XXX X 1 %(x)8.3f%(y)8.3f%(z)8.3f\n" % locals()) print "Wrote pruned path to %(new_pdb)r" % locals() return new_outfile, new_pdb
df1 = df1.replace({'stn_code': interchange_codes}) df1 = df1.drop_duplicates() df2 = pd.DataFrame() for index, row in df.iterrows(): graph.add_edge(row['n1'], row['n2'], weight=row['time']) for index1, row1 in tqdm(df1['stn_code'].iteritems(), total=df1.size): #row1 = "BP10" list1 = [] for index2, row2 in df1['stn_code'].iteritems(): if row2 != row1: if row1 not in results: results[row1] = {} if row2 not in results[row1]: results[row1][row2] = [] results[row1][row2] = list(nx.dijkstra_path(graph, row1, row2)) with open("train_routes_nx_tel3.json", "w") as outfile: json.dump(results, outfile, sort_keys=True, indent=4, ensure_ascii=False) import matplotlib.pyplot as plt pos = nx.kamada_kawai_layout(graph, scale=10) # positions for all nodes # nodes nx.draw_networkx_nodes(graph, pos, node_size=5) # edges nx.draw_networkx_edges(graph, pos) # labels nx.draw_networkx_labels(graph, pos, font_size=5, font_family="sans-serif")
g.add_node(i) # Printing Nodes # print("Nodes are ") print(g.nodes()) # Adding Edges g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(4, 6) g.add_edge(5, 4) g.add_edge(2, 3) g.add_edge(2, 6) # Edge Testing print("Edges are ") print(g.edges()) nx.draw(g) plt.show() # dijkstra's Algorithm h = nx.Graph() e = [('a', 'b', 1), ('b', 'c', 2), ('a', 'c', 3), ('c', 'd', 4), ('d', 'e', 2), ('b', 'e', 1)] h.add_weighted_edges_from(e) nx.draw(h, with_labels=True) plt.show() print(nx.dijkstra_path(h, 'a', 'e'))
def tempo_minimo(grafo, cidade, tempo): def comprimentos(path): vertices = [] vertices.append(path[0]) custo_comprimento = G.edges[path[0], path[1]]['weight'] custo_vertices = 0 for i in range(1, len(path) - 1): custo_comprimento = custo_comprimento + G.edges[path[i], path[i + 1]]['weight'] if path[i] not in vertices: custo_comprimento = custo_comprimento + G.edges[ path[i], path[i]]['weight'] custo_vertices += G.edges[path[i], path[i]]['weight'] vertices.append(path[i]) return custo_comprimento, custo_vertices custo = 0 G = nx.read_edgelist(grafo) caminho = [] caminho.append(cidade) visitados = [cidade] #vértices visitados n_visitados = list(G.nodes()) #vértices não visitados n_visitados.remove(cidade) while custo < tempo: A = [] # lista de vértices adjacentes for n in G.adj[cidade]: if n not in visitados: A.append(n) if len(A) == 0: min = float('inf') for i in n_visitados: tam = nx.dijkstra_path_length( G, source=cidade, target=i) + G.edges[i, i]['weight'] if tam < min: min = tam cidademenor = i W = nx.dijkstra_path(G, source=cidade, target=cidademenor) caminho += W[1:-1] else: for i in A: min = float('inf') if G.edges[cidade, i]['weight'] + G.edges[i, i]['weight'] < min: min = G.edges[cidade, i]['weight'] + G.edges[i, i]['weight'] cidademenor = i caminho.append(cidademenor) n_visitados.remove(cidademenor) if len(n_visitados) == 0: break if cidademenor not in visitados: visitados.append(cidademenor) cidade = cidademenor custo = custo + min caminho_novo = caminho while True: custo, custo_vertices = comprimentos(caminho_novo) if custo > tempo: caminho_novo = caminho[:-1] caminho.remove(caminho[len(caminho) - 1]) else: break print('O melhor caminho é', caminho_novo, 'cujo custo é', custo, '. E o tempo de trabalho é:', custo_vertices)
def Get_ShortestRoute(src_host,dst_host,src_sw,dst_sw,Error_list,shortest_path,begin_insert): #获取网络所有链路的列表 url = 'http://localhost:8080/wm/topology/links/json' links = json.loads(urllib2.urlopen(url).read()) #获取拓扑的交换机链路信息形成图 topo = set(tuple()) sw = set() src_dst_sw_port = dict(tuple()) for link in links: src = int(link['src-switch'].replace(':',''),16) dst = int(link['dst-switch'].replace(':',''),16) src_port = int(link['src-port']) dst_port = int(link['dst-port']) src_dst_sw_port.setdefault(str(src)+str(dst),(src_port,dst_port)) topo.add((src,dst)) sw.add(src) sw.add(dst) # print src_dst_sw_port G = nx.Graph() for s in sw: G.add_node(s) G.add_edges_from(topo) # pos = nx.spectral_layout(G) # nx.draw(G,pos,with_labels=True,node_size = 1,font_size=24,font_color='red') # plt.savefig("Graph.png") try: #生成最短路径 t1=datetime.datetime.now().microsecond shortest_sw_path = nx.dijkstra_path(G,src_sw,dst_sw) t2=datetime.datetime.now().microsecond dijkstra_path_time=str(t2-t1)+"ms" t3=datetime.datetime.now().microsecond nx.all_pairs_shortest_path(G)[src_sw][dst_sw] t4=datetime.datetime.now().microsecond all_shortest_path_time=str(t4-t3)+"ms" def k_shortest_paths(G, source, target, k, weight=None): return list(islice(nx.shortest_simple_paths(G, source, target),k)) t5=datetime.datetime.now().microsecond k_shortest_paths(G,src_sw,dst_sw,1) t6=datetime.datetime.now().microsecond k_shortest_paths_time=str(t6-t5)+"ms" if(len(shortest_sw_path)>=2): # print shortest_sw_path for i in range(0,len(shortest_sw_path)-1): src_sw = str(shortest_sw_path[i]) dst_sw = str(shortest_sw_path[i+1]) src_dst_port = None src_dst_port = src_dst_sw_port.get(src_sw+dst_sw) if(src_dst_port is None): src_dst_port = src_dst_sw_port.get(dst_sw+src_sw) shortest_path.insert(begin_insert,'s'+src_sw+'-eth'+str(src_dst_port[1])) begin_insert += 1 shortest_path.insert(begin_insert,'s'+dst_sw+'-eth'+str(src_dst_port[0])) begin_insert += 1 else: shortest_path.insert(begin_insert,'s'+src_sw+'-eth'+str(src_dst_port[0])) begin_insert += 1 shortest_path.insert(begin_insert,'s'+dst_sw+'-eth'+str(src_dst_port[1])) begin_insert += 1 shortest_path.append({"dijkstra_path_time":dijkstra_path_time}) shortest_path.append({"all_shortest_path_time":all_shortest_path_time}) shortest_path.append({"k_shortest_paths_time":k_shortest_paths_time}) except Exception,e: print e Error_list = [] shortest_path = [] if 's' not in src_host: src_host = 'h' + src_host if 's' not in dst_host: dst_host = 'h' + dst_host Error_list.append(str(src_host)+' to '+str(dst_host)+' unreachable')
def update(): env.update_vehicle_info = False # Clean out the old object env.vehicles_active = [] # Refill total = len(env.vehicles) for i,v in enumerate(env.vehicles): veh = dict() # Who am I? veh['id'] = v['id'] # Where am I? veh['route index'] = env.traci.vehicle.getRouteIndex(veh['id']) # What is my route? veh['route id'] = env.traci.vehicle.getRouteID(veh['id']) # What is my sink node? veh['destination node'] = env.vehicles_dest[int(veh['id'][3:])] if veh['route index'] < 0: veh['route index'] = 0 veh['position on edge (m)'] = 0.000001 eid = env.traci.route.getEdges(veh['route id'])[0] else: # How far along the edge am I (m)? veh['position on edge (m)'] = env.traci.vehicle.getLanePosition(veh['id']) # What edge am I on? eid = env.traci.vehicle.getRoadID(veh['id']) # Obtain the edge object. Here we can have two cases: # 1. veh is at an intersection # 2. veh is on an edg # Veh is within an intersection. Assume the start of the next edge with a position on edge (m) of zero. if ':' in eid: veh['route'] = env.traci.route.getEdges(veh['route id']) eid = veh['route'][veh['route index']+1] veh['current edge'] = purr.filterdicts(env.edges,'id',eid)[0] veh['position on edge (m)'] = 0.000001 else: veh['current edge'] = purr.filterdicts(env.edges,'id',eid)[0] # How far am I along the edge (weight) veh['position on edge (s)'] = veh['position on edge (m)'] / float(veh['current edge']['speed']) # How much weight to the end of the edge? edge_candidates = env.nx.get_edge_data(veh['current edge']['from'],veh['current edge']['to']) for j in range(len(edge_candidates)): if veh['current edge']['id'] == edge_candidates[j]['id']: veh['weight remaining'] = edge_candidates[j]['weight'] - veh['position on edge (s)'] break continue # What is the weight of Veh --> Dest veh['veh2dest weight'] = veh['weight remaining'] + nxops.path_info(env.nx,nx.dijkstra_path(env.nx,veh['current edge']['to'],veh['destination node']['id']))[0] env.vehicles_active.append(veh) purr.update(i+1,total,"Updating vehicle location data ") # ~ env.recalculate_nash = True continue print() return
import networkx as nx import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt # create directed graph G = nx.DiGraph() # add nodes of the graph G.add_node('A') G.add_node('B') G.add_node('C') G.add_node('D') G.add_node('E') # add links of the graph G.add_edge('A', 'B', weight=4) G.add_edge('A', 'C', weight=1) G.add_edge('C', 'B', weight=2) G.add_edge('C', 'D', weight=2) G.add_edge('B', 'E', weight=3) G.add_edge('D', 'E', weight=3) # there are other ways adding nodes and edges you can check it online # find the shortest path from node A pred, dist = nx.dijkstra_predecessor_and_distance(G, 'A') print("The pred for each node with respect to source A") print(sorted(pred.items())) print("The distance label for each node with respect to A") print(sorted(dist.items())) print("The shrotest path between A and E is") # print shortest path between a pair of nodes print(nx.dijkstra_path(G, 'A', 'E'))
# Create the graph based on the 2d matrix. graph = create_graph(matrix) pos = dict(zip(graph, graph)) path = [] node_sizes = list(map(lambda n: 50 if n == point1 or n == point2 else 20, graph.nodes())) # Plot graph. plt.subplot(221) plt.title("Graph") nx.draw(graph, pos, node_color = color_map(graph, [], (-1, -1), (-1, -1)), node_size = node_sizes) # Calculate the path between the two points using Dijkstra's algorithm. try: path = nx.dijkstra_path(graph, point1, point2) print("Dijkstra Path") print(path) except nx.exception.NodeNotFound: print("The node/nodes are not found in the graph.") except: print("Cound not find path in graph.") # Plot Dijkstra's path. plt.subplot(222) plt.title("Dijkstra Path") nx.draw(graph, pos, node_color = color_map(graph, path[1:-1], point1, point2), with_labels=False, node_size = node_sizes) # Calculate the path between the two points using A* algorithm. try: path = nx.astar_path(graph, point1, point2, dist)