Python networkx.MultiGraph() Examples
The following are 30
code examples of networkx.MultiGraph().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def adjacency_list(self): """Return an adjacency list representation of the graph. The output adjacency list is in the order of G.nodes(). For directed graphs, only outgoing adjacencies are included. Returns ------- adj_list : lists of lists The adjacency structure of the graph as a list of lists. See Also -------- adjacency_iter Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> G.adjacency_list() # in order given by G.nodes() [[1], [0, 2], [1, 3], [2]] """ return list(map(list,iter(self.adj.values())))
Example #2
Source File: test_function.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_get_edge_attributes(): graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()] for G in graphs: G = nx.path_graph(3, create_using=G) attr = 'hello' vals = 100 nx.set_edge_attributes(G, attr, vals) attrs = nx.get_edge_attributes(G, attr) assert_equal(len(attrs), 2) if G.is_multigraph(): keys = [(0,1,0), (1,2,0)] else: keys = [(0,1), (1,2)] for key in keys: assert_equal(attrs[key], 100)
Example #3
Source File: ontol.py From ontobio with BSD 3-Clause "New" or "Revised" License | 6 votes |
def merge(self, ontologies): """ Merges specified ontology into current ontology """ if self.xref_graph is None: self.xref_graph = nx.MultiGraph() logger.info("Merging source: {} xrefs: {}".format(self, len(self.xref_graph.edges()))) for ont in ontologies: logger.info("Merging {} into {}".format(ont, self)) g = self.get_graph() srcg = ont.get_graph() for n in srcg.nodes(): g.add_node(n, **srcg.node[n]) for (o,s,m) in srcg.edges(data=True): g.add_edge(o,s,**m) if ont.xref_graph is not None: for (o,s,m) in ont.xref_graph.edges(data=True): self.xref_graph.add_edge(o,s,**m)
Example #4
Source File: mininet_test_watcher.py From faucet with Apache License 2.0 | 6 votes |
def generate_predicted_graph(self, dpids, switch_links, host_links, host_information): """Creates the predicted network graph""" self.predicted_network_graph = networkx.MultiGraph() for dpid in dpids: self.predicted_network_graph.add_node(dpid) for link in switch_links: u, v = link self.predicted_network_graph.add_edge(self.dpids[u], self.dpids[v]) self.host_name_to_index = {} for host_id, host_info in host_information.items(): host_name = host_info['host'].name self.host_name_to_index[host_name] = host_id self.predicted_network_graph.add_node(host_name) links = host_links[host_id] for link in links: self.predicted_network_graph.add_edge(host_name, self.dpids[link])
Example #5
Source File: test_function.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_set_edge_attributes_multi(): graphs = [nx.MultiGraph(), nx.MultiDiGraph()] for G in graphs: G = nx.path_graph(3, create_using=G) # Test single value attr = 'hello' vals = 3 nx.set_edge_attributes(G, attr, vals) assert_equal(G[0][1][0][attr], vals) assert_equal(G[1][2][0][attr], vals) # Test multiple values attr = 'hi' edges = [(0,1,0), (1,2,0)] vals = dict(zip(edges, range(len(edges)))) nx.set_edge_attributes(G, attr, vals) assert_equal(G[0][1][0][attr], 0) assert_equal(G[1][2][0][attr], 1)
Example #6
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def __len__(self): """Return the number of nodes. Use the expression 'len(G)'. Returns ------- nnodes : int The number of nodes in the graph. Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> len(G) 4 """ return len(self.node)
Example #7
Source File: nx_pydot.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def read_dot(path): """Return a NetworkX MultiGraph or MultiDiGraph from a dot file on path. Parameters ---------- path : filename or file handle Returns ------- G : NetworkX multigraph A MultiGraph or MultiDiGraph. Notes ----- Use G = nx.Graph(read_dot(path)) to return a Graph instead of a MultiGraph. """ import pydotplus data = path.read() P = pydotplus.graph_from_dot_data(data) return from_pydot(P)
Example #8
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def number_of_nodes(self): """Return the number of nodes in the graph. Returns ------- nnodes : int The number of nodes in the graph. See Also -------- order, __len__ which are identical Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) >>> len(G) 3 """ return len(self.node)
Example #9
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def has_node(self, n): """Return True if the graph contains the node n. Parameters ---------- n : node Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) >>> G.has_node(0) True It is more readable and simpler to use >>> 0 in G True """ try: return n in self.node except TypeError: return False
Example #10
Source File: drawing.py From peregrine with MIT License | 6 votes |
def format_graph_for_json(graph, raise_errors=True): """ Currently, only supported types for graph are Graph, DiGraph, MultiGraph, and MultiDiGraph. graph must be an instance of one of these types, not a class that inherits from one. """ graph_dict = nx.to_dict_of_dicts(graph) graph_type = '' for key, value in accepted_types.items(): if type(graph) == key: graph_type = value break if graph_type == '': if raise_errors: raise TypeError('parameter graph is not of the accepted types.graph is of' 'type {}'.format(str(type(graph)))) else: graph_type = 'other' return {'graph_type': graph_type, 'graph_dict': graph_dict}
Example #11
Source File: utils.py From momepy with MIT License | 6 votes |
def gdf_to_nx(gdf_network, approach="primal", length="mm_len"): """ Convert LineString GeoDataFrame to networkx.MultiGraph Parameters ---------- gdf_network : GeoDataFrame GeoDataFrame containing objects to convert approach : str, default 'primal' Decide wheter genereate ``'primal'`` or ``'dual'`` graph. length : str, default mm_len name of attribute of segment length (geographical) which will be saved to graph Returns ------- networkx.Graph Graph """ gdf_network = gdf_network.copy() if "key" in gdf_network.columns: gdf_network.rename(columns={"key": "__key"}, inplace=True) # generate graph from GeoDataFrame of LineStrings net = nx.MultiGraph() net.graph["crs"] = gdf_network.crs gdf_network[length] = gdf_network.geometry.length fields = list(gdf_network.columns) if approach == "primal": _generate_primal(net, gdf_network, fields) elif approach == "dual": _generate_dual(net, gdf_network, fields) else: raise ValueError( "Approach {} is not supported. Use 'primal' or 'dual'.".format(approach) ) return net
Example #12
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def neighbors_iter(self, n): """Return an iterator over all neighbors of node n. Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> [n for n in G.neighbors_iter(0)] [1] Notes ----- It is faster to use the idiom "in G[0]", e.g. >>> G = nx.path_graph(4) >>> [n for n in G[0]] [1] """ try: return iter(self.adj[n]) except KeyError: raise NetworkXError("The node %s is not in the graph."%(n,))
Example #13
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def nodes_iter(self, data=False): """Return an iterator over the nodes. Parameters ---------- data : boolean, optional (default=False) If False the iterator returns nodes. If True return a two-tuple of node and node data dictionary Returns ------- niter : iterator An iterator over nodes. If data=True the iterator gives two-tuples containing (node, node data, dictionary) Notes ----- If the node data is not required it is simpler and equivalent to use the expression 'for n in G'. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) >>> [d for n,d in G.nodes_iter(data=True)] [{}, {}, {}] """ if data: return iter(self.node.items()) return iter(self.node)
Example #14
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def remove_nodes_from(self, nodes): """Remove multiple nodes. Parameters ---------- nodes : iterable container A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored. See Also -------- remove_node Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) >>> e = G.nodes() >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> G.nodes() [] """ adj = self.adj for n in nodes: try: del self.node[n] for u in list(adj[n].keys()): # keys() handles self-loops del adj[u][n] #(allows mutation of dict in loop) del adj[n] except KeyError: pass
Example #15
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def remove_edges_from(self, ebunch): """Remove all edges specified in ebunch. Parameters ---------- ebunch: list or container of edge tuples Each edge given in the list or container will be removed from the graph. The edges can be: - 2-tuples (u,v) edge between u and v. - 3-tuples (u,v,k) where k is ignored. See Also -------- remove_edge : remove a single edge Notes ----- Will fail silently if an edge in ebunch is not in the graph. Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> ebunch=[(1,2),(2,3)] >>> G.remove_edges_from(ebunch) """ adj=self.adj for e in ebunch: u,v = e[:2] # ignore edge data if present if u in adj and v in adj[u]: del adj[u][v] if u != v: # self loop needs only one entry removed del adj[v][u]
Example #16
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def nodes(self, data=False): """Return a list of the nodes in the graph. Parameters ---------- data : boolean, optional (default=False) If False return a list of nodes. If True return a two-tuple of node and node data dictionary Returns ------- nlist : list A list of nodes. If data=True a list of two-tuples containing (node, node data dictionary). Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2]) >>> G.nodes() [0, 1, 2] >>> G.add_node(1, time='5pm') >>> G.nodes(data=True) [(0, {}), (1, {'time': '5pm'}), (2, {})] """ return list(self.nodes_iter(data=data))
Example #17
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def __getitem__(self, n): """Return a dict of neighbors of node n. Use the expression 'G[n]'. Parameters ---------- n : node A node in the graph. Returns ------- adj_dict : dictionary The adjacency dictionary for nodes connected to n. Notes ----- G[n] is similar to G.neighbors(n) but the internal data dictionary is returned instead of a list. Assigning G[n] will corrupt the internal graph data structure. Use G[n] for reading data only. Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> G[0] {1: {}} """ return self.adj[n]
Example #18
Source File: test_sparse6.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_parse_multigraph_graph(self): graph_data = ':An' G = nx.parse_sparse6(graph_data) assert_true(type(G), nx.Graph) multigraph_data = ':Ab' M = nx.parse_sparse6(multigraph_data) assert_true(type(M), nx.MultiGraph)
Example #19
Source File: test_convert_numpy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_symmetric(self): """Tests that a symmetric matrix has edges added only once to an undirected multigraph when using :func:`networkx.from_numpy_matrix`. """ A = np.matrix([[0, 1], [1, 0]]) G = nx.from_numpy_matrix(A, create_using=nx.MultiGraph()) expected = nx.MultiGraph() expected.add_edge(0, 1, weight=1) assert_graphs_equal(G, expected)
Example #20
Source File: timingclasses.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def has_edge(self, u, v): """Return True if the edge (u,v) is in the graph. Parameters ---------- u,v : nodes Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects. Returns ------- edge_ind : bool True if edge is in the graph, False otherwise. Examples -------- Can be called either using two nodes u,v or edge tuple (u,v) >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_path([0,1,2,3]) >>> G.has_edge(0,1) # using two nodes True >>> e = (0,1) >>> G.has_edge(*e) # e is a 2-tuple (u,v) True >>> e = (0,1,{'weight':7}) >>> G.has_edge(*e[:2]) # e is a 3-tuple (u,v,data_dictionary) True The following syntax are all equivalent: >>> G.has_edge(0,1) True >>> 1 in G[0] # though this gives KeyError if 0 not in G True """ try: return v in self.adj[u] except KeyError: return False
Example #21
Source File: test_convert_scipy.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_symmetric(self): """Tests that a symmetric matrix has edges added only once to an undirected multigraph when using :func:`networkx.from_scipy_sparse_matrix`. """ A = sparse.csr_matrix([[0, 1], [1, 0]]) G = nx.from_scipy_sparse_matrix(A, create_using=nx.MultiGraph()) expected = nx.MultiGraph() expected.add_edge(0, 1, weight=1) assert_graphs_equal(G, expected)
Example #22
Source File: graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def make_graph(self, graph_xml, graphml_keys, defaults): # set default graph type edgedefault = graph_xml.get("edgedefault", None) if edgedefault=='directed': G=nx.MultiDiGraph() else: G=nx.MultiGraph() # set defaults for graph attributes G.graph['node_default']={} G.graph['edge_default']={} for key_id,value in defaults.items(): key_for=graphml_keys[key_id]['for'] name=graphml_keys[key_id]['name'] python_type=graphml_keys[key_id]['type'] if key_for=='node': G.graph['node_default'].update({name:python_type(value)}) if key_for=='edge': G.graph['edge_default'].update({name:python_type(value)}) # hyperedges are not supported hyperedge=graph_xml.find("{%s}hyperedge" % self.NS_GRAPHML) if hyperedge is not None: raise nx.NetworkXError("GraphML reader does not support hyperedges") # add nodes for node_xml in graph_xml.findall("{%s}node" % self.NS_GRAPHML): self.add_node(G, node_xml, graphml_keys) # add edges for edge_xml in graph_xml.findall("{%s}edge" % self.NS_GRAPHML): self.add_edge(G, edge_xml, graphml_keys) # add graph data data = self.decode_data_elements(graphml_keys, graph_xml) G.graph.update(data) # switch to Graph or DiGraph if no parallel edges were found. if not self.multigraph: if G.is_directed(): return nx.DiGraph(G) else: return nx.Graph(G) else: return G
Example #23
Source File: graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def parse_graphml(graphml_string,node_type=str): """Read graph in GraphML format from string. Parameters ---------- graphml_string : string String containing graphml information (e.g., contents of a graphml file). node_type: Python type (default: str) Convert node ids to this type Returns ------- graph: NetworkX graph If no parallel edges are found a Graph or DiGraph is returned. Otherwise a MultiGraph or MultiDiGraph is returned. Examples -------- >>> G=nx.path_graph(4) >>> linefeed=chr(10) # linefeed=\n >>> s=linefeed.join(nx.generate_graphml(G)) >>> H=nx.parse_graphml(s) Notes ----- This implementation does not support mixed graphs (directed and unidirected edges together), hypergraphs, nested graphs, or ports. For multigraphs the GraphML edge "id" will be used as the edge key. If not specified then they "key" attribute will be used. If there is no "key" attribute a default NetworkX multigraph edge key will be provided. """ reader = GraphMLReader(node_type=node_type) # need to check for multiple graphs glist=list(reader(string=graphml_string)) return glist[0]
Example #24
Source File: graphml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def read_graphml(path,node_type=str): """Read graph in GraphML format from path. Parameters ---------- path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be compressed. node_type: Python type (default: str) Convert node ids to this type Returns ------- graph: NetworkX graph If no parallel edges are found a Graph or DiGraph is returned. Otherwise a MultiGraph or MultiDiGraph is returned. Notes ----- This implementation does not support mixed graphs (directed and unidirected edges together), hypergraphs, nested graphs, or ports. For multigraphs the GraphML edge "id" will be used as the edge key. If not specified then they "key" attribute will be used. If there is no "key" attribute a default NetworkX multigraph edge key will be provided. Files with the yEd "yfiles" extension will can be read but the graphics information is discarded. yEd compressed files ("file.graphmlz" extension) can be read by renaming the file to "file.graphml.gz". """ reader = GraphMLReader(node_type=node_type) # need to check for multiple graphs glist=list(reader(path=path)) return glist[0]
Example #25
Source File: test_adjacency.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_multigraph(self): G = nx.MultiGraph() G.add_edge(1,2,key='first') G.add_edge(1,2,key='second',color='blue') H = adjacency_graph(adjacency_data(G)) nx.is_isomorphic(G,H) assert_equal(H[1][2]['second']['color'],'blue')
Example #26
Source File: gexf.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def read_gexf(path,node_type=None,relabel=False,version='1.1draft'): """Read graph in GEXF format from path. "GEXF (Graph Exchange XML Format) is a language for describing complex networks structures, their associated data and dynamics" [1]_. Parameters ---------- path : file or string File or file name to write. File names ending in .gz or .bz2 will be compressed. node_type: Python type (default: None) Convert node ids to this type if not None. relabel : bool (default: False) If True relabel the nodes to use the GEXF node "label" attribute instead of the node "id" attribute as the NetworkX node label. Returns ------- graph: NetworkX graph If no parallel edges are found a Graph or DiGraph is returned. Otherwise a MultiGraph or MultiDiGraph is returned. Notes ----- This implementation does not support mixed graphs (directed and undirected edges together). References ---------- .. [1] GEXF graph format, http://gexf.net/format/ """ reader = GEXFReader(node_type=node_type,version=version) if relabel: G=relabel_gexf_graph(reader(path)) else: G=reader(path) return G
Example #27
Source File: test_edgelist.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_edgelist_multigraph(self): G=self.XG (fd,fname)=tempfile.mkstemp() nx.write_edgelist(G,fname) H=nx.read_edgelist(fname,nodetype=int,create_using=nx.MultiGraph()) H2=nx.read_edgelist(fname,nodetype=int,create_using=nx.MultiGraph()) assert_not_equal(H,H2) # they should be different graphs assert_nodes_equal(H.nodes(),G.nodes()) assert_edges_equal(H.edges(),G.edges()) os.close(fd) os.unlink(fname)
Example #28
Source File: tests.py From networkx_viewer with GNU General Public License v3.0 | 5 votes |
def setUp(self): super(TestGraphCanvasMultiGraph, self).setUp() # Add in some extra edges G = nx.MultiGraph(self.input_G) G.add_edge('a','c') G.add_edge('out',12) G.add_edge('out',12) G.add_edge('out',12) self.input_G = G.copy() # Viewer under test self.a = nxv.GraphCanvas(G)
Example #29
Source File: test_yaml.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def build_graphs(self): self.G = nx.Graph(name="test") e = [('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] self.G.add_edges_from(e) self.G.add_node('g') self.DG = nx.DiGraph(self.G) self.MG = nx.MultiGraph() self.MG.add_weighted_edges_from([(1,2,5),(1,2,5),(1,2,1),(3,3,42)])
Example #30
Source File: test_edgelist.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def setUp(self): self.G=nx.Graph(name="test") e=[('a','b'),('b','c'),('c','d'),('d','e'),('e','f'),('a','f')] self.G.add_edges_from(e) self.G.add_node('g') self.DG=nx.DiGraph(self.G) self.XG=nx.MultiGraph() self.XG.add_weighted_edges_from([(1,2,5),(1,2,5),(1,2,1),(3,3,42)]) self. XDG=nx.MultiDiGraph(self.XG)