我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用networkx.MultiGraph()。
def get_graph_for_vlan(vlan): """Builds a simple topology graph of the active netboxes in vlan. Any netbox that seems to be down at the moment will not be included in the graph. :returns: A networkx.Graph object. """ swpvlan = SwPortVlan.objects.filter(vlan=vlan).select_related( 'interface', 'interface__netbox', 'interface__to_netbox', 'interface__to_interface') graph = networkx.MultiGraph(name='graph for vlan %s' % vlan) for swp in swpvlan: source = swp.interface.netbox source_ifc = swp.interface target = swp.interface.to_netbox target_ifc = swp.interface.to_interface if target: key = tuple(sorted( (source_ifc.id, target_ifc.id if target_ifc else None))) data = set([source_ifc, target_ifc]) graph.add_edge(source, target, key=key, data=data) return graph
def Euler_Tour(multigraph): """ Uses Fleury's algorithm to find the Euler Tour of the MultiGraph. """ tour = [] temp_graph = nx.MultiGraph() graph_nodes = nx.nodes(multigraph) current_node = graph_nodes[0] tour.append(current_node) while nx.number_of_edges(multigraph) > 0: for edge in multigraph.edges(current_node): temp_graph = copy.deepcopy(multigraph) temp_graph.remove_edge(edge[0], edge[1], key=None) if nx.is_connected(temp_graph): tour.append(edge[1]) current_node = edge[1] multigraph.remove_edge(edge[0], edge[1], key=None) break else: tour.append(edge[1]) current_node = edge[1] multigraph.remove_edge(edge[0], edge[1], key=None) multigraph.remove_nodes_from(nx.isolates(multigraph)) return tour
def _get_shortest__path_between_subgraphs_helper(graph, a, b): """Calculate the shortest path that occurs between two disconnected subgraphs A and B going through nodes in the source graph :param nx.MultiGraph graph: A graph :param nx.MultiGraph a: A subgraph of :code:`graph`, disjoint from :code:`b` :param nx.MultiGraph b: A subgraph of :code:`graph`, disjoint from :code:`a` :return: A list of the shortest paths between the two subgraphs :rtype: list """ shortest_paths = [] for na, nb in itt.product(a, b): a_b_shortest_path = nx.shortest_path(graph, na, nb) shortest_paths.append(a_b_shortest_path) b_a_shortest_path = nx.shortest_path(graph, nb, na) shortest_paths.append(b_a_shortest_path) min_len = min(map(len, shortest_paths)) return [p for p in shortest_paths if len(p) == min_len]
def projected_graph(B, nodes, multigraph=False): if B.is_multigraph(): raise nx.NetworkXError("not defined for multigraphs") if B.is_directed(): directed=True if multigraph: G=nx.MultiDiGraph() else: G=nx.DiGraph() else: directed=False if multigraph: G=nx.MultiGraph() else: G=nx.Graph() G.graph.update(B.graph) G.add_nodes_from((n,B.node[n]) for n in nodes) i = 0 nodes = set(nodes) tenpercent = len(nodes) / 10 for u in nodes: if i % tenpercent == 0: logging.info(str(10 * i / tenpercent) + "%") i += 1 nbrs2=set((v for nbr in B[u] for v in B[nbr])) & nodes - set([u]) if multigraph: for n in nbrs2: if directed: links=set(B[u]) & set(B.pred[n]) else: links=set(B[u]) & set(B[n]) for l in links: if not G.has_edge(u,n,l): G.add_edge(u,n,key=l) else: G.add_edges_from((u,n) for n in nbrs2) return G
def get_label_from_edge(g, edge, attribute_name='label'): edge_attributes = g.get_edge_data(edge[0], edge[1]) if edge_attributes is None and nx.is_directed(g): edge_attributes = g.get_edge_data(edge[1], edge[0]) labels = [] if type(g) == nx.MultiDiGraph or type(g) == nx.MultiGraph: for index in edge_attributes: if attribute_name in edge_attributes[index]: labels.append(edge_attributes[index][attribute_name]) else: if attribute_name in edge_attributes: labels.append(edge_attributes[attribute_name]) return labels
def __init__(self): self.g = nx.MultiGraph() self.newNodeUid = 0 self.startNode = None self.finishNode = None self.distTol = 75 # Distance tolerance to consider two nodes to be the same self.farAway = 10000 # A long distance...
def build_graph(nodes, edges, multi=False): graph = nx.MultiGraph() if multi else nx.Graph() for i in range(len(nodes)): graph.add_node(i, pts=nodes[i], o=nodes[i].mean(axis=0)) for s,e,pts in edges: l = np.linalg.norm(pts[1:]-pts[:-1], axis=1).sum() graph.add_edge(s,e, pts=pts, weight=l) return graph
def load(self, ips): if not isinstance(ips.data, nx.MultiGraph): IPy.alert("Please build graph!"); return False; return True;
def graph_from_edges(edges): """ Construct an undirected multigraph from a list containing data on weighted edges. Parameters ---------- edges : list List of tuples each containing first node, second node, weight, key. Returns ------- M : :class:`networkx.classes.multigraph.MultiGraph """ M = nx.MultiGraph() for e in edges: n0, n1, weight, key = e M.add_edge(n0, n1, weight=weight, key=key) return M
def shortest_path(paths, graph): """ Finding minimum path lengths between sources and targets pairs defined in paths. Parameters ---------- ways : list List of tuples containing a source and target node graph : :class:`networkx.classes.multigraph.MultiGraph Graph representation of an electrical grid. Returns ------- df : pd.DataFrame DataFrame holding source and target node and the minimum path length. """ idxnames = ['source', 'target'] idx = pd.MultiIndex.from_tuples(paths, names=idxnames) df = pd.DataFrame(index=idx, columns=['path_length']) df.sort_index(inplace=True) for s, t in paths: try: df.loc[(s, t), 'path_length'] = \ nx.dijkstra_path_length(graph, s, t) except NetworkXNoPath: continue return df
def graph_constructor(directed, multi): '''Returns the class to construct the appropriate graph type.''' if directed: if multi: constructor = nx.MultiDiGraph else: constructor = nx.DiGraph else: if multi: constructor = nx.MultiGraph else: constructor = nx.Graph return constructor
def create_Multigraph(M, MST, indexes, odd_vertices): """Creates a MultiGraph consisting of vertices of both MST and MCPM. """ multigraph = nx.MultiGraph() for u,v,d in MST: multigraph.add_edge(u,v,weight=d) for pair in indexes: multigraph.add_edge(pair[0],pair[1],weight=M[pair[0]][pair[1]]) return multigraph
def get_undirected(G): """ Convert a directed graph to an undirected graph that maintains parallel edges if geometries differ. Parameters ---------- G : networkx multidigraph Returns ------- networkx multigraph """ start_time = time.time() # set from/to nodes before making graph undirected G = G.copy() for u, v, k in G.edges(keys=True): G.edges[u, v, k]['from'] = u G.edges[u, v, k]['to'] = v # now convert multidigraph to a multigraph, retaining all edges in both # directions for now, as well as all graph attributes H = nx.MultiGraph() H.add_nodes_from(G.nodes(data=True)) H.add_edges_from(G.edges(keys=True, data=True)) H.graph = G.graph H.name = G.name # the previous operation added all directed edges from G as undirected # edges in H. this means we have duplicate edges for every bi-directional # street. so, look through the edges and remove any duplicates duplicate_edges = [] for u, v, key, data in H.edges(keys=True, data=True): # if we haven't already flagged this edge as a duplicate if not (u, v, key) in duplicate_edges: # look at every other edge between u and v, one at a time for key_other in H[u][v]: # don't compare this edge to itself if not key_other == key: # compare the first edge's data to the second's to see if # they are duplicates data_other = H.edges[u, v, key_other] if is_duplicate_edge(data, data_other): # if they match up, flag the duplicate for removal duplicate_edges.append((u, v, key_other)) H.remove_edges_from(duplicate_edges) log('Made undirected graph in {:,.2f} seconds'.format(time.time() - start_time)) return H
def makeEulerianGraph(self, G): oddNodes = [] for n in G.nodes(): if G.degree(n) % 2 != 0: oddNodes.append(n) #self.log("Number of nodes with odd degree: " + str(len(oddNodes))) if len(oddNodes) == 0: return G self.computeEdgeWeights(G) pathsToDuplicate = [] while(oddNodes): n1 = oddNodes[0] shortestPaths = [] #For every other node, find the shortest path to the closest node for n2 in oddNodes: if n2 != n1: #self.log(str(n1) + " " + str(n2)) shortestPath = nx.astar_path(G, n1, n2, lambda n1, n2: self.dist(G.node[n1], G.node[n2]), 'weight') #self.log(str(len(shortestPath))) shortestPaths.append(shortestPath) if len(shortestPath) <= STOP_SHORTEST_PATH_IF_SMALLER_OR_EQUAL_TO: #If we find a path of length <= STOP_SHORTEST_PATH_IF_SMALLER_OR_EQUAL_TO, #we assume it's good enough (to speed up calculation) break #For all the shortest paths from n1, we take the shortest one and therefore get the closest odd node shortestShortestPath = min(shortestPaths, key=lambda x: self.pathLength(G, x)) closestNode = shortestShortestPath[-1] pathsToDuplicate.append(shortestShortestPath) oddNodes.pop(0) oddNodes.remove(closestNode) numberOfDuplicatedEdges = 0 lenghtOfDuplicatedEdges = 0.0 for path in pathsToDuplicate: numberOfDuplicatedEdges += len(path)-1 pathLength = self.pathLength(G, path) #self.log("Path length: " + str(pathLength)) lenghtOfDuplicatedEdges += pathLength #self.log("Number of duplicated edges: " + str(numberOfDuplicatedEdges)) #self.log("Length of duplicated edges: " + str(lenghtOfDuplicatedEdges)) #Convert the graph to a MultiGraph to allow parallel edges G2 = nx.MultiGraph(G) for path in pathsToDuplicate: nx.add_path(G2, path) return G2 #Doesn't modify input graph #faster than makeEulerianGraph but creates an extra node
def read_gml(path, relabel=False): """Read graph in GML format from path. Parameters ---------- path : filename or filehandle The filename or filehandle to read from. relabel : bool, optional If True use the GML node label attribute for node names otherwise use the node id. Returns ------- G : MultiGraph or MultiDiGraph Raises ------ ImportError If the pyparsing module is not available. See Also -------- write_gml, parse_gml Notes ----- Requires pyparsing: http://pyparsing.wikispaces.com/ The GML specification says that files should be ASCII encoded, with any extended ASCII characters (iso8859-1) appearing as HTML character entities. References ---------- GML specification: http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html Examples -------- >>> G=nx.path_graph(4) >>> nx.write_gml(G,'test.gml') >>> H=nx.read_gml('test.gml') """ lines = (unescape(line.decode('ascii')) for line in path) G = parse_gml(lines, relabel=relabel) return G