index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
31,049
networkx.generators.trees
random_tree
Returns a uniformly random tree on `n` nodes. .. deprecated:: 3.2 ``random_tree`` is deprecated and will be removed in NX v3.4 Use ``random_labeled_tree`` instead. Parameters ---------- n : int A positive integer representing the number of nodes in the tree. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- NetworkX graph A tree, given as an undirected graph, whose nodes are numbers in the set {0, …, *n* - 1}. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). Notes ----- The current implementation of this function generates a uniformly random Prüfer sequence then converts that to a tree via the :func:`~networkx.from_prufer_sequence` function. Since there is a bijection between Prüfer sequences of length *n* - 2 and trees on *n* nodes, the tree is chosen uniformly at random from the set of all trees on *n* nodes. Examples -------- >>> tree = nx.random_tree(n=10, seed=0) >>> nx.write_network_text(tree, sources=[0]) ╙── 0 ├── 3 └── 4 ├── 6 │ ├── 1 │ ├── 2 │ └── 7 │ └── 8 │ └── 5 └── 9 >>> tree = nx.random_tree(n=10, seed=0, create_using=nx.DiGraph) >>> nx.write_network_text(tree) ╙── 0 ├─╼ 3 └─╼ 4 ├─╼ 6 │ ├─╼ 1 │ ├─╼ 2 │ └─╼ 7 │ └─╼ 8 │ └─╼ 5 └─╼ 9
def random_unlabeled_rooted_tree(n, *, number_of_trees=None, seed=None): """Returns a number of unlabeled rooted trees uniformly at random Returns one or more (depending on `number_of_trees`) unlabeled rooted trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. The "root" graph attribute identifies the root of the tree. Notes ----- The trees are generated using the "RANRUT" algorithm from [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 """ if n == 0: raise nx.NetworkXPointlessConcept("the null graph is not a tree") cache_trees = [0, 1] # initial cache of number of rooted trees if number_of_trees is None: return _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) return [ _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) for i in range(number_of_trees) ]
(n, seed=None, create_using=None, *, backend=None, **backend_kwargs)
31,050
networkx.algorithms.triads
random_triad
Returns a random triad from a directed graph. .. deprecated:: 3.3 random_triad is deprecated and will be removed in version 3.5. Use random sampling directly instead:: G.subgraph(random.sample(list(G), 3)) Parameters ---------- G : digraph A NetworkX DiGraph seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G2 : subgraph A randomly selected triad (order-3 NetworkX DiGraph) Raises ------ NetworkXError If the input Graph has less than 3 nodes. Examples -------- >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 1), (5, 6), (5, 4), (6, 7)]) >>> triad = nx.random_triad(G, seed=1) >>> triad.edges OutEdgeView([(1, 2)])
null
(G, seed=None, *, backend=None, **backend_kwargs)
31,051
networkx.generators.trees
random_unlabeled_rooted_forest
Returns a forest or list of forests selected at random. Returns one or more (depending on `number_of_forests`) unlabeled rooted forests with `n` nodes, and with no more than `q` nodes per tree, drawn uniformly at random. The "roots" graph attribute identifies the roots of the forest. Parameters ---------- n : int The number of nodes q : int or None (default) The maximum number of nodes per tree. number_of_forests : int or None (default) If not None, this number of forests is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_forests` is specified) with nodes in the set {0, …, *n* - 1}. The "roots" graph attribute is a set containing the roots of the trees in the forest. Notes ----- This function implements the algorithm "Forest" of [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_forests` optional argument to reuse the counting functions. Raises ------ ValueError If `n` is non-zero but `q` is zero. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3
def random_unlabeled_rooted_tree(n, *, number_of_trees=None, seed=None): """Returns a number of unlabeled rooted trees uniformly at random Returns one or more (depending on `number_of_trees`) unlabeled rooted trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. The "root" graph attribute identifies the root of the tree. Notes ----- The trees are generated using the "RANRUT" algorithm from [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 """ if n == 0: raise nx.NetworkXPointlessConcept("the null graph is not a tree") cache_trees = [0, 1] # initial cache of number of rooted trees if number_of_trees is None: return _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) return [ _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) for i in range(number_of_trees) ]
(n, *, q=None, number_of_forests=None, seed=None, backend=None, **backend_kwargs)
31,052
networkx.generators.trees
random_unlabeled_rooted_tree
Returns a number of unlabeled rooted trees uniformly at random Returns one or more (depending on `number_of_trees`) unlabeled rooted trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. The "root" graph attribute identifies the root of the tree. Notes ----- The trees are generated using the "RANRUT" algorithm from [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3
def random_unlabeled_rooted_tree(n, *, number_of_trees=None, seed=None): """Returns a number of unlabeled rooted trees uniformly at random Returns one or more (depending on `number_of_trees`) unlabeled rooted trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. The "root" graph attribute identifies the root of the tree. Notes ----- The trees are generated using the "RANRUT" algorithm from [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 """ if n == 0: raise nx.NetworkXPointlessConcept("the null graph is not a tree") cache_trees = [0, 1] # initial cache of number of rooted trees if number_of_trees is None: return _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) return [ _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) for i in range(number_of_trees) ]
(n, *, number_of_trees=None, seed=None, backend=None, **backend_kwargs)
31,053
networkx.generators.trees
random_unlabeled_tree
Returns a tree or list of trees chosen randomly. Returns one or more (depending on `number_of_trees`) unlabeled trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). Notes ----- This function generates an unlabeled tree uniformly at random using Wilf's algorithm "Free" of [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. References ---------- .. [1] Wilf, Herbert S. "The uniform selection of free trees." Journal of Algorithms 2.2 (1981): 204-207. https://doi.org/10.1016/0196-6774(81)90021-3
def random_unlabeled_rooted_tree(n, *, number_of_trees=None, seed=None): """Returns a number of unlabeled rooted trees uniformly at random Returns one or more (depending on `number_of_trees`) unlabeled rooted trees with `n` nodes drawn uniformly at random. Parameters ---------- n : int The number of nodes number_of_trees : int or None (default) If not None, this number of trees is generated and returned. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- :class:`networkx.Graph` or list of :class:`networkx.Graph` A single `networkx.Graph` (or a list thereof, if `number_of_trees` is specified) with nodes in the set {0, …, *n* - 1}. The "root" graph attribute identifies the root of the tree. Notes ----- The trees are generated using the "RANRUT" algorithm from [1]_. The algorithm needs to compute some counting functions that are relatively expensive: in case several trees are needed, it is advisable to use the `number_of_trees` optional argument to reuse the counting functions. Raises ------ NetworkXPointlessConcept If `n` is zero (because the null graph is not a tree). References ---------- .. [1] Nijenhuis, Albert, and Wilf, Herbert S. "Combinatorial algorithms: for computers and calculators." Academic Press, 1978. https://doi.org/10.1016/C2013-0-11243-3 """ if n == 0: raise nx.NetworkXPointlessConcept("the null graph is not a tree") cache_trees = [0, 1] # initial cache of number of rooted trees if number_of_trees is None: return _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) return [ _to_nx(*_random_unlabeled_rooted_tree(n, cache_trees, seed), root=0) for i in range(number_of_trees) ]
(n, *, number_of_trees=None, seed=None, backend=None, **backend_kwargs)
31,055
networkx.readwrite.adjlist
read_adjlist
Read graph in adjacency list format from path. Parameters ---------- path : string or file Filename or file handle to read. Filenames ending in .gz or .bz2 will be uncompressed. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : Python type, optional Convert nodes to this type. comments : string, optional Marker for comment lines delimiter : string, optional Separator for node labels. The default is whitespace. Returns ------- G: NetworkX graph The graph corresponding to the lines in adjacency list format. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_adjlist(G, "test.adjlist") >>> G = nx.read_adjlist("test.adjlist") The path can be a filehandle or a string with the name of the file. If a filehandle is provided, it has to be opened in 'rb' mode. >>> fh = open("test.adjlist", "rb") >>> G = nx.read_adjlist(fh) Filenames ending in .gz or .bz2 will be compressed. >>> nx.write_adjlist(G, "test.adjlist.gz") >>> G = nx.read_adjlist("test.adjlist.gz") The optional nodetype is a function to convert node strings to nodetype. For example >>> G = nx.read_adjlist("test.adjlist", nodetype=int) will attempt to convert all nodes to integer type. Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.) The optional create_using parameter indicates the type of NetworkX graph created. The default is `nx.Graph`, an undirected graph. To read the data as a directed graph use >>> G = nx.read_adjlist("test.adjlist", create_using=nx.DiGraph) Notes ----- This format does not store graph or node data. See Also -------- write_adjlist
null
(path, comments='#', delimiter=None, create_using=None, nodetype=None, encoding='utf-8', *, backend=None, **backend_kwargs)
31,056
networkx.readwrite.edgelist
read_edgelist
Read a graph from a list of edges. Parameters ---------- path : file or string File or filename to read. If a file is provided, it must be opened in 'rb' mode. Filenames ending in .gz or .bz2 will be uncompressed. comments : string, optional The character used to indicate the start of a comment. To specify that no character should be treated as a comment, use ``comments=None``. delimiter : string, optional The string used to separate values. The default is whitespace. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : int, float, str, Python type, optional Convert node data from strings to specified type data : bool or list of (label,type) tuples Tuples specifying dictionary key names and types for edge data edgetype : int, float, str, Python type, optional OBSOLETE Convert edge data from strings to specified type and use as 'weight' encoding: string, optional Specify which encoding to use when reading file. Returns ------- G : graph A networkx Graph or other type specified with create_using Examples -------- >>> nx.write_edgelist(nx.path_graph(4), "test.edgelist") >>> G = nx.read_edgelist("test.edgelist") >>> fh = open("test.edgelist", "rb") >>> G = nx.read_edgelist(fh) >>> fh.close() >>> G = nx.read_edgelist("test.edgelist", nodetype=int) >>> G = nx.read_edgelist("test.edgelist", create_using=nx.DiGraph) Edgelist with data in a list: >>> textline = "1 2 3" >>> fh = open("test.edgelist", "w") >>> d = fh.write(textline) >>> fh.close() >>> G = nx.read_edgelist("test.edgelist", nodetype=int, data=(("weight", float),)) >>> list(G) [1, 2] >>> list(G.edges(data=True)) [(1, 2, {'weight': 3.0})] See parse_edgelist() for more examples of formatting. See Also -------- parse_edgelist write_edgelist Notes ----- Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.)
null
(path, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding='utf-8', *, backend=None, **backend_kwargs)
31,057
networkx.readwrite.gexf
read_gexf
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 read. File names ending in .gz or .bz2 will be decompressed. 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. version : string (default: 1.2draft) Version of GEFX File Format (see http://gexf.net/schema.html) Supported values: "1.1draft", "1.2draft" 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 File Format, http://gexf.net/
def add_node(self, G, node_xml, node_attr, node_pid=None): # add a single node with attributes to the graph # get attributes and subattributues for node data = self.decode_attr_elements(node_attr, node_xml) data = self.add_parents(data, node_xml) # add any parents if self.VERSION == "1.1": data = self.add_slices(data, node_xml) # add slices else: data = self.add_spells(data, node_xml) # add spells data = self.add_viz(data, node_xml) # add viz data = self.add_start_end(data, node_xml) # add start/end # find the node id and cast it to the appropriate type node_id = node_xml.get("id") if self.node_type is not None: node_id = self.node_type(node_id) # every node should have a label node_label = node_xml.get("label") data["label"] = node_label # parent node id node_pid = node_xml.get("pid", node_pid) if node_pid is not None: data["pid"] = node_pid # check for subnodes, recursive subnodes = node_xml.find(f"{{{self.NS_GEXF}}}nodes") if subnodes is not None: for node_xml in subnodes.findall(f"{{{self.NS_GEXF}}}node"): self.add_node(G, node_xml, node_attr, node_pid=node_id) G.add_node(node_id, **data)
(path, node_type=None, relabel=False, version='1.2draft', *, backend=None, **backend_kwargs)
31,058
networkx.readwrite.gml
read_gml
Read graph in GML format from `path`. Parameters ---------- path : filename or filehandle The filename or filehandle to read from. label : string, optional If not None, the parsed nodes will be renamed according to node attributes indicated by `label`. Default value: 'label'. destringizer : callable, optional A `destringizer` that recovers values stored as strings in GML. If it cannot convert a string to a value, a `ValueError` is raised. Default value : None. Returns ------- G : NetworkX graph The parsed graph. Raises ------ NetworkXError If the input cannot be parsed. See Also -------- write_gml, parse_gml literal_destringizer Notes ----- GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of writing `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For writing other data types, and for reading data other than `str` you need to explicitly supply a `stringizer`/`destringizer`. For additional documentation on the GML file format, please see the `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_. See the module docstring :mod:`networkx.readwrite.gml` for more details. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_gml(G, "test.gml") GML values are interpreted as strings by default: >>> H = nx.read_gml("test.gml") >>> H.nodes NodeView(('0', '1', '2', '3')) When a `destringizer` is provided, GML values are converted to the provided type. For example, integer nodes can be recovered as shown below: >>> J = nx.read_gml("test.gml", destringizer=int) >>> J.nodes NodeView((0, 1, 2, 3))
def generate_gml(G, stringizer=None): r"""Generate a single entry of the graph `G` in GML format. Parameters ---------- G : NetworkX graph The graph to be converted to GML. stringizer : callable, optional A `stringizer` which converts non-int/non-float/non-dict values into strings. If it cannot convert a value into a string, it should raise a `ValueError` to indicate that. Default value: None. Returns ------- lines: generator of strings Lines of GML data. Newlines are not appended. Raises ------ NetworkXError If `stringizer` cannot convert a value into a string, or the value to convert is not a string while `stringizer` is None. See Also -------- literal_stringizer Notes ----- Graph attributes named 'directed', 'multigraph', 'node' or 'edge', node attributes named 'id' or 'label', edge attributes named 'source' or 'target' (or 'key' if `G` is a multigraph) are ignored because these attribute names are used to encode the graph structure. GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing as HTML character entities. Without specifying a `stringizer`/`destringizer`, the code is capable of writing `int`/`float`/`str`/`dict`/`list` data as required by the GML specification. For writing other data types, and for reading data other than `str` you need to explicitly supply a `stringizer`/`destringizer`. For additional documentation on the GML file format, please see the `GML url <https://web.archive.org/web/20190207140002/http://www.fim.uni-passau.de/index.php?id=17297&L=1>`_. See the module docstring :mod:`networkx.readwrite.gml` for more details. Examples -------- >>> G = nx.Graph() >>> G.add_node("1") >>> print("\n".join(nx.generate_gml(G))) graph [ node [ id 0 label "1" ] ] >>> G = nx.MultiGraph([("a", "b"), ("a", "b")]) >>> print("\n".join(nx.generate_gml(G))) graph [ multigraph 1 node [ id 0 label "a" ] node [ id 1 label "b" ] edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 1 ] ] """ valid_keys = re.compile("^[A-Za-z][0-9A-Za-z_]*$") def stringize(key, value, ignored_keys, indent, in_list=False): if not isinstance(key, str): raise NetworkXError(f"{key!r} is not a string") if not valid_keys.match(key): raise NetworkXError(f"{key!r} is not a valid key") if not isinstance(key, str): key = str(key) if key not in ignored_keys: if isinstance(value, int | bool): if key == "label": yield indent + key + ' "' + str(value) + '"' elif value is True: # python bool is an instance of int yield indent + key + " 1" elif value is False: yield indent + key + " 0" # GML only supports signed 32-bit integers elif value < -(2**31) or value >= 2**31: yield indent + key + ' "' + str(value) + '"' else: yield indent + key + " " + str(value) elif isinstance(value, float): text = repr(value).upper() # GML matches INF to keys, so prepend + to INF. Use repr(float(*)) # instead of string literal to future proof against changes to repr. if text == repr(float("inf")).upper(): text = "+" + text else: # GML requires that a real literal contain a decimal point, but # repr may not output a decimal point when the mantissa is # integral and hence needs fixing. epos = text.rfind("E") if epos != -1 and text.find(".", 0, epos) == -1: text = text[:epos] + "." + text[epos:] if key == "label": yield indent + key + ' "' + text + '"' else: yield indent + key + " " + text elif isinstance(value, dict): yield indent + key + " [" next_indent = indent + " " for key, value in value.items(): yield from stringize(key, value, (), next_indent) yield indent + "]" elif isinstance(value, tuple) and key == "label": yield indent + key + f" \"({','.join(repr(v) for v in value)})\"" elif isinstance(value, list | tuple) and key != "label" and not in_list: if len(value) == 0: yield indent + key + " " + f'"{value!r}"' if len(value) == 1: yield indent + key + " " + f'"{LIST_START_VALUE}"' for val in value: yield from stringize(key, val, (), indent, True) else: if stringizer: try: value = stringizer(value) except ValueError as err: raise NetworkXError( f"{value!r} cannot be converted into a string" ) from err if not isinstance(value, str): raise NetworkXError(f"{value!r} is not a string") yield indent + key + ' "' + escape(value) + '"' multigraph = G.is_multigraph() yield "graph [" # Output graph attributes if G.is_directed(): yield " directed 1" if multigraph: yield " multigraph 1" ignored_keys = {"directed", "multigraph", "node", "edge"} for attr, value in G.graph.items(): yield from stringize(attr, value, ignored_keys, " ") # Output node data node_id = dict(zip(G, range(len(G)))) ignored_keys = {"id", "label"} for node, attrs in G.nodes.items(): yield " node [" yield " id " + str(node_id[node]) yield from stringize("label", node, (), " ") for attr, value in attrs.items(): yield from stringize(attr, value, ignored_keys, " ") yield " ]" # Output edge data ignored_keys = {"source", "target"} kwargs = {"data": True} if multigraph: ignored_keys.add("key") kwargs["keys"] = True for e in G.edges(**kwargs): yield " edge [" yield " source " + str(node_id[e[0]]) yield " target " + str(node_id[e[1]]) if multigraph: yield from stringize("key", e[2], (), " ") for attr, value in e[-1].items(): yield from stringize(attr, value, ignored_keys, " ") yield " ]" yield "]"
(path, label='label', destringizer=None, *, backend=None, **backend_kwargs)
31,059
networkx.readwrite.graph6
read_graph6
Read simple undirected graphs in graph6 format from path. Parameters ---------- path : file or string File or filename to write. Returns ------- G : Graph or list of Graphs If the file contains multiple lines then a list of graphs is returned Raises ------ NetworkXError If the string is unable to be parsed in graph6 format Examples -------- You can read a graph6 file by giving the path to the file:: >>> import tempfile >>> with tempfile.NamedTemporaryFile(delete=False) as f: ... _ = f.write(b">>graph6<<A_\n") ... _ = f.seek(0) ... G = nx.read_graph6(f.name) >>> list(G.edges()) [(0, 1)] You can also read a graph6 file by giving an open file-like object:: >>> import tempfile >>> with tempfile.NamedTemporaryFile() as f: ... _ = f.write(b">>graph6<<A_\n") ... _ = f.seek(0) ... G = nx.read_graph6(f) >>> list(G.edges()) [(0, 1)] See Also -------- from_graph6_bytes, write_graph6 References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
null
(path, *, backend=None, **backend_kwargs)
31,060
networkx.readwrite.graphml
read_graphml
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 edge_key_type: Python type (default: int) Convert graphml edge ids to this type. Multigraphs use id as edge key. Non-multigraphs add to edge attribute dict with name "id". force_multigraph : bool (default: False) If True, return a multigraph with edge keys. If False (the default) return a multigraph when multiedges are in the graph. Returns ------- graph: NetworkX graph If parallel edges are present or `force_multigraph=True` then a MultiGraph or MultiDiGraph is returned. Otherwise a Graph/DiGraph. The returned graph is directed if the file indicates it should be. Notes ----- Default node and edge attributes are not propagated to each node and edge. They can be obtained from `G.graph` and applied to node and edge attributes if desired using something like this: >>> default_color = G.graph["node_default"]["color"] # doctest: +SKIP >>> for node, data in G.nodes(data=True): # doctest: +SKIP ... if "color" not in data: ... data["color"] = default_color >>> default_color = G.graph["edge_default"]["color"] # doctest: +SKIP >>> for u, v, data in G.edges(data=True): # doctest: +SKIP ... if "color" not in data: ... data["color"] = default_color 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 can be read. The type of the node's shape is preserved in the `shape_type` node attribute. yEd compressed files ("file.graphmlz" extension) can be read by renaming the file to "file.graphml.gz".
def add_graph_element(self, G): """ Serialize graph G in GraphML to the stream. """ if G.is_directed(): default_edge_type = "directed" else: default_edge_type = "undirected" graphid = G.graph.pop("id", None) if graphid is None: graph_element = self._xml.element("graph", edgedefault=default_edge_type) else: graph_element = self._xml.element( "graph", edgedefault=default_edge_type, id=graphid ) # gather attributes types for the whole graph # to find the most general numeric format needed. # Then pass through attributes to create key_id for each. graphdata = { k: v for k, v in G.graph.items() if k not in ("node_default", "edge_default") } node_default = G.graph.get("node_default", {}) edge_default = G.graph.get("edge_default", {}) # Graph attributes for k, v in graphdata.items(): self.attribute_types[(str(k), "graph")].add(type(v)) for k, v in graphdata.items(): element_type = self.get_xml_type(self.attr_type(k, "graph", v)) self.get_key(str(k), element_type, "graph", None) # Nodes and data for node, d in G.nodes(data=True): for k, v in d.items(): self.attribute_types[(str(k), "node")].add(type(v)) for node, d in G.nodes(data=True): for k, v in d.items(): T = self.get_xml_type(self.attr_type(k, "node", v)) self.get_key(str(k), T, "node", node_default.get(k)) # Edges and data if G.is_multigraph(): for u, v, ekey, d in G.edges(keys=True, data=True): for k, v in d.items(): self.attribute_types[(str(k), "edge")].add(type(v)) for u, v, ekey, d in G.edges(keys=True, data=True): for k, v in d.items(): T = self.get_xml_type(self.attr_type(k, "edge", v)) self.get_key(str(k), T, "edge", edge_default.get(k)) else: for u, v, d in G.edges(data=True): for k, v in d.items(): self.attribute_types[(str(k), "edge")].add(type(v)) for u, v, d in G.edges(data=True): for k, v in d.items(): T = self.get_xml_type(self.attr_type(k, "edge", v)) self.get_key(str(k), T, "edge", edge_default.get(k)) # Now add attribute keys to the xml file for key in self.xml: self._xml.write(key, pretty_print=self._prettyprint) # The incremental_writer writes each node/edge as it is created incremental_writer = IncrementalElement(self._xml, self._prettyprint) with graph_element: self.add_attributes("graph", incremental_writer, graphdata, {}) self.add_nodes(G, incremental_writer) # adds attributes too self.add_edges(G, incremental_writer) # adds attributes too
(path, node_type=<class 'str'>, edge_key_type=<class 'int'>, force_multigraph=False, *, backend=None, **backend_kwargs)
31,061
networkx.readwrite.leda
read_leda
Read graph in LEDA format from path. Parameters ---------- path : file or string File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed. Returns ------- G : NetworkX graph Examples -------- G=nx.read_leda('file.leda') References ---------- .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
null
(path, encoding='UTF-8', *, backend=None, **backend_kwargs)
31,062
networkx.readwrite.multiline_adjlist
read_multiline_adjlist
Read graph in multi-line adjacency list format from path. Parameters ---------- path : string or file Filename or file handle to read. Filenames ending in .gz or .bz2 will be uncompressed. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : Python type, optional Convert nodes to this type. edgetype : Python type, optional Convert edge data to this type. comments : string, optional Marker for comment lines delimiter : string, optional Separator for node labels. The default is whitespace. Returns ------- G: NetworkX graph Examples -------- >>> G = nx.path_graph(4) >>> nx.write_multiline_adjlist(G, "test.adjlist") >>> G = nx.read_multiline_adjlist("test.adjlist") The path can be a file or a string with the name of the file. If a file s provided, it has to be opened in 'rb' mode. >>> fh = open("test.adjlist", "rb") >>> G = nx.read_multiline_adjlist(fh) Filenames ending in .gz or .bz2 will be compressed. >>> nx.write_multiline_adjlist(G, "test.adjlist.gz") >>> G = nx.read_multiline_adjlist("test.adjlist.gz") The optional nodetype is a function to convert node strings to nodetype. For example >>> G = nx.read_multiline_adjlist("test.adjlist", nodetype=int) will attempt to convert all nodes to integer type. The optional edgetype is a function to convert edge data strings to edgetype. >>> G = nx.read_multiline_adjlist("test.adjlist") The optional create_using parameter is a NetworkX graph container. The default is Graph(), an undirected graph. To read the data as a directed graph use >>> G = nx.read_multiline_adjlist("test.adjlist", create_using=nx.DiGraph) Notes ----- This format does not store graph, node, or edge data. See Also -------- write_multiline_adjlist
null
(path, comments='#', delimiter=None, create_using=None, nodetype=None, edgetype=None, encoding='utf-8', *, backend=None, **backend_kwargs)
31,063
networkx.readwrite.pajek
read_pajek
Read graph in Pajek format from path. Parameters ---------- path : file or string File or filename to write. Filenames ending in .gz or .bz2 will be uncompressed. Returns ------- G : NetworkX MultiGraph or MultiDiGraph. Examples -------- >>> G = nx.path_graph(4) >>> nx.write_pajek(G, "test.net") >>> G = nx.read_pajek("test.net") To create a Graph instead of a MultiGraph use >>> G1 = nx.Graph(G) References ---------- See http://vlado.fmf.uni-lj.si/pub/networks/pajek/doc/draweps.htm for format information.
null
(path, encoding='UTF-8', *, backend=None, **backend_kwargs)
31,064
networkx.readwrite.sparse6
read_sparse6
Read an undirected graph in sparse6 format from path. Parameters ---------- path : file or string File or filename to write. Returns ------- G : Graph/Multigraph or list of Graphs/MultiGraphs If the file contains multiple lines then a list of graphs is returned Raises ------ NetworkXError If the string is unable to be parsed in sparse6 format Examples -------- You can read a sparse6 file by giving the path to the file:: >>> import tempfile >>> with tempfile.NamedTemporaryFile(delete=False) as f: ... _ = f.write(b">>sparse6<<:An\n") ... _ = f.seek(0) ... G = nx.read_sparse6(f.name) >>> list(G.edges()) [(0, 1)] You can also read a sparse6 file by giving an open file-like object:: >>> import tempfile >>> with tempfile.NamedTemporaryFile() as f: ... _ = f.write(b">>sparse6<<:An\n") ... _ = f.seek(0) ... G = nx.read_sparse6(f) >>> list(G.edges()) [(0, 1)] See Also -------- read_sparse6, from_sparse6_bytes References ---------- .. [1] Sparse6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html>
null
(path, *, backend=None, **backend_kwargs)
31,065
networkx.readwrite.edgelist
read_weighted_edgelist
Read a graph as list of edges with numeric weights. Parameters ---------- path : file or string File or filename to read. If a file is provided, it must be opened in 'rb' mode. Filenames ending in .gz or .bz2 will be uncompressed. comments : string, optional The character used to indicate the start of a comment. delimiter : string, optional The string used to separate values. The default is whitespace. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. nodetype : int, float, str, Python type, optional Convert node data from strings to specified type encoding: string, optional Specify which encoding to use when reading file. Returns ------- G : graph A networkx Graph or other type specified with create_using Notes ----- Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.) Example edgelist file format. With numeric edge data:: # read with # >>> G=nx.read_weighted_edgelist(fh) # source target data a b 1 a c 3.14159 d e 42 See Also -------- write_weighted_edgelist
null
(path, comments='#', delimiter=None, create_using=None, nodetype=None, encoding='utf-8', *, backend=None, **backend_kwargs)
31,067
networkx.algorithms.reciprocity
reciprocity
Compute the reciprocity in a directed graph. The reciprocity of a directed graph is defined as the ratio of the number of edges pointing in both directions to the total number of edges in the graph. Formally, $r = |{(u,v) \in G|(v,u) \in G}| / |{(u,v) \in G}|$. The reciprocity of a single node u is defined similarly, it is the ratio of the number of edges in both directions to the total number of edges attached to node u. Parameters ---------- G : graph A networkx directed graph nodes : container of nodes, optional (default=whole graph) Compute reciprocity for nodes in this container. Returns ------- out : dictionary Reciprocity keyed by node label. Notes ----- The reciprocity is not defined for isolated nodes. In such cases this function will return None.
null
(G, nodes=None, *, backend=None, **backend_kwargs)
31,068
networkx.algorithms.shortest_paths.dense
reconstruct_path
Reconstruct a path from source to target using the predecessors dict as returned by floyd_warshall_predecessor_and_distance Parameters ---------- source : node Starting node for path target : node Ending node for path predecessors: dictionary Dictionary, keyed by source and target, of predecessors in the shortest path, as returned by floyd_warshall_predecessor_and_distance Returns ------- path : list A list of nodes containing the shortest path from source to target If source and target are the same, an empty list is returned Notes ----- This function is meant to give more applicability to the floyd_warshall_predecessor_and_distance function See Also -------- floyd_warshall_predecessor_and_distance
null
(source, target, predecessors, *, backend=None, **backend_kwargs)
31,069
networkx.algorithms.cycles
recursive_simple_cycles
Find simple cycles (elementary circuits) of a directed graph. A `simple cycle`, or `elementary circuit`, is a closed path where no node appears twice. Two elementary circuits are distinct if they are not cyclic permutations of each other. This version uses a recursive algorithm to build a list of cycles. You should probably use the iterator version called simple_cycles(). Warning: This recursive version uses lots of RAM! It appears in NetworkX for pedagogical value. Parameters ---------- G : NetworkX DiGraph A directed graph Returns ------- A list of cycles, where each cycle is represented by a list of nodes along the cycle. Example: >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)] >>> G = nx.DiGraph(edges) >>> nx.recursive_simple_cycles(G) [[0], [2], [0, 1, 2], [0, 2], [1, 2]] Notes ----- The implementation follows pp. 79-80 in [1]_. The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ elementary circuits. References ---------- .. [1] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975. https://doi.org/10.1137/0204007 See Also -------- simple_cycles, cycle_basis
def recursive_simple_cycles(G): """Find simple cycles (elementary circuits) of a directed graph. A `simple cycle`, or `elementary circuit`, is a closed path where no node appears twice. Two elementary circuits are distinct if they are not cyclic permutations of each other. This version uses a recursive algorithm to build a list of cycles. You should probably use the iterator version called simple_cycles(). Warning: This recursive version uses lots of RAM! It appears in NetworkX for pedagogical value. Parameters ---------- G : NetworkX DiGraph A directed graph Returns ------- A list of cycles, where each cycle is represented by a list of nodes along the cycle. Example: >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)] >>> G = nx.DiGraph(edges) >>> nx.recursive_simple_cycles(G) [[0], [2], [0, 1, 2], [0, 2], [1, 2]] Notes ----- The implementation follows pp. 79-80 in [1]_. The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ elementary circuits. References ---------- .. [1] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975. https://doi.org/10.1137/0204007 See Also -------- simple_cycles, cycle_basis """ # Jon Olav Vik, 2010-08-09 def _unblock(thisnode): """Recursively unblock and remove nodes from B[thisnode].""" if blocked[thisnode]: blocked[thisnode] = False while B[thisnode]: _unblock(B[thisnode].pop()) def circuit(thisnode, startnode, component): closed = False # set to True if elementary path is closed path.append(thisnode) blocked[thisnode] = True for nextnode in component[thisnode]: # direct successors of thisnode if nextnode == startnode: result.append(path[:]) closed = True elif not blocked[nextnode]: if circuit(nextnode, startnode, component): closed = True if closed: _unblock(thisnode) else: for nextnode in component[thisnode]: if thisnode not in B[nextnode]: # TODO: use set for speedup? B[nextnode].append(thisnode) path.pop() # remove thisnode from path return closed path = [] # stack of nodes in current path blocked = defaultdict(bool) # vertex: blocked from search? B = defaultdict(list) # graph portions that yield no elementary circuit result = [] # list to accumulate the circuits found # Johnson's algorithm exclude self cycle edges like (v, v) # To be backward compatible, we record those cycles in advance # and then remove from subG for v in G: if G.has_edge(v, v): result.append([v]) G.remove_edge(v, v) # Johnson's algorithm requires some ordering of the nodes. # They might not be sortable so we assign an arbitrary ordering. ordering = dict(zip(G, range(len(G)))) for s in ordering: # Build the subgraph induced by s and following nodes in the ordering subgraph = G.subgraph(node for node in G if ordering[node] >= ordering[s]) # Find the strongly connected component in the subgraph # that contains the least node according to the ordering strongcomp = nx.strongly_connected_components(subgraph) mincomp = min(strongcomp, key=lambda ns: min(ordering[n] for n in ns)) component = G.subgraph(mincomp) if len(component) > 1: # smallest node in the component according to the ordering startnode = min(component, key=ordering.__getitem__) for node in component: blocked[node] = False B[node][:] = [] dummy = circuit(startnode, startnode, component) return result
(G, *, backend=None, **backend_kwargs)
31,072
networkx.readwrite.gexf
relabel_gexf_graph
Relabel graph using "label" node keyword for node label. Parameters ---------- G : graph A NetworkX graph read from GEXF data Returns ------- H : graph A NetworkX graph with relabeled nodes Raises ------ NetworkXError If node labels are missing or not unique while relabel=True. Notes ----- This function relabels the nodes in a NetworkX graph with the "label" attribute. It also handles relabeling the specific GEXF node attributes "parents", and "pid".
def relabel_gexf_graph(G): """Relabel graph using "label" node keyword for node label. Parameters ---------- G : graph A NetworkX graph read from GEXF data Returns ------- H : graph A NetworkX graph with relabeled nodes Raises ------ NetworkXError If node labels are missing or not unique while relabel=True. Notes ----- This function relabels the nodes in a NetworkX graph with the "label" attribute. It also handles relabeling the specific GEXF node attributes "parents", and "pid". """ # build mapping of node labels, do some error checking try: mapping = [(u, G.nodes[u]["label"]) for u in G] except KeyError as err: raise nx.NetworkXError( "Failed to relabel nodes: missing node labels found. Use relabel=False." ) from err x, y = zip(*mapping) if len(set(y)) != len(G): raise nx.NetworkXError( "Failed to relabel nodes: " "duplicate node labels found. " "Use relabel=False." ) mapping = dict(mapping) H = nx.relabel_nodes(G, mapping) # relabel attributes for n in G: m = mapping[n] H.nodes[m]["id"] = n H.nodes[m].pop("label") if "pid" in H.nodes[m]: H.nodes[m]["pid"] = mapping[G.nodes[n]["pid"]] if "parents" in H.nodes[m]: H.nodes[m]["parents"] = [mapping[p] for p in G.nodes[n]["parents"]] return H
(G)
31,073
networkx.relabel
relabel_nodes
Relabel the nodes of the graph G according to a given mapping. The original node ordering may not be preserved if `copy` is `False` and the mapping includes overlap between old and new labels. Parameters ---------- G : graph A NetworkX graph mapping : dictionary A dictionary with the old labels as keys and new labels as values. A partial mapping is allowed. Mapping 2 nodes to a single node is allowed. Any non-node keys in the mapping are ignored. copy : bool (optional, default=True) If True return a copy, or if False relabel the nodes in place. Examples -------- To create a new graph with nodes relabeled according to a given dictionary: >>> G = nx.path_graph(3) >>> sorted(G) [0, 1, 2] >>> mapping = {0: "a", 1: "b", 2: "c"} >>> H = nx.relabel_nodes(G, mapping) >>> sorted(H) ['a', 'b', 'c'] Nodes can be relabeled with any hashable object, including numbers and strings: >>> import string >>> G = nx.path_graph(26) # nodes are integers 0 through 25 >>> sorted(G)[:3] [0, 1, 2] >>> mapping = dict(zip(G, string.ascii_lowercase)) >>> G = nx.relabel_nodes(G, mapping) # nodes are characters a through z >>> sorted(G)[:3] ['a', 'b', 'c'] >>> mapping = dict(zip(G, range(1, 27))) >>> G = nx.relabel_nodes(G, mapping) # nodes are integers 1 through 26 >>> sorted(G)[:3] [1, 2, 3] To perform a partial in-place relabeling, provide a dictionary mapping only a subset of the nodes, and set the `copy` keyword argument to False: >>> G = nx.path_graph(3) # nodes 0-1-2 >>> mapping = {0: "a", 1: "b"} # 0->'a' and 1->'b' >>> G = nx.relabel_nodes(G, mapping, copy=False) >>> sorted(G, key=str) [2, 'a', 'b'] A mapping can also be given as a function: >>> G = nx.path_graph(3) >>> H = nx.relabel_nodes(G, lambda x: x**2) >>> list(H) [0, 1, 4] In a multigraph, relabeling two or more nodes to the same new node will retain all edges, but may change the edge keys in the process: >>> G = nx.MultiGraph() >>> G.add_edge(0, 1, value="a") # returns the key for this edge 0 >>> G.add_edge(0, 2, value="b") 0 >>> G.add_edge(0, 3, value="c") 0 >>> mapping = {1: 4, 2: 4, 3: 4} >>> H = nx.relabel_nodes(G, mapping, copy=True) >>> print(H[0]) {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}} This works for in-place relabeling too: >>> G = nx.relabel_nodes(G, mapping, copy=False) >>> print(G[0]) {4: {0: {'value': 'a'}, 1: {'value': 'b'}, 2: {'value': 'c'}}} Notes ----- Only the nodes specified in the mapping will be relabeled. Any non-node keys in the mapping are ignored. The keyword setting copy=False modifies the graph in place. Relabel_nodes avoids naming collisions by building a directed graph from ``mapping`` which specifies the order of relabelings. Naming collisions, such as a->b, b->c, are ordered such that "b" gets renamed to "c" before "a" gets renamed "b". In cases of circular mappings (e.g. a->b, b->a), modifying the graph is not possible in-place and an exception is raised. In that case, use copy=True. If a relabel operation on a multigraph would cause two or more edges to have the same source, target and key, the second edge must be assigned a new key to retain all edges. The new key is set to the lowest non-negative integer not already used as a key for edges between these two nodes. Note that this means non-numeric keys may be replaced by numeric keys. See Also -------- convert_node_labels_to_integers
null
(G, mapping, copy=True, *, backend=None, **backend_kwargs)
31,074
networkx.generators.community
relaxed_caveman_graph
Returns a relaxed caveman graph. A relaxed caveman graph starts with `l` cliques of size `k`. Edges are then randomly rewired with probability `p` to link different cliques. Parameters ---------- l : int Number of groups k : int Size of cliques p : float Probability of rewiring each edge. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- G : NetworkX Graph Relaxed Caveman Graph Raises ------ NetworkXError If p is not in [0,1] Examples -------- >>> G = nx.relaxed_caveman_graph(2, 3, 0.1, seed=42) References ---------- .. [1] Santo Fortunato, Community Detection in Graphs, Physics Reports Volume 486, Issues 3-5, February 2010, Pages 75-174. https://arxiv.org/abs/0906.0612
def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed): """Returns a list of sets, each of which represents a community. ``degree_seq`` is the degree sequence that must be met by the graph. ``community_sizes`` is the community size distribution that must be met by the generated list of sets. ``mu`` is a float in the interval [0, 1] indicating the fraction of intra-community edges incident to each node. ``max_iters`` is the number of times to try to add a node to a community. This must be greater than the length of ``degree_seq``, otherwise this function will always fail. If the number of iterations exceeds this value, :exc:`~networkx.exception.ExceededMaxIterations` is raised. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. The communities returned by this are sets of integers in the set {0, ..., *n* - 1}, where *n* is the length of ``degree_seq``. """ # This assumes the nodes in the graph will be natural numbers. result = [set() for _ in community_sizes] n = len(degree_seq) free = list(range(n)) for i in range(max_iters): v = free.pop() c = seed.choice(range(len(community_sizes))) # s = int(degree_seq[v] * (1 - mu) + 0.5) s = round(degree_seq[v] * (1 - mu)) # If the community is large enough, add the node to the chosen # community. Otherwise, return it to the list of unaffiliated # nodes. if s < community_sizes[c]: result[c].add(v) else: free.append(v) # If the community is too big, remove a node from it. if len(result[c]) > community_sizes[c]: free.append(result[c].pop()) if not free: return result msg = "Could not assign communities; try increasing min_community" raise nx.ExceededMaxIterations(msg)
(l, k, p, seed=None, *, backend=None, **backend_kwargs)
31,076
networkx.drawing.layout
rescale_layout
Returns scaled position array to (-scale, scale) in all axes. The function acts on NumPy arrays which hold position information. Each position is one row of the array. The dimension of the space equals the number of columns. Each coordinate in one column. To rescale, the mean (center) is subtracted from each axis separately. Then all values are scaled so that the largest magnitude value from all axes equals `scale` (thus, the aspect ratio is preserved). The resulting NumPy Array is returned (order of rows unchanged). Parameters ---------- pos : numpy array positions to be scaled. Each row is a position. scale : number (default: 1) The size of the resulting extent in all directions. Returns ------- pos : numpy array scaled positions. Each row is a position. See Also -------- rescale_layout_dict
def rescale_layout(pos, scale=1): """Returns scaled position array to (-scale, scale) in all axes. The function acts on NumPy arrays which hold position information. Each position is one row of the array. The dimension of the space equals the number of columns. Each coordinate in one column. To rescale, the mean (center) is subtracted from each axis separately. Then all values are scaled so that the largest magnitude value from all axes equals `scale` (thus, the aspect ratio is preserved). The resulting NumPy Array is returned (order of rows unchanged). Parameters ---------- pos : numpy array positions to be scaled. Each row is a position. scale : number (default: 1) The size of the resulting extent in all directions. Returns ------- pos : numpy array scaled positions. Each row is a position. See Also -------- rescale_layout_dict """ import numpy as np # Find max length over all dimensions pos -= pos.mean(axis=0) lim = np.abs(pos).max() # max coordinate for all axes # rescale to (-scale, scale) in all directions, preserves aspect if lim > 0: pos *= scale / lim return pos
(pos, scale=1)
31,077
networkx.drawing.layout
rescale_layout_dict
Return a dictionary of scaled positions keyed by node Parameters ---------- pos : A dictionary of positions keyed by node scale : number (default: 1) The size of the resulting extent in all directions. Returns ------- pos : A dictionary of positions keyed by node Examples -------- >>> import numpy as np >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))} >>> nx.rescale_layout_dict(pos) {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])} >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))} >>> nx.rescale_layout_dict(pos, scale=2) {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])} See Also -------- rescale_layout
def rescale_layout_dict(pos, scale=1): """Return a dictionary of scaled positions keyed by node Parameters ---------- pos : A dictionary of positions keyed by node scale : number (default: 1) The size of the resulting extent in all directions. Returns ------- pos : A dictionary of positions keyed by node Examples -------- >>> import numpy as np >>> pos = {0: np.array((0, 0)), 1: np.array((1, 1)), 2: np.array((0.5, 0.5))} >>> nx.rescale_layout_dict(pos) {0: array([-1., -1.]), 1: array([1., 1.]), 2: array([0., 0.])} >>> pos = {0: np.array((0, 0)), 1: np.array((-1, 1)), 2: np.array((-0.5, 0.5))} >>> nx.rescale_layout_dict(pos, scale=2) {0: array([ 2., -2.]), 1: array([-2., 2.]), 2: array([0., 0.])} See Also -------- rescale_layout """ import numpy as np if not pos: # empty_graph return {} pos_v = np.array(list(pos.values())) pos_v = rescale_layout(pos_v, scale=scale) return dict(zip(pos, pos_v))
(pos, scale=1)
31,078
networkx.algorithms.distance_measures
resistance_distance
Returns the resistance distance between pairs of nodes in graph G. The resistance distance between two nodes of a graph is akin to treating the graph as a grid of resistors with a resistance equal to the provided weight [1]_, [2]_. If weight is not provided, then a weight of 1 is used for all edges. If two nodes are the same, the resistance distance is zero. Parameters ---------- G : NetworkX graph A graph nodeA : node or None, optional (default=None) A node within graph G. If None, compute resistance distance using all nodes as source nodes. nodeB : node or None, optional (default=None) A node within graph G. If None, compute resistance distance using all nodes as target nodes. weight : string or None, optional (default=None) The edge data key used to compute the resistance distance. If None, then each edge has weight 1. invert_weight : boolean (default=True) Proper calculation of resistance distance requires building the Laplacian matrix with the reciprocal of the weight. Not required if the weight is already inverted. Weight cannot be zero. Returns ------- rd : dict or float If `nodeA` and `nodeB` are given, resistance distance between `nodeA` and `nodeB`. If `nodeA` or `nodeB` is unspecified (the default), a dictionary of nodes with resistance distances as the value. Raises ------ NetworkXNotImplemented If `G` is a directed graph. NetworkXError If `G` is not connected, or contains no nodes, or `nodeA` is not in `G` or `nodeB` is not in `G`. Examples -------- >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)]) >>> round(nx.resistance_distance(G, 1, 3), 10) 0.625 Notes ----- The implementation is based on Theorem A in [2]_. Self-loops are ignored. Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights. References ---------- .. [1] Wikipedia "Resistance distance." https://en.wikipedia.org/wiki/Resistance_distance .. [2] D. J. Klein and M. Randic. Resistance distance. J. of Math. Chem. 12:81-95, 1993.
def effective_graph_resistance(G, weight=None, invert_weight=True): """Returns the Effective graph resistance of G. Also known as the Kirchhoff index. The effective graph resistance is defined as the sum of the resistance distance of every node pair in G [1]_. If weight is not provided, then a weight of 1 is used for all edges. The effective graph resistance of a disconnected graph is infinite. Parameters ---------- G : NetworkX graph A graph weight : string or None, optional (default=None) The edge data key used to compute the effective graph resistance. If None, then each edge has weight 1. invert_weight : boolean (default=True) Proper calculation of resistance distance requires building the Laplacian matrix with the reciprocal of the weight. Not required if the weight is already inverted. Weight cannot be zero. Returns ------- RG : float The effective graph resistance of `G`. Raises ------ NetworkXNotImplemented If `G` is a directed graph. NetworkXError If `G` does not contain any nodes. Examples -------- >>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)]) >>> round(nx.effective_graph_resistance(G), 10) 10.25 Notes ----- The implementation is based on Theorem 2.2 in [2]_. Self-loops are ignored. Multi-edges are contracted in one edge with weight equal to the harmonic sum of the weights. References ---------- .. [1] Wolfram "Kirchhoff Index." https://mathworld.wolfram.com/KirchhoffIndex.html .. [2] W. Ellens, F. M. Spieksma, P. Van Mieghem, A. Jamakovic, R. E. Kooij. Effective graph resistance. Lin. Alg. Appl. 435:2491-2506, 2011. """ import numpy as np if len(G) == 0: raise nx.NetworkXError("Graph G must contain at least one node.") # Disconnected graphs have infinite Effective graph resistance if not nx.is_connected(G): return float("inf") # Invert weights G = G.copy() if invert_weight and weight is not None: if G.is_multigraph(): for u, v, k, d in G.edges(keys=True, data=True): d[weight] = 1 / d[weight] else: for u, v, d in G.edges(data=True): d[weight] = 1 / d[weight] # Get Laplacian eigenvalues mu = np.sort(nx.laplacian_spectrum(G, weight=weight)) # Compute Effective graph resistance based on spectrum of the Laplacian # Self-loops are ignored return float(np.sum(1 / mu[1:]) * G.number_of_nodes())
(G, nodeA=None, nodeB=None, weight=None, invert_weight=True, *, backend=None, **backend_kwargs)
31,079
networkx.algorithms.link_prediction
resource_allocation_index
Compute the resource allocation index of all node pairs in ebunch. Resource allocation index of `u` and `v` is defined as .. math:: \sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{1}{|\Gamma(w)|} where $\Gamma(u)$ denotes the set of neighbors of $u$. Parameters ---------- G : graph A NetworkX undirected graph. ebunch : iterable of node pairs, optional (default = None) Resource allocation index will be computed for each pair of nodes given in the iterable. The pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then all nonexistent edges in the graph will be used. Default value: None. Returns ------- piter : iterator An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their resource allocation index. Raises ------ NetworkXNotImplemented If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`. NodeNotFound If `ebunch` has a node that is not in `G`. Examples -------- >>> G = nx.complete_graph(5) >>> preds = nx.resource_allocation_index(G, [(0, 1), (2, 3)]) >>> for u, v, p in preds: ... print(f"({u}, {v}) -> {p:.8f}") (0, 1) -> 0.75000000 (2, 3) -> 0.75000000 References ---------- .. [1] T. Zhou, L. Lu, Y.-C. Zhang. Predicting missing links via local information. Eur. Phys. J. B 71 (2009) 623. https://arxiv.org/pdf/0901.0553.pdf
null
(G, ebunch=None, *, backend=None, **backend_kwargs)
31,080
networkx.classes.function
restricted_view
Returns a view of `G` with hidden nodes and edges. The resulting subgraph filters out node `nodes` and edges `edges`. Filtered out nodes also filter out any of their edges. Parameters ---------- G : NetworkX Graph nodes : iterable An iterable of nodes. Nodes not present in `G` are ignored. edges : iterable An iterable of edges. Edges not present in `G` are ignored. Returns ------- subgraph : SubGraph View A read-only restricted view of `G` filtering out nodes and edges. Changes to `G` are reflected in the view. Notes ----- To create a mutable subgraph with its own copies of nodes edges and attributes use `subgraph.copy()` or `Graph(subgraph)` If you create a subgraph of a subgraph recursively you may end up with a chain of subgraph views. Such chains can get quite slow for lengths near 15. To avoid long chains, try to make your subgraph based on the original graph. We do not rule out chains programmatically so that odd cases like an `edge_subgraph` of a `restricted_view` can be created. Examples -------- >>> G = nx.path_graph(5) >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)]) >>> list(H.nodes) [1, 2, 3, 4] >>> list(H.edges) [(2, 3)]
def restricted_view(G, nodes, edges): """Returns a view of `G` with hidden nodes and edges. The resulting subgraph filters out node `nodes` and edges `edges`. Filtered out nodes also filter out any of their edges. Parameters ---------- G : NetworkX Graph nodes : iterable An iterable of nodes. Nodes not present in `G` are ignored. edges : iterable An iterable of edges. Edges not present in `G` are ignored. Returns ------- subgraph : SubGraph View A read-only restricted view of `G` filtering out nodes and edges. Changes to `G` are reflected in the view. Notes ----- To create a mutable subgraph with its own copies of nodes edges and attributes use `subgraph.copy()` or `Graph(subgraph)` If you create a subgraph of a subgraph recursively you may end up with a chain of subgraph views. Such chains can get quite slow for lengths near 15. To avoid long chains, try to make your subgraph based on the original graph. We do not rule out chains programmatically so that odd cases like an `edge_subgraph` of a `restricted_view` can be created. Examples -------- >>> G = nx.path_graph(5) >>> H = nx.restricted_view(G, [0], [(1, 2), (3, 4)]) >>> list(H.nodes) [1, 2, 3, 4] >>> list(H.edges) [(2, 3)] """ nxf = nx.filters hide_nodes = nxf.hide_nodes(nodes) if G.is_multigraph(): if G.is_directed(): hide_edges = nxf.hide_multidiedges(edges) else: hide_edges = nxf.hide_multiedges(edges) else: if G.is_directed(): hide_edges = nxf.hide_diedges(edges) else: hide_edges = nxf.hide_edges(edges) return nx.subgraph_view(G, filter_node=hide_nodes, filter_edge=hide_edges)
(G, nodes, edges)
31,081
networkx.algorithms.operators.unary
reverse
Returns the reverse directed graph of G. Parameters ---------- G : directed graph A NetworkX directed graph copy : bool If True, then a new graph is returned. If False, then the graph is reversed in place. Returns ------- H : directed graph The reversed G. Raises ------ NetworkXError If graph is undirected. Examples -------- >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)]) >>> G_reversed = nx.reverse(G) >>> G_reversed.edges() OutEdgeView([(2, 1), (3, 1), (3, 2), (4, 3), (5, 3)])
null
(G, copy=True, *, backend=None, **backend_kwargs)
31,082
networkx.classes.graphviews
reverse_view
View of `G` with edge directions reversed `reverse_view` returns a read-only view of the input graph where edge directions are reversed. Identical to digraph.reverse(copy=False) Parameters ---------- G : networkx.DiGraph Returns ------- graph : networkx.DiGraph Examples -------- >>> G = nx.DiGraph() >>> G.add_edge(1, 2) >>> G.add_edge(2, 3) >>> G.edges() OutEdgeView([(1, 2), (2, 3)]) >>> view = nx.reverse_view(G) >>> view.edges() OutEdgeView([(2, 1), (3, 2)])
null
(G)
31,083
networkx.algorithms.richclub
rich_club_coefficient
Returns the rich-club coefficient of the graph `G`. For each degree *k*, the *rich-club coefficient* is the ratio of the number of actual to the number of potential edges for nodes with degree greater than *k*: .. math:: \phi(k) = \frac{2 E_k}{N_k (N_k - 1)} where `N_k` is the number of nodes with degree larger than *k*, and `E_k` is the number of edges among those nodes. Parameters ---------- G : NetworkX graph Undirected graph with neither parallel edges nor self-loops. normalized : bool (optional) Normalize using randomized network as in [1]_ Q : float (optional, default=100) If `normalized` is True, perform `Q * m` double-edge swaps, where `m` is the number of edges in `G`, to use as a null-model for normalization. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- rc : dictionary A dictionary, keyed by degree, with rich-club coefficient values. Raises ------ NetworkXError If `G` has fewer than four nodes and ``normalized=True``. A randomly sampled graph for normalization cannot be generated in this case. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)]) >>> rc = nx.rich_club_coefficient(G, normalized=False, seed=42) >>> rc[0] 0.4 Notes ----- The rich club definition and algorithm are found in [1]_. This algorithm ignores any edge weights and is not defined for directed graphs or graphs with parallel edges or self loops. Normalization is done by computing the rich club coefficient for a randomly sampled graph with the same degree distribution as `G` by repeatedly swapping the endpoints of existing edges. For graphs with fewer than 4 nodes, it is not possible to generate a random graph with a prescribed degree distribution, as the degree distribution fully determines the graph (hence making the coefficients trivially normalized to 1). This function raises an exception in this case. Estimates for appropriate values of `Q` are found in [2]_. References ---------- .. [1] Julian J. McAuley, Luciano da Fontoura Costa, and Tibério S. Caetano, "The rich-club phenomenon across complex network hierarchies", Applied Physics Letters Vol 91 Issue 8, August 2007. https://arxiv.org/abs/physics/0701290 .. [2] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon, "Uniform generation of random graphs with arbitrary degree sequences", 2006. https://arxiv.org/abs/cond-mat/0312028
null
(G, normalized=True, Q=100, seed=None, *, backend=None, **backend_kwargs)
31,085
networkx.generators.community
ring_of_cliques
Defines a "ring of cliques" graph. A ring of cliques graph is consisting of cliques, connected through single links. Each clique is a complete graph. Parameters ---------- num_cliques : int Number of cliques clique_size : int Size of cliques Returns ------- G : NetworkX Graph ring of cliques graph Raises ------ NetworkXError If the number of cliques is lower than 2 or if the size of cliques is smaller than 2. Examples -------- >>> G = nx.ring_of_cliques(8, 4) See Also -------- connected_caveman_graph Notes ----- The `connected_caveman_graph` graph removes a link from each clique to connect it with the next clique. Instead, the `ring_of_cliques` graph simply adds the link without removing any link from the cliques.
def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed): """Returns a list of sets, each of which represents a community. ``degree_seq`` is the degree sequence that must be met by the graph. ``community_sizes`` is the community size distribution that must be met by the generated list of sets. ``mu`` is a float in the interval [0, 1] indicating the fraction of intra-community edges incident to each node. ``max_iters`` is the number of times to try to add a node to a community. This must be greater than the length of ``degree_seq``, otherwise this function will always fail. If the number of iterations exceeds this value, :exc:`~networkx.exception.ExceededMaxIterations` is raised. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. The communities returned by this are sets of integers in the set {0, ..., *n* - 1}, where *n* is the length of ``degree_seq``. """ # This assumes the nodes in the graph will be natural numbers. result = [set() for _ in community_sizes] n = len(degree_seq) free = list(range(n)) for i in range(max_iters): v = free.pop() c = seed.choice(range(len(community_sizes))) # s = int(degree_seq[v] * (1 - mu) + 0.5) s = round(degree_seq[v] * (1 - mu)) # If the community is large enough, add the node to the chosen # community. Otherwise, return it to the list of unaffiliated # nodes. if s < community_sizes[c]: result[c].add(v) else: free.append(v) # If the community is too big, remove a node from it. if len(result[c]) > community_sizes[c]: free.append(result[c].pop()) if not free: return result msg = "Could not assign communities; try increasing min_community" raise nx.ExceededMaxIterations(msg)
(num_cliques, clique_size, *, backend=None, **backend_kwargs)
31,086
networkx.algorithms.operators.product
rooted_product
Return the rooted product of graphs G and H rooted at root in H. A new graph is constructed representing the rooted product of the inputted graphs, G and H, with a root in H. A rooted product duplicates H for each nodes in G with the root of H corresponding to the node in G. Nodes are renamed as the direct product of G and H. The result is a subgraph of the cartesian product. Parameters ---------- G,H : graph A NetworkX graph root : node A node in H Returns ------- R : The rooted product of G and H with a specified root in H Notes ----- The nodes of R are the Cartesian Product of the nodes of G and H. The nodes of G and H are not relabeled.
null
(G, H, root, *, backend=None, **backend_kwargs)
31,087
networkx.algorithms.smetric
s_metric
Returns the s-metric [1]_ of graph. The s-metric is defined as the sum of the products ``deg(u) * deg(v)`` for every edge ``(u, v)`` in `G`. Parameters ---------- G : graph The graph used to compute the s-metric. normalized : bool (optional) Normalize the value. .. deprecated:: 3.2 The `normalized` keyword argument is deprecated and will be removed in the future Returns ------- s : float The s-metric of the graph. References ---------- .. [1] Lun Li, David Alderson, John C. Doyle, and Walter Willinger, Towards a Theory of Scale-Free Graphs: Definition, Properties, and Implications (Extended Version), 2005. https://arxiv.org/abs/cond-mat/0501169
null
(G, *, backend=None, **kwargs)
31,088
networkx.generators.directed
scale_free_graph
Returns a scale-free directed graph. Parameters ---------- n : integer Number of nodes in graph alpha : float Probability for adding a new node connected to an existing node chosen randomly according to the in-degree distribution. beta : float Probability for adding an edge between two existing nodes. One existing node is chosen randomly according the in-degree distribution and the other chosen randomly according to the out-degree distribution. gamma : float Probability for adding a new node connected to an existing node chosen randomly according to the out-degree distribution. delta_in : float Bias for choosing nodes from in-degree distribution. delta_out : float Bias for choosing nodes from out-degree distribution. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. initial_graph : MultiDiGraph instance, optional Build the scale-free graph starting from this initial MultiDiGraph, if provided. Returns ------- MultiDiGraph Examples -------- Create a scale-free graph on one hundred nodes:: >>> G = nx.scale_free_graph(100) Notes ----- The sum of `alpha`, `beta`, and `gamma` must be 1. References ---------- .. [1] B. Bollobás, C. Borgs, J. Chayes, and O. Riordan, Directed scale-free graphs, Proceedings of the fourteenth annual ACM-SIAM Symposium on Discrete Algorithms, 132--139, 2003.
null
(n, alpha=0.41, beta=0.54, gamma=0.05, delta_in=0.2, delta_out=0, seed=None, initial_graph=None, *, backend=None, **backend_kwargs)
31,089
networkx.algorithms.wiener
schultz_index
Returns the Schultz Index (of the first kind) of `G` The *Schultz Index* [3]_ of a graph is the sum over all node pairs of distances times the sum of degrees. Consider an undirected graph `G`. For each node pair ``(u, v)`` compute ``dist(u, v) * (deg(u) + deg(v)`` where ``dist`` is the shortest path length between two nodes and ``deg`` is the degree of a node. The Schultz Index is the sum of these quantities over all (unordered) pairs of nodes. Parameters ---------- G : NetworkX graph The undirected graph of interest. weight : string or None, optional (default: None) If None, every edge has weight 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. The edge weights are used to computing shortest-path distances. Returns ------- number The first kind of Schultz Index of the graph `G`. Examples -------- The Schultz Index of the (unweighted) complete graph on *n* nodes equals the number of pairs of the *n* nodes times ``2 * (n - 1)``, since each pair of nodes is at distance one and the sum of degree of two nodes is ``2 * (n - 1)``. >>> n = 10 >>> G = nx.complete_graph(n) >>> nx.schultz_index(G) == (n * (n - 1) / 2) * (2 * (n - 1)) True Graph that is disconnected >>> nx.schultz_index(nx.empty_graph(2)) inf References ---------- .. [1] I. Gutman, Selected properties of the Schultz molecular topological index, J. Chem. Inf. Comput. Sci. 34 (1994), 1087–1089. https://doi.org/10.1021/ci00021a009 .. [2] M.V. Diudeaa and I. Gutman, Wiener-Type Topological Indices, Croatica Chemica Acta, 71 (1998), 21-51. https://hrcak.srce.hr/132323 .. [3] H. P. Schultz, Topological organic chemistry. 1. Graph theory and topological indices of alkanes,i J. Chem. Inf. Comput. Sci. 29 (1989), 239–257.
null
(G, weight=None, *, backend=None, **backend_kwargs)
31,091
networkx.algorithms.centrality.second_order
second_order_centrality
Compute the second order centrality for nodes of G. The second order centrality of a given node is the standard deviation of the return times to that node of a perpetual random walk on G: Parameters ---------- G : graph A NetworkX connected and undirected graph. weight : string or None, optional (default="weight") The name of an edge attribute that holds the numerical value used as a weight. If None then each edge has weight 1. Returns ------- nodes : dictionary Dictionary keyed by node with second order centrality as the value. Examples -------- >>> G = nx.star_graph(10) >>> soc = nx.second_order_centrality(G) >>> print(sorted(soc.items(), key=lambda x: x[1])[0][0]) # pick first id 0 Raises ------ NetworkXException If the graph G is empty, non connected or has negative weights. See Also -------- betweenness_centrality Notes ----- Lower values of second order centrality indicate higher centrality. The algorithm is from Kermarrec, Le Merrer, Sericola and Trédan [1]_. This code implements the analytical version of the algorithm, i.e., there is no simulation of a random walk process involved. The random walk is here unbiased (corresponding to eq 6 of the paper [1]_), thus the centrality values are the standard deviations for random walk return times on the transformed input graph G (equal in-degree at each nodes by adding self-loops). Complexity of this implementation, made to run locally on a single machine, is O(n^3), with n the size of G, which makes it viable only for small graphs. References ---------- .. [1] Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan "Second order centrality: Distributed assessment of nodes criticity in complex networks", Elsevier Computer Communications 34(5):619-628, 2011.
null
(G, weight='weight', *, backend=None, **backend_kwargs)
31,092
networkx.generators.small
sedgewick_maze_graph
Return a small maze with a cycle. This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_. Nodes are numbered 0,..,7 Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Small maze with a cycle References ---------- .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick
def sedgewick_maze_graph(create_using=None): """ Return a small maze with a cycle. This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_. Nodes are numbered 0,..,7 Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Small maze with a cycle References ---------- .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick """ G = empty_graph(0, create_using) G.add_nodes_from(range(8)) G.add_edges_from([[0, 2], [0, 7], [0, 5]]) G.add_edges_from([[1, 7], [2, 6]]) G.add_edges_from([[3, 4], [3, 5]]) G.add_edges_from([[4, 5], [4, 7], [4, 6]]) G.name = "Sedgewick Maze" return G
(create_using=None, *, backend=None, **backend_kwargs)
31,093
networkx.classes.function
selfloop_edges
Returns an iterator over selfloop edges. A selfloop edge has the same node at both ends. Parameters ---------- G : graph A NetworkX graph. data : string or bool, optional (default=False) Return selfloop edges as two tuples (u, v) (data=False) or three-tuples (u, v, datadict) (data=True) or three-tuples (u, v, datavalue) (data='attrname') keys : bool, optional (default=False) If True, return edge keys with each edge. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False. Returns ------- edgeiter : iterator over edge tuples An iterator over all selfloop edges. See Also -------- nodes_with_selfloops, number_of_selfloops Examples -------- >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc >>> ekey = G.add_edge(1, 1) >>> ekey = G.add_edge(1, 2) >>> list(nx.selfloop_edges(G)) [(1, 1)] >>> list(nx.selfloop_edges(G, data=True)) [(1, 1, {})] >>> list(nx.selfloop_edges(G, keys=True)) [(1, 1, 0)] >>> list(nx.selfloop_edges(G, keys=True, data=True)) [(1, 1, 0, {})]
def selfloop_edges(G, data=False, keys=False, default=None): """Returns an iterator over selfloop edges. A selfloop edge has the same node at both ends. Parameters ---------- G : graph A NetworkX graph. data : string or bool, optional (default=False) Return selfloop edges as two tuples (u, v) (data=False) or three-tuples (u, v, datadict) (data=True) or three-tuples (u, v, datavalue) (data='attrname') keys : bool, optional (default=False) If True, return edge keys with each edge. default : value, optional (default=None) Value used for edges that don't have the requested attribute. Only relevant if data is not True or False. Returns ------- edgeiter : iterator over edge tuples An iterator over all selfloop edges. See Also -------- nodes_with_selfloops, number_of_selfloops Examples -------- >>> G = nx.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc >>> ekey = G.add_edge(1, 1) >>> ekey = G.add_edge(1, 2) >>> list(nx.selfloop_edges(G)) [(1, 1)] >>> list(nx.selfloop_edges(G, data=True)) [(1, 1, {})] >>> list(nx.selfloop_edges(G, keys=True)) [(1, 1, 0)] >>> list(nx.selfloop_edges(G, keys=True, data=True)) [(1, 1, 0, {})] """ if data is True: if G.is_multigraph(): if keys is True: return ( (n, n, k, d) for n, nbrs in G._adj.items() if n in nbrs for k, d in nbrs[n].items() ) else: return ( (n, n, d) for n, nbrs in G._adj.items() if n in nbrs for d in nbrs[n].values() ) else: return ((n, n, nbrs[n]) for n, nbrs in G._adj.items() if n in nbrs) elif data is not False: if G.is_multigraph(): if keys is True: return ( (n, n, k, d.get(data, default)) for n, nbrs in G._adj.items() if n in nbrs for k, d in nbrs[n].items() ) else: return ( (n, n, d.get(data, default)) for n, nbrs in G._adj.items() if n in nbrs for d in nbrs[n].values() ) else: return ( (n, n, nbrs[n].get(data, default)) for n, nbrs in G._adj.items() if n in nbrs ) else: if G.is_multigraph(): if keys is True: return ( (n, n, k) for n, nbrs in G._adj.items() if n in nbrs for k in nbrs[n] ) else: return ( (n, n) for n, nbrs in G._adj.items() if n in nbrs for i in range(len(nbrs[n])) # for easy edge removal (#4068) ) else: return ((n, n) for n, nbrs in G._adj.items() if n in nbrs)
(G, data=False, keys=False, default=None)
31,095
networkx.classes.function
set_edge_attributes
Sets edge attributes from a given value or dictionary of values. .. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x. Parameters ---------- G : NetworkX Graph values : scalar value, dict-like What the edge attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every edge in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the edge attribute for each edge. The attribute name will be `name`. If `values` is a dict or a dict of dict, it should be keyed by edge tuple to either an attribute value or a dict of attribute key/value pairs used to update the edge's attributes. For multigraphs, the edge tuples must be of the form ``(u, v, key)``, where `u` and `v` are nodes and `key` is the edge key. For non-multigraphs, the keys must be tuples of the form ``(u, v)``. name : string (optional, default=None) Name of the edge attribute to set if values is a scalar. Examples -------- After computing some property of the edges of a graph, you may want to assign a edge attribute to store the value of that property for each edge:: >>> G = nx.path_graph(3) >>> bb = nx.edge_betweenness_centrality(G, normalized=False) >>> nx.set_edge_attributes(G, bb, "betweenness") >>> G.edges[1, 2]["betweenness"] 2.0 If you provide a list as the second argument, updates to the list will be reflected in the edge attribute for each edge:: >>> labels = [] >>> nx.set_edge_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.edges[0, 1]["labels"] ['foo'] >>> G.edges[1, 2]["labels"] ['foo'] If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update edge attributes:: >>> G = nx.path_graph(3) >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}} >>> nx.set_edge_attributes(G, attrs) >>> G[0][1]["attr1"] 20 >>> G[0][1]["attr2"] 'nothing' >>> G[1][2]["attr2"] 3 The attributes of one Graph can be used to set those of another. >>> H = nx.path_graph(3) >>> nx.set_edge_attributes(H, G.edges) Note that if the dict contains edges that are not in `G`, they are silently ignored:: >>> G = nx.Graph([(0, 1)]) >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}}) >>> (1, 2) in G.edges() False For multigraphs, the `values` dict is expected to be keyed by 3-tuples including the edge key:: >>> MG = nx.MultiGraph() >>> edges = [(0, 1), (0, 1)] >>> MG.add_edges_from(edges) # Returns list of edge keys [0, 1] >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}} >>> nx.set_edge_attributes(MG, attributes) >>> MG[0][1][0]["cost"] 21 >>> MG[0][1][1]["cost"] 7 If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple multiedge to a 2-tuple edge and the last multiedge's attribute value will overwrite the previous values. Continuing from the previous case we get:: >>> H = nx.path_graph([0, 1, 2]) >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()}) >>> nx.get_edge_attributes(H, "cost") {(0, 1): 7}
def set_edge_attributes(G, values, name=None): """Sets edge attributes from a given value or dictionary of values. .. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x. Parameters ---------- G : NetworkX Graph values : scalar value, dict-like What the edge attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every edge in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the edge attribute for each edge. The attribute name will be `name`. If `values` is a dict or a dict of dict, it should be keyed by edge tuple to either an attribute value or a dict of attribute key/value pairs used to update the edge's attributes. For multigraphs, the edge tuples must be of the form ``(u, v, key)``, where `u` and `v` are nodes and `key` is the edge key. For non-multigraphs, the keys must be tuples of the form ``(u, v)``. name : string (optional, default=None) Name of the edge attribute to set if values is a scalar. Examples -------- After computing some property of the edges of a graph, you may want to assign a edge attribute to store the value of that property for each edge:: >>> G = nx.path_graph(3) >>> bb = nx.edge_betweenness_centrality(G, normalized=False) >>> nx.set_edge_attributes(G, bb, "betweenness") >>> G.edges[1, 2]["betweenness"] 2.0 If you provide a list as the second argument, updates to the list will be reflected in the edge attribute for each edge:: >>> labels = [] >>> nx.set_edge_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.edges[0, 1]["labels"] ['foo'] >>> G.edges[1, 2]["labels"] ['foo'] If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update edge attributes:: >>> G = nx.path_graph(3) >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}} >>> nx.set_edge_attributes(G, attrs) >>> G[0][1]["attr1"] 20 >>> G[0][1]["attr2"] 'nothing' >>> G[1][2]["attr2"] 3 The attributes of one Graph can be used to set those of another. >>> H = nx.path_graph(3) >>> nx.set_edge_attributes(H, G.edges) Note that if the dict contains edges that are not in `G`, they are silently ignored:: >>> G = nx.Graph([(0, 1)]) >>> nx.set_edge_attributes(G, {(1, 2): {"weight": 2.0}}) >>> (1, 2) in G.edges() False For multigraphs, the `values` dict is expected to be keyed by 3-tuples including the edge key:: >>> MG = nx.MultiGraph() >>> edges = [(0, 1), (0, 1)] >>> MG.add_edges_from(edges) # Returns list of edge keys [0, 1] >>> attributes = {(0, 1, 0): {"cost": 21}, (0, 1, 1): {"cost": 7}} >>> nx.set_edge_attributes(MG, attributes) >>> MG[0][1][0]["cost"] 21 >>> MG[0][1][1]["cost"] 7 If MultiGraph attributes are desired for a Graph, you must convert the 3-tuple multiedge to a 2-tuple edge and the last multiedge's attribute value will overwrite the previous values. Continuing from the previous case we get:: >>> H = nx.path_graph([0, 1, 2]) >>> nx.set_edge_attributes(H, {(u, v): ed for u, v, ed in MG.edges.data()}) >>> nx.get_edge_attributes(H, "cost") {(0, 1): 7} """ if name is not None: # `values` does not contain attribute names try: # if `values` is a dict using `.items()` => {edge: value} if G.is_multigraph(): for (u, v, key), value in values.items(): try: G._adj[u][v][key][name] = value except KeyError: pass else: for (u, v), value in values.items(): try: G._adj[u][v][name] = value except KeyError: pass except AttributeError: # treat `values` as a constant for u, v, data in G.edges(data=True): data[name] = values else: # `values` consists of doct-of-dict {edge: {attr: value}} shape if G.is_multigraph(): for (u, v, key), d in values.items(): try: G._adj[u][v][key].update(d) except KeyError: pass else: for (u, v), d in values.items(): try: G._adj[u][v].update(d) except KeyError: pass nx._clear_cache(G)
(G, values, name=None)
31,096
networkx.classes.function
set_node_attributes
Sets node attributes from a given value or dictionary of values. .. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x. Parameters ---------- G : NetworkX Graph values : scalar value, dict-like What the node attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every node in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the node attribute for every node. The attribute name will be `name`. If `values` is a dict or a dict of dict, it should be keyed by node to either an attribute value or a dict of attribute key/value pairs used to update the node's attributes. name : string (optional, default=None) Name of the node attribute to set if values is a scalar. Examples -------- After computing some property of the nodes of a graph, you may want to assign a node attribute to store the value of that property for each node:: >>> G = nx.path_graph(3) >>> bb = nx.betweenness_centrality(G) >>> isinstance(bb, dict) True >>> nx.set_node_attributes(G, bb, "betweenness") >>> G.nodes[1]["betweenness"] 1.0 If you provide a list as the second argument, updates to the list will be reflected in the node attribute for each node:: >>> G = nx.path_graph(3) >>> labels = [] >>> nx.set_node_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.nodes[0]["labels"] ['foo'] >>> G.nodes[1]["labels"] ['foo'] >>> G.nodes[2]["labels"] ['foo'] If you provide a dictionary of dictionaries as the second argument, the outer dictionary is assumed to be keyed by node to an inner dictionary of node attributes for that node:: >>> G = nx.path_graph(3) >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}} >>> nx.set_node_attributes(G, attrs) >>> G.nodes[0]["attr1"] 20 >>> G.nodes[0]["attr2"] 'nothing' >>> G.nodes[1]["attr2"] 3 >>> G.nodes[2] {} Note that if the dictionary contains nodes that are not in `G`, the values are silently ignored:: >>> G = nx.Graph() >>> G.add_node(0) >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color") >>> G.nodes[0]["color"] 'red' >>> 1 in G.nodes False
def set_node_attributes(G, values, name=None): """Sets node attributes from a given value or dictionary of values. .. Warning:: The call order of arguments `values` and `name` switched between v1.x & v2.x. Parameters ---------- G : NetworkX Graph values : scalar value, dict-like What the node attribute should be set to. If `values` is not a dictionary, then it is treated as a single attribute value that is then applied to every node in `G`. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the node attribute for every node. The attribute name will be `name`. If `values` is a dict or a dict of dict, it should be keyed by node to either an attribute value or a dict of attribute key/value pairs used to update the node's attributes. name : string (optional, default=None) Name of the node attribute to set if values is a scalar. Examples -------- After computing some property of the nodes of a graph, you may want to assign a node attribute to store the value of that property for each node:: >>> G = nx.path_graph(3) >>> bb = nx.betweenness_centrality(G) >>> isinstance(bb, dict) True >>> nx.set_node_attributes(G, bb, "betweenness") >>> G.nodes[1]["betweenness"] 1.0 If you provide a list as the second argument, updates to the list will be reflected in the node attribute for each node:: >>> G = nx.path_graph(3) >>> labels = [] >>> nx.set_node_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.nodes[0]["labels"] ['foo'] >>> G.nodes[1]["labels"] ['foo'] >>> G.nodes[2]["labels"] ['foo'] If you provide a dictionary of dictionaries as the second argument, the outer dictionary is assumed to be keyed by node to an inner dictionary of node attributes for that node:: >>> G = nx.path_graph(3) >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}} >>> nx.set_node_attributes(G, attrs) >>> G.nodes[0]["attr1"] 20 >>> G.nodes[0]["attr2"] 'nothing' >>> G.nodes[1]["attr2"] 3 >>> G.nodes[2] {} Note that if the dictionary contains nodes that are not in `G`, the values are silently ignored:: >>> G = nx.Graph() >>> G.add_node(0) >>> nx.set_node_attributes(G, {0: "red", 1: "blue"}, name="color") >>> G.nodes[0]["color"] 'red' >>> 1 in G.nodes False """ # Set node attributes based on type of `values` if name is not None: # `values` must not be a dict of dict try: # `values` is a dict for n, v in values.items(): try: G.nodes[n][name] = values[n] except KeyError: pass except AttributeError: # `values` is a constant for n in G: G.nodes[n][name] = values else: # `values` must be dict of dict for n, d in values.items(): try: G.nodes[n].update(d) except KeyError: pass nx._clear_cache(G)
(G, values, name=None)
31,097
networkx.drawing.layout
shell_layout
Position nodes in concentric circles. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. nlist : list of lists List of node lists for each shell. rotate : angle in radians (default=pi/len(nlist)) Angle by which to rotate the starting position of each shell relative to the starting position of the previous shell. To recreate behavior before v2.5 use rotate=0. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int Dimension of layout, currently only dim=2 is supported. Other dimension values result in a ValueError. Returns ------- pos : dict A dictionary of positions keyed by node Raises ------ ValueError If dim != 2 Examples -------- >>> G = nx.path_graph(4) >>> shells = [[0], [1, 2, 3]] >>> pos = nx.shell_layout(G, shells) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
def shell_layout(G, nlist=None, rotate=None, scale=1, center=None, dim=2): """Position nodes in concentric circles. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. nlist : list of lists List of node lists for each shell. rotate : angle in radians (default=pi/len(nlist)) Angle by which to rotate the starting position of each shell relative to the starting position of the previous shell. To recreate behavior before v2.5 use rotate=0. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int Dimension of layout, currently only dim=2 is supported. Other dimension values result in a ValueError. Returns ------- pos : dict A dictionary of positions keyed by node Raises ------ ValueError If dim != 2 Examples -------- >>> G = nx.path_graph(4) >>> shells = [[0], [1, 2, 3]] >>> pos = nx.shell_layout(G, shells) Notes ----- This algorithm currently only works in two dimensions and does not try to minimize edge crossings. """ import numpy as np if dim != 2: raise ValueError("can only handle 2 dimensions") G, center = _process_params(G, center, dim) if len(G) == 0: return {} if len(G) == 1: return {nx.utils.arbitrary_element(G): center} if nlist is None: # draw the whole graph in one shell nlist = [list(G)] radius_bump = scale / len(nlist) if len(nlist[0]) == 1: # single node at center radius = 0.0 else: # else start at r=1 radius = radius_bump if rotate is None: rotate = np.pi / len(nlist) first_theta = rotate npos = {} for nodes in nlist: # Discard the last angle (endpoint=False) since 2*pi matches 0 radians theta = ( np.linspace(0, 2 * np.pi, len(nodes), endpoint=False, dtype=np.float32) + first_theta ) pos = radius * np.column_stack([np.cos(theta), np.sin(theta)]) + center npos.update(zip(nodes, pos)) radius += radius_bump first_theta += rotate return npos
(G, nlist=None, rotate=None, scale=1, center=None, dim=2)
31,098
networkx.algorithms.shortest_paths.generic
shortest_path
Compute shortest paths in the graph. Parameters ---------- G : NetworkX graph source : node, optional Starting node for path. If not specified, compute shortest paths for each possible starting node. target : node, optional Ending node for path. If not specified, compute shortest paths to all possible nodes. weight : None, string or function, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. method : string, optional (default = 'dijkstra') The algorithm to use to compute the path. Supported options: 'dijkstra', 'bellman-ford'. Other inputs produce a ValueError. If `weight` is None, unweighted graph methods are used, and this suggestion is ignored. Returns ------- path: list or dictionary All returned paths include both the source and target in the path. If the source and target are both specified, return a single list of nodes in a shortest path from the source to the target. If only the source is specified, return a dictionary keyed by targets with a list of nodes in a shortest path from the source to one of the targets. If only the target is specified, return a dictionary keyed by sources with a list of nodes in a shortest path from one of the sources to the target. If neither the source nor target are specified return a dictionary of dictionaries with path[source][target]=[list of nodes in path]. Raises ------ NodeNotFound If `source` is not in `G`. ValueError If `method` is not among the supported options. Examples -------- >>> G = nx.path_graph(5) >>> print(nx.shortest_path(G, source=0, target=4)) [0, 1, 2, 3, 4] >>> p = nx.shortest_path(G, source=0) # target not specified >>> p[3] # shortest path from source=0 to target=3 [0, 1, 2, 3] >>> p = nx.shortest_path(G, target=4) # source not specified >>> p[1] # shortest path from source=1 to target=4 [1, 2, 3, 4] >>> p = dict(nx.shortest_path(G)) # source, target not specified >>> p[2][4] # shortest path from source=2 to target=4 [2, 3, 4] Notes ----- There may be more than one shortest path between a source and target. This returns only one of them. See Also -------- all_pairs_shortest_path all_pairs_dijkstra_path all_pairs_bellman_ford_path single_source_shortest_path single_source_dijkstra_path single_source_bellman_ford_path
null
(G, source=None, target=None, weight=None, method='dijkstra', *, backend=None, **backend_kwargs)
31,099
networkx.algorithms.shortest_paths.generic
shortest_path_length
Compute shortest path lengths in the graph. Parameters ---------- G : NetworkX graph source : node, optional Starting node for path. If not specified, compute shortest path lengths using all nodes as source nodes. target : node, optional Ending node for path. If not specified, compute shortest path lengths using all nodes as target nodes. weight : None, string or function, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. method : string, optional (default = 'dijkstra') The algorithm to use to compute the path length. Supported options: 'dijkstra', 'bellman-ford'. Other inputs produce a ValueError. If `weight` is None, unweighted graph methods are used, and this suggestion is ignored. Returns ------- length: int or iterator If the source and target are both specified, return the length of the shortest path from the source to the target. If only the source is specified, return a dict keyed by target to the shortest path length from the source to that target. If only the target is specified, return a dict keyed by source to the shortest path length from that source to the target. If neither the source nor target are specified, return an iterator over (source, dictionary) where dictionary is keyed by target to shortest path length from source to that target. Raises ------ NodeNotFound If `source` is not in `G`. NetworkXNoPath If no path exists between source and target. ValueError If `method` is not among the supported options. Examples -------- >>> G = nx.path_graph(5) >>> nx.shortest_path_length(G, source=0, target=4) 4 >>> p = nx.shortest_path_length(G, source=0) # target not specified >>> p[4] 4 >>> p = nx.shortest_path_length(G, target=4) # source not specified >>> p[0] 4 >>> p = dict(nx.shortest_path_length(G)) # source,target not specified >>> p[0][4] 4 Notes ----- The length of the path is always 1 less than the number of nodes involved in the path since the length measures the number of edges followed. For digraphs this returns the shortest directed path length. To find path lengths in the reverse direction use G.reverse(copy=False) first to flip the edge orientation. See Also -------- all_pairs_shortest_path_length all_pairs_dijkstra_path_length all_pairs_bellman_ford_path_length single_source_shortest_path_length single_source_dijkstra_path_length single_source_bellman_ford_path_length
null
(G, source=None, target=None, weight=None, method='dijkstra', *, backend=None, **backend_kwargs)
31,101
networkx.algorithms.simple_paths
shortest_simple_paths
Generate all simple paths in the graph G from source to target, starting from shortest ones. A simple path is a path with no repeated nodes. If a weighted shortest path search is to be used, no negative weights are allowed. Parameters ---------- G : NetworkX graph source : node Starting node for path target : node Ending node for path weight : string or function If it is a string, it is the name of the edge attribute to be used as a weight. If it is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. If None all edges are considered to have unit weight. Default value None. Returns ------- path_generator: generator A generator that produces lists of simple paths, in order from shortest to longest. Raises ------ NetworkXNoPath If no path exists between source and target. NetworkXError If source or target nodes are not in the input graph. NetworkXNotImplemented If the input graph is a Multi[Di]Graph. Examples -------- >>> G = nx.cycle_graph(7) >>> paths = list(nx.shortest_simple_paths(G, 0, 3)) >>> print(paths) [[0, 1, 2, 3], [0, 6, 5, 4, 3]] You can use this function to efficiently compute the k shortest/best paths between two nodes. >>> from itertools import islice >>> def k_shortest_paths(G, source, target, k, weight=None): ... return list( ... islice(nx.shortest_simple_paths(G, source, target, weight=weight), k) ... ) >>> for path in k_shortest_paths(G, 0, 3, 2): ... print(path) [0, 1, 2, 3] [0, 6, 5, 4, 3] Notes ----- This procedure is based on algorithm by Jin Y. Yen [1]_. Finding the first $K$ paths requires $O(KN^3)$ operations. See Also -------- all_shortest_paths shortest_path all_simple_paths References ---------- .. [1] Jin Y. Yen, "Finding the K Shortest Loopless Paths in a Network", Management Science, Vol. 17, No. 11, Theory Series (Jul., 1971), pp. 712-716.
def _bidirectional_dijkstra( G, source, target, weight="weight", ignore_nodes=None, ignore_edges=None ): """Dijkstra's algorithm for shortest paths using bidirectional search. This function returns the shortest path between source and target ignoring nodes and edges in the containers ignore_nodes and ignore_edges. This is a custom modification of the standard Dijkstra bidirectional shortest path implementation at networkx.algorithms.weighted Parameters ---------- G : NetworkX graph source : node Starting node. target : node Ending node. weight: string, function, optional (default='weight') Edge data key or weight function corresponding to the edge weight ignore_nodes : container of nodes nodes to ignore, optional ignore_edges : container of edges edges to ignore, optional Returns ------- length : number Shortest path length. Returns a tuple of two dictionaries keyed by node. The first dictionary stores distance from the source. The second stores the path from the source to that node. Raises ------ NetworkXNoPath If no path exists between source and target. Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. In practice bidirectional Dijkstra is much more than twice as fast as ordinary Dijkstra. Ordinary Dijkstra expands nodes in a sphere-like manner from the source. The radius of this sphere will eventually be the length of the shortest path. Bidirectional Dijkstra will expand nodes from both the source and the target, making two spheres of half this radius. Volume of the first sphere is pi*r*r while the others are 2*pi*r/2*r/2, making up half the volume. This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows and roundoff errors can cause problems). See Also -------- shortest_path shortest_path_length """ if ignore_nodes and (source in ignore_nodes or target in ignore_nodes): raise nx.NetworkXNoPath(f"No path between {source} and {target}.") if source == target: if source not in G: raise nx.NodeNotFound(f"Node {source} not in graph") return (0, [source]) # handle either directed or undirected if G.is_directed(): Gpred = G.predecessors Gsucc = G.successors else: Gpred = G.neighbors Gsucc = G.neighbors # support optional nodes filter if ignore_nodes: def filter_iter(nodes): def iterate(v): for w in nodes(v): if w not in ignore_nodes: yield w return iterate Gpred = filter_iter(Gpred) Gsucc = filter_iter(Gsucc) # support optional edges filter if ignore_edges: if G.is_directed(): def filter_pred_iter(pred_iter): def iterate(v): for w in pred_iter(v): if (w, v) not in ignore_edges: yield w return iterate def filter_succ_iter(succ_iter): def iterate(v): for w in succ_iter(v): if (v, w) not in ignore_edges: yield w return iterate Gpred = filter_pred_iter(Gpred) Gsucc = filter_succ_iter(Gsucc) else: def filter_iter(nodes): def iterate(v): for w in nodes(v): if (v, w) not in ignore_edges and (w, v) not in ignore_edges: yield w return iterate Gpred = filter_iter(Gpred) Gsucc = filter_iter(Gsucc) push = heappush pop = heappop # Init: Forward Backward dists = [{}, {}] # dictionary of final distances paths = [{source: [source]}, {target: [target]}] # dictionary of paths fringe = [[], []] # heap of (distance, node) tuples for # extracting next node to expand seen = [{source: 0}, {target: 0}] # dictionary of distances to # nodes seen c = count() # initialize fringe heap push(fringe[0], (0, next(c), source)) push(fringe[1], (0, next(c), target)) # neighs for extracting correct neighbor information neighs = [Gsucc, Gpred] # variables to hold shortest discovered path # finaldist = 1e30000 finalpath = [] dir = 1 while fringe[0] and fringe[1]: # choose direction # dir == 0 is forward direction and dir == 1 is back dir = 1 - dir # extract closest to expand (dist, _, v) = pop(fringe[dir]) if v in dists[dir]: # Shortest path to v has already been found continue # update distance dists[dir][v] = dist # equal to seen[dir][v] if v in dists[1 - dir]: # if we have scanned v in both directions we are done # we have now discovered the shortest path return (finaldist, finalpath) wt = _weight_function(G, weight) for w in neighs[dir](v): if dir == 0: # forward minweight = wt(v, w, G.get_edge_data(v, w)) vwLength = dists[dir][v] + minweight else: # back, must remember to change v,w->w,v minweight = wt(w, v, G.get_edge_data(w, v)) vwLength = dists[dir][v] + minweight if w in dists[dir]: if vwLength < dists[dir][w]: raise ValueError("Contradictory paths found: negative weights?") elif w not in seen[dir] or vwLength < seen[dir][w]: # relaxing seen[dir][w] = vwLength push(fringe[dir], (vwLength, next(c), w)) paths[dir][w] = paths[dir][v] + [w] if w in seen[0] and w in seen[1]: # see if this path is better than the already # discovered shortest path totaldist = seen[0][w] + seen[1][w] if finalpath == [] or finaldist > totaldist: finaldist = totaldist revpath = paths[1][w][:] revpath.reverse() finalpath = paths[0][w] + revpath[1:] raise nx.NetworkXNoPath(f"No path between {source} and {target}.")
(G, source, target, weight=None, *, backend=None, **backend_kwargs)
31,102
networkx.algorithms.smallworld
sigma
Returns the small-world coefficient (sigma) of the given graph. The small-world coefficient is defined as: sigma = C/Cr / L/Lr where C and L are respectively the average clustering coefficient and average shortest path length of G. Cr and Lr are respectively the average clustering coefficient and average shortest path length of an equivalent random graph. A graph is commonly classified as small-world if sigma>1. Parameters ---------- G : NetworkX graph An undirected graph. niter : integer (optional, default=100) Approximate number of rewiring per edge to compute the equivalent random graph. nrand : integer (optional, default=10) Number of random graphs generated to compute the average clustering coefficient (Cr) and average shortest path length (Lr). seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- sigma : float The small-world coefficient of G. Notes ----- The implementation is adapted from Humphries et al. [1]_ [2]_. References ---------- .. [1] The brainstem reticular formation is a small-world, not scale-free, network M. D. Humphries, K. Gurney and T. J. Prescott, Proc. Roy. Soc. B 2006 273, 503-511, doi:10.1098/rspb.2005.3354. .. [2] Humphries and Gurney (2008). "Network 'Small-World-Ness': A Quantitative Method for Determining Canonical Network Equivalence". PLoS One. 3 (4). PMID 18446219. doi:10.1371/journal.pone.0002051.
null
(G, niter=100, nrand=10, seed=None, *, backend=None, **backend_kwargs)
31,104
networkx.algorithms.cycles
simple_cycles
Find simple cycles (elementary circuits) of a graph. A `simple cycle`, or `elementary circuit`, is a closed path where no node appears twice. In a directed graph, two simple cycles are distinct if they are not cyclic permutations of each other. In an undirected graph, two simple cycles are distinct if they are not cyclic permutations of each other nor of the other's reversal. Optionally, the cycles are bounded in length. In the unbounded case, we use a nonrecursive, iterator/generator version of Johnson's algorithm [1]_. In the bounded case, we use a version of the algorithm of Gupta and Suzumura[2]_. There may be better algorithms for some cases [3]_ [4]_ [5]_. The algorithms of Johnson, and Gupta and Suzumura, are enhanced by some well-known preprocessing techniques. When G is directed, we restrict our attention to strongly connected components of G, generate all simple cycles containing a certain node, remove that node, and further decompose the remainder into strongly connected components. When G is undirected, we restrict our attention to biconnected components, generate all simple cycles containing a particular edge, remove that edge, and further decompose the remainder into biconnected components. Note that multigraphs are supported by this function -- and in undirected multigraphs, a pair of parallel edges is considered a cycle of length 2. Likewise, self-loops are considered to be cycles of length 1. We define cycles as sequences of nodes; so the presence of loops and parallel edges does not change the number of simple cycles in a graph. Parameters ---------- G : NetworkX DiGraph A directed graph length_bound : int or None, optional (default=None) If length_bound is an int, generate all simple cycles of G with length at most length_bound. Otherwise, generate all simple cycles of G. Yields ------ list of nodes Each cycle is represented by a list of nodes along the cycle. Examples -------- >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)] >>> G = nx.DiGraph(edges) >>> sorted(nx.simple_cycles(G)) [[0], [0, 1, 2], [0, 2], [1, 2], [2]] To filter the cycles so that they don't include certain nodes or edges, copy your graph and eliminate those nodes or edges before calling. For example, to exclude self-loops from the above example: >>> H = G.copy() >>> H.remove_edges_from(nx.selfloop_edges(G)) >>> sorted(nx.simple_cycles(H)) [[0, 1, 2], [0, 2], [1, 2]] Notes ----- When length_bound is None, the time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ simple circuits. Otherwise, when length_bound > 1, the time complexity is $O((c+n)(k-1)d^k)$ where $d$ is the average degree of the nodes of G and $k$ = length_bound. Raises ------ ValueError when length_bound < 0. References ---------- .. [1] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975. https://doi.org/10.1137/0204007 .. [2] Finding All Bounded-Length Simple Cycles in a Directed Graph A. Gupta and T. Suzumura https://arxiv.org/abs/2105.10094 .. [3] Enumerating the cycles of a digraph: a new preprocessing strategy. G. Loizou and P. Thanish, Information Sciences, v. 27, 163-182, 1982. .. [4] A search strategy for the elementary cycles of a directed graph. J.L. Szwarcfiter and P.E. Lauer, BIT NUMERICAL MATHEMATICS, v. 16, no. 2, 192-204, 1976. .. [5] Optimal Listing of Cycles and st-Paths in Undirected Graphs R. Ferreira and R. Grossi and A. Marino and N. Pisanti and R. Rizzi and G. Sacomoto https://arxiv.org/abs/1205.2766 See Also -------- cycle_basis chordless_cycles
def recursive_simple_cycles(G): """Find simple cycles (elementary circuits) of a directed graph. A `simple cycle`, or `elementary circuit`, is a closed path where no node appears twice. Two elementary circuits are distinct if they are not cyclic permutations of each other. This version uses a recursive algorithm to build a list of cycles. You should probably use the iterator version called simple_cycles(). Warning: This recursive version uses lots of RAM! It appears in NetworkX for pedagogical value. Parameters ---------- G : NetworkX DiGraph A directed graph Returns ------- A list of cycles, where each cycle is represented by a list of nodes along the cycle. Example: >>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)] >>> G = nx.DiGraph(edges) >>> nx.recursive_simple_cycles(G) [[0], [2], [0, 1, 2], [0, 2], [1, 2]] Notes ----- The implementation follows pp. 79-80 in [1]_. The time complexity is $O((n+e)(c+1))$ for $n$ nodes, $e$ edges and $c$ elementary circuits. References ---------- .. [1] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1, 77-84, 1975. https://doi.org/10.1137/0204007 See Also -------- simple_cycles, cycle_basis """ # Jon Olav Vik, 2010-08-09 def _unblock(thisnode): """Recursively unblock and remove nodes from B[thisnode].""" if blocked[thisnode]: blocked[thisnode] = False while B[thisnode]: _unblock(B[thisnode].pop()) def circuit(thisnode, startnode, component): closed = False # set to True if elementary path is closed path.append(thisnode) blocked[thisnode] = True for nextnode in component[thisnode]: # direct successors of thisnode if nextnode == startnode: result.append(path[:]) closed = True elif not blocked[nextnode]: if circuit(nextnode, startnode, component): closed = True if closed: _unblock(thisnode) else: for nextnode in component[thisnode]: if thisnode not in B[nextnode]: # TODO: use set for speedup? B[nextnode].append(thisnode) path.pop() # remove thisnode from path return closed path = [] # stack of nodes in current path blocked = defaultdict(bool) # vertex: blocked from search? B = defaultdict(list) # graph portions that yield no elementary circuit result = [] # list to accumulate the circuits found # Johnson's algorithm exclude self cycle edges like (v, v) # To be backward compatible, we record those cycles in advance # and then remove from subG for v in G: if G.has_edge(v, v): result.append([v]) G.remove_edge(v, v) # Johnson's algorithm requires some ordering of the nodes. # They might not be sortable so we assign an arbitrary ordering. ordering = dict(zip(G, range(len(G)))) for s in ordering: # Build the subgraph induced by s and following nodes in the ordering subgraph = G.subgraph(node for node in G if ordering[node] >= ordering[s]) # Find the strongly connected component in the subgraph # that contains the least node according to the ordering strongcomp = nx.strongly_connected_components(subgraph) mincomp = min(strongcomp, key=lambda ns: min(ordering[n] for n in ns)) component = G.subgraph(mincomp) if len(component) > 1: # smallest node in the component according to the ordering startnode = min(component, key=ordering.__getitem__) for node in component: blocked[node] = False B[node][:] = [] dummy = circuit(startnode, startnode, component) return result
(G, length_bound=None, *, backend=None, **backend_kwargs)
31,106
networkx.algorithms.similarity
simrank_similarity
Returns the SimRank similarity of nodes in the graph ``G``. SimRank is a similarity metric that says "two objects are considered to be similar if they are referenced by similar objects." [1]_. The pseudo-code definition from the paper is:: def simrank(G, u, v): in_neighbors_u = G.predecessors(u) in_neighbors_v = G.predecessors(v) scale = C / (len(in_neighbors_u) * len(in_neighbors_v)) return scale * sum( simrank(G, w, x) for w, x in product(in_neighbors_u, in_neighbors_v) ) where ``G`` is the graph, ``u`` is the source, ``v`` is the target, and ``C`` is a float decay or importance factor between 0 and 1. The SimRank algorithm for determining node similarity is defined in [2]_. Parameters ---------- G : NetworkX graph A NetworkX graph source : node If this is specified, the returned dictionary maps each node ``v`` in the graph to the similarity between ``source`` and ``v``. target : node If both ``source`` and ``target`` are specified, the similarity value between ``source`` and ``target`` is returned. If ``target`` is specified but ``source`` is not, this argument is ignored. importance_factor : float The relative importance of indirect neighbors with respect to direct neighbors. max_iterations : integer Maximum number of iterations. tolerance : float Error tolerance used to check convergence. When an iteration of the algorithm finds that no similarity value changes more than this amount, the algorithm halts. Returns ------- similarity : dictionary or float If ``source`` and ``target`` are both ``None``, this returns a dictionary of dictionaries, where keys are node pairs and value are similarity of the pair of nodes. If ``source`` is not ``None`` but ``target`` is, this returns a dictionary mapping node to the similarity of ``source`` and that node. If neither ``source`` nor ``target`` is ``None``, this returns the similarity value for the given pair of nodes. Raises ------ ExceededMaxIterations If the algorithm does not converge within ``max_iterations``. NodeNotFound If either ``source`` or ``target`` is not in `G`. Examples -------- >>> G = nx.cycle_graph(2) >>> nx.simrank_similarity(G) {0: {0: 1.0, 1: 0.0}, 1: {0: 0.0, 1: 1.0}} >>> nx.simrank_similarity(G, source=0) {0: 1.0, 1: 0.0} >>> nx.simrank_similarity(G, source=0, target=0) 1.0 The result of this function can be converted to a numpy array representing the SimRank matrix by using the node order of the graph to determine which row and column represent each node. Other ordering of nodes is also possible. >>> import numpy as np >>> sim = nx.simrank_similarity(G) >>> np.array([[sim[u][v] for v in G] for u in G]) array([[1., 0.], [0., 1.]]) >>> sim_1d = nx.simrank_similarity(G, source=0) >>> np.array([sim[0][v] for v in G]) array([1., 0.]) References ---------- .. [1] https://en.wikipedia.org/wiki/SimRank .. [2] G. Jeh and J. Widom. "SimRank: a measure of structural-context similarity", In KDD'02: Proceedings of the Eighth ACM SIGKDD International Conference on Knowledge Discovery and Data Mining, pp. 538--543. ACM Press, 2002.
def optimize_edit_paths( G1, G2, node_match=None, edge_match=None, node_subst_cost=None, node_del_cost=None, node_ins_cost=None, edge_subst_cost=None, edge_del_cost=None, edge_ins_cost=None, upper_bound=None, strictly_decreasing=True, roots=None, timeout=None, ): """GED (graph edit distance) calculation: advanced interface. Graph edit path is a sequence of node and edge edit operations transforming graph G1 to graph isomorphic to G2. Edit operations include substitutions, deletions, and insertions. Graph edit distance is defined as minimum cost of edit path. Parameters ---------- G1, G2: graphs The two graphs G1 and G2 must be of the same type. node_match : callable A function that returns True if node n1 in G1 and n2 in G2 should be considered equal during matching. The function will be called like node_match(G1.nodes[n1], G2.nodes[n2]). That is, the function will receive the node attribute dictionaries for n1 and n2 as inputs. Ignored if node_subst_cost is specified. If neither node_match nor node_subst_cost are specified then node attributes are not considered. edge_match : callable A function that returns True if the edge attribute dictionaries for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should be considered equal during matching. The function will be called like edge_match(G1[u1][v1], G2[u2][v2]). That is, the function will receive the edge attribute dictionaries of the edges under consideration. Ignored if edge_subst_cost is specified. If neither edge_match nor edge_subst_cost are specified then edge attributes are not considered. node_subst_cost, node_del_cost, node_ins_cost : callable Functions that return the costs of node substitution, node deletion, and node insertion, respectively. The functions will be called like node_subst_cost(G1.nodes[n1], G2.nodes[n2]), node_del_cost(G1.nodes[n1]), node_ins_cost(G2.nodes[n2]). That is, the functions will receive the node attribute dictionaries as inputs. The functions are expected to return positive numeric values. Function node_subst_cost overrides node_match if specified. If neither node_match nor node_subst_cost are specified then default node substitution cost of 0 is used (node attributes are not considered during matching). If node_del_cost is not specified then default node deletion cost of 1 is used. If node_ins_cost is not specified then default node insertion cost of 1 is used. edge_subst_cost, edge_del_cost, edge_ins_cost : callable Functions that return the costs of edge substitution, edge deletion, and edge insertion, respectively. The functions will be called like edge_subst_cost(G1[u1][v1], G2[u2][v2]), edge_del_cost(G1[u1][v1]), edge_ins_cost(G2[u2][v2]). That is, the functions will receive the edge attribute dictionaries as inputs. The functions are expected to return positive numeric values. Function edge_subst_cost overrides edge_match if specified. If neither edge_match nor edge_subst_cost are specified then default edge substitution cost of 0 is used (edge attributes are not considered during matching). If edge_del_cost is not specified then default edge deletion cost of 1 is used. If edge_ins_cost is not specified then default edge insertion cost of 1 is used. upper_bound : numeric Maximum edit distance to consider. strictly_decreasing : bool If True, return consecutive approximations of strictly decreasing cost. Otherwise, return all edit paths of cost less than or equal to the previous minimum cost. roots : 2-tuple Tuple where first element is a node in G1 and the second is a node in G2. These nodes are forced to be matched in the comparison to allow comparison between rooted graphs. timeout : numeric Maximum number of seconds to execute. After timeout is met, the current best GED is returned. Returns ------- Generator of tuples (node_edit_path, edge_edit_path, cost) node_edit_path : list of tuples (u, v) edge_edit_path : list of tuples ((u1, v1), (u2, v2)) cost : numeric See Also -------- graph_edit_distance, optimize_graph_edit_distance, optimal_edit_paths References ---------- .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick Martineau. An Exact Graph Edit Distance Algorithm for Solving Pattern Recognition Problems. 4th International Conference on Pattern Recognition Applications and Methods 2015, Jan 2015, Lisbon, Portugal. 2015, <10.5220/0005209202710278>. <hal-01168816> https://hal.archives-ouvertes.fr/hal-01168816 """ # TODO: support DiGraph import numpy as np import scipy as sp @dataclass class CostMatrix: C: ... lsa_row_ind: ... lsa_col_ind: ... ls: ... def make_CostMatrix(C, m, n): # assert(C.shape == (m + n, m + n)) lsa_row_ind, lsa_col_ind = sp.optimize.linear_sum_assignment(C) # Fixup dummy assignments: # each substitution i<->j should have dummy assignment m+j<->n+i # NOTE: fast reduce of Cv relies on it # assert len(lsa_row_ind) == len(lsa_col_ind) indexes = zip(range(len(lsa_row_ind)), lsa_row_ind, lsa_col_ind) subst_ind = [k for k, i, j in indexes if i < m and j < n] indexes = zip(range(len(lsa_row_ind)), lsa_row_ind, lsa_col_ind) dummy_ind = [k for k, i, j in indexes if i >= m and j >= n] # assert len(subst_ind) == len(dummy_ind) lsa_row_ind[dummy_ind] = lsa_col_ind[subst_ind] + m lsa_col_ind[dummy_ind] = lsa_row_ind[subst_ind] + n return CostMatrix( C, lsa_row_ind, lsa_col_ind, C[lsa_row_ind, lsa_col_ind].sum() ) def extract_C(C, i, j, m, n): # assert(C.shape == (m + n, m + n)) row_ind = [k in i or k - m in j for k in range(m + n)] col_ind = [k in j or k - n in i for k in range(m + n)] return C[row_ind, :][:, col_ind] def reduce_C(C, i, j, m, n): # assert(C.shape == (m + n, m + n)) row_ind = [k not in i and k - m not in j for k in range(m + n)] col_ind = [k not in j and k - n not in i for k in range(m + n)] return C[row_ind, :][:, col_ind] def reduce_ind(ind, i): # assert set(ind) == set(range(len(ind))) rind = ind[[k not in i for k in ind]] for k in set(i): rind[rind >= k] -= 1 return rind def match_edges(u, v, pending_g, pending_h, Ce, matched_uv=None): """ Parameters: u, v: matched vertices, u=None or v=None for deletion/insertion pending_g, pending_h: lists of edges not yet mapped Ce: CostMatrix of pending edge mappings matched_uv: partial vertex edit path list of tuples (u, v) of previously matched vertex mappings u<->v, u=None or v=None for deletion/insertion Returns: list of (i, j): indices of edge mappings g<->h localCe: local CostMatrix of edge mappings (basically submatrix of Ce at cross of rows i, cols j) """ M = len(pending_g) N = len(pending_h) # assert Ce.C.shape == (M + N, M + N) # only attempt to match edges after one node match has been made # this will stop self-edges on the first node being automatically deleted # even when a substitution is the better option if matched_uv is None or len(matched_uv) == 0: g_ind = [] h_ind = [] else: g_ind = [ i for i in range(M) if pending_g[i][:2] == (u, u) or any( pending_g[i][:2] in ((p, u), (u, p), (p, p)) for p, q in matched_uv ) ] h_ind = [ j for j in range(N) if pending_h[j][:2] == (v, v) or any( pending_h[j][:2] in ((q, v), (v, q), (q, q)) for p, q in matched_uv ) ] m = len(g_ind) n = len(h_ind) if m or n: C = extract_C(Ce.C, g_ind, h_ind, M, N) # assert C.shape == (m + n, m + n) # Forbid structurally invalid matches # NOTE: inf remembered from Ce construction for k, i in enumerate(g_ind): g = pending_g[i][:2] for l, j in enumerate(h_ind): h = pending_h[j][:2] if nx.is_directed(G1) or nx.is_directed(G2): if any( g == (p, u) and h == (q, v) or g == (u, p) and h == (v, q) for p, q in matched_uv ): continue else: if any( g in ((p, u), (u, p)) and h in ((q, v), (v, q)) for p, q in matched_uv ): continue if g == (u, u) or any(g == (p, p) for p, q in matched_uv): continue if h == (v, v) or any(h == (q, q) for p, q in matched_uv): continue C[k, l] = inf localCe = make_CostMatrix(C, m, n) ij = [ ( g_ind[k] if k < m else M + h_ind[l], h_ind[l] if l < n else N + g_ind[k], ) for k, l in zip(localCe.lsa_row_ind, localCe.lsa_col_ind) if k < m or l < n ] else: ij = [] localCe = CostMatrix(np.empty((0, 0)), [], [], 0) return ij, localCe def reduce_Ce(Ce, ij, m, n): if len(ij): i, j = zip(*ij) m_i = m - sum(1 for t in i if t < m) n_j = n - sum(1 for t in j if t < n) return make_CostMatrix(reduce_C(Ce.C, i, j, m, n), m_i, n_j) return Ce def get_edit_ops( matched_uv, pending_u, pending_v, Cv, pending_g, pending_h, Ce, matched_cost ): """ Parameters: matched_uv: partial vertex edit path list of tuples (u, v) of vertex mappings u<->v, u=None or v=None for deletion/insertion pending_u, pending_v: lists of vertices not yet mapped Cv: CostMatrix of pending vertex mappings pending_g, pending_h: lists of edges not yet mapped Ce: CostMatrix of pending edge mappings matched_cost: cost of partial edit path Returns: sequence of (i, j): indices of vertex mapping u<->v Cv_ij: reduced CostMatrix of pending vertex mappings (basically Cv with row i, col j removed) list of (x, y): indices of edge mappings g<->h Ce_xy: reduced CostMatrix of pending edge mappings (basically Ce with rows x, cols y removed) cost: total cost of edit operation NOTE: most promising ops first """ m = len(pending_u) n = len(pending_v) # assert Cv.C.shape == (m + n, m + n) # 1) a vertex mapping from optimal linear sum assignment i, j = min( (k, l) for k, l in zip(Cv.lsa_row_ind, Cv.lsa_col_ind) if k < m or l < n ) xy, localCe = match_edges( pending_u[i] if i < m else None, pending_v[j] if j < n else None, pending_g, pending_h, Ce, matched_uv, ) Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h)) # assert Ce.ls <= localCe.ls + Ce_xy.ls if prune(matched_cost + Cv.ls + localCe.ls + Ce_xy.ls): pass else: # get reduced Cv efficiently Cv_ij = CostMatrix( reduce_C(Cv.C, (i,), (j,), m, n), reduce_ind(Cv.lsa_row_ind, (i, m + j)), reduce_ind(Cv.lsa_col_ind, (j, n + i)), Cv.ls - Cv.C[i, j], ) yield (i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls # 2) other candidates, sorted by lower-bound cost estimate other = [] fixed_i, fixed_j = i, j if m <= n: candidates = ( (t, fixed_j) for t in range(m + n) if t != fixed_i and (t < m or t == m + fixed_j) ) else: candidates = ( (fixed_i, t) for t in range(m + n) if t != fixed_j and (t < n or t == n + fixed_i) ) for i, j in candidates: if prune(matched_cost + Cv.C[i, j] + Ce.ls): continue Cv_ij = make_CostMatrix( reduce_C(Cv.C, (i,), (j,), m, n), m - 1 if i < m else m, n - 1 if j < n else n, ) # assert Cv.ls <= Cv.C[i, j] + Cv_ij.ls if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + Ce.ls): continue xy, localCe = match_edges( pending_u[i] if i < m else None, pending_v[j] if j < n else None, pending_g, pending_h, Ce, matched_uv, ) if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls): continue Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h)) # assert Ce.ls <= localCe.ls + Ce_xy.ls if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls + Ce_xy.ls): continue other.append(((i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls)) yield from sorted(other, key=lambda t: t[4] + t[1].ls + t[3].ls) def get_edit_paths( matched_uv, pending_u, pending_v, Cv, matched_gh, pending_g, pending_h, Ce, matched_cost, ): """ Parameters: matched_uv: partial vertex edit path list of tuples (u, v) of vertex mappings u<->v, u=None or v=None for deletion/insertion pending_u, pending_v: lists of vertices not yet mapped Cv: CostMatrix of pending vertex mappings matched_gh: partial edge edit path list of tuples (g, h) of edge mappings g<->h, g=None or h=None for deletion/insertion pending_g, pending_h: lists of edges not yet mapped Ce: CostMatrix of pending edge mappings matched_cost: cost of partial edit path Returns: sequence of (vertex_path, edge_path, cost) vertex_path: complete vertex edit path list of tuples (u, v) of vertex mappings u<->v, u=None or v=None for deletion/insertion edge_path: complete edge edit path list of tuples (g, h) of edge mappings g<->h, g=None or h=None for deletion/insertion cost: total cost of edit path NOTE: path costs are non-increasing """ # debug_print('matched-uv:', matched_uv) # debug_print('matched-gh:', matched_gh) # debug_print('matched-cost:', matched_cost) # debug_print('pending-u:', pending_u) # debug_print('pending-v:', pending_v) # debug_print(Cv.C) # assert list(sorted(G1.nodes)) == list(sorted(list(u for u, v in matched_uv if u is not None) + pending_u)) # assert list(sorted(G2.nodes)) == list(sorted(list(v for u, v in matched_uv if v is not None) + pending_v)) # debug_print('pending-g:', pending_g) # debug_print('pending-h:', pending_h) # debug_print(Ce.C) # assert list(sorted(G1.edges)) == list(sorted(list(g for g, h in matched_gh if g is not None) + pending_g)) # assert list(sorted(G2.edges)) == list(sorted(list(h for g, h in matched_gh if h is not None) + pending_h)) # debug_print() if prune(matched_cost + Cv.ls + Ce.ls): return if not max(len(pending_u), len(pending_v)): # assert not len(pending_g) # assert not len(pending_h) # path completed! # assert matched_cost <= maxcost_value nonlocal maxcost_value maxcost_value = min(maxcost_value, matched_cost) yield matched_uv, matched_gh, matched_cost else: edit_ops = get_edit_ops( matched_uv, pending_u, pending_v, Cv, pending_g, pending_h, Ce, matched_cost, ) for ij, Cv_ij, xy, Ce_xy, edit_cost in edit_ops: i, j = ij # assert Cv.C[i, j] + sum(Ce.C[t] for t in xy) == edit_cost if prune(matched_cost + edit_cost + Cv_ij.ls + Ce_xy.ls): continue # dive deeper u = pending_u.pop(i) if i < len(pending_u) else None v = pending_v.pop(j) if j < len(pending_v) else None matched_uv.append((u, v)) for x, y in xy: len_g = len(pending_g) len_h = len(pending_h) matched_gh.append( ( pending_g[x] if x < len_g else None, pending_h[y] if y < len_h else None, ) ) sortedx = sorted(x for x, y in xy) sortedy = sorted(y for x, y in xy) G = [ (pending_g.pop(x) if x < len(pending_g) else None) for x in reversed(sortedx) ] H = [ (pending_h.pop(y) if y < len(pending_h) else None) for y in reversed(sortedy) ] yield from get_edit_paths( matched_uv, pending_u, pending_v, Cv_ij, matched_gh, pending_g, pending_h, Ce_xy, matched_cost + edit_cost, ) # backtrack if u is not None: pending_u.insert(i, u) if v is not None: pending_v.insert(j, v) matched_uv.pop() for x, g in zip(sortedx, reversed(G)): if g is not None: pending_g.insert(x, g) for y, h in zip(sortedy, reversed(H)): if h is not None: pending_h.insert(y, h) for _ in xy: matched_gh.pop() # Initialization pending_u = list(G1.nodes) pending_v = list(G2.nodes) initial_cost = 0 if roots: root_u, root_v = roots if root_u not in pending_u or root_v not in pending_v: raise nx.NodeNotFound("Root node not in graph.") # remove roots from pending pending_u.remove(root_u) pending_v.remove(root_v) # cost matrix of vertex mappings m = len(pending_u) n = len(pending_v) C = np.zeros((m + n, m + n)) if node_subst_cost: C[0:m, 0:n] = np.array( [ node_subst_cost(G1.nodes[u], G2.nodes[v]) for u in pending_u for v in pending_v ] ).reshape(m, n) if roots: initial_cost = node_subst_cost(G1.nodes[root_u], G2.nodes[root_v]) elif node_match: C[0:m, 0:n] = np.array( [ 1 - int(node_match(G1.nodes[u], G2.nodes[v])) for u in pending_u for v in pending_v ] ).reshape(m, n) if roots: initial_cost = 1 - node_match(G1.nodes[root_u], G2.nodes[root_v]) else: # all zeroes pass # assert not min(m, n) or C[0:m, 0:n].min() >= 0 if node_del_cost: del_costs = [node_del_cost(G1.nodes[u]) for u in pending_u] else: del_costs = [1] * len(pending_u) # assert not m or min(del_costs) >= 0 if node_ins_cost: ins_costs = [node_ins_cost(G2.nodes[v]) for v in pending_v] else: ins_costs = [1] * len(pending_v) # assert not n or min(ins_costs) >= 0 inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1 C[0:m, n : n + m] = np.array( [del_costs[i] if i == j else inf for i in range(m) for j in range(m)] ).reshape(m, m) C[m : m + n, 0:n] = np.array( [ins_costs[i] if i == j else inf for i in range(n) for j in range(n)] ).reshape(n, n) Cv = make_CostMatrix(C, m, n) # debug_print(f"Cv: {m} x {n}") # debug_print(Cv.C) pending_g = list(G1.edges) pending_h = list(G2.edges) # cost matrix of edge mappings m = len(pending_g) n = len(pending_h) C = np.zeros((m + n, m + n)) if edge_subst_cost: C[0:m, 0:n] = np.array( [ edge_subst_cost(G1.edges[g], G2.edges[h]) for g in pending_g for h in pending_h ] ).reshape(m, n) elif edge_match: C[0:m, 0:n] = np.array( [ 1 - int(edge_match(G1.edges[g], G2.edges[h])) for g in pending_g for h in pending_h ] ).reshape(m, n) else: # all zeroes pass # assert not min(m, n) or C[0:m, 0:n].min() >= 0 if edge_del_cost: del_costs = [edge_del_cost(G1.edges[g]) for g in pending_g] else: del_costs = [1] * len(pending_g) # assert not m or min(del_costs) >= 0 if edge_ins_cost: ins_costs = [edge_ins_cost(G2.edges[h]) for h in pending_h] else: ins_costs = [1] * len(pending_h) # assert not n or min(ins_costs) >= 0 inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1 C[0:m, n : n + m] = np.array( [del_costs[i] if i == j else inf for i in range(m) for j in range(m)] ).reshape(m, m) C[m : m + n, 0:n] = np.array( [ins_costs[i] if i == j else inf for i in range(n) for j in range(n)] ).reshape(n, n) Ce = make_CostMatrix(C, m, n) # debug_print(f'Ce: {m} x {n}') # debug_print(Ce.C) # debug_print() maxcost_value = Cv.C.sum() + Ce.C.sum() + 1 if timeout is not None: if timeout <= 0: raise nx.NetworkXError("Timeout value must be greater than 0") start = time.perf_counter() def prune(cost): if timeout is not None: if time.perf_counter() - start > timeout: return True if upper_bound is not None: if cost > upper_bound: return True if cost > maxcost_value: return True if strictly_decreasing and cost >= maxcost_value: return True return False # Now go! done_uv = [] if roots is None else [roots] for vertex_path, edge_path, cost in get_edit_paths( done_uv, pending_u, pending_v, Cv, [], pending_g, pending_h, Ce, initial_cost ): # assert sorted(G1.nodes) == sorted(u for u, v in vertex_path if u is not None) # assert sorted(G2.nodes) == sorted(v for u, v in vertex_path if v is not None) # assert sorted(G1.edges) == sorted(g for g, h in edge_path if g is not None) # assert sorted(G2.edges) == sorted(h for g, h in edge_path if h is not None) # print(vertex_path, edge_path, cost, file = sys.stderr) # assert cost == maxcost_value yield list(vertex_path), list(edge_path), float(cost)
(G, source=None, target=None, importance_factor=0.9, max_iterations=1000, tolerance=0.0001, *, backend=None, **backend_kwargs)
31,107
networkx.algorithms.shortest_paths.generic
single_source_all_shortest_paths
Compute all shortest simple paths from the given source in the graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. weight : None, string or function, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. method : string, optional (default = 'dijkstra') The algorithm to use to compute the path lengths. Supported options: 'dijkstra', 'bellman-ford'. Other inputs produce a ValueError. If `weight` is None, unweighted graph methods are used, and this suggestion is ignored. Returns ------- paths : generator of dictionary A generator of all paths between source and all nodes in the graph. Raises ------ ValueError If `method` is not among the supported options. Examples -------- >>> G = nx.Graph() >>> nx.add_path(G, [0, 1, 2, 3, 0]) >>> dict(nx.single_source_all_shortest_paths(G, source=0)) {0: [[0]], 1: [[0, 1]], 2: [[0, 1, 2], [0, 3, 2]], 3: [[0, 3]]} Notes ----- There may be many shortest paths between the source and target. If G contains zero-weight cycles, this function will not produce all shortest paths because doing so would produce infinitely many paths of unbounded length -- instead, we only produce the shortest simple paths. See Also -------- shortest_path all_shortest_paths single_source_shortest_path all_pairs_shortest_path all_pairs_all_shortest_paths
null
(G, source, weight=None, method='dijkstra', *, backend=None, **backend_kwargs)
31,108
networkx.algorithms.shortest_paths.weighted
single_source_bellman_ford
Compute shortest paths and lengths in a weighted graph G. Uses Bellman-Ford algorithm for shortest paths. Parameters ---------- G : NetworkX graph source : node label Starting node for path target : node label, optional Ending node for path weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- distance, path : pair of dictionaries, or numeric and list If target is None, returns a tuple of two dictionaries keyed by node. The first dictionary stores distance from one of the source nodes. The second stores the path from one of the sources to that node. If target is not None, returns a tuple of (distance, path) where distance is the distance from source to target and path is a list representing the path from source to target. Raises ------ NodeNotFound If `source` is not in `G`. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.single_source_bellman_ford(G, 0) >>> length[4] 4 >>> for node in [0, 1, 2, 3, 4]: ... print(f"{node}: {length[node]}") 0: 0 1: 1 2: 2 3: 3 4: 4 >>> path[4] [0, 1, 2, 3, 4] >>> length, path = nx.single_source_bellman_ford(G, 0, 1) >>> length 1 >>> path [0, 1] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- single_source_dijkstra single_source_bellman_ford_path single_source_bellman_ford_path_length
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, target=None, weight='weight', *, backend=None, **backend_kwargs)
31,109
networkx.algorithms.shortest_paths.weighted
single_source_bellman_ford_path
Compute shortest path between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. weight : string or function (default="weight") If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- paths : dictionary Dictionary of shortest path lengths keyed by target. Raises ------ NodeNotFound If `source` is not in `G`. Examples -------- >>> G = nx.path_graph(5) >>> path = nx.single_source_bellman_ford_path(G, 0) >>> path[4] [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- single_source_dijkstra, single_source_bellman_ford
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, weight='weight', *, backend=None, **backend_kwargs)
31,110
networkx.algorithms.shortest_paths.weighted
single_source_bellman_ford_path_length
Compute the shortest path length between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path weight : string or function (default="weight") If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number. Returns ------- length : dictionary Dictionary of shortest path length keyed by target Raises ------ NodeNotFound If `source` is not in `G`. Examples -------- >>> G = nx.path_graph(5) >>> length = nx.single_source_bellman_ford_path_length(G, 0) >>> length[4] 4 >>> for node in [0, 1, 2, 3, 4]: ... print(f"{node}: {length[node]}") 0: 0 1: 1 2: 2 3: 3 4: 4 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. See Also -------- single_source_dijkstra, single_source_bellman_ford
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, weight='weight', *, backend=None, **backend_kwargs)
31,111
networkx.algorithms.shortest_paths.weighted
single_source_dijkstra
Find shortest weighted paths and lengths from a source node. Compute the shortest path length between source and all other reachable nodes for a weighted graph. Uses Dijkstra's algorithm to compute shortest paths and lengths between a source and all other reachable nodes in a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path target : node label, optional Ending node for path cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number or None to indicate a hidden edge. Returns ------- distance, path : pair of dictionaries, or numeric and list. If target is None, paths and lengths to all nodes are computed. The return value is a tuple of two dictionaries keyed by target nodes. The first dictionary stores distance to each target node. The second stores the path to each target node. If target is not None, returns a tuple (distance, path), where distance is the distance from source to target and path is a list representing the path from source to target. Raises ------ NodeNotFound If `source` is not in `G`. Examples -------- >>> G = nx.path_graph(5) >>> length, path = nx.single_source_dijkstra(G, 0) >>> length[4] 4 >>> for node in [0, 1, 2, 3, 4]: ... print(f"{node}: {length[node]}") 0: 0 1: 1 2: 2 3: 3 4: 4 >>> path[4] [0, 1, 2, 3, 4] >>> length, path = nx.single_source_dijkstra(G, 0, 1) >>> length 1 >>> path [0, 1] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. Based on the Python cookbook recipe (119466) at https://code.activestate.com/recipes/119466/ This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows and roundoff errors can cause problems). See Also -------- single_source_dijkstra_path single_source_dijkstra_path_length single_source_bellman_ford
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, target=None, cutoff=None, weight='weight', *, backend=None, **backend_kwargs)
31,112
networkx.algorithms.shortest_paths.weighted
single_source_dijkstra_path
Find shortest weighted paths in G from a source node. Compute shortest path between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number or None to indicate a hidden edge. Returns ------- paths : dictionary Dictionary of shortest path lengths keyed by target. Raises ------ NodeNotFound If `source` is not in `G`. Examples -------- >>> G = nx.path_graph(5) >>> path = nx.single_source_dijkstra_path(G, 0) >>> path[4] [0, 1, 2, 3, 4] Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. See Also -------- single_source_dijkstra, single_source_bellman_ford
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, cutoff=None, weight='weight', *, backend=None, **backend_kwargs)
31,113
networkx.algorithms.shortest_paths.weighted
single_source_dijkstra_path_length
Find shortest weighted path lengths in G from a source node. Compute the shortest path length between source and all other reachable nodes for a weighted graph. Parameters ---------- G : NetworkX graph source : node label Starting node for path cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. weight : string or function If this is a string, then edge weights will be accessed via the edge attribute with this key (that is, the weight of the edge joining `u` to `v` will be ``G.edges[u, v][weight]``). If no such edge attribute exists, the weight of the edge is assumed to be one. If this is a function, the weight of an edge is the value returned by the function. The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. The function must return a number or None to indicate a hidden edge. Returns ------- length : dict Dict keyed by node to shortest path length from source. Raises ------ NodeNotFound If `source` is not in `G`. Examples -------- >>> G = nx.path_graph(5) >>> length = nx.single_source_dijkstra_path_length(G, 0) >>> length[4] 4 >>> for node in [0, 1, 2, 3, 4]: ... print(f"{node}: {length[node]}") 0: 0 1: 1 2: 2 3: 3 4: 4 Notes ----- Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed. The weight function can be used to hide edges by returning None. So ``weight = lambda u, v, d: 1 if d['color']=="red" else None`` will find the shortest red path. See Also -------- single_source_dijkstra, single_source_bellman_ford_path_length
def _dijkstra_multisource( G, sources, weight, pred=None, paths=None, cutoff=None, target=None ): """Uses Dijkstra's algorithm to find shortest weighted paths Parameters ---------- G : NetworkX graph sources : non-empty iterable of nodes Starting nodes for paths. If this is just an iterable containing a single node, then all paths computed by this function will start from that node. If there are two or more nodes in this iterable, the computed paths may begin from any one of the start nodes. weight: function Function with (u, v, data) input that returns that edge's weight or None to indicate a hidden edge pred: dict of lists, optional(default=None) dict to store a list of predecessors keyed by that node If None, predecessors are not stored. paths: dict, optional (default=None) dict to store the path list from source to each node, keyed by node. If None, paths are not stored. target : node label, optional Ending node for path. Search is halted when target is found. cutoff : integer or float, optional Length (sum of edge weights) at which the search is stopped. If cutoff is provided, only return paths with summed weight <= cutoff. Returns ------- distance : dictionary A mapping from node to shortest distance to that node from one of the source nodes. Raises ------ NodeNotFound If any of `sources` is not in `G`. Notes ----- The optional predecessor and path dictionaries can be accessed by the caller through the original pred and paths objects passed as arguments. No need to explicitly return pred or paths. """ G_succ = G._adj # For speed-up (and works for both directed and undirected graphs) push = heappush pop = heappop dist = {} # dictionary of final distances seen = {} # fringe is heapq with 3-tuples (distance,c,node) # use the count c to avoid comparing nodes (may not be able to) c = count() fringe = [] for source in sources: seen[source] = 0 push(fringe, (0, next(c), source)) while fringe: (d, _, v) = pop(fringe) if v in dist: continue # already searched this node. dist[v] = d if v == target: break for u, e in G_succ[v].items(): cost = weight(v, u, e) if cost is None: continue vu_dist = dist[v] + cost if cutoff is not None: if vu_dist > cutoff: continue if u in dist: u_dist = dist[u] if vu_dist < u_dist: raise ValueError("Contradictory paths found:", "negative weights?") elif pred is not None and vu_dist == u_dist: pred[u].append(v) elif u not in seen or vu_dist < seen[u]: seen[u] = vu_dist push(fringe, (vu_dist, next(c), u)) if paths is not None: paths[u] = paths[v] + [u] if pred is not None: pred[u] = [v] elif vu_dist == seen[u]: if pred is not None: pred[u].append(v) # The optional predecessor and path dictionaries can be accessed # by the caller via the pred and paths objects passed as arguments. return dist
(G, source, cutoff=None, weight='weight', *, backend=None, **backend_kwargs)
31,114
networkx.algorithms.shortest_paths.unweighted
single_source_shortest_path
Compute shortest path between source and all other nodes reachable from source. Parameters ---------- G : NetworkX graph source : node label Starting node for path cutoff : integer, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- paths : dictionary Dictionary, keyed by target, of shortest paths. Examples -------- >>> G = nx.path_graph(5) >>> path = nx.single_source_shortest_path(G, 0) >>> path[4] [0, 1, 2, 3, 4] Notes ----- The shortest path is not necessarily unique. So there can be multiple paths between the source and each target node, all of which have the same 'shortest' length. For each target node, this function returns only one of those paths. See Also -------- shortest_path
null
(G, source, cutoff=None, *, backend=None, **backend_kwargs)
31,115
networkx.algorithms.shortest_paths.unweighted
single_source_shortest_path_length
Compute the shortest path lengths from source to all reachable nodes. Parameters ---------- G : NetworkX graph source : node Starting node for path cutoff : integer, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- lengths : dict Dict keyed by node to shortest path length to source. Examples -------- >>> G = nx.path_graph(5) >>> length = nx.single_source_shortest_path_length(G, 0) >>> length[4] 4 >>> for node in length: ... print(f"{node}: {length[node]}") 0: 0 1: 1 2: 2 3: 3 4: 4 See Also -------- shortest_path_length
null
(G, source, cutoff=None, *, backend=None, **backend_kwargs)
31,116
networkx.algorithms.shortest_paths.unweighted
single_target_shortest_path
Compute shortest path to target from all nodes that reach target. Parameters ---------- G : NetworkX graph target : node label Target node for path cutoff : integer, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- paths : dictionary Dictionary, keyed by target, of shortest paths. Examples -------- >>> G = nx.path_graph(5, create_using=nx.DiGraph()) >>> path = nx.single_target_shortest_path(G, 4) >>> path[0] [0, 1, 2, 3, 4] Notes ----- The shortest path is not necessarily unique. So there can be multiple paths between the source and each target node, all of which have the same 'shortest' length. For each target node, this function returns only one of those paths. See Also -------- shortest_path, single_source_shortest_path
null
(G, target, cutoff=None, *, backend=None, **backend_kwargs)
31,117
networkx.algorithms.shortest_paths.unweighted
single_target_shortest_path_length
Compute the shortest path lengths to target from all reachable nodes. Parameters ---------- G : NetworkX graph target : node Target node for path cutoff : integer, optional Depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- lengths : iterator (source, shortest path length) iterator Examples -------- >>> G = nx.path_graph(5, create_using=nx.DiGraph()) >>> length = dict(nx.single_target_shortest_path_length(G, 4)) >>> length[0] 4 >>> for node in range(5): ... print(f"{node}: {length[node]}") 0: 4 1: 3 2: 2 3: 1 4: 0 See Also -------- single_source_shortest_path_length, shortest_path_length
null
(G, target, cutoff=None, *, backend=None, **backend_kwargs)
31,121
networkx.algorithms.summarization
snap_aggregation
Creates a summary graph based on attributes and connectivity. This function uses the Summarization by Grouping Nodes on Attributes and Pairwise edges (SNAP) algorithm for summarizing a given graph by grouping nodes by node attributes and their edge attributes into supernodes in a summary graph. This name SNAP should not be confused with the Stanford Network Analysis Project (SNAP). Here is a high-level view of how this algorithm works: 1) Group nodes by node attribute values. 2) Iteratively split groups until all nodes in each group have edges to nodes in the same groups. That is, until all the groups are homogeneous in their member nodes' edges to other groups. For example, if all the nodes in group A only have edge to nodes in group B, then the group is homogeneous and does not need to be split. If all nodes in group B have edges with nodes in groups {A, C}, but some also have edges with other nodes in B, then group B is not homogeneous and needs to be split into groups have edges with {A, C} and a group of nodes having edges with {A, B, C}. This way, viewers of the summary graph can assume that all nodes in the group have the exact same node attributes and the exact same edges. 3) Build the output summary graph, where the groups are represented by super-nodes. Edges represent the edges shared between all the nodes in each respective groups. A SNAP summary graph can be used to visualize graphs that are too large to display or visually analyze, or to efficiently identify sets of similar nodes with similar connectivity patterns to other sets of similar nodes based on specified node and/or edge attributes in a graph. Parameters ---------- G: graph Networkx Graph to be summarized node_attributes: iterable, required An iterable of the node attributes used to group nodes in the summarization process. Nodes with the same values for these attributes will be grouped together in the summary graph. edge_attributes: iterable, optional An iterable of the edge attributes considered in the summarization process. If provided, unique combinations of the attribute values found in the graph are used to determine the edge types in the graph. If not provided, all edges are considered to be of the same type. prefix: str The prefix used to denote supernodes in the summary graph. Defaults to 'Supernode-'. supernode_attribute: str The node attribute for recording the supernode groupings of nodes. Defaults to 'group'. superedge_attribute: str The edge attribute for recording the edge types of multiple edges. Defaults to 'types'. Returns ------- networkx.Graph: summary graph Examples -------- SNAP aggregation takes a graph and summarizes it in the context of user-provided node and edge attributes such that a viewer can more easily extract and analyze the information represented by the graph >>> nodes = { ... "A": dict(color="Red"), ... "B": dict(color="Red"), ... "C": dict(color="Red"), ... "D": dict(color="Red"), ... "E": dict(color="Blue"), ... "F": dict(color="Blue"), ... } >>> edges = [ ... ("A", "E", "Strong"), ... ("B", "F", "Strong"), ... ("C", "E", "Weak"), ... ("D", "F", "Weak"), ... ] >>> G = nx.Graph() >>> for node in nodes: ... attributes = nodes[node] ... G.add_node(node, **attributes) >>> for source, target, type in edges: ... G.add_edge(source, target, type=type) >>> node_attributes = ("color",) >>> edge_attributes = ("type",) >>> summary_graph = nx.snap_aggregation( ... G, node_attributes=node_attributes, edge_attributes=edge_attributes ... ) Notes ----- The summary graph produced is called a maximum Attribute-edge compatible (AR-compatible) grouping. According to [1]_, an AR-compatible grouping means that all nodes in each group have the same exact node attribute values and the same exact edges and edge types to one or more nodes in the same groups. The maximal AR-compatible grouping is the grouping with the minimal cardinality. The AR-compatible grouping is the most detailed grouping provided by any of the SNAP algorithms. References ---------- .. [1] Y. Tian, R. A. Hankins, and J. M. Patel. Efficient aggregation for graph summarization. In Proc. 2008 ACM-SIGMOD Int. Conf. Management of Data (SIGMOD’08), pages 567–580, Vancouver, Canada, June 2008.
null
(G, node_attributes, edge_attributes=(), prefix='Supernode-', supernode_attribute='group', superedge_attribute='types', *, backend=None, **backend_kwargs)
31,123
networkx.generators.geometric
soft_random_geometric_graph
Returns a soft random geometric graph in the unit cube. The soft random geometric graph [1] model places `n` nodes uniformly at random in the unit cube in dimension `dim`. Two nodes of distance, `dist`, computed by the `p`-Minkowski distance metric are joined by an edge with probability `p_dist` if the computed distance metric value of the nodes is at most `radius`, otherwise they are not joined. Edges within `radius` of each other are determined using a KDTree when SciPy is available. This reduces the time complexity from :math:`O(n^2)` to :math:`O(n)`. Parameters ---------- n : int or iterable Number of nodes or iterable of nodes radius: float Distance threshold value dim : int, optional Dimension of graph pos : dict, optional A dictionary keyed by node with node positions as values. p : float, optional Which Minkowski distance metric to use. `p` has to meet the condition ``1 <= p <= infinity``. If this argument is not specified, the :math:`L^2` metric (the Euclidean distance metric), p = 2 is used. This should not be confused with the `p` of an Erdős-Rényi random graph, which represents probability. p_dist : function, optional A probability density function computing the probability of connecting two nodes that are of distance, dist, computed by the Minkowski distance metric. The probability density function, `p_dist`, must be any function that takes the metric value as input and outputs a single probability value between 0-1. The scipy.stats package has many probability distribution functions implemented and tools for custom probability distribution definitions [2], and passing the .pdf method of scipy.stats distributions can be used here. If the probability function, `p_dist`, is not supplied, the default function is an exponential distribution with rate parameter :math:`\lambda=1`. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. pos_name : string, default="pos" The name of the node attribute which represents the position in 2D coordinates of the node in the returned graph. Returns ------- Graph A soft random geometric graph, undirected and without self-loops. Each node has a node attribute ``'pos'`` that stores the position of that node in Euclidean space as provided by the ``pos`` keyword argument or, if ``pos`` was not provided, as generated by this function. Examples -------- Default Graph: G = nx.soft_random_geometric_graph(50, 0.2) Custom Graph: Create a soft random geometric graph on 100 uniformly distributed nodes where nodes are joined by an edge with probability computed from an exponential distribution with rate parameter :math:`\lambda=1` if their Euclidean distance is at most 0.2. Notes ----- This uses a *k*-d tree to build the graph. The `pos` keyword argument can be used to specify node positions so you can create an arbitrary distribution and domain for positions. For example, to use a 2D Gaussian distribution of node positions with mean (0, 0) and standard deviation 2 The scipy.stats package can be used to define the probability distribution with the .pdf method used as `p_dist`. :: >>> import random >>> import math >>> n = 100 >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)} >>> p_dist = lambda dist: math.exp(-dist) >>> G = nx.soft_random_geometric_graph(n, 0.2, pos=pos, p_dist=p_dist) References ---------- .. [1] Penrose, Mathew D. "Connectivity of soft random geometric graphs." The Annals of Applied Probability 26.2 (2016): 986-1028. .. [2] scipy.stats - https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
def thresholded_random_geometric_graph( n, radius, theta, dim=2, pos=None, weight=None, p=2, seed=None, *, pos_name="pos", weight_name="weight", ): r"""Returns a thresholded random geometric graph in the unit cube. The thresholded random geometric graph [1] model places `n` nodes uniformly at random in the unit cube of dimensions `dim`. Each node `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are joined by an edge if they are within the maximum connection distance, `radius` computed by the `p`-Minkowski distance and the summation of weights :math:`w_u` + :math:`w_v` is greater than or equal to the threshold parameter `theta`. Edges within `radius` of each other are determined using a KDTree when SciPy is available. This reduces the time complexity from :math:`O(n^2)` to :math:`O(n)`. Parameters ---------- n : int or iterable Number of nodes or iterable of nodes radius: float Distance threshold value theta: float Threshold value dim : int, optional Dimension of graph pos : dict, optional A dictionary keyed by node with node positions as values. weight : dict, optional Node weights as a dictionary of numbers keyed by node. p : float, optional (default 2) Which Minkowski distance metric to use. `p` has to meet the condition ``1 <= p <= infinity``. If this argument is not specified, the :math:`L^2` metric (the Euclidean distance metric), p = 2 is used. This should not be confused with the `p` of an Erdős-Rényi random graph, which represents probability. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. pos_name : string, default="pos" The name of the node attribute which represents the position in 2D coordinates of the node in the returned graph. weight_name : string, default="weight" The name of the node attribute which represents the weight of the node in the returned graph. Returns ------- Graph A thresholded random geographic graph, undirected and without self-loops. Each node has a node attribute ``'pos'`` that stores the position of that node in Euclidean space as provided by the ``pos`` keyword argument or, if ``pos`` was not provided, as generated by this function. Similarly, each node has a nodethre attribute ``'weight'`` that stores the weight of that node as provided or as generated. Examples -------- Default Graph: G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1) Custom Graph: Create a thresholded random geometric graph on 50 uniformly distributed nodes where nodes are joined by an edge if their sum weights drawn from a exponential distribution with rate = 5 are >= theta = 0.1 and their Euclidean distance is at most 0.2. Notes ----- This uses a *k*-d tree to build the graph. The `pos` keyword argument can be used to specify node positions so you can create an arbitrary distribution and domain for positions. For example, to use a 2D Gaussian distribution of node positions with mean (0, 0) and standard deviation 2 If weights are not specified they are assigned to nodes by drawing randomly from the exponential distribution with rate parameter :math:`\lambda=1`. To specify weights from a different distribution, use the `weight` keyword argument:: :: >>> import random >>> import math >>> n = 50 >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)} >>> w = {i: random.expovariate(5.0) for i in range(n)} >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w) References ---------- .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf """ G = nx.empty_graph(n) G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})" # If no weights are provided, choose them from an exponential # distribution. if weight is None: weight = {v: seed.expovariate(1) for v in G} # If no positions are provided, choose uniformly random vectors in # Euclidean space of the specified dimension. if pos is None: pos = {v: [seed.random() for i in range(dim)] for v in G} # If no distance metric is provided, use Euclidean distance. nx.set_node_attributes(G, weight, weight_name) nx.set_node_attributes(G, pos, pos_name) edges = ( (u, v) for u, v in _geometric_edges(G, radius, p, pos_name) if weight[u] + weight[v] >= theta ) G.add_edges_from(edges) return G
(n, radius, dim=2, pos=None, p=2, p_dist=None, seed=None, *, pos_name='pos', backend=None, **backend_kwargs)
31,124
networkx.algorithms.sparsifiers
spanner
Returns a spanner of the given graph with the given stretch. A spanner of a graph G = (V, E) with stretch t is a subgraph H = (V, E_S) such that E_S is a subset of E and the distance between any pair of nodes in H is at most t times the distance between the nodes in G. Parameters ---------- G : NetworkX graph An undirected simple graph. stretch : float The stretch of the spanner. weight : object The edge attribute to use as distance. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- NetworkX graph A spanner of the given graph with the given stretch. Raises ------ ValueError If a stretch less than 1 is given. Notes ----- This function implements the spanner algorithm by Baswana and Sen, see [1]. This algorithm is a randomized las vegas algorithm: The expected running time is O(km) where k = (stretch + 1) // 2 and m is the number of edges in G. The returned graph is always a spanner of the given graph with the specified stretch. For weighted graphs the number of edges in the spanner is O(k * n^(1 + 1 / k)) where k is defined as above and n is the number of nodes in G. For unweighted graphs the number of edges is O(n^(1 + 1 / k) + kn). References ---------- [1] S. Baswana, S. Sen. A Simple and Linear Time Randomized Algorithm for Computing Sparse Spanners in Weighted Graphs. Random Struct. Algorithms 30(4): 532-563 (2007).
null
(G, stretch, weight=None, seed=None, *, backend=None, **backend_kwargs)
31,127
networkx.linalg.algebraicconnectivity
spectral_bisection
Bisect the graph using the Fiedler vector. This method uses the Fiedler vector to bisect a graph. The partition is defined by the nodes which are associated with either positive or negative values in the vector. Parameters ---------- G : NetworkX Graph weight : str, optional (default: weight) The data key used to determine the weight of each edge. If None, then each edge has unit weight. normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used. tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation. method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG). The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used. =============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ======================================== seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- bisection : tuple of sets Sets with the bisection of nodes Examples -------- >>> G = nx.barbell_graph(3, 0) >>> nx.spectral_bisection(G) ({0, 1, 2}, {3, 4, 5}) References ---------- .. [1] M. E. J Newman 'Networks: An Introduction', pages 364-370 Oxford University Press 2011.
null
(G, weight='weight', normalized=False, tol=1e-08, method='tracemin_pcg', seed=None, *, backend=None, **backend_kwargs)
31,128
networkx.generators.spectral_graph_forge
spectral_graph_forge
Returns a random simple graph with spectrum resembling that of `G` This algorithm, called Spectral Graph Forge (SGF), computes the eigenvectors of a given graph adjacency matrix, filters them and builds a random graph with a similar eigenstructure. SGF has been proved to be particularly useful for synthesizing realistic social networks and it can also be used to anonymize graph sensitive data. Parameters ---------- G : Graph alpha : float Ratio representing the percentage of eigenvectors of G to consider, values in [0,1]. transformation : string, optional Represents the intended matrix linear transformation, possible values are 'identity' and 'modularity' seed : integer, random_state, or None (default) Indicator of numpy random number generation state. See :ref:`Randomness<randomness>`. Returns ------- H : Graph A graph with a similar eigenvector structure of the input one. Raises ------ NetworkXError If transformation has a value different from 'identity' or 'modularity' Notes ----- Spectral Graph Forge (SGF) generates a random simple graph resembling the global properties of the given one. It leverages the low-rank approximation of the associated adjacency matrix driven by the *alpha* precision parameter. SGF preserves the number of nodes of the input graph and their ordering. This way, nodes of output graphs resemble the properties of the input one and attributes can be directly mapped. It considers the graph adjacency matrices which can optionally be transformed to other symmetric real matrices (currently transformation options include *identity* and *modularity*). The *modularity* transformation, in the sense of Newman's modularity matrix allows the focusing on community structure related properties of the graph. SGF applies a low-rank approximation whose fixed rank is computed from the ratio *alpha* of the input graph adjacency matrix dimension. This step performs a filtering on the input eigenvectors similar to the low pass filtering common in telecommunications. The filtered values (after truncation) are used as input to a Bernoulli sampling for constructing a random adjacency matrix. References ---------- .. [1] L. Baldesi, C. T. Butts, A. Markopoulou, "Spectral Graph Forge: Graph Generation Targeting Modularity", IEEE Infocom, '18. https://arxiv.org/abs/1801.01715 .. [2] M. Newman, "Networks: an introduction", Oxford university press, 2010 Examples -------- >>> G = nx.karate_club_graph() >>> H = nx.spectral_graph_forge(G, 0.3) >>>
null
(G, alpha, transformation='identity', seed=None, *, backend=None, **backend_kwargs)
31,129
networkx.drawing.layout
spectral_layout
Position nodes using the eigenvectors of the graph Laplacian. Using the unnormalized Laplacian, the layout shows possible clusters of nodes which are an approximation of the ratio cut. If dim is the number of dimensions then the positions are the entries of the dim eigenvectors corresponding to the ascending eigenvalues starting from the second one. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. weight : string or None optional (default='weight') The edge attribute that holds the numerical value used for the edge weight. If None, then all edge weights are 1. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int Dimension of layout. Returns ------- pos : dict A dictionary of positions keyed by node Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.spectral_layout(G) Notes ----- Directed graphs will be considered as undirected graphs when positioning the nodes. For larger graphs (>500 nodes) this will use the SciPy sparse eigenvalue solver (ARPACK).
def spectral_layout(G, weight="weight", scale=1, center=None, dim=2): """Position nodes using the eigenvectors of the graph Laplacian. Using the unnormalized Laplacian, the layout shows possible clusters of nodes which are an approximation of the ratio cut. If dim is the number of dimensions then the positions are the entries of the dim eigenvectors corresponding to the ascending eigenvalues starting from the second one. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. weight : string or None optional (default='weight') The edge attribute that holds the numerical value used for the edge weight. If None, then all edge weights are 1. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int Dimension of layout. Returns ------- pos : dict A dictionary of positions keyed by node Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.spectral_layout(G) Notes ----- Directed graphs will be considered as undirected graphs when positioning the nodes. For larger graphs (>500 nodes) this will use the SciPy sparse eigenvalue solver (ARPACK). """ # handle some special cases that break the eigensolvers import numpy as np G, center = _process_params(G, center, dim) if len(G) <= 2: if len(G) == 0: pos = np.array([]) elif len(G) == 1: pos = np.array([center]) else: pos = np.array([np.zeros(dim), np.array(center) * 2.0]) return dict(zip(G, pos)) try: # Sparse matrix if len(G) < 500: # dense solver is faster for small graphs raise ValueError A = nx.to_scipy_sparse_array(G, weight=weight, dtype="d") # Symmetrize directed graphs if G.is_directed(): A = A + np.transpose(A) pos = _sparse_spectral(A, dim) except (ImportError, ValueError): # Dense matrix A = nx.to_numpy_array(G, weight=weight) # Symmetrize directed graphs if G.is_directed(): A += A.T pos = _spectral(A, dim) pos = rescale_layout(pos, scale=scale) + center pos = dict(zip(G, pos)) return pos
(G, weight='weight', scale=1, center=None, dim=2)
31,130
networkx.linalg.algebraicconnectivity
spectral_ordering
Compute the spectral_ordering of a graph. The spectral ordering of a graph is an ordering of its nodes where nodes in the same weakly connected components appear contiguous and ordered by their corresponding elements in the Fiedler vector of the component. Parameters ---------- G : NetworkX graph A graph. weight : object, optional (default: None) The data key used to determine the weight of each edge. If None, then each edge has unit weight. normalized : bool, optional (default: False) Whether the normalized Laplacian matrix is used. tol : float, optional (default: 1e-8) Tolerance of relative residual in eigenvalue computation. method : string, optional (default: 'tracemin_pcg') Method of eigenvalue computation. It must be one of the tracemin options shown below (TraceMIN), 'lanczos' (Lanczos iteration) or 'lobpcg' (LOBPCG). The TraceMIN algorithm uses a linear system solver. The following values allow specifying the solver to be used. =============== ======================================== Value Solver =============== ======================================== 'tracemin_pcg' Preconditioned conjugate gradient method 'tracemin_lu' LU factorization =============== ======================================== seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. Returns ------- spectral_ordering : NumPy array of floats. Spectral ordering of nodes. Raises ------ NetworkXError If G is empty. Notes ----- Edge weights are interpreted by their absolute values. For MultiGraph's, weights of parallel edges are summed. Zero-weighted edges are ignored. See Also -------- laplacian_matrix
null
(G, weight='weight', normalized=False, tol=1e-08, method='tracemin_pcg', seed=None, *, backend=None, **backend_kwargs)
31,132
networkx.drawing.layout
spiral_layout
Position nodes in a spiral layout. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int, default=2 Dimension of layout, currently only dim=2 is supported. Other dimension values result in a ValueError. resolution : float, default=0.35 The compactness of the spiral layout returned. Lower values result in more compressed spiral layouts. equidistant : bool, default=False If True, nodes will be positioned equidistant from each other by decreasing angle further from center. If False, nodes will be positioned at equal angles from each other by increasing separation further from center. Returns ------- pos : dict A dictionary of positions keyed by node Raises ------ ValueError If dim != 2 Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.spiral_layout(G) >>> nx.draw(G, pos=pos) Notes ----- This algorithm currently only works in two dimensions.
def spiral_layout(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False): """Position nodes in a spiral layout. Parameters ---------- G : NetworkX graph or list of nodes A position will be assigned to every node in G. scale : number (default: 1) Scale factor for positions. center : array-like or None Coordinate pair around which to center the layout. dim : int, default=2 Dimension of layout, currently only dim=2 is supported. Other dimension values result in a ValueError. resolution : float, default=0.35 The compactness of the spiral layout returned. Lower values result in more compressed spiral layouts. equidistant : bool, default=False If True, nodes will be positioned equidistant from each other by decreasing angle further from center. If False, nodes will be positioned at equal angles from each other by increasing separation further from center. Returns ------- pos : dict A dictionary of positions keyed by node Raises ------ ValueError If dim != 2 Examples -------- >>> G = nx.path_graph(4) >>> pos = nx.spiral_layout(G) >>> nx.draw(G, pos=pos) Notes ----- This algorithm currently only works in two dimensions. """ import numpy as np if dim != 2: raise ValueError("can only handle 2 dimensions") G, center = _process_params(G, center, dim) if len(G) == 0: return {} if len(G) == 1: return {nx.utils.arbitrary_element(G): center} pos = [] if equidistant: chord = 1 step = 0.5 theta = resolution theta += chord / (step * theta) for _ in range(len(G)): r = step * theta theta += chord / r pos.append([np.cos(theta) * r, np.sin(theta) * r]) else: dist = np.arange(len(G), dtype=float) angle = resolution * dist pos = np.transpose(dist * np.array([np.cos(angle), np.sin(angle)])) pos = rescale_layout(np.array(pos), scale=scale) + center pos = dict(zip(G, pos)) return pos
(G, scale=1, center=None, dim=2, resolution=0.35, equidistant=False)
31,134
networkx.algorithms.cluster
square_clustering
Compute the squares clustering coefficient for nodes. For each node return the fraction of possible squares that exist at the node [1]_ .. math:: C_4(v) = \frac{ \sum_{u=1}^{k_v} \sum_{w=u+1}^{k_v} q_v(u,w) }{ \sum_{u=1}^{k_v} \sum_{w=u+1}^{k_v} [a_v(u,w) + q_v(u,w)]}, where :math:`q_v(u,w)` are the number of common neighbors of :math:`u` and :math:`w` other than :math:`v` (ie squares), and :math:`a_v(u,w) = (k_u - (1+q_v(u,w)+\theta_{uv})) + (k_w - (1+q_v(u,w)+\theta_{uw}))`, where :math:`\theta_{uw} = 1` if :math:`u` and :math:`w` are connected and 0 otherwise. [2]_ Parameters ---------- G : graph nodes : container of nodes, optional (default=all nodes in G) Compute clustering for nodes in this container. Returns ------- c4 : dictionary A dictionary keyed by node with the square clustering coefficient value. Examples -------- >>> G = nx.complete_graph(5) >>> print(nx.square_clustering(G, 0)) 1.0 >>> print(nx.square_clustering(G)) {0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0} Notes ----- While :math:`C_3(v)` (triangle clustering) gives the probability that two neighbors of node v are connected with each other, :math:`C_4(v)` is the probability that two neighbors of node v share a common neighbor different from v. This algorithm can be applied to both bipartite and unipartite networks. References ---------- .. [1] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005 Cycles and clustering in bipartite networks. Physical Review E (72) 056127. .. [2] Zhang, Peng et al. Clustering Coefficient and Community Structure of Bipartite Networks. Physica A: Statistical Mechanics and its Applications 387.27 (2008): 6869–6875. https://arxiv.org/abs/0710.0117v1
null
(G, nodes=None, *, backend=None, **backend_kwargs)
31,135
networkx.generators.classic
star_graph
Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)).
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(n, create_using=None, *, backend=None, **backend_kwargs)
31,137
networkx.generators.community
stochastic_block_model
Returns a stochastic block model graph. This model partitions the nodes in blocks of arbitrary sizes, and places edges between pairs of nodes independently, with a probability that depends on the blocks. Parameters ---------- sizes : list of ints Sizes of blocks p : list of list of floats Element (r,s) gives the density of edges going from the nodes of group r to nodes of group s. p must match the number of groups (len(sizes) == len(p)), and it must be symmetric if the graph is undirected. nodelist : list, optional The block tags are assigned according to the node identifiers in nodelist. If nodelist is None, then the ordering is the range [0,sum(sizes)-1]. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : boolean optional, default=False Whether to create a directed graph or not. selfloops : boolean optional, default=False Whether to include self-loops or not. sparse: boolean optional, default=True Use the sparse heuristic to speed up the generator. Returns ------- g : NetworkX Graph or DiGraph Stochastic block model graph of size sum(sizes) Raises ------ NetworkXError If probabilities are not in [0,1]. If the probability matrix is not square (directed case). If the probability matrix is not symmetric (undirected case). If the sizes list does not match nodelist or the probability matrix. If nodelist contains duplicate. Examples -------- >>> sizes = [75, 75, 300] >>> probs = [[0.25, 0.05, 0.02], [0.05, 0.35, 0.07], [0.02, 0.07, 0.40]] >>> g = nx.stochastic_block_model(sizes, probs, seed=0) >>> len(g) 450 >>> H = nx.quotient_graph(g, g.graph["partition"], relabel=True) >>> for v in H.nodes(data=True): ... print(round(v[1]["density"], 3)) 0.245 0.348 0.405 >>> for v in H.edges(data=True): ... print(round(1.0 * v[2]["weight"] / (sizes[v[0]] * sizes[v[1]]), 3)) 0.051 0.022 0.07 See Also -------- random_partition_graph planted_partition_graph gaussian_random_partition_graph gnp_random_graph References ---------- .. [1] Holland, P. W., Laskey, K. B., & Leinhardt, S., "Stochastic blockmodels: First steps", Social networks, 5(2), 109-137, 1983.
def _generate_communities(degree_seq, community_sizes, mu, max_iters, seed): """Returns a list of sets, each of which represents a community. ``degree_seq`` is the degree sequence that must be met by the graph. ``community_sizes`` is the community size distribution that must be met by the generated list of sets. ``mu`` is a float in the interval [0, 1] indicating the fraction of intra-community edges incident to each node. ``max_iters`` is the number of times to try to add a node to a community. This must be greater than the length of ``degree_seq``, otherwise this function will always fail. If the number of iterations exceeds this value, :exc:`~networkx.exception.ExceededMaxIterations` is raised. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. The communities returned by this are sets of integers in the set {0, ..., *n* - 1}, where *n* is the length of ``degree_seq``. """ # This assumes the nodes in the graph will be natural numbers. result = [set() for _ in community_sizes] n = len(degree_seq) free = list(range(n)) for i in range(max_iters): v = free.pop() c = seed.choice(range(len(community_sizes))) # s = int(degree_seq[v] * (1 - mu) + 0.5) s = round(degree_seq[v] * (1 - mu)) # If the community is large enough, add the node to the chosen # community. Otherwise, return it to the list of unaffiliated # nodes. if s < community_sizes[c]: result[c].add(v) else: free.append(v) # If the community is too big, remove a node from it. if len(result[c]) > community_sizes[c]: free.append(result[c].pop()) if not free: return result msg = "Could not assign communities; try increasing min_community" raise nx.ExceededMaxIterations(msg)
(sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True, *, backend=None, **backend_kwargs)
31,138
networkx.generators.stochastic
stochastic_graph
Returns a right-stochastic representation of directed graph `G`. A right-stochastic graph is a weighted digraph in which for each node, the sum of the weights of all the out-edges of that node is 1. If the graph is already weighted (for example, via a 'weight' edge attribute), the reweighting takes that into account. Parameters ---------- G : directed graph A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`. copy : boolean, optional If this is True, then this function returns a new graph with the stochastic reweighting. Otherwise, the original graph is modified in-place (and also returned, for convenience). weight : edge attribute key (optional, default='weight') Edge attribute key used for reading the existing weight and setting the new weight. If no attribute with this key is found for an edge, then the edge weight is assumed to be 1. If an edge has a weight, it must be a positive number.
null
(G, copy=True, weight='weight', *, backend=None, **backend_kwargs)
31,139
networkx.algorithms.connectivity.stoerwagner
stoer_wagner
Returns the weighted minimum edge cut using the Stoer-Wagner algorithm. Determine the minimum edge cut of a connected graph using the Stoer-Wagner algorithm. In weighted cases, all weights must be nonnegative. The running time of the algorithm depends on the type of heaps used: ============== ============================================= Type of heap Running time ============== ============================================= Binary heap $O(n (m + n) \log n)$ Fibonacci heap $O(nm + n^2 \log n)$ Pairing heap $O(2^{2 \sqrt{\log \log n}} nm + n^2 \log n)$ ============== ============================================= Parameters ---------- G : NetworkX graph Edges of the graph are expected to have an attribute named by the weight parameter below. If this attribute is not present, the edge is considered to have unit weight. weight : string Name of the weight attribute of the edges. If the attribute is not present, unit weight is assumed. Default value: 'weight'. heap : class Type of heap to be used in the algorithm. It should be a subclass of :class:`MinHeap` or implement a compatible interface. If a stock heap implementation is to be used, :class:`BinaryHeap` is recommended over :class:`PairingHeap` for Python implementations without optimized attribute accesses (e.g., CPython) despite a slower asymptotic running time. For Python implementations with optimized attribute accesses (e.g., PyPy), :class:`PairingHeap` provides better performance. Default value: :class:`BinaryHeap`. Returns ------- cut_value : integer or float The sum of weights of edges in a minimum cut. partition : pair of node lists A partitioning of the nodes that defines a minimum cut. Raises ------ NetworkXNotImplemented If the graph is directed or a multigraph. NetworkXError If the graph has less than two nodes, is not connected or has a negative-weighted edge. Examples -------- >>> G = nx.Graph() >>> G.add_edge("x", "a", weight=3) >>> G.add_edge("x", "b", weight=1) >>> G.add_edge("a", "c", weight=3) >>> G.add_edge("b", "c", weight=5) >>> G.add_edge("b", "d", weight=4) >>> G.add_edge("d", "e", weight=2) >>> G.add_edge("c", "y", weight=2) >>> G.add_edge("e", "y", weight=3) >>> cut_value, partition = nx.stoer_wagner(G) >>> cut_value 4
null
(G, weight='weight', heap=<class 'networkx.utils.heaps.BinaryHeap'>, *, backend=None, **backend_kwargs)
31,140
networkx.algorithms.operators.product
strong_product
Returns the strong product of G and H. The strong product $P$ of the graphs $G$ and $H$ has a node set that is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$. $P$ has an edge $((u,v), (x,y))$ if and only if $u==v$ and $(x,y)$ is an edge in $H$, or $x==y$ and $(u,v)$ is an edge in $G$, or $(u,v)$ is an edge in $G$ and $(x,y)$ is an edge in $H$. Parameters ---------- G, H: graphs Networkx graphs. Returns ------- P: NetworkX graph The Cartesian product of G and H. P will be a multi-graph if either G or H is a multi-graph. Will be a directed if G and H are directed, and undirected if G and H are undirected. Raises ------ NetworkXError If G and H are not both directed or both undirected. Notes ----- Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None. Examples -------- >>> G = nx.Graph() >>> H = nx.Graph() >>> G.add_node(0, a1=True) >>> H.add_node("a", a2="Spam") >>> P = nx.strong_product(G, H) >>> list(P) [(0, 'a')] Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
null
(G, H, *, backend=None, **backend_kwargs)
31,142
networkx.algorithms.components.strongly_connected
strongly_connected_components
Generate nodes in strongly connected components of graph. Parameters ---------- G : NetworkX Graph A directed graph. Returns ------- comp : generator of sets A generator of sets of nodes, one for each strongly connected component of G. Raises ------ NetworkXNotImplemented If G is undirected. Examples -------- Generate a sorted list of strongly connected components, largest first. >>> G = nx.cycle_graph(4, create_using=nx.DiGraph()) >>> nx.add_cycle(G, [10, 11, 12]) >>> [len(c) for c in sorted(nx.strongly_connected_components(G), key=len, reverse=True)] [4, 3] If you only want the largest component, it's more efficient to use max instead of sort. >>> largest = max(nx.strongly_connected_components(G), key=len) See Also -------- connected_components weakly_connected_components kosaraju_strongly_connected_components Notes ----- Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_. Nonrecursive version of algorithm. References ---------- .. [1] Depth-first search and linear graph algorithms, R. Tarjan SIAM Journal of Computing 1(2):146-160, (1972). .. [2] On finding the strongly connected components in a directed graph. E. Nuutila and E. Soisalon-Soinen Information Processing Letters 49(1): 9-14, (1994)..
null
(G, *, backend=None, **backend_kwargs)
31,143
networkx.algorithms.components.strongly_connected
strongly_connected_components_recursive
Generate nodes in strongly connected components of graph. .. deprecated:: 3.2 This function is deprecated and will be removed in a future version of NetworkX. Use `strongly_connected_components` instead. Recursive version of algorithm. Parameters ---------- G : NetworkX Graph A directed graph. Returns ------- comp : generator of sets A generator of sets of nodes, one for each strongly connected component of G. Raises ------ NetworkXNotImplemented If G is undirected. Examples -------- Generate a sorted list of strongly connected components, largest first. >>> G = nx.cycle_graph(4, create_using=nx.DiGraph()) >>> nx.add_cycle(G, [10, 11, 12]) >>> [ ... len(c) ... for c in sorted( ... nx.strongly_connected_components_recursive(G), key=len, reverse=True ... ) ... ] [4, 3] If you only want the largest component, it's more efficient to use max instead of sort. >>> largest = max(nx.strongly_connected_components_recursive(G), key=len) To create the induced subgraph of the components use: >>> S = [G.subgraph(c).copy() for c in nx.weakly_connected_components(G)] See Also -------- connected_components Notes ----- Uses Tarjan's algorithm[1]_ with Nuutila's modifications[2]_. References ---------- .. [1] Depth-first search and linear graph algorithms, R. Tarjan SIAM Journal of Computing 1(2):146-160, (1972). .. [2] On finding the strongly connected components in a directed graph. E. Nuutila and E. Soisalon-Soinen Information Processing Letters 49(1): 9-14, (1994)..
null
(G, *, backend=None, **backend_kwargs)
31,145
networkx.classes.function
subgraph
Returns the subgraph induced on nodes in nbunch. Parameters ---------- G : graph A NetworkX graph nbunch : list, iterable A container of nodes that will be iterated through once (thus it should be an iterator or be iterable). Each element of the container should be a valid node type: any hashable type except None. If nbunch is None, return all edges data in the graph. Nodes in nbunch that are not in the graph will be (quietly) ignored. Notes ----- subgraph(G) calls G.subgraph()
def subgraph(G, nbunch): """Returns the subgraph induced on nodes in nbunch. Parameters ---------- G : graph A NetworkX graph nbunch : list, iterable A container of nodes that will be iterated through once (thus it should be an iterator or be iterable). Each element of the container should be a valid node type: any hashable type except None. If nbunch is None, return all edges data in the graph. Nodes in nbunch that are not in the graph will be (quietly) ignored. Notes ----- subgraph(G) calls G.subgraph() """ return G.subgraph(nbunch)
(G, nbunch)
31,147
networkx.algorithms.centrality.subgraph_alg
subgraph_centrality
Returns subgraph centrality for each node in G. Subgraph centrality of a node `n` is the sum of weighted closed walks of all lengths starting and ending at node `n`. The weights decrease with path length. Each closed walk is associated with a connected subgraph ([1]_). Parameters ---------- G: graph Returns ------- nodes : dictionary Dictionary of nodes with subgraph centrality as the value. Raises ------ NetworkXError If the graph is not undirected and simple. See Also -------- subgraph_centrality_exp: Alternative algorithm of the subgraph centrality for each node of G. Notes ----- This version of the algorithm computes eigenvalues and eigenvectors of the adjacency matrix. Subgraph centrality of a node `u` in G can be found using a spectral decomposition of the adjacency matrix [1]_, .. math:: SC(u)=\sum_{j=1}^{N}(v_{j}^{u})^2 e^{\lambda_{j}}, where `v_j` is an eigenvector of the adjacency matrix `A` of G corresponding to the eigenvalue `\lambda_j`. Examples -------- (Example from [1]_) >>> G = nx.Graph( ... [ ... (1, 2), ... (1, 5), ... (1, 8), ... (2, 3), ... (2, 8), ... (3, 4), ... (3, 6), ... (4, 5), ... (4, 7), ... (5, 6), ... (6, 7), ... (7, 8), ... ] ... ) >>> sc = nx.subgraph_centrality(G) >>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)]) ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90'] References ---------- .. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez, "Subgraph centrality in complex networks", Physical Review E 71, 056103 (2005). https://arxiv.org/abs/cond-mat/0504730
null
(G, *, backend=None, **backend_kwargs)
31,148
networkx.algorithms.centrality.subgraph_alg
subgraph_centrality_exp
Returns the subgraph centrality for each node of G. Subgraph centrality of a node `n` is the sum of weighted closed walks of all lengths starting and ending at node `n`. The weights decrease with path length. Each closed walk is associated with a connected subgraph ([1]_). Parameters ---------- G: graph Returns ------- nodes:dictionary Dictionary of nodes with subgraph centrality as the value. Raises ------ NetworkXError If the graph is not undirected and simple. See Also -------- subgraph_centrality: Alternative algorithm of the subgraph centrality for each node of G. Notes ----- This version of the algorithm exponentiates the adjacency matrix. The subgraph centrality of a node `u` in G can be found using the matrix exponential of the adjacency matrix of G [1]_, .. math:: SC(u)=(e^A)_{uu} . References ---------- .. [1] Ernesto Estrada, Juan A. Rodriguez-Velazquez, "Subgraph centrality in complex networks", Physical Review E 71, 056103 (2005). https://arxiv.org/abs/cond-mat/0504730 Examples -------- (Example from [1]_) >>> G = nx.Graph( ... [ ... (1, 2), ... (1, 5), ... (1, 8), ... (2, 3), ... (2, 8), ... (3, 4), ... (3, 6), ... (4, 5), ... (4, 7), ... (5, 6), ... (6, 7), ... (7, 8), ... ] ... ) >>> sc = nx.subgraph_centrality_exp(G) >>> print([f"{node} {sc[node]:0.2f}" for node in sorted(sc)]) ['1 3.90', '2 3.90', '3 3.64', '4 3.71', '5 3.64', '6 3.71', '7 3.64', '8 3.90']
null
(G, *, backend=None, **backend_kwargs)
31,149
networkx.classes.graphviews
subgraph_view
View of `G` applying a filter on nodes and edges. `subgraph_view` provides a read-only view of the input graph that excludes nodes and edges based on the outcome of two filter functions `filter_node` and `filter_edge`. The `filter_node` function takes one argument --- the node --- and returns `True` if the node should be included in the subgraph, and `False` if it should not be included. The `filter_edge` function takes two (or three arguments if `G` is a multi-graph) --- the nodes describing an edge, plus the edge-key if parallel edges are possible --- and returns `True` if the edge should be included in the subgraph, and `False` if it should not be included. Both node and edge filter functions are called on graph elements as they are queried, meaning there is no up-front cost to creating the view. Parameters ---------- G : networkx.Graph A directed/undirected graph/multigraph filter_node : callable, optional A function taking a node as input, which returns `True` if the node should appear in the view. filter_edge : callable, optional A function taking as input the two nodes describing an edge (plus the edge-key if `G` is a multi-graph), which returns `True` if the edge should appear in the view. Returns ------- graph : networkx.Graph A read-only graph view of the input graph. Examples -------- >>> G = nx.path_graph(6) Filter functions operate on the node, and return `True` if the node should appear in the view: >>> def filter_node(n1): ... return n1 != 5 >>> view = nx.subgraph_view(G, filter_node=filter_node) >>> view.nodes() NodeView((0, 1, 2, 3, 4)) We can use a closure pattern to filter graph elements based on additional data --- for example, filtering on edge data attached to the graph: >>> G[3][4]["cross_me"] = False >>> def filter_edge(n1, n2): ... return G[n1][n2].get("cross_me", True) >>> view = nx.subgraph_view(G, filter_edge=filter_edge) >>> view.edges() EdgeView([(0, 1), (1, 2), (2, 3), (4, 5)]) >>> view = nx.subgraph_view( ... G, ... filter_node=filter_node, ... filter_edge=filter_edge, ... ) >>> view.nodes() NodeView((0, 1, 2, 3, 4)) >>> view.edges() EdgeView([(0, 1), (1, 2), (2, 3)])
null
(G, *, filter_node=<function no_filter at 0x7f8cfd0cc820>, filter_edge=<function no_filter at 0x7f8cfd0cc820>)
31,151
networkx.generators.sudoku
sudoku_graph
Returns the n-Sudoku graph. The default value of n is 3. The n-Sudoku graph is a graph with n^4 vertices, corresponding to the cells of an n^2 by n^2 grid. Two distinct vertices are adjacent if and only if they belong to the same row, column, or n-by-n box. Parameters ---------- n: integer The order of the Sudoku graph, equal to the square root of the number of rows. The default is 3. Returns ------- NetworkX graph The n-Sudoku graph Sud(n). Examples -------- >>> G = nx.sudoku_graph() >>> G.number_of_nodes() 81 >>> G.number_of_edges() 810 >>> sorted(G.neighbors(42)) [6, 15, 24, 33, 34, 35, 36, 37, 38, 39, 40, 41, 43, 44, 51, 52, 53, 60, 69, 78] >>> G = nx.sudoku_graph(2) >>> G.number_of_nodes() 16 >>> G.number_of_edges() 56 References ---------- .. [1] Herzberg, A. M., & Murty, M. R. (2007). Sudoku squares and chromatic polynomials. Notices of the AMS, 54(6), 708-717. .. [2] Sander, Torsten (2009), "Sudoku graphs are integral", Electronic Journal of Combinatorics, 16 (1): Note 25, 7pp, MR 2529816 .. [3] Wikipedia contributors. "Glossary of Sudoku." Wikipedia, The Free Encyclopedia, 3 Dec. 2019. Web. 22 Dec. 2019.
null
(n=3, *, backend=None, **backend_kwargs)
31,154
networkx.algorithms.operators.binary
symmetric_difference
Returns new graph with edges that exist in either G or H but not both. The node sets of H and G must be the same. Parameters ---------- G,H : graph A NetworkX graph. G and H must have the same node sets. Returns ------- D : A new graph with the same type as G. Notes ----- Attributes from the graph, nodes, and edges are not copied to the new graph. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3)]) >>> H = nx.Graph([(0, 1), (1, 2), (0, 3)]) >>> R = nx.symmetric_difference(G, H) >>> R.nodes NodeView((0, 1, 2, 3)) >>> R.edges EdgeView([(0, 2), (0, 3), (1, 3)])
null
(G, H, *, backend=None, **backend_kwargs)
31,155
networkx.generators.classic
tadpole_graph
Returns the (m,n)-tadpole graph; ``C_m`` connected to ``P_n``. This graph on m+n nodes connects a cycle of size `m` to a path of length `n`. It looks like a tadpole. It is also called a kite graph or a dragon graph. .. plot:: >>> nx.draw(nx.tadpole_graph(3, 5)) Parameters ---------- m, n : int or iterable container of nodes If an integer, nodes are from ``range(m)`` and ``range(m,m+n)``. If a container of nodes, those nodes appear in the graph. Warning: `m` and `n` are not checked for duplicates and if present the resulting graph may not be as desired. The nodes for `m` appear in the cycle graph $C_m$ and the nodes for `n` appear in the path $P_n$. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- Networkx graph A cycle of size `m` connected to a path of length `n`. Raises ------ NetworkXError If ``m < 2``. The tadpole graph is undefined for ``m<2``. Notes ----- The 2 subgraphs are joined via an edge ``(m-1, m)``. If ``n=0``, this is a cycle graph. `m` and/or `n` can be a container of nodes instead of an integer.
def star_graph(n, create_using=None): """Return the star graph The star graph consists of one center node connected to n outer nodes. .. plot:: >>> nx.draw(nx.star_graph(6)) Parameters ---------- n : int or iterable If an integer, node labels are 0 to n with center 0. If an iterable of nodes, the center is the first. Warning: n is not checked for duplicates and if present the resulting graph may not be as desired. Make sure you have no duplicates. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Notes ----- The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)). """ n, nodes = n if isinstance(n, numbers.Integral): nodes.append(int(n)) # there should be n+1 nodes G = empty_graph(nodes, create_using) if G.is_directed(): raise NetworkXError("Directed Graph not supported") if len(nodes) > 1: hub, *spokes = nodes G.add_edges_from((hub, node) for node in spokes) return G
(m, n, create_using=None, *, backend=None, **backend_kwargs)
31,156
networkx.algorithms.operators.product
tensor_product
Returns the tensor product of G and H. The tensor product $P$ of the graphs $G$ and $H$ has a node set that is the Cartesian product of the node sets, $V(P)=V(G) \times V(H)$. $P$ has an edge $((u,v), (x,y))$ if and only if $(u,x)$ is an edge in $G$ and $(v,y)$ is an edge in $H$. Tensor product is sometimes also referred to as the categorical product, direct product, cardinal product or conjunction. Parameters ---------- G, H: graphs Networkx graphs. Returns ------- P: NetworkX graph The tensor product of G and H. P will be a multi-graph if either G or H is a multi-graph, will be a directed if G and H are directed, and undirected if G and H are undirected. Raises ------ NetworkXError If G and H are not both directed or both undirected. Notes ----- Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None. Examples -------- >>> G = nx.Graph() >>> H = nx.Graph() >>> G.add_node(0, a1=True) >>> H.add_node("a", a2="Spam") >>> P = nx.tensor_product(G, H) >>> list(P) [(0, 'a')] Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
null
(G, H, *, backend=None, **backend_kwargs)
31,157
networkx.generators.small
tetrahedral_graph
Returns the 3-regular Platonic Tetrahedral graph. Tetrahedral graph has 4 nodes and 6 edges. It is a special case of the complete graph, K4, and wheel graph, W4. It is one of the 5 platonic graphs [1]_. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Tetrahedral Graph References ---------- .. [1] https://en.wikipedia.org/wiki/Tetrahedron#Tetrahedral_graph
def sedgewick_maze_graph(create_using=None): """ Return a small maze with a cycle. This is the maze used in Sedgewick, 3rd Edition, Part 5, Graph Algorithms, Chapter 18, e.g. Figure 18.2 and following [1]_. Nodes are numbered 0,..,7 Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Small maze with a cycle References ---------- .. [1] Figure 18.2, Chapter 18, Graph Algorithms (3rd Ed), Sedgewick """ G = empty_graph(0, create_using) G.add_nodes_from(range(8)) G.add_edges_from([[0, 2], [0, 7], [0, 5]]) G.add_edges_from([[1, 7], [2, 6]]) G.add_edges_from([[3, 4], [3, 5]]) G.add_edges_from([[4, 5], [4, 7], [4, 6]]) G.name = "Sedgewick Maze" return G
(create_using=None, *, backend=None, **backend_kwargs)
31,159
networkx.generators.geometric
thresholded_random_geometric_graph
Returns a thresholded random geometric graph in the unit cube. The thresholded random geometric graph [1] model places `n` nodes uniformly at random in the unit cube of dimensions `dim`. Each node `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are joined by an edge if they are within the maximum connection distance, `radius` computed by the `p`-Minkowski distance and the summation of weights :math:`w_u` + :math:`w_v` is greater than or equal to the threshold parameter `theta`. Edges within `radius` of each other are determined using a KDTree when SciPy is available. This reduces the time complexity from :math:`O(n^2)` to :math:`O(n)`. Parameters ---------- n : int or iterable Number of nodes or iterable of nodes radius: float Distance threshold value theta: float Threshold value dim : int, optional Dimension of graph pos : dict, optional A dictionary keyed by node with node positions as values. weight : dict, optional Node weights as a dictionary of numbers keyed by node. p : float, optional (default 2) Which Minkowski distance metric to use. `p` has to meet the condition ``1 <= p <= infinity``. If this argument is not specified, the :math:`L^2` metric (the Euclidean distance metric), p = 2 is used. This should not be confused with the `p` of an Erdős-Rényi random graph, which represents probability. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. pos_name : string, default="pos" The name of the node attribute which represents the position in 2D coordinates of the node in the returned graph. weight_name : string, default="weight" The name of the node attribute which represents the weight of the node in the returned graph. Returns ------- Graph A thresholded random geographic graph, undirected and without self-loops. Each node has a node attribute ``'pos'`` that stores the position of that node in Euclidean space as provided by the ``pos`` keyword argument or, if ``pos`` was not provided, as generated by this function. Similarly, each node has a nodethre attribute ``'weight'`` that stores the weight of that node as provided or as generated. Examples -------- Default Graph: G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1) Custom Graph: Create a thresholded random geometric graph on 50 uniformly distributed nodes where nodes are joined by an edge if their sum weights drawn from a exponential distribution with rate = 5 are >= theta = 0.1 and their Euclidean distance is at most 0.2. Notes ----- This uses a *k*-d tree to build the graph. The `pos` keyword argument can be used to specify node positions so you can create an arbitrary distribution and domain for positions. For example, to use a 2D Gaussian distribution of node positions with mean (0, 0) and standard deviation 2 If weights are not specified they are assigned to nodes by drawing randomly from the exponential distribution with rate parameter :math:`\lambda=1`. To specify weights from a different distribution, use the `weight` keyword argument:: :: >>> import random >>> import math >>> n = 50 >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)} >>> w = {i: random.expovariate(5.0) for i in range(n)} >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w) References ---------- .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf
def thresholded_random_geometric_graph( n, radius, theta, dim=2, pos=None, weight=None, p=2, seed=None, *, pos_name="pos", weight_name="weight", ): r"""Returns a thresholded random geometric graph in the unit cube. The thresholded random geometric graph [1] model places `n` nodes uniformly at random in the unit cube of dimensions `dim`. Each node `u` is assigned a weight :math:`w_u`. Two nodes `u` and `v` are joined by an edge if they are within the maximum connection distance, `radius` computed by the `p`-Minkowski distance and the summation of weights :math:`w_u` + :math:`w_v` is greater than or equal to the threshold parameter `theta`. Edges within `radius` of each other are determined using a KDTree when SciPy is available. This reduces the time complexity from :math:`O(n^2)` to :math:`O(n)`. Parameters ---------- n : int or iterable Number of nodes or iterable of nodes radius: float Distance threshold value theta: float Threshold value dim : int, optional Dimension of graph pos : dict, optional A dictionary keyed by node with node positions as values. weight : dict, optional Node weights as a dictionary of numbers keyed by node. p : float, optional (default 2) Which Minkowski distance metric to use. `p` has to meet the condition ``1 <= p <= infinity``. If this argument is not specified, the :math:`L^2` metric (the Euclidean distance metric), p = 2 is used. This should not be confused with the `p` of an Erdős-Rényi random graph, which represents probability. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. pos_name : string, default="pos" The name of the node attribute which represents the position in 2D coordinates of the node in the returned graph. weight_name : string, default="weight" The name of the node attribute which represents the weight of the node in the returned graph. Returns ------- Graph A thresholded random geographic graph, undirected and without self-loops. Each node has a node attribute ``'pos'`` that stores the position of that node in Euclidean space as provided by the ``pos`` keyword argument or, if ``pos`` was not provided, as generated by this function. Similarly, each node has a nodethre attribute ``'weight'`` that stores the weight of that node as provided or as generated. Examples -------- Default Graph: G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1) Custom Graph: Create a thresholded random geometric graph on 50 uniformly distributed nodes where nodes are joined by an edge if their sum weights drawn from a exponential distribution with rate = 5 are >= theta = 0.1 and their Euclidean distance is at most 0.2. Notes ----- This uses a *k*-d tree to build the graph. The `pos` keyword argument can be used to specify node positions so you can create an arbitrary distribution and domain for positions. For example, to use a 2D Gaussian distribution of node positions with mean (0, 0) and standard deviation 2 If weights are not specified they are assigned to nodes by drawing randomly from the exponential distribution with rate parameter :math:`\lambda=1`. To specify weights from a different distribution, use the `weight` keyword argument:: :: >>> import random >>> import math >>> n = 50 >>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)} >>> w = {i: random.expovariate(5.0) for i in range(n)} >>> G = nx.thresholded_random_geometric_graph(n, 0.2, 0.1, 2, pos, w) References ---------- .. [1] http://cole-maclean.github.io/blog/files/thesis.pdf """ G = nx.empty_graph(n) G.name = f"thresholded_random_geometric_graph({n}, {radius}, {theta}, {dim})" # If no weights are provided, choose them from an exponential # distribution. if weight is None: weight = {v: seed.expovariate(1) for v in G} # If no positions are provided, choose uniformly random vectors in # Euclidean space of the specified dimension. if pos is None: pos = {v: [seed.random() for i in range(dim)] for v in G} # If no distance metric is provided, use Euclidean distance. nx.set_node_attributes(G, weight, weight_name) nx.set_node_attributes(G, pos, pos_name) edges = ( (u, v) for u, v in _geometric_edges(G, radius, p, pos_name) if weight[u] + weight[v] >= theta ) G.add_edges_from(edges) return G
(n, radius, theta, dim=2, pos=None, weight=None, p=2, seed=None, *, pos_name='pos', weight_name='weight', backend=None, **backend_kwargs)
31,162
networkx.convert
to_dict_of_dicts
Returns adjacency representation of graph as a dictionary of dictionaries. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist edge_data : scalar, optional If provided, the value of the dictionary will be set to `edge_data` for all edges. Usual values could be `1` or `True`. If `edge_data` is `None` (the default), the edgedata in `G` is used, resulting in a dict-of-dict-of-dicts. If `G` is a MultiGraph, the result will be a dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize handling edge data. `edge_data` should *not* be a container. Returns ------- dod : dict A nested dictionary representation of `G`. Note that the level of nesting depends on the type of `G` and the value of `edge_data` (see Examples). See Also -------- from_dict_of_dicts, to_dict_of_lists Notes ----- For a more custom approach to handling edge data, try:: dod = { n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()} for n, nbrdict in G.adj.items() } where `custom` returns the desired edge data for each edge between `n` and `nbr`, given existing edge data `dd`. Examples -------- >>> G = nx.path_graph(3) >>> nx.to_dict_of_dicts(G) {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}} Edge data is preserved by default (``edge_data=None``), resulting in dict-of-dict-of-dicts where the innermost dictionary contains the edge data: >>> G = nx.Graph() >>> G.add_edges_from( ... [ ... (0, 1, {"weight": 1.0}), ... (1, 2, {"weight": 2.0}), ... (2, 0, {"weight": 1.0}), ... ] ... ) >>> d = nx.to_dict_of_dicts(G) >>> d # doctest: +SKIP {0: {1: {'weight': 1.0}, 2: {'weight': 1.0}}, 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}}, 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}} >>> d[1][2]["weight"] 2.0 If `edge_data` is not `None`, edge data in the original graph (if any) is replaced: >>> d = nx.to_dict_of_dicts(G, edge_data=1) >>> d {0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}} >>> d[1][2] 1 This also applies to MultiGraphs: edge data is preserved by default: >>> G = nx.MultiGraph() >>> G.add_edge(0, 1, key="a", weight=1.0) 'a' >>> G.add_edge(0, 1, key="b", weight=5.0) 'b' >>> d = nx.to_dict_of_dicts(G) >>> d # doctest: +SKIP {0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}, 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}} >>> d[0][1]["b"]["weight"] 5.0 But multi edge data is lost if `edge_data` is not `None`: >>> d = nx.to_dict_of_dicts(G, edge_data=10) >>> d {0: {1: 10}, 1: {0: 10}}
def to_dict_of_dicts(G, nodelist=None, edge_data=None): """Returns adjacency representation of graph as a dictionary of dictionaries. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist edge_data : scalar, optional If provided, the value of the dictionary will be set to `edge_data` for all edges. Usual values could be `1` or `True`. If `edge_data` is `None` (the default), the edgedata in `G` is used, resulting in a dict-of-dict-of-dicts. If `G` is a MultiGraph, the result will be a dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize handling edge data. `edge_data` should *not* be a container. Returns ------- dod : dict A nested dictionary representation of `G`. Note that the level of nesting depends on the type of `G` and the value of `edge_data` (see Examples). See Also -------- from_dict_of_dicts, to_dict_of_lists Notes ----- For a more custom approach to handling edge data, try:: dod = { n: {nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()} for n, nbrdict in G.adj.items() } where `custom` returns the desired edge data for each edge between `n` and `nbr`, given existing edge data `dd`. Examples -------- >>> G = nx.path_graph(3) >>> nx.to_dict_of_dicts(G) {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}} Edge data is preserved by default (``edge_data=None``), resulting in dict-of-dict-of-dicts where the innermost dictionary contains the edge data: >>> G = nx.Graph() >>> G.add_edges_from( ... [ ... (0, 1, {"weight": 1.0}), ... (1, 2, {"weight": 2.0}), ... (2, 0, {"weight": 1.0}), ... ] ... ) >>> d = nx.to_dict_of_dicts(G) >>> d # doctest: +SKIP {0: {1: {'weight': 1.0}, 2: {'weight': 1.0}}, 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}}, 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}} >>> d[1][2]["weight"] 2.0 If `edge_data` is not `None`, edge data in the original graph (if any) is replaced: >>> d = nx.to_dict_of_dicts(G, edge_data=1) >>> d {0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}} >>> d[1][2] 1 This also applies to MultiGraphs: edge data is preserved by default: >>> G = nx.MultiGraph() >>> G.add_edge(0, 1, key="a", weight=1.0) 'a' >>> G.add_edge(0, 1, key="b", weight=5.0) 'b' >>> d = nx.to_dict_of_dicts(G) >>> d # doctest: +SKIP {0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}, 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}} >>> d[0][1]["b"]["weight"] 5.0 But multi edge data is lost if `edge_data` is not `None`: >>> d = nx.to_dict_of_dicts(G, edge_data=10) >>> d {0: {1: 10}, 1: {0: 10}} """ dod = {} if nodelist is None: if edge_data is None: for u, nbrdict in G.adjacency(): dod[u] = nbrdict.copy() else: # edge_data is not None for u, nbrdict in G.adjacency(): dod[u] = dod.fromkeys(nbrdict, edge_data) else: # nodelist is not None if edge_data is None: for u in nodelist: dod[u] = {} for v, data in ((v, data) for v, data in G[u].items() if v in nodelist): dod[u][v] = data else: # nodelist and edge_data are not None for u in nodelist: dod[u] = {} for v in (v for v in G[u] if v in nodelist): dod[u][v] = edge_data return dod
(G, nodelist=None, edge_data=None)
31,163
networkx.convert
to_dict_of_lists
Returns adjacency representation of graph as a dictionary of lists. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist Notes ----- Completely ignores edge data for MultiGraph and MultiDiGraph.
null
(G, nodelist=None, *, backend=None, **backend_kwargs)
31,164
networkx.classes.function
to_directed
Returns a directed view of the graph `graph`. Identical to graph.to_directed(as_view=True) Note that graph.to_directed defaults to `as_view=False` while this function always provides a view.
def to_directed(graph): """Returns a directed view of the graph `graph`. Identical to graph.to_directed(as_view=True) Note that graph.to_directed defaults to `as_view=False` while this function always provides a view. """ return graph.to_directed(as_view=True)
(graph)
31,165
networkx.convert
to_edgelist
Returns a list of edges in the graph. Parameters ---------- G : graph A NetworkX graph nodelist : list Use only nodes specified in nodelist
null
(G, nodelist=None, *, backend=None, **backend_kwargs)
31,166
networkx.readwrite.graph6
to_graph6_bytes
Convert a simple undirected graph to bytes in graph6 format. Parameters ---------- G : Graph (undirected) nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used. header: bool If True add '>>graph6<<' bytes to head of data. Raises ------ NetworkXNotImplemented If the graph is directed or is a multigraph. ValueError If the graph has at least ``2 ** 36`` nodes; the graph6 format is only defined for graphs of order less than ``2 ** 36``. Examples -------- >>> nx.to_graph6_bytes(nx.path_graph(2)) b'>>graph6<<A_\n' See Also -------- from_graph6_bytes, read_graph6, write_graph6_bytes Notes ----- The returned bytes end with a newline character. The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are silently ignored. References ---------- .. [1] Graph6 specification <http://users.cecs.anu.edu.au/~bdm/data/formats.html>
null
(G, nodes=None, header=True)
31,167
networkx.drawing.nx_latex
to_latex
Return latex code to draw the graph(s) in `Gbunch` The TikZ drawing utility in LaTeX is used to draw the graph(s). If `Gbunch` is a graph, it is drawn in a figure environment. If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment within a single figure environment. If `as_document` is True, the figure is wrapped inside a document environment so that the resulting string is ready to be compiled by LaTeX. Otherwise, the string is ready for inclusion in a larger tex document using ``\include`` or ``\input`` statements. Parameters ========== Gbunch : NetworkX graph or iterable of NetworkX graphs The NetworkX graph to be drawn or an iterable of graphs to be drawn inside subfigures of a single figure. pos : string or list of strings The name of the node attribute on `G` that holds the position of each node. Positions can be sequences of length 2 with numbers for (x,y) coordinates. They can also be strings to denote positions in TikZ style, such as (x, y) or (angle:radius). If a dict, it should be keyed by node to a position. If an empty dict, a circular layout is computed by TikZ. If you are drawing many graphs in subfigures, use a list of position dicts. tikz_options : string The tikzpicture options description defining the options for the picture. Often large scale options like `[scale=2]`. default_node_options : string The draw options for a path of nodes. Individual node options override these. node_options : string or dict The name of the node attribute on `G` that holds the options for each node. Or a dict keyed by node to a string holding the options for that node. node_label : string or dict The name of the node attribute on `G` that holds the node label (text) displayed for each node. If the attribute is "" or not present, the node itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed. Or a dict keyed by node to a string holding the label for that node. default_edge_options : string The options for the scope drawing all edges. The default is "[-]" for undirected graphs and "[->]" for directed graphs. edge_options : string or dict The name of the edge attribute on `G` that holds the options for each edge. If the edge is a self-loop and ``"loop" not in edge_options`` the option "loop," is added to the options for the self-loop edge. Hence you can use "[loop above]" explicitly, but the default is "[loop]". Or a dict keyed by edge to a string holding the options for that edge. edge_label : string or dict The name of the edge attribute on `G` that holds the edge label (text) displayed for each edge. If the attribute is "" or not present, no edge label is drawn. Or a dict keyed by edge to a string holding the label for that edge. edge_label_options : string or dict The name of the edge attribute on `G` that holds the label options for each edge. For example, "[sloped,above,blue]". The default is no options. Or a dict keyed by edge to a string holding the label options for that edge. caption : string The caption string for the figure environment latex_label : string The latex label used for the figure for easy referral from the main text sub_captions : list of strings The sub_caption string for each subfigure in the figure sub_latex_labels : list of strings The latex label for each subfigure in the figure n_rows : int The number of rows of subfigures to arrange for multiple graphs as_document : bool Whether to wrap the latex code in a document environment for compiling document_wrapper : formatted text string with variable ``content``. This text is called to evaluate the content embedded in a document environment with a preamble setting up TikZ. figure_wrapper : formatted text string This text is evaluated with variables ``content``, ``caption`` and ``label``. It wraps the content and if a caption is provided, adds the latex code for that caption, and if a label is provided, adds the latex code for a label. subfigure_wrapper : formatted text string This text evaluate variables ``size``, ``content``, ``caption`` and ``label``. It wraps the content and if a caption is provided, adds the latex code for that caption, and if a label is provided, adds the latex code for a label. The size is the vertical size of each row of subfigures as a fraction. Returns ======= latex_code : string The text string which draws the desired graph(s) when compiled by LaTeX. See Also ======== write_latex to_latex_raw
def to_latex( Gbunch, pos="pos", tikz_options="", default_node_options="", node_options="node_options", node_label="node_label", default_edge_options="", edge_options="edge_options", edge_label="edge_label", edge_label_options="edge_label_options", caption="", latex_label="", sub_captions=None, sub_labels=None, n_rows=1, as_document=True, document_wrapper=_DOC_WRAPPER_TIKZ, figure_wrapper=_FIG_WRAPPER, subfigure_wrapper=_SUBFIG_WRAPPER, ): """Return latex code to draw the graph(s) in `Gbunch` The TikZ drawing utility in LaTeX is used to draw the graph(s). If `Gbunch` is a graph, it is drawn in a figure environment. If `Gbunch` is an iterable of graphs, each is drawn in a subfigure environment within a single figure environment. If `as_document` is True, the figure is wrapped inside a document environment so that the resulting string is ready to be compiled by LaTeX. Otherwise, the string is ready for inclusion in a larger tex document using ``\\include`` or ``\\input`` statements. Parameters ========== Gbunch : NetworkX graph or iterable of NetworkX graphs The NetworkX graph to be drawn or an iterable of graphs to be drawn inside subfigures of a single figure. pos : string or list of strings The name of the node attribute on `G` that holds the position of each node. Positions can be sequences of length 2 with numbers for (x,y) coordinates. They can also be strings to denote positions in TikZ style, such as (x, y) or (angle:radius). If a dict, it should be keyed by node to a position. If an empty dict, a circular layout is computed by TikZ. If you are drawing many graphs in subfigures, use a list of position dicts. tikz_options : string The tikzpicture options description defining the options for the picture. Often large scale options like `[scale=2]`. default_node_options : string The draw options for a path of nodes. Individual node options override these. node_options : string or dict The name of the node attribute on `G` that holds the options for each node. Or a dict keyed by node to a string holding the options for that node. node_label : string or dict The name of the node attribute on `G` that holds the node label (text) displayed for each node. If the attribute is "" or not present, the node itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed. Or a dict keyed by node to a string holding the label for that node. default_edge_options : string The options for the scope drawing all edges. The default is "[-]" for undirected graphs and "[->]" for directed graphs. edge_options : string or dict The name of the edge attribute on `G` that holds the options for each edge. If the edge is a self-loop and ``"loop" not in edge_options`` the option "loop," is added to the options for the self-loop edge. Hence you can use "[loop above]" explicitly, but the default is "[loop]". Or a dict keyed by edge to a string holding the options for that edge. edge_label : string or dict The name of the edge attribute on `G` that holds the edge label (text) displayed for each edge. If the attribute is "" or not present, no edge label is drawn. Or a dict keyed by edge to a string holding the label for that edge. edge_label_options : string or dict The name of the edge attribute on `G` that holds the label options for each edge. For example, "[sloped,above,blue]". The default is no options. Or a dict keyed by edge to a string holding the label options for that edge. caption : string The caption string for the figure environment latex_label : string The latex label used for the figure for easy referral from the main text sub_captions : list of strings The sub_caption string for each subfigure in the figure sub_latex_labels : list of strings The latex label for each subfigure in the figure n_rows : int The number of rows of subfigures to arrange for multiple graphs as_document : bool Whether to wrap the latex code in a document environment for compiling document_wrapper : formatted text string with variable ``content``. This text is called to evaluate the content embedded in a document environment with a preamble setting up TikZ. figure_wrapper : formatted text string This text is evaluated with variables ``content``, ``caption`` and ``label``. It wraps the content and if a caption is provided, adds the latex code for that caption, and if a label is provided, adds the latex code for a label. subfigure_wrapper : formatted text string This text evaluate variables ``size``, ``content``, ``caption`` and ``label``. It wraps the content and if a caption is provided, adds the latex code for that caption, and if a label is provided, adds the latex code for a label. The size is the vertical size of each row of subfigures as a fraction. Returns ======= latex_code : string The text string which draws the desired graph(s) when compiled by LaTeX. See Also ======== write_latex to_latex_raw """ if hasattr(Gbunch, "adj"): raw = to_latex_raw( Gbunch, pos, tikz_options, default_node_options, node_options, node_label, default_edge_options, edge_options, edge_label, edge_label_options, ) else: # iterator of graphs sbf = subfigure_wrapper size = 1 / n_rows N = len(Gbunch) if isinstance(pos, str | dict): pos = [pos] * N if sub_captions is None: sub_captions = [""] * N if sub_labels is None: sub_labels = [""] * N if not (len(Gbunch) == len(pos) == len(sub_captions) == len(sub_labels)): raise nx.NetworkXError( "length of Gbunch, sub_captions and sub_figures must agree" ) raw = "" for G, pos, subcap, sublbl in zip(Gbunch, pos, sub_captions, sub_labels): subraw = to_latex_raw( G, pos, tikz_options, default_node_options, node_options, node_label, default_edge_options, edge_options, edge_label, edge_label_options, ) cap = f" \\caption{{{subcap}}}" if subcap else "" lbl = f"\\label{{{sublbl}}}" if sublbl else "" raw += sbf.format(size=size, content=subraw, caption=cap, label=lbl) raw += "\n" # put raw latex code into a figure environment and optionally into a document raw = raw[:-1] cap = f"\n \\caption{{{caption}}}" if caption else "" lbl = f"\\label{{{latex_label}}}" if latex_label else "" fig = figure_wrapper.format(content=raw, caption=cap, label=lbl) if as_document: return document_wrapper.format(content=fig) return fig
(Gbunch, pos='pos', tikz_options='', default_node_options='', node_options='node_options', node_label='node_label', default_edge_options='', edge_options='edge_options', edge_label='edge_label', edge_label_options='edge_label_options', caption='', latex_label='', sub_captions=None, sub_labels=None, n_rows=1, as_document=True, document_wrapper='\\documentclass{{report}}\n\\usepackage{{tikz}}\n\\usepackage{{subcaption}}\n\n\\begin{{document}}\n{content}\n\\end{{document}}', figure_wrapper='\\begin{{figure}}\n{content}{caption}{label}\n\\end{{figure}}', subfigure_wrapper=' \\begin{{subfigure}}{{{size}\\textwidth}}\n{content}{caption}{label}\n \\end{{subfigure}}')
31,168
networkx.drawing.nx_latex
to_latex_raw
Return a string of the LaTeX/TikZ code to draw `G` This function produces just the code for the tikzpicture without any enclosing environment. Parameters ========== G : NetworkX graph The NetworkX graph to be drawn pos : string or dict (default "pos") The name of the node attribute on `G` that holds the position of each node. Positions can be sequences of length 2 with numbers for (x,y) coordinates. They can also be strings to denote positions in TikZ style, such as (x, y) or (angle:radius). If a dict, it should be keyed by node to a position. If an empty dict, a circular layout is computed by TikZ. tikz_options : string The tikzpicture options description defining the options for the picture. Often large scale options like `[scale=2]`. default_node_options : string The draw options for a path of nodes. Individual node options override these. node_options : string or dict The name of the node attribute on `G` that holds the options for each node. Or a dict keyed by node to a string holding the options for that node. node_label : string or dict The name of the node attribute on `G` that holds the node label (text) displayed for each node. If the attribute is "" or not present, the node itself is drawn as a string. LaTeX processing such as ``"$A_1$"`` is allowed. Or a dict keyed by node to a string holding the label for that node. default_edge_options : string The options for the scope drawing all edges. The default is "[-]" for undirected graphs and "[->]" for directed graphs. edge_options : string or dict The name of the edge attribute on `G` that holds the options for each edge. If the edge is a self-loop and ``"loop" not in edge_options`` the option "loop," is added to the options for the self-loop edge. Hence you can use "[loop above]" explicitly, but the default is "[loop]". Or a dict keyed by edge to a string holding the options for that edge. edge_label : string or dict The name of the edge attribute on `G` that holds the edge label (text) displayed for each edge. If the attribute is "" or not present, no edge label is drawn. Or a dict keyed by edge to a string holding the label for that edge. edge_label_options : string or dict The name of the edge attribute on `G` that holds the label options for each edge. For example, "[sloped,above,blue]". The default is no options. Or a dict keyed by edge to a string holding the label options for that edge. Returns ======= latex_code : string The text string which draws the desired graph(s) when compiled by LaTeX. See Also ======== to_latex write_latex
null
(G, pos='pos', tikz_options='', default_node_options='', node_options='node_options', node_label='label', default_edge_options='', edge_options='edge_options', edge_label='label', edge_label_options='edge_label_options')
31,169
networkx.algorithms.tree.coding
to_nested_tuple
Returns a nested tuple representation of the given tree. The nested tuple representation of a tree is defined recursively. The tree with one node and no edges is represented by the empty tuple, ``()``. A tree with ``k`` subtrees is represented by a tuple of length ``k`` in which each element is the nested tuple representation of a subtree. Parameters ---------- T : NetworkX graph An undirected graph object representing a tree. root : node The node in ``T`` to interpret as the root of the tree. canonical_form : bool If ``True``, each tuple is sorted so that the function returns a canonical form for rooted trees. This means "lighter" subtrees will appear as nested tuples before "heavier" subtrees. In this way, each isomorphic rooted tree has the same nested tuple representation. Returns ------- tuple A nested tuple representation of the tree. Notes ----- This function is *not* the inverse of :func:`from_nested_tuple`; the only guarantee is that the rooted trees are isomorphic. See also -------- from_nested_tuple to_prufer_sequence Examples -------- The tree need not be a balanced binary tree:: >>> T = nx.Graph() >>> T.add_edges_from([(0, 1), (0, 2), (0, 3)]) >>> T.add_edges_from([(1, 4), (1, 5)]) >>> T.add_edges_from([(3, 6), (3, 7)]) >>> root = 0 >>> nx.to_nested_tuple(T, root) (((), ()), (), ((), ())) Continuing the above example, if ``canonical_form`` is ``True``, the nested tuples will be sorted:: >>> nx.to_nested_tuple(T, root, canonical_form=True) ((), ((), ()), ((), ())) Even the path graph can be interpreted as a tree:: >>> T = nx.path_graph(4) >>> root = 0 >>> nx.to_nested_tuple(T, root) ((((),),),)
null
(T, root, canonical_form=False, *, backend=None, **backend_kwargs)
31,170
networkx.convert
to_networkx_graph
Make a NetworkX graph from a known data structure. The preferred way to call this is automatically from the class constructor >>> d = {0: {1: {"weight": 1}}} # dict-of-dicts single edge (0,1) >>> G = nx.Graph(d) instead of the equivalent >>> G = nx.from_dict_of_dicts(d) Parameters ---------- data : object to be converted Current known types are: any NetworkX graph dict-of-dicts dict-of-lists container (e.g. set, list, tuple) of edges iterator (e.g. itertools.chain) that produces edges generator of edges Pandas DataFrame (row per edge) 2D numpy array scipy sparse array pygraphviz agraph create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. multigraph_input : bool (default False) If True and data is a dict_of_dicts, try to create a multigraph assuming dict_of_dict_of_lists. If data and create_using are both multigraphs then create a multigraph from a multigraph.
def to_networkx_graph(data, create_using=None, multigraph_input=False): """Make a NetworkX graph from a known data structure. The preferred way to call this is automatically from the class constructor >>> d = {0: {1: {"weight": 1}}} # dict-of-dicts single edge (0,1) >>> G = nx.Graph(d) instead of the equivalent >>> G = nx.from_dict_of_dicts(d) Parameters ---------- data : object to be converted Current known types are: any NetworkX graph dict-of-dicts dict-of-lists container (e.g. set, list, tuple) of edges iterator (e.g. itertools.chain) that produces edges generator of edges Pandas DataFrame (row per edge) 2D numpy array scipy sparse array pygraphviz agraph create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. multigraph_input : bool (default False) If True and data is a dict_of_dicts, try to create a multigraph assuming dict_of_dict_of_lists. If data and create_using are both multigraphs then create a multigraph from a multigraph. """ # NX graph if hasattr(data, "adj"): try: result = from_dict_of_dicts( data.adj, create_using=create_using, multigraph_input=data.is_multigraph(), ) # data.graph should be dict-like result.graph.update(data.graph) # data.nodes should be dict-like # result.add_node_from(data.nodes.items()) possible but # for custom node_attr_dict_factory which may be hashable # will be unexpected behavior for n, dd in data.nodes.items(): result._node[n].update(dd) return result except Exception as err: raise nx.NetworkXError("Input is not a correct NetworkX graph.") from err # pygraphviz agraph if hasattr(data, "is_strict"): try: return nx.nx_agraph.from_agraph(data, create_using=create_using) except Exception as err: raise nx.NetworkXError("Input is not a correct pygraphviz graph.") from err # dict of dicts/lists if isinstance(data, dict): try: return from_dict_of_dicts( data, create_using=create_using, multigraph_input=multigraph_input ) except Exception as err1: if multigraph_input is True: raise nx.NetworkXError( f"converting multigraph_input raised:\n{type(err1)}: {err1}" ) try: return from_dict_of_lists(data, create_using=create_using) except Exception as err2: raise TypeError("Input is not known type.") from err2 # Pandas DataFrame try: import pandas as pd if isinstance(data, pd.DataFrame): if data.shape[0] == data.shape[1]: try: return nx.from_pandas_adjacency(data, create_using=create_using) except Exception as err: msg = "Input is not a correct Pandas DataFrame adjacency matrix." raise nx.NetworkXError(msg) from err else: try: return nx.from_pandas_edgelist( data, edge_attr=True, create_using=create_using ) except Exception as err: msg = "Input is not a correct Pandas DataFrame edge-list." raise nx.NetworkXError(msg) from err except ImportError: warnings.warn("pandas not found, skipping conversion test.", ImportWarning) # numpy array try: import numpy as np if isinstance(data, np.ndarray): try: return nx.from_numpy_array(data, create_using=create_using) except Exception as err: raise nx.NetworkXError( f"Failed to interpret array as an adjacency matrix." ) from err except ImportError: warnings.warn("numpy not found, skipping conversion test.", ImportWarning) # scipy sparse array - any format try: import scipy if hasattr(data, "format"): try: return nx.from_scipy_sparse_array(data, create_using=create_using) except Exception as err: raise nx.NetworkXError( "Input is not a correct scipy sparse array type." ) from err except ImportError: warnings.warn("scipy not found, skipping conversion test.", ImportWarning) # Note: most general check - should remain last in order of execution # Includes containers (e.g. list, set, dict, etc.), generators, and # iterators (e.g. itertools.chain) of edges if isinstance(data, Collection | Generator | Iterator): try: return from_edgelist(data, create_using=create_using) except Exception as err: raise nx.NetworkXError("Input is not a valid edge list") from err raise nx.NetworkXError("Input is not a known data type for conversion.")
(data, create_using=None, multigraph_input=False)
31,171
networkx.convert_matrix
to_numpy_array
Returns the graph adjacency matrix as a NumPy array. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy array. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``. dtype : NumPy data type, optional A NumPy data type used to initialize the array. If None, then the NumPy default is used. The dtype can be structured if `weight=None`, in which case the dtype field names are used to look up edge attributes. The result is a structured array where each named field in the dtype corresponds to the adjacency for that edge attribute. See examples for details. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. If None, then the NumPy default is used. multigraph_weight : callable, optional An function that determines how weights in multigraphs are handled. The function should accept a sequence of weights and return a single value. The default is to sum the weights of the multiple edges. weight : string or None optional (default = 'weight') The edge attribute that holds the numerical value used for the edge weight. If an edge does not have that attribute, then the value 1 is used instead. `weight` must be ``None`` if a structured dtype is used. nonedge : array_like (default = 0.0) The value used to represent non-edges in the adjacency matrix. The array values corresponding to nonedges are typically set to zero. However, this could be undesirable if there are array values corresponding to actual edges that also have the value zero. If so, one might prefer nonedges to have some other value, such as ``nan``. Returns ------- A : NumPy ndarray Graph adjacency matrix Raises ------ NetworkXError If `dtype` is a structured dtype and `G` is a multigraph ValueError If `dtype` is a structured dtype and `weight` is not `None` See Also -------- from_numpy_array Notes ----- For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``. Entries in the adjacency matrix are given by the `weight` edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the `multigraph_weight` parameter. The default is to sum the weight attributes for each of the parallel edges. When `nodelist` does not contain every node in `G`, the adjacency matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal array entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting NumPy array can be modified as follows: >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_numpy_array(G) >>> A array([[1.]]) >>> A[np.diag_indices_from(A)] *= 2 >>> A array([[2.]]) Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> nx.to_numpy_array(G, nodelist=[0, 1, 2]) array([[0., 2., 0.], [1., 0., 0.], [0., 0., 4.]]) When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist` and their edges are not included in the adjacency matrix. Here is an example: >>> G = nx.Graph() >>> G.add_edge(3, 1) >>> G.add_edge(2, 0) >>> G.add_edge(2, 1) >>> G.add_edge(3, 0) >>> nx.to_numpy_array(G, nodelist=[1, 2, 3]) array([[0., 1., 1.], [1., 0., 0.], [1., 0., 0.]]) This function can also be used to create adjacency matrices for multiple edge attributes with structured dtypes: >>> G = nx.Graph() >>> G.add_edge(0, 1, weight=10) >>> G.add_edge(1, 2, cost=5) >>> G.add_edge(2, 3, weight=3, cost=-4.0) >>> dtype = np.dtype([("weight", int), ("cost", float)]) >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None) >>> A["weight"] array([[ 0, 10, 0, 0], [10, 0, 1, 0], [ 0, 1, 0, 3], [ 0, 0, 3, 0]]) >>> A["cost"] array([[ 0., 1., 0., 0.], [ 1., 0., 5., 0.], [ 0., 5., 0., -4.], [ 0., 0., -4., 0.]]) As stated above, the argument "nonedge" is useful especially when there are actually edges with weight 0 in the graph. Setting a nonedge value different than 0, makes it much clearer to differentiate such 0-weighted edges and actual nonedge values. >>> G = nx.Graph() >>> G.add_edge(3, 1, weight=2) >>> G.add_edge(2, 0, weight=0) >>> G.add_edge(2, 1, weight=0) >>> G.add_edge(3, 0, weight=1) >>> nx.to_numpy_array(G, nonedge=-1.0) array([[-1., 2., -1., 1.], [ 2., -1., 0., -1.], [-1., 0., -1., 0.], [ 1., -1., 0., -1.]])
def to_numpy_array( G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight="weight", nonedge=0.0, ): """Returns the graph adjacency matrix as a NumPy array. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy array. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``. dtype : NumPy data type, optional A NumPy data type used to initialize the array. If None, then the NumPy default is used. The dtype can be structured if `weight=None`, in which case the dtype field names are used to look up edge attributes. The result is a structured array where each named field in the dtype corresponds to the adjacency for that edge attribute. See examples for details. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. If None, then the NumPy default is used. multigraph_weight : callable, optional An function that determines how weights in multigraphs are handled. The function should accept a sequence of weights and return a single value. The default is to sum the weights of the multiple edges. weight : string or None optional (default = 'weight') The edge attribute that holds the numerical value used for the edge weight. If an edge does not have that attribute, then the value 1 is used instead. `weight` must be ``None`` if a structured dtype is used. nonedge : array_like (default = 0.0) The value used to represent non-edges in the adjacency matrix. The array values corresponding to nonedges are typically set to zero. However, this could be undesirable if there are array values corresponding to actual edges that also have the value zero. If so, one might prefer nonedges to have some other value, such as ``nan``. Returns ------- A : NumPy ndarray Graph adjacency matrix Raises ------ NetworkXError If `dtype` is a structured dtype and `G` is a multigraph ValueError If `dtype` is a structured dtype and `weight` is not `None` See Also -------- from_numpy_array Notes ----- For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``. Entries in the adjacency matrix are given by the `weight` edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the `multigraph_weight` parameter. The default is to sum the weight attributes for each of the parallel edges. When `nodelist` does not contain every node in `G`, the adjacency matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal array entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting NumPy array can be modified as follows: >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_numpy_array(G) >>> A array([[1.]]) >>> A[np.diag_indices_from(A)] *= 2 >>> A array([[2.]]) Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> nx.to_numpy_array(G, nodelist=[0, 1, 2]) array([[0., 2., 0.], [1., 0., 0.], [0., 0., 4.]]) When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist` and their edges are not included in the adjacency matrix. Here is an example: >>> G = nx.Graph() >>> G.add_edge(3, 1) >>> G.add_edge(2, 0) >>> G.add_edge(2, 1) >>> G.add_edge(3, 0) >>> nx.to_numpy_array(G, nodelist=[1, 2, 3]) array([[0., 1., 1.], [1., 0., 0.], [1., 0., 0.]]) This function can also be used to create adjacency matrices for multiple edge attributes with structured dtypes: >>> G = nx.Graph() >>> G.add_edge(0, 1, weight=10) >>> G.add_edge(1, 2, cost=5) >>> G.add_edge(2, 3, weight=3, cost=-4.0) >>> dtype = np.dtype([("weight", int), ("cost", float)]) >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None) >>> A["weight"] array([[ 0, 10, 0, 0], [10, 0, 1, 0], [ 0, 1, 0, 3], [ 0, 0, 3, 0]]) >>> A["cost"] array([[ 0., 1., 0., 0.], [ 1., 0., 5., 0.], [ 0., 5., 0., -4.], [ 0., 0., -4., 0.]]) As stated above, the argument "nonedge" is useful especially when there are actually edges with weight 0 in the graph. Setting a nonedge value different than 0, makes it much clearer to differentiate such 0-weighted edges and actual nonedge values. >>> G = nx.Graph() >>> G.add_edge(3, 1, weight=2) >>> G.add_edge(2, 0, weight=0) >>> G.add_edge(2, 1, weight=0) >>> G.add_edge(3, 0, weight=1) >>> nx.to_numpy_array(G, nonedge=-1.0) array([[-1., 2., -1., 1.], [ 2., -1., 0., -1.], [-1., 0., -1., 0.], [ 1., -1., 0., -1.]]) """ import numpy as np if nodelist is None: nodelist = list(G) nlen = len(nodelist) # Input validation nodeset = set(nodelist) if nodeset - set(G): raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G") if len(nodeset) < nlen: raise nx.NetworkXError("nodelist contains duplicates.") A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order) # Corner cases: empty nodelist or graph without any edges if nlen == 0 or G.number_of_edges() == 0: return A # If dtype is structured and weight is None, use dtype field names as # edge attributes edge_attrs = None # Only single edge attribute by default if A.dtype.names: if weight is None: edge_attrs = dtype.names else: raise ValueError( "Specifying `weight` not supported for structured dtypes\n." "To create adjacency matrices from structured dtypes, use `weight=None`." ) # Map nodes to row/col in matrix idx = dict(zip(nodelist, range(nlen))) if len(nodelist) < len(G): G = G.subgraph(nodelist).copy() # Collect all edge weights and reduce with `multigraph_weights` if G.is_multigraph(): if edge_attrs: raise nx.NetworkXError( "Structured arrays are not supported for MultiGraphs" ) d = defaultdict(list) for u, v, wt in G.edges(data=weight, default=1.0): d[(idx[u], idx[v])].append(wt) i, j = np.array(list(d.keys())).T # indices wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights else: i, j, wts = [], [], [] # Special branch: multi-attr adjacency from structured dtypes if edge_attrs: # Extract edges with all data for u, v, data in G.edges(data=True): i.append(idx[u]) j.append(idx[v]) wts.append(data) # Map each attribute to the appropriate named field in the # structured dtype for attr in edge_attrs: attr_data = [wt.get(attr, 1.0) for wt in wts] A[attr][i, j] = attr_data if not G.is_directed(): A[attr][j, i] = attr_data return A for u, v, wt in G.edges(data=weight, default=1.0): i.append(idx[u]) j.append(idx[v]) wts.append(wt) # Set array values with advanced indexing A[i, j] = wts if not G.is_directed(): A[j, i] = wts return A
(G, nodelist=None, dtype=None, order=None, multigraph_weight=<built-in function sum>, weight='weight', nonedge=0.0, *, backend=None, **backend_kwargs)
31,172
networkx.convert_matrix
to_pandas_adjacency
Returns the graph adjacency matrix as a Pandas DataFrame. Parameters ---------- G : graph The NetworkX graph used to construct the Pandas DataFrame. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is None, then the ordering is produced by G.nodes(). multigraph_weight : {sum, min, max}, optional An operator that determines how weights in multigraphs are handled. The default is to sum the weights of the multiple edges. weight : string or None, optional The edge attribute that holds the numerical value used for the edge weight. If an edge does not have that attribute, then the value 1 is used instead. nonedge : float, optional The matrix values corresponding to nonedges are typically set to zero. However, this could be undesirable if there are matrix values corresponding to actual edges that also have the value zero. If so, one might prefer nonedges to have some other value, such as nan. Returns ------- df : Pandas DataFrame Graph adjacency matrix Notes ----- For directed graphs, entry i,j corresponds to an edge from i to j. The DataFrame entries are assigned to the weight edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the 'multigraph_weight' parameter. The default is to sum the weight attributes for each of the parallel edges. When `nodelist` does not contain every node in `G`, the matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting Pandas DataFrame can be modified as follows:: >>> import pandas as pd >>> G = nx.Graph([(1, 1), (2, 2)]) >>> df = nx.to_pandas_adjacency(G) >>> df 1 2 1 1.0 0.0 2 0.0 1.0 >>> diag_idx = list(range(len(df))) >>> df.iloc[diag_idx, diag_idx] *= 2 >>> df 1 2 1 2.0 0.0 2 0.0 2.0 Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> nx.to_pandas_adjacency(G, nodelist=[0, 1, 2], dtype=int) 0 1 2 0 0 2 0 1 1 0 0 2 0 0 4
def to_numpy_array( G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight="weight", nonedge=0.0, ): """Returns the graph adjacency matrix as a NumPy array. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy array. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``. dtype : NumPy data type, optional A NumPy data type used to initialize the array. If None, then the NumPy default is used. The dtype can be structured if `weight=None`, in which case the dtype field names are used to look up edge attributes. The result is a structured array where each named field in the dtype corresponds to the adjacency for that edge attribute. See examples for details. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. If None, then the NumPy default is used. multigraph_weight : callable, optional An function that determines how weights in multigraphs are handled. The function should accept a sequence of weights and return a single value. The default is to sum the weights of the multiple edges. weight : string or None optional (default = 'weight') The edge attribute that holds the numerical value used for the edge weight. If an edge does not have that attribute, then the value 1 is used instead. `weight` must be ``None`` if a structured dtype is used. nonedge : array_like (default = 0.0) The value used to represent non-edges in the adjacency matrix. The array values corresponding to nonedges are typically set to zero. However, this could be undesirable if there are array values corresponding to actual edges that also have the value zero. If so, one might prefer nonedges to have some other value, such as ``nan``. Returns ------- A : NumPy ndarray Graph adjacency matrix Raises ------ NetworkXError If `dtype` is a structured dtype and `G` is a multigraph ValueError If `dtype` is a structured dtype and `weight` is not `None` See Also -------- from_numpy_array Notes ----- For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``. Entries in the adjacency matrix are given by the `weight` edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the `multigraph_weight` parameter. The default is to sum the weight attributes for each of the parallel edges. When `nodelist` does not contain every node in `G`, the adjacency matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal array entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting NumPy array can be modified as follows: >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_numpy_array(G) >>> A array([[1.]]) >>> A[np.diag_indices_from(A)] *= 2 >>> A array([[2.]]) Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> nx.to_numpy_array(G, nodelist=[0, 1, 2]) array([[0., 2., 0.], [1., 0., 0.], [0., 0., 4.]]) When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist` and their edges are not included in the adjacency matrix. Here is an example: >>> G = nx.Graph() >>> G.add_edge(3, 1) >>> G.add_edge(2, 0) >>> G.add_edge(2, 1) >>> G.add_edge(3, 0) >>> nx.to_numpy_array(G, nodelist=[1, 2, 3]) array([[0., 1., 1.], [1., 0., 0.], [1., 0., 0.]]) This function can also be used to create adjacency matrices for multiple edge attributes with structured dtypes: >>> G = nx.Graph() >>> G.add_edge(0, 1, weight=10) >>> G.add_edge(1, 2, cost=5) >>> G.add_edge(2, 3, weight=3, cost=-4.0) >>> dtype = np.dtype([("weight", int), ("cost", float)]) >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None) >>> A["weight"] array([[ 0, 10, 0, 0], [10, 0, 1, 0], [ 0, 1, 0, 3], [ 0, 0, 3, 0]]) >>> A["cost"] array([[ 0., 1., 0., 0.], [ 1., 0., 5., 0.], [ 0., 5., 0., -4.], [ 0., 0., -4., 0.]]) As stated above, the argument "nonedge" is useful especially when there are actually edges with weight 0 in the graph. Setting a nonedge value different than 0, makes it much clearer to differentiate such 0-weighted edges and actual nonedge values. >>> G = nx.Graph() >>> G.add_edge(3, 1, weight=2) >>> G.add_edge(2, 0, weight=0) >>> G.add_edge(2, 1, weight=0) >>> G.add_edge(3, 0, weight=1) >>> nx.to_numpy_array(G, nonedge=-1.0) array([[-1., 2., -1., 1.], [ 2., -1., 0., -1.], [-1., 0., -1., 0.], [ 1., -1., 0., -1.]]) """ import numpy as np if nodelist is None: nodelist = list(G) nlen = len(nodelist) # Input validation nodeset = set(nodelist) if nodeset - set(G): raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G") if len(nodeset) < nlen: raise nx.NetworkXError("nodelist contains duplicates.") A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order) # Corner cases: empty nodelist or graph without any edges if nlen == 0 or G.number_of_edges() == 0: return A # If dtype is structured and weight is None, use dtype field names as # edge attributes edge_attrs = None # Only single edge attribute by default if A.dtype.names: if weight is None: edge_attrs = dtype.names else: raise ValueError( "Specifying `weight` not supported for structured dtypes\n." "To create adjacency matrices from structured dtypes, use `weight=None`." ) # Map nodes to row/col in matrix idx = dict(zip(nodelist, range(nlen))) if len(nodelist) < len(G): G = G.subgraph(nodelist).copy() # Collect all edge weights and reduce with `multigraph_weights` if G.is_multigraph(): if edge_attrs: raise nx.NetworkXError( "Structured arrays are not supported for MultiGraphs" ) d = defaultdict(list) for u, v, wt in G.edges(data=weight, default=1.0): d[(idx[u], idx[v])].append(wt) i, j = np.array(list(d.keys())).T # indices wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights else: i, j, wts = [], [], [] # Special branch: multi-attr adjacency from structured dtypes if edge_attrs: # Extract edges with all data for u, v, data in G.edges(data=True): i.append(idx[u]) j.append(idx[v]) wts.append(data) # Map each attribute to the appropriate named field in the # structured dtype for attr in edge_attrs: attr_data = [wt.get(attr, 1.0) for wt in wts] A[attr][i, j] = attr_data if not G.is_directed(): A[attr][j, i] = attr_data return A for u, v, wt in G.edges(data=weight, default=1.0): i.append(idx[u]) j.append(idx[v]) wts.append(wt) # Set array values with advanced indexing A[i, j] = wts if not G.is_directed(): A[j, i] = wts return A
(G, nodelist=None, dtype=None, order=None, multigraph_weight=<built-in function sum>, weight='weight', nonedge=0.0, *, backend=None, **backend_kwargs)
31,173
networkx.convert_matrix
to_pandas_edgelist
Returns the graph edge list as a Pandas DataFrame. Parameters ---------- G : graph The NetworkX graph used to construct the Pandas DataFrame. source : str or int, optional A valid column name (string or integer) for the source nodes (for the directed case). target : str or int, optional A valid column name (string or integer) for the target nodes (for the directed case). nodelist : list, optional Use only nodes specified in nodelist dtype : dtype, default None Use to create the DataFrame. Data type to force. Only a single dtype is allowed. If None, infer. edge_key : str or int or None, optional (default=None) A valid column name (string or integer) for the edge keys (for the multigraph case). If None, edge keys are not stored in the DataFrame. Returns ------- df : Pandas DataFrame Graph edge list Examples -------- >>> G = nx.Graph( ... [ ... ("A", "B", {"cost": 1, "weight": 7}), ... ("C", "E", {"cost": 9, "weight": 10}), ... ] ... ) >>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"]) >>> df[["source", "target", "cost", "weight"]] source target cost weight 0 A B 1 7 1 C E 9 10 >>> G = nx.MultiGraph([("A", "B", {"cost": 1}), ("A", "B", {"cost": 9})]) >>> df = nx.to_pandas_edgelist(G, nodelist=["A", "C"], edge_key="ekey") >>> df[["source", "target", "cost", "ekey"]] source target cost ekey 0 A B 1 0 1 A B 9 1
def to_numpy_array( G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight="weight", nonedge=0.0, ): """Returns the graph adjacency matrix as a NumPy array. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy array. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``. dtype : NumPy data type, optional A NumPy data type used to initialize the array. If None, then the NumPy default is used. The dtype can be structured if `weight=None`, in which case the dtype field names are used to look up edge attributes. The result is a structured array where each named field in the dtype corresponds to the adjacency for that edge attribute. See examples for details. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. If None, then the NumPy default is used. multigraph_weight : callable, optional An function that determines how weights in multigraphs are handled. The function should accept a sequence of weights and return a single value. The default is to sum the weights of the multiple edges. weight : string or None optional (default = 'weight') The edge attribute that holds the numerical value used for the edge weight. If an edge does not have that attribute, then the value 1 is used instead. `weight` must be ``None`` if a structured dtype is used. nonedge : array_like (default = 0.0) The value used to represent non-edges in the adjacency matrix. The array values corresponding to nonedges are typically set to zero. However, this could be undesirable if there are array values corresponding to actual edges that also have the value zero. If so, one might prefer nonedges to have some other value, such as ``nan``. Returns ------- A : NumPy ndarray Graph adjacency matrix Raises ------ NetworkXError If `dtype` is a structured dtype and `G` is a multigraph ValueError If `dtype` is a structured dtype and `weight` is not `None` See Also -------- from_numpy_array Notes ----- For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``. Entries in the adjacency matrix are given by the `weight` edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the `multigraph_weight` parameter. The default is to sum the weight attributes for each of the parallel edges. When `nodelist` does not contain every node in `G`, the adjacency matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal array entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting NumPy array can be modified as follows: >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_numpy_array(G) >>> A array([[1.]]) >>> A[np.diag_indices_from(A)] *= 2 >>> A array([[2.]]) Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> nx.to_numpy_array(G, nodelist=[0, 1, 2]) array([[0., 2., 0.], [1., 0., 0.], [0., 0., 4.]]) When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist` and their edges are not included in the adjacency matrix. Here is an example: >>> G = nx.Graph() >>> G.add_edge(3, 1) >>> G.add_edge(2, 0) >>> G.add_edge(2, 1) >>> G.add_edge(3, 0) >>> nx.to_numpy_array(G, nodelist=[1, 2, 3]) array([[0., 1., 1.], [1., 0., 0.], [1., 0., 0.]]) This function can also be used to create adjacency matrices for multiple edge attributes with structured dtypes: >>> G = nx.Graph() >>> G.add_edge(0, 1, weight=10) >>> G.add_edge(1, 2, cost=5) >>> G.add_edge(2, 3, weight=3, cost=-4.0) >>> dtype = np.dtype([("weight", int), ("cost", float)]) >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None) >>> A["weight"] array([[ 0, 10, 0, 0], [10, 0, 1, 0], [ 0, 1, 0, 3], [ 0, 0, 3, 0]]) >>> A["cost"] array([[ 0., 1., 0., 0.], [ 1., 0., 5., 0.], [ 0., 5., 0., -4.], [ 0., 0., -4., 0.]]) As stated above, the argument "nonedge" is useful especially when there are actually edges with weight 0 in the graph. Setting a nonedge value different than 0, makes it much clearer to differentiate such 0-weighted edges and actual nonedge values. >>> G = nx.Graph() >>> G.add_edge(3, 1, weight=2) >>> G.add_edge(2, 0, weight=0) >>> G.add_edge(2, 1, weight=0) >>> G.add_edge(3, 0, weight=1) >>> nx.to_numpy_array(G, nonedge=-1.0) array([[-1., 2., -1., 1.], [ 2., -1., 0., -1.], [-1., 0., -1., 0.], [ 1., -1., 0., -1.]]) """ import numpy as np if nodelist is None: nodelist = list(G) nlen = len(nodelist) # Input validation nodeset = set(nodelist) if nodeset - set(G): raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G") if len(nodeset) < nlen: raise nx.NetworkXError("nodelist contains duplicates.") A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order) # Corner cases: empty nodelist or graph without any edges if nlen == 0 or G.number_of_edges() == 0: return A # If dtype is structured and weight is None, use dtype field names as # edge attributes edge_attrs = None # Only single edge attribute by default if A.dtype.names: if weight is None: edge_attrs = dtype.names else: raise ValueError( "Specifying `weight` not supported for structured dtypes\n." "To create adjacency matrices from structured dtypes, use `weight=None`." ) # Map nodes to row/col in matrix idx = dict(zip(nodelist, range(nlen))) if len(nodelist) < len(G): G = G.subgraph(nodelist).copy() # Collect all edge weights and reduce with `multigraph_weights` if G.is_multigraph(): if edge_attrs: raise nx.NetworkXError( "Structured arrays are not supported for MultiGraphs" ) d = defaultdict(list) for u, v, wt in G.edges(data=weight, default=1.0): d[(idx[u], idx[v])].append(wt) i, j = np.array(list(d.keys())).T # indices wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights else: i, j, wts = [], [], [] # Special branch: multi-attr adjacency from structured dtypes if edge_attrs: # Extract edges with all data for u, v, data in G.edges(data=True): i.append(idx[u]) j.append(idx[v]) wts.append(data) # Map each attribute to the appropriate named field in the # structured dtype for attr in edge_attrs: attr_data = [wt.get(attr, 1.0) for wt in wts] A[attr][i, j] = attr_data if not G.is_directed(): A[attr][j, i] = attr_data return A for u, v, wt in G.edges(data=weight, default=1.0): i.append(idx[u]) j.append(idx[v]) wts.append(wt) # Set array values with advanced indexing A[i, j] = wts if not G.is_directed(): A[j, i] = wts return A
(G, source='source', target='target', nodelist=None, dtype=None, edge_key=None, *, backend=None, **backend_kwargs)
31,174
networkx.algorithms.tree.coding
to_prufer_sequence
Returns the Prüfer sequence of the given tree. A *Prüfer sequence* is a list of *n* - 2 numbers between 0 and *n* - 1, inclusive. The tree corresponding to a given Prüfer sequence can be recovered by repeatedly joining a node in the sequence with a node with the smallest potential degree according to the sequence. Parameters ---------- T : NetworkX graph An undirected graph object representing a tree. Returns ------- list The Prüfer sequence of the given tree. Raises ------ NetworkXPointlessConcept If the number of nodes in `T` is less than two. NotATree If `T` is not a tree. KeyError If the set of nodes in `T` is not {0, …, *n* - 1}. Notes ----- There is a bijection from labeled trees to Prüfer sequences. This function is the inverse of the :func:`from_prufer_sequence` function. Sometimes Prüfer sequences use nodes labeled from 1 to *n* instead of from 0 to *n* - 1. This function requires nodes to be labeled in the latter form. You can use :func:`~networkx.relabel_nodes` to relabel the nodes of your tree to the appropriate format. This implementation is from [1]_ and has a running time of $O(n)$. See also -------- to_nested_tuple from_prufer_sequence References ---------- .. [1] Wang, Xiaodong, Lei Wang, and Yingjie Wu. "An optimal algorithm for Prufer codes." *Journal of Software Engineering and Applications* 2.02 (2009): 111. <https://doi.org/10.4236/jsea.2009.22016> Examples -------- There is a bijection between Prüfer sequences and labeled trees, so this function is the inverse of the :func:`from_prufer_sequence` function: >>> edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)] >>> tree = nx.Graph(edges) >>> sequence = nx.to_prufer_sequence(tree) >>> sequence [3, 3, 3, 4] >>> tree2 = nx.from_prufer_sequence(sequence) >>> list(tree2.edges()) == edges True
null
(T, *, backend=None, **backend_kwargs)
31,175
networkx.convert_matrix
to_scipy_sparse_array
Returns the graph adjacency matrix as a SciPy sparse array. Parameters ---------- G : graph The NetworkX graph used to construct the sparse matrix. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is None, then the ordering is produced by G.nodes(). dtype : NumPy data-type, optional A valid NumPy dtype used to initialize the array. If None, then the NumPy default is used. weight : string or None optional (default='weight') The edge attribute that holds the numerical value used for the edge weight. If None then all edge weights are 1. format : str in {'bsr', 'csr', 'csc', 'coo', 'lil', 'dia', 'dok'} The type of the matrix to be returned (default 'csr'). For some algorithms different implementations of sparse matrices can perform better. See [1]_ for details. Returns ------- A : SciPy sparse array Graph adjacency matrix. Notes ----- For directed graphs, matrix entry i,j corresponds to an edge from i to j. The matrix entries are populated using the edge attribute held in parameter weight. When an edge does not have that attribute, the value of the entry is 1. For multiple edges the matrix values are the sums of the edge weights. When `nodelist` does not contain every node in `G`, the adjacency matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting SciPy sparse array can be modified as follows: >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_scipy_sparse_array(G) >>> print(A.todense()) [[1]] >>> A.setdiag(A.diagonal() * 2) >>> print(A.toarray()) [[2]] Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> S = nx.to_scipy_sparse_array(G, nodelist=[0, 1, 2]) >>> print(S.toarray()) [[0 2 0] [1 0 0] [0 0 4]] References ---------- .. [1] Scipy Dev. References, "Sparse Matrices", https://docs.scipy.org/doc/scipy/reference/sparse.html
def to_numpy_array( G, nodelist=None, dtype=None, order=None, multigraph_weight=sum, weight="weight", nonedge=0.0, ): """Returns the graph adjacency matrix as a NumPy array. Parameters ---------- G : graph The NetworkX graph used to construct the NumPy array. nodelist : list, optional The rows and columns are ordered according to the nodes in `nodelist`. If `nodelist` is ``None``, then the ordering is produced by ``G.nodes()``. dtype : NumPy data type, optional A NumPy data type used to initialize the array. If None, then the NumPy default is used. The dtype can be structured if `weight=None`, in which case the dtype field names are used to look up edge attributes. The result is a structured array where each named field in the dtype corresponds to the adjacency for that edge attribute. See examples for details. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. If None, then the NumPy default is used. multigraph_weight : callable, optional An function that determines how weights in multigraphs are handled. The function should accept a sequence of weights and return a single value. The default is to sum the weights of the multiple edges. weight : string or None optional (default = 'weight') The edge attribute that holds the numerical value used for the edge weight. If an edge does not have that attribute, then the value 1 is used instead. `weight` must be ``None`` if a structured dtype is used. nonedge : array_like (default = 0.0) The value used to represent non-edges in the adjacency matrix. The array values corresponding to nonedges are typically set to zero. However, this could be undesirable if there are array values corresponding to actual edges that also have the value zero. If so, one might prefer nonedges to have some other value, such as ``nan``. Returns ------- A : NumPy ndarray Graph adjacency matrix Raises ------ NetworkXError If `dtype` is a structured dtype and `G` is a multigraph ValueError If `dtype` is a structured dtype and `weight` is not `None` See Also -------- from_numpy_array Notes ----- For directed graphs, entry ``i, j`` corresponds to an edge from ``i`` to ``j``. Entries in the adjacency matrix are given by the `weight` edge attribute. When an edge does not have a weight attribute, the value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined by the `multigraph_weight` parameter. The default is to sum the weight attributes for each of the parallel edges. When `nodelist` does not contain every node in `G`, the adjacency matrix is built from the subgraph of `G` that is induced by the nodes in `nodelist`. The convention used for self-loop edges in graphs is to assign the diagonal array entry value to the weight attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge weight is desired the resulting NumPy array can be modified as follows: >>> import numpy as np >>> G = nx.Graph([(1, 1)]) >>> A = nx.to_numpy_array(G) >>> A array([[1.]]) >>> A[np.diag_indices_from(A)] *= 2 >>> A array([[2.]]) Examples -------- >>> G = nx.MultiDiGraph() >>> G.add_edge(0, 1, weight=2) 0 >>> G.add_edge(1, 0) 0 >>> G.add_edge(2, 2, weight=3) 0 >>> G.add_edge(2, 2) 1 >>> nx.to_numpy_array(G, nodelist=[0, 1, 2]) array([[0., 2., 0.], [1., 0., 0.], [0., 0., 4.]]) When `nodelist` argument is used, nodes of `G` which do not appear in the `nodelist` and their edges are not included in the adjacency matrix. Here is an example: >>> G = nx.Graph() >>> G.add_edge(3, 1) >>> G.add_edge(2, 0) >>> G.add_edge(2, 1) >>> G.add_edge(3, 0) >>> nx.to_numpy_array(G, nodelist=[1, 2, 3]) array([[0., 1., 1.], [1., 0., 0.], [1., 0., 0.]]) This function can also be used to create adjacency matrices for multiple edge attributes with structured dtypes: >>> G = nx.Graph() >>> G.add_edge(0, 1, weight=10) >>> G.add_edge(1, 2, cost=5) >>> G.add_edge(2, 3, weight=3, cost=-4.0) >>> dtype = np.dtype([("weight", int), ("cost", float)]) >>> A = nx.to_numpy_array(G, dtype=dtype, weight=None) >>> A["weight"] array([[ 0, 10, 0, 0], [10, 0, 1, 0], [ 0, 1, 0, 3], [ 0, 0, 3, 0]]) >>> A["cost"] array([[ 0., 1., 0., 0.], [ 1., 0., 5., 0.], [ 0., 5., 0., -4.], [ 0., 0., -4., 0.]]) As stated above, the argument "nonedge" is useful especially when there are actually edges with weight 0 in the graph. Setting a nonedge value different than 0, makes it much clearer to differentiate such 0-weighted edges and actual nonedge values. >>> G = nx.Graph() >>> G.add_edge(3, 1, weight=2) >>> G.add_edge(2, 0, weight=0) >>> G.add_edge(2, 1, weight=0) >>> G.add_edge(3, 0, weight=1) >>> nx.to_numpy_array(G, nonedge=-1.0) array([[-1., 2., -1., 1.], [ 2., -1., 0., -1.], [-1., 0., -1., 0.], [ 1., -1., 0., -1.]]) """ import numpy as np if nodelist is None: nodelist = list(G) nlen = len(nodelist) # Input validation nodeset = set(nodelist) if nodeset - set(G): raise nx.NetworkXError(f"Nodes {nodeset - set(G)} in nodelist is not in G") if len(nodeset) < nlen: raise nx.NetworkXError("nodelist contains duplicates.") A = np.full((nlen, nlen), fill_value=nonedge, dtype=dtype, order=order) # Corner cases: empty nodelist or graph without any edges if nlen == 0 or G.number_of_edges() == 0: return A # If dtype is structured and weight is None, use dtype field names as # edge attributes edge_attrs = None # Only single edge attribute by default if A.dtype.names: if weight is None: edge_attrs = dtype.names else: raise ValueError( "Specifying `weight` not supported for structured dtypes\n." "To create adjacency matrices from structured dtypes, use `weight=None`." ) # Map nodes to row/col in matrix idx = dict(zip(nodelist, range(nlen))) if len(nodelist) < len(G): G = G.subgraph(nodelist).copy() # Collect all edge weights and reduce with `multigraph_weights` if G.is_multigraph(): if edge_attrs: raise nx.NetworkXError( "Structured arrays are not supported for MultiGraphs" ) d = defaultdict(list) for u, v, wt in G.edges(data=weight, default=1.0): d[(idx[u], idx[v])].append(wt) i, j = np.array(list(d.keys())).T # indices wts = [multigraph_weight(ws) for ws in d.values()] # reduced weights else: i, j, wts = [], [], [] # Special branch: multi-attr adjacency from structured dtypes if edge_attrs: # Extract edges with all data for u, v, data in G.edges(data=True): i.append(idx[u]) j.append(idx[v]) wts.append(data) # Map each attribute to the appropriate named field in the # structured dtype for attr in edge_attrs: attr_data = [wt.get(attr, 1.0) for wt in wts] A[attr][i, j] = attr_data if not G.is_directed(): A[attr][j, i] = attr_data return A for u, v, wt in G.edges(data=weight, default=1.0): i.append(idx[u]) j.append(idx[v]) wts.append(wt) # Set array values with advanced indexing A[i, j] = wts if not G.is_directed(): A[j, i] = wts return A
(G, nodelist=None, dtype=None, weight='weight', format='csr', *, backend=None, **backend_kwargs)
31,176
networkx.readwrite.sparse6
to_sparse6_bytes
Convert an undirected graph to bytes in sparse6 format. Parameters ---------- G : Graph (undirected) nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used. header: bool If True add '>>sparse6<<' bytes to head of data. Raises ------ NetworkXNotImplemented If the graph is directed. ValueError If the graph has at least ``2 ** 36`` nodes; the sparse6 format is only defined for graphs of order less than ``2 ** 36``. Examples -------- >>> nx.to_sparse6_bytes(nx.path_graph(2)) b'>>sparse6<<:An\n' See Also -------- to_sparse6_bytes, read_sparse6, write_sparse6_bytes Notes ----- The returned bytes end with a newline character. The format does not support edge or node labels. References ---------- .. [1] Graph6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html>
def to_sparse6_bytes(G, nodes=None, header=True): """Convert an undirected graph to bytes in sparse6 format. Parameters ---------- G : Graph (undirected) nodes: list or iterable Nodes are labeled 0...n-1 in the order provided. If None the ordering given by ``G.nodes()`` is used. header: bool If True add '>>sparse6<<' bytes to head of data. Raises ------ NetworkXNotImplemented If the graph is directed. ValueError If the graph has at least ``2 ** 36`` nodes; the sparse6 format is only defined for graphs of order less than ``2 ** 36``. Examples -------- >>> nx.to_sparse6_bytes(nx.path_graph(2)) b'>>sparse6<<:An\\n' See Also -------- to_sparse6_bytes, read_sparse6, write_sparse6_bytes Notes ----- The returned bytes end with a newline character. The format does not support edge or node labels. References ---------- .. [1] Graph6 specification <https://users.cecs.anu.edu.au/~bdm/data/formats.html> """ if nodes is not None: G = G.subgraph(nodes) G = nx.convert_node_labels_to_integers(G, ordering="sorted") return b"".join(_generate_sparse6_bytes(G, nodes, header))
(G, nodes=None, header=True)
31,177
networkx.classes.function
to_undirected
Returns an undirected view of the graph `graph`. Identical to graph.to_undirected(as_view=True) Note that graph.to_undirected defaults to `as_view=False` while this function always provides a view.
def to_undirected(graph): """Returns an undirected view of the graph `graph`. Identical to graph.to_undirected(as_view=True) Note that graph.to_undirected defaults to `as_view=False` while this function always provides a view. """ return graph.to_undirected(as_view=True)
(graph)