Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/bridges.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/broadcasting.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/chains.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/chordal.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/clique.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/cluster.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/communicability_alg.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/covering.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/d_separation.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/efficiency_measures.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/hybrid.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/isolate.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/link_prediction.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/moral.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/node_classification.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/non_randomness.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/perfect_graph.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/planar_drawing.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/polynomials.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/regular.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/richclub.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/similarity.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/smetric.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/structuralholes.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/triads.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/voronoi.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/walks.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/__pycache__/wiener.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__init__.pyAdded+88
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/__init__.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/basic.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/centrality.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/cluster.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/covering.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/edgelist.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/extendability.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/generators.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/link_analysis.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/matching.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/matrix.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/projection.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/redundancy.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/spectral.cpython-312.pycAdded
- lib/python3.12/site-packages/networkx/algorithms/bipartite/basic.pyAdded+322
- lib/python3.12/site-packages/networkx/algorithms/bipartite/centrality.pyAdded+290
- lib/python3.12/site-packages/networkx/algorithms/bipartite/cluster.pyAdded+289
- lib/python3.12/site-packages/networkx/algorithms/bipartite/covering.pyAdded+57
- lib/python3.12/site-packages/networkx/algorithms/bipartite/edgelist.pyAdded+360
- lib/python3.12/site-packages/networkx/algorithms/bipartite/extendability.pyAdded+105
- lib/python3.12/site-packages/networkx/algorithms/bipartite/generators.pyAdded+603
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788r"""This module provides functions and operations for bipartitegraphs. Bipartite graphs `B = (U, V, E)` have two node sets `U,V` and edges in`E` that only connect nodes from opposite sets. It is common in the literatureto use an spatial analogy referring to the two node sets as top and bottom nodes.
The bipartite algorithms are not imported into the networkx namespaceat the top level so the easiest way to use them is with:
>>> from networkx.algorithms import bipartite
NetworkX does not have a custom bipartite graph class but the Graph()or DiGraph() classes can be used to represent bipartite graphs. However,you have to keep track of which set each node belongs to, and makesure that there is no edge between nodes of the same set. The convention usedin NetworkX is to use a node attribute named `bipartite` with values 0 or 1 toidentify the sets each node belongs to. This convention is not enforced inthe source code of bipartite functions, it's only a recommendation.
For example:
>>> B = nx.Graph()>>> # Add nodes with the node attribute "bipartite">>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)>>> B.add_nodes_from(["a", "b", "c"], bipartite=1)>>> # Add edges only between nodes of opposite node sets>>> B.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
Many algorithms of the bipartite module of NetworkX require, as an argument, acontainer with all the nodes that belong to one set, in addition to the bipartitegraph `B`. The functions in the bipartite package do not check that the node setis actually correct nor that the input graph is actually bipartite.If `B` is connected, you can find the two node sets using a two-coloringalgorithm:
>>> nx.is_connected(B)True>>> bottom_nodes, top_nodes = bipartite.sets(B)
However, if the input graph is not connected, there are more than one possiblecolorations. This is the reason why we require the user to pass a containerwith all nodes of one bipartite node set as an argument to most bipartitefunctions. In the face of ambiguity, we refuse the temptation to guess andraise an :exc:`AmbiguousSolution <networkx.AmbiguousSolution>`Exception if the input graph for:func:`bipartite.sets <networkx.algorithms.bipartite.basic.sets>`is disconnected.
Using the `bipartite` node attribute, you can easily get the two node sets:
>>> top_nodes = {n for n, d in B.nodes(data=True) if d["bipartite"] == 0}>>> bottom_nodes = set(B) - top_nodes
So you can easily use the bipartite algorithms that require, as an argument, acontainer with all nodes that belong to one node set:
>>> print(round(bipartite.density(B, bottom_nodes), 2))0.5>>> G = bipartite.projected_graph(B, top_nodes)
All bipartite graph generators in NetworkX build bipartite graphs with the`bipartite` node attribute. Thus, you can use the same approach:
>>> RB = bipartite.random_graph(5, 7, 0.2)>>> RB_top = {n for n, d in RB.nodes(data=True) if d["bipartite"] == 0}>>> RB_bottom = set(RB) - RB_top>>> list(RB_top)[0, 1, 2, 3, 4]>>> list(RB_bottom)[5, 6, 7, 8, 9, 10, 11]
For other bipartite graph generators see:mod:`Generators <networkx.algorithms.bipartite.generators>`.
"""
from networkx.algorithms.bipartite.basic import *from networkx.algorithms.bipartite.centrality import *from networkx.algorithms.bipartite.cluster import *from networkx.algorithms.bipartite.covering import *from networkx.algorithms.bipartite.edgelist import *from networkx.algorithms.bipartite.matching import *from networkx.algorithms.bipartite.matrix import *from networkx.algorithms.bipartite.projection import *from networkx.algorithms.bipartite.redundancy import *from networkx.algorithms.bipartite.spectral import *from networkx.algorithms.bipartite.generators import *from networkx.algorithms.bipartite.extendability import *from networkx.algorithms.bipartite.link_analysis import *123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322"""==========================Bipartite Graph Algorithms=========================="""
import networkx as nxfrom networkx.algorithms.components import connected_componentsfrom networkx.exception import AmbiguousSolution
__all__ = [ "is_bipartite", "is_bipartite_node_set", "color", "sets", "density", "degrees",]
@nx._dispatchabledef color(G): """Returns a two-coloring of the graph.
Raises an exception if the graph is not bipartite.
Parameters ---------- G : NetworkX graph
Returns ------- color : dictionary A dictionary keyed by node with a 1 or 0 as data for each node color.
Raises ------ NetworkXError If the graph is not two-colorable.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> c = bipartite.color(G) >>> print(c) {0: 1, 1: 0, 2: 1, 3: 0}
You can use this to set a node attribute indicating the bipartite set:
>>> nx.set_node_attributes(G, c, "bipartite") >>> print(G.nodes[0]["bipartite"]) 1 >>> print(G.nodes[1]["bipartite"]) 0 """ if G.is_directed(): import itertools
def neighbors(v): return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)])
else: neighbors = G.neighbors
color = {} for n in G: # handle disconnected graphs if n in color or len(G[n]) == 0: # skip isolates continue queue = [n] color[n] = 1 # nodes seen with color (1 or 0) while queue: v = queue.pop() c = 1 - color[v] # opposite color of node v for w in neighbors(v): if w in color: if color[w] == color[v]: raise nx.NetworkXError("Graph is not bipartite.") else: color[w] = c queue.append(w) # color isolates with 0 color.update(dict.fromkeys(nx.isolates(G), 0)) return color
@nx._dispatchabledef is_bipartite(G): """Returns True if graph G is bipartite, False if not.
Parameters ---------- G : NetworkX graph
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> print(bipartite.is_bipartite(G)) True
See Also -------- color, is_bipartite_node_set """ try: color(G) return True except nx.NetworkXError: return False
@nx._dispatchabledef is_bipartite_node_set(G, nodes): """Returns True if nodes and G/nodes are a bipartition of G.
Parameters ---------- G : NetworkX graph
nodes: list or container Check if nodes are a one of a bipartite set.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> X = set([1, 3]) >>> bipartite.is_bipartite_node_set(G, X) True
Notes ----- An exception is raised if the input nodes are not distinct, because in this case some bipartite algorithms will yield incorrect results. For connected graphs the bipartite sets are unique. This function handles disconnected graphs. """ S = set(nodes)
if len(S) < len(nodes): # this should maybe just return False? raise AmbiguousSolution( "The input node set contains duplicates.\n" "This may lead to incorrect results when using it in bipartite algorithms.\n" "Consider using set(nodes) as the input" )
for CC in (G.subgraph(c).copy() for c in connected_components(G)): X, Y = sets(CC) if not ( (X.issubset(S) and Y.isdisjoint(S)) or (Y.issubset(S) and X.isdisjoint(S)) ): return False return True
@nx._dispatchabledef sets(G, top_nodes=None): """Returns bipartite node sets of graph G.
Raises an exception if the graph is not bipartite or if the input graph is disconnected and thus more than one valid solution exists. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
Parameters ---------- G : NetworkX graph
top_nodes : container, optional Container with all nodes in one bipartite node set. If not supplied it will be computed. But if more than one solution exists an exception will be raised.
Returns ------- X : set Nodes from one side of the bipartite graph. Y : set Nodes from the other side.
Raises ------ AmbiguousSolution Raised if the input bipartite graph is disconnected and no container with all nodes in one bipartite set is provided. When determining the nodes in each bipartite set more than one valid solution is possible if the input graph is disconnected. NetworkXError Raised if the input graph is not bipartite.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> X, Y = bipartite.sets(G) >>> list(X) [0, 2] >>> list(Y) [1, 3]
See Also -------- color
""" if G.is_directed(): is_connected = nx.is_weakly_connected else: is_connected = nx.is_connected if top_nodes is not None: X = set(top_nodes) Y = set(G) - X else: if not is_connected(G): msg = "Disconnected graph: Ambiguous solution for bipartite sets." raise nx.AmbiguousSolution(msg) c = color(G) X = {n for n, is_top in c.items() if is_top} Y = {n for n, is_top in c.items() if not is_top} return (X, Y)
@nx._dispatchable(graphs="B")def density(B, nodes): """Returns density of bipartite graph B.
Parameters ---------- B : NetworkX graph
nodes: list or container Nodes in one node set of the bipartite graph.
Returns ------- d : float The bipartite density
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.complete_bipartite_graph(3, 2) >>> X = set([0, 1, 2]) >>> bipartite.density(G, X) 1.0 >>> Y = set([3, 4]) >>> bipartite.density(G, Y) 1.0
Notes ----- The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid ambiguity in the case of disconnected graphs. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
See Also -------- color """ n = len(B) m = nx.number_of_edges(B) nb = len(nodes) nt = n - nb if m == 0: # includes cases n==0 and n==1 d = 0.0 else: if B.is_directed(): d = m / (2 * nb * nt) else: d = m / (nb * nt) return d
@nx._dispatchable(graphs="B", edge_attrs="weight")def degrees(B, nodes, weight=None): """Returns the degrees of the two node sets in the bipartite graph B.
Parameters ---------- B : NetworkX graph
nodes: list or container Nodes in one node set of the bipartite graph.
weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns ------- (degX,degY) : tuple of dictionaries The degrees of the two bipartite sets as dictionaries keyed by node.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.complete_bipartite_graph(3, 2) >>> Y = set([3, 4]) >>> degX, degY = bipartite.degrees(G, Y) >>> dict(degX) {0: 2, 1: 2, 2: 2}
Notes ----- The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid ambiguity in the case of disconnected graphs. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
See Also -------- color, density """ bottom = set(nodes) top = set(B) - bottom return (B.degree(top, weight), B.degree(bottom, weight))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290import networkx as nx
__all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"]
@nx._dispatchable(name="bipartite_degree_centrality")def degree_centrality(G, nodes): r"""Compute the degree centrality for nodes in a bipartite network.
The degree centrality for a node `v` is the fraction of nodes connected to it.
Parameters ---------- G : graph A bipartite network
nodes : list or container Container with all nodes in one bipartite node set.
Returns ------- centrality : dictionary Dictionary keyed by node with bipartite degree centrality as the value.
Examples -------- >>> G = nx.wheel_graph(5) >>> top_nodes = {0, 1, 2} >>> nx.bipartite.degree_centrality(G, nodes=top_nodes) {0: 2.0, 1: 1.5, 2: 1.5, 3: 1.0, 4: 1.0}
See Also -------- betweenness_centrality closeness_centrality :func:`~networkx.algorithms.bipartite.basic.sets` :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
Notes ----- The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains all nodes from both bipartite node sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree (which is `n-1` where `n` is the number of nodes in G).
In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in the opposite node set [1]_. The degree centrality for a node `v` in the bipartite sets `U` with `n` nodes and `V` with `m` nodes is
.. math::
d_{v} = \frac{deg(v)}{m}, \mbox{for} v \in U ,
d_{v} = \frac{deg(v)}{n}, \mbox{for} v \in V ,
where `deg(v)` is the degree of node `v`.
References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. https://dx.doi.org/10.4135/9781446294413.n28 """ top = set(nodes) bottom = set(G) - top s = 1.0 / len(bottom) centrality = {n: d * s for n, d in G.degree(top)} s = 1.0 / len(top) centrality.update({n: d * s for n, d in G.degree(bottom)}) return centrality
@nx._dispatchable(name="bipartite_betweenness_centrality")def betweenness_centrality(G, nodes): r"""Compute betweenness centrality for nodes in a bipartite network.
Betweenness centrality of a node `v` is the sum of the fraction of all-pairs shortest paths that pass through `v`.
Values of betweenness are normalized by the maximum possible value which for bipartite graphs is limited by the relative size of the two node sets [1]_.
Let `n` be the number of nodes in the node set `U` and `m` be the number of nodes in the node set `V`, then nodes in `U` are normalized by dividing by
.. math::
\frac{1}{2} [m^2 (s + 1)^2 + m (s + 1)(2t - s - 1) - t (2s - t + 3)] ,
where
.. math::
s = (n - 1) \div m , t = (n - 1) \mod m ,
and nodes in `V` are normalized by dividing by
.. math::
\frac{1}{2} [n^2 (p + 1)^2 + n (p + 1)(2r - p - 1) - r (2p - r + 3)] ,
where,
.. math::
p = (m - 1) \div n , r = (m - 1) \mod n .
Parameters ---------- G : graph A bipartite graph
nodes : list or container Container with all nodes in one bipartite node set.
Returns ------- betweenness : dictionary Dictionary keyed by node with bipartite betweenness centrality as the value.
Examples -------- >>> G = nx.cycle_graph(4) >>> top_nodes = {1, 2} >>> nx.bipartite.betweenness_centrality(G, nodes=top_nodes) {0: 0.25, 1: 0.25, 2: 0.25, 3: 0.25}
See Also -------- degree_centrality closeness_centrality :func:`~networkx.algorithms.bipartite.basic.sets` :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
Notes ----- The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains all nodes from both node sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. https://dx.doi.org/10.4135/9781446294413.n28 """ top = set(nodes) bottom = set(G) - top n = len(top) m = len(bottom) s, t = divmod(n - 1, m) bet_max_top = ( ((m**2) * ((s + 1) ** 2)) + (m * (s + 1) * (2 * t - s - 1)) - (t * ((2 * s) - t + 3)) ) / 2.0 p, r = divmod(m - 1, n) bet_max_bot = ( ((n**2) * ((p + 1) ** 2)) + (n * (p + 1) * (2 * r - p - 1)) - (r * ((2 * p) - r + 3)) ) / 2.0 betweenness = nx.betweenness_centrality(G, normalized=False, weight=None) for node in top: betweenness[node] /= bet_max_top for node in bottom: betweenness[node] /= bet_max_bot return betweenness
@nx._dispatchable(name="bipartite_closeness_centrality")def closeness_centrality(G, nodes, normalized=True): r"""Compute the closeness centrality for nodes in a bipartite network.
The closeness of a node is the distance to all other nodes in the graph or in the case that the graph is not connected to all other nodes in the connected component containing that node.
Parameters ---------- G : graph A bipartite network
nodes : list or container Container with all nodes in one bipartite node set.
normalized : bool, optional If True (default) normalize by connected component size.
Returns ------- closeness : dictionary Dictionary keyed by node with bipartite closeness centrality as the value.
Examples -------- >>> G = nx.wheel_graph(5) >>> top_nodes = {0, 1, 2} >>> nx.bipartite.closeness_centrality(G, nodes=top_nodes) {0: 1.5, 1: 1.2, 2: 1.2, 3: 1.0, 4: 1.0}
See Also -------- betweenness_centrality degree_centrality :func:`~networkx.algorithms.bipartite.basic.sets` :func:`~networkx.algorithms.bipartite.basic.is_bipartite`
Notes ----- The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains all nodes from both node sets. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
Closeness centrality is normalized by the minimum distance possible. In the bipartite case the minimum distance for a node in one bipartite node set is 1 from all nodes in the other node set and 2 from all other nodes in its own set [1]_. Thus the closeness centrality for node `v` in the two bipartite sets `U` with `n` nodes and `V` with `m` nodes is
.. math::
c_{v} = \frac{m + 2(n - 1)}{d}, \mbox{for} v \in U,
c_{v} = \frac{n + 2(m - 1)}{d}, \mbox{for} v \in V,
where `d` is the sum of the distances from `v` to all other nodes.
Higher values of closeness indicate higher centrality.
As in the unipartite case, setting normalized=True causes the values to normalized further to n-1 / size(G)-1 where n is the number of nodes in the connected part of graph containing the node. If the graph is not completely connected, this algorithm computes the closeness centrality for each connected part separately.
References ---------- .. [1] Borgatti, S.P. and Halgin, D. In press. "Analyzing Affiliation Networks". In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications. https://dx.doi.org/10.4135/9781446294413.n28 """ closeness = {} path_length = nx.single_source_shortest_path_length top = set(nodes) bottom = set(G) - top n = len(top) m = len(bottom) for node in top: sp = dict(path_length(G, node)) totsp = sum(sp.values()) if totsp > 0.0 and len(G) > 1: closeness[node] = (m + 2 * (n - 1)) / totsp if normalized: s = (len(sp) - 1) / (len(G) - 1) closeness[node] *= s else: closeness[node] = 0.0 for node in bottom: sp = dict(path_length(G, node)) totsp = sum(sp.values()) if totsp > 0.0 and len(G) > 1: closeness[node] = (n + 2 * (m - 1)) / totsp if normalized: s = (len(sp) - 1) / (len(G) - 1) closeness[node] *= s else: closeness[node] = 0.0 return closeness123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""Functions for computing clustering of pairs"""
import itertools
import networkx as nx
__all__ = [ "clustering", "average_clustering", "latapy_clustering", "robins_alexander_clustering",]
def cc_dot(nu, nv): return len(nu & nv) / len(nu | nv)
def cc_max(nu, nv): return len(nu & nv) / max(len(nu), len(nv))
def cc_min(nu, nv): return len(nu & nv) / min(len(nu), len(nv))
modes = {"dot": cc_dot, "min": cc_min, "max": cc_max}
@nx._dispatchabledef latapy_clustering(G, nodes=None, mode="dot"): r"""Compute a bipartite clustering coefficient for nodes.
The bipartite clustering coefficient is a measure of local density of connections defined as [1]_:
.. math::
c_u = \frac{\sum_{v \in N(N(u))} c_{uv} }{|N(N(u))|}
where `N(N(u))` are the second order neighbors of `u` in `G` excluding `u`, and `c_{uv}` is the pairwise clustering coefficient between nodes `u` and `v`.
The mode selects the function for `c_{uv}` which can be:
`dot`:
.. math::
c_{uv}=\frac{|N(u)\cap N(v)|}{|N(u) \cup N(v)|}
`min`:
.. math::
c_{uv}=\frac{|N(u)\cap N(v)|}{min(|N(u)|,|N(v)|)}
`max`:
.. math::
c_{uv}=\frac{|N(u)\cap N(v)|}{max(|N(u)|,|N(v)|)}
Parameters ---------- G : graph A bipartite graph
nodes : list or iterable (optional) Compute bipartite clustering for these nodes. The default is all nodes in G.
mode : string The pairwise bipartite clustering method to be used in the computation. It must be "dot", "max", or "min".
Returns ------- clustering : dictionary A dictionary keyed by node with the clustering coefficient value.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) # path graphs are bipartite >>> c = bipartite.clustering(G) >>> c[0] 0.5 >>> c = bipartite.clustering(G, mode="min") >>> c[0] 1.0
See Also -------- robins_alexander_clustering average_clustering networkx.algorithms.cluster.square_clustering
References ---------- .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social Networks 30(1), 31--48. """ if not nx.algorithms.bipartite.is_bipartite(G): raise nx.NetworkXError("Graph is not bipartite")
try: cc_func = modes[mode] except KeyError as err: raise nx.NetworkXError( "Mode for bipartite clustering must be: dot, min or max" ) from err
if nodes is None: nodes = G ccs = {} for v in nodes: cc = 0.0 nbrs2 = {u for nbr in G[v] for u in G[nbr]} - {v} for u in nbrs2: cc += cc_func(set(G[u]), set(G[v])) if cc > 0.0: # len(nbrs2)>0 cc /= len(nbrs2) ccs[v] = cc return ccs
clustering = latapy_clustering
@nx._dispatchable(name="bipartite_average_clustering")def average_clustering(G, nodes=None, mode="dot"): r"""Compute the average bipartite clustering coefficient.
A clustering coefficient for the whole graph is the average,
.. math::
C = \frac{1}{n}\sum_{v \in G} c_v,
where `n` is the number of nodes in `G`.
Similar measures for the two bipartite sets can be defined [1]_
.. math::
C_X = \frac{1}{|X|}\sum_{v \in X} c_v,
where `X` is a bipartite set of `G`.
Parameters ---------- G : graph a bipartite graph
nodes : list or iterable, optional A container of nodes to use in computing the average. The nodes should be either the entire graph (the default) or one of the bipartite sets.
mode : string The pairwise bipartite clustering method. It must be "dot", "max", or "min"
Returns ------- clustering : float The average bipartite clustering for the given set of nodes or the entire graph if no nodes are specified.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.star_graph(3) # star graphs are bipartite >>> bipartite.average_clustering(G) 0.75 >>> X, Y = bipartite.sets(G) >>> bipartite.average_clustering(G, X) 0.0 >>> bipartite.average_clustering(G, Y) 1.0
See Also -------- clustering
Notes ----- The container of nodes passed to this function must contain all of the nodes in one of the bipartite sets ("top" or "bottom") in order to compute the correct average bipartite clustering coefficients. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX.
References ---------- .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social Networks 30(1), 31--48. """ if nodes is None: nodes = G ccs = latapy_clustering(G, nodes=nodes, mode=mode) return sum(ccs[v] for v in nodes) / len(nodes)
@nx._dispatchabledef robins_alexander_clustering(G): r"""Compute the bipartite clustering of G.
Robins and Alexander [1]_ defined bipartite clustering coefficient as four times the number of four cycles `C_4` divided by the number of three paths `L_3` in a bipartite graph:
.. math::
CC_4 = \frac{4 * C_4}{L_3}
Parameters ---------- G : graph a bipartite graph
Returns ------- clustering : float The Robins and Alexander bipartite clustering for the input graph.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.davis_southern_women_graph() >>> print(round(bipartite.robins_alexander_clustering(G), 3)) 0.468
See Also -------- latapy_clustering networkx.algorithms.cluster.square_clustering
References ---------- .. [1] Robins, G. and M. Alexander (2004). Small worlds among interlocking directors: Network structure and distance in bipartite graphs. Computational & Mathematical Organization Theory 10(1), 69–94.
""" if G.order() < 4 or G.size() < 3: return 0 L_3 = _threepaths(G) if L_3 == 0: return 0 C_4 = _four_cycles(G) return (4.0 * C_4) / L_3
def _four_cycles(G): # Also see `square_clustering` which counts squares in a similar way cycles = 0 seen = set() G_adj = G._adj for v in G: seen.add(v) v_neighbors = set(G_adj[v]) if len(v_neighbors) < 2: # Can't form a square without at least two neighbors continue two_hop_neighbors = set().union(*(G_adj[u] for u in v_neighbors)) two_hop_neighbors -= seen for x in two_hop_neighbors: p2 = len(v_neighbors.intersection(G_adj[x])) cycles += p2 * (p2 - 1) return cycles / 4
def _threepaths(G): paths = 0 for v in G: for u in G[v]: for w in set(G[u]) - {v}: paths += len(set(G[w]) - {v, u}) # Divide by two because we count each three path twice # one for each possible starting point return paths / 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Functions related to graph covers."""
import networkx as nxfrom networkx.algorithms.bipartite.matching import hopcroft_karp_matchingfrom networkx.algorithms.covering import min_edge_cover as _min_edge_coverfrom networkx.utils import not_implemented_for
__all__ = ["min_edge_cover"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchable(name="bipartite_min_edge_cover")def min_edge_cover(G, matching_algorithm=None): """Returns a set of edges which constitutes the minimum edge cover of the graph.
The smallest edge cover can be found in polynomial time by finding a maximum matching and extending it greedily so that all nodes are covered.
Parameters ---------- G : NetworkX graph An undirected bipartite graph.
matching_algorithm : function A function that returns a maximum cardinality matching in a given bipartite graph. The function must take one input, the graph ``G``, and return a dictionary mapping each node to its mate. If not specified, :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching` will be used. Other possibilities include :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`,
Returns ------- set A set of the edges in a minimum edge cover of the graph, given as pairs of nodes. It contains both the edges `(u, v)` and `(v, u)` for given nodes `u` and `v` among the edges of minimum edge cover.
Notes ----- An edge cover of a graph is a set of edges such that every node of the graph is incident to at least one edge of the set. A minimum edge cover is an edge covering of smallest cardinality.
Due to its implementation, the worst-case running time of this algorithm is bounded by the worst-case running time of the function ``matching_algorithm``. """ if G.order() == 0: # Special case for the empty graph return set() if matching_algorithm is None: matching_algorithm = hopcroft_karp_matching return _min_edge_cover(G, matching_algorithm=matching_algorithm)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360"""********************Bipartite Edge Lists********************Read and write NetworkX graphs as bipartite edge lists.
Format------You can read or write three formats of edge lists with these functions.
Node pairs with no data::
1 2
Python dictionary as data::
1 2 {'weight':7, 'color':'green'}
Arbitrary data::
1 2 7 green
For each edge (u, v) the node u is assigned to part 0 and the node v to part 1."""
__all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"]
import networkx as nxfrom networkx.utils import not_implemented_for, open_file
@open_file(1, mode="wb")def write_edgelist(G, path, comments="#", delimiter=" ", data=True, encoding="utf-8"): """Write a bipartite graph as a list of edges.
Parameters ---------- G : Graph A NetworkX bipartite graph path : file or string File or filename to write. If a file is provided, it must be opened in 'wb' mode. Filenames ending in .gz or .bz2 will be compressed. 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. data : bool or list, optional If False write no edge data. If True write a string representation of the edge data dictionary.. If a list (or other iterable) is provided, write the keys specified in the list. encoding: string, optional Specify which encoding to use when writing file.
Examples -------- >>> G = nx.path_graph(4) >>> G.add_nodes_from([0, 2], bipartite=0) >>> G.add_nodes_from([1, 3], bipartite=1) >>> nx.write_edgelist(G, "test.edgelist") >>> fh = open("test.edgelist_open", "wb") >>> nx.write_edgelist(G, fh) >>> nx.write_edgelist(G, "test.edgelist.gz") >>> nx.write_edgelist(G, "test.edgelist_nodata.gz", data=False)
>>> G = nx.Graph() >>> G.add_edge(1, 2, weight=7, color="red") >>> nx.write_edgelist(G, "test.edgelist_bigger_nodata", data=False) >>> nx.write_edgelist(G, "test.edgelist_color", data=["color"]) >>> nx.write_edgelist(G, "test.edgelist_color_weight", data=["color", "weight"])
See Also -------- write_edgelist generate_edgelist """ for line in generate_edgelist(G, delimiter, data): line += "\n" path.write(line.encode(encoding))
@not_implemented_for("directed")def generate_edgelist(G, delimiter=" ", data=True): """Generate a single line of the bipartite graph G in edge list format.
Parameters ---------- G : NetworkX graph The graph is assumed to have node attribute `part` set to 0,1 representing the two graph parts
delimiter : string, optional Separator for node labels
data : bool or list of keys If False generate no edge data. If True use a dictionary representation of edge data. If a list of keys use a list of data values corresponding to the keys.
Returns ------- lines : string Lines of data in adjlist format.
Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> G.add_nodes_from([0, 2], bipartite=0) >>> G.add_nodes_from([1, 3], bipartite=1) >>> G[1][2]["weight"] = 3 >>> G[2][3]["capacity"] = 12 >>> for line in bipartite.generate_edgelist(G, data=False): ... print(line) 0 1 2 1 2 3
>>> for line in bipartite.generate_edgelist(G): ... print(line) 0 1 {} 2 1 {'weight': 3} 2 3 {'capacity': 12}
>>> for line in bipartite.generate_edgelist(G, data=["weight"]): ... print(line) 0 1 2 1 3 2 3 """ try: part0 = [n for n, d in G.nodes.items() if d["bipartite"] == 0] except BaseException as err: raise AttributeError("Missing node attribute `bipartite`") from err if data is True or data is False: for n in part0: for edge in G.edges(n, data=data): yield delimiter.join(map(str, edge)) else: for n in part0: for u, v, d in G.edges(n, data=True): edge = [u, v] try: edge.extend(d[k] for k in data) except KeyError: pass # missing data for this edge, should warn? yield delimiter.join(map(str, edge))
@nx._dispatchable(name="bipartite_parse_edgelist", graphs=None, returns_graph=True)def parse_edgelist( lines, comments="#", delimiter=None, create_using=None, nodetype=None, data=True): """Parse lines of an edge list representation of a bipartite graph.
Parameters ---------- lines : list or iterator of strings Input data in edgelist format comments : string, optional Marker for comment lines delimiter : string, optional Separator for node labels create_using: NetworkX graph container, optional Use given NetworkX graph for holding nodes or edges. nodetype : Python type, optional Convert nodes to this type. data : bool or list of (label,type) tuples If False generate no edge data or if True use a dictionary representation of edge data or a list tuples specifying dictionary key names and types for edge data.
Returns ------- G: NetworkX Graph The bipartite graph corresponding to lines
Examples -------- Edgelist with no data:
>>> from networkx.algorithms import bipartite >>> lines = ["1 2", "2 3", "3 4"] >>> G = bipartite.parse_edgelist(lines, nodetype=int) >>> sorted(G.nodes()) [1, 2, 3, 4] >>> sorted(G.nodes(data=True)) [(1, {'bipartite': 0}), (2, {'bipartite': 0}), (3, {'bipartite': 0}), (4, {'bipartite': 1})] >>> sorted(G.edges()) [(1, 2), (2, 3), (3, 4)]
Edgelist with data in Python dictionary representation:
>>> lines = ["1 2 {'weight':3}", "2 3 {'weight':27}", "3 4 {'weight':3.0}"] >>> G = bipartite.parse_edgelist(lines, nodetype=int) >>> sorted(G.nodes()) [1, 2, 3, 4] >>> sorted(G.edges(data=True)) [(1, 2, {'weight': 3}), (2, 3, {'weight': 27}), (3, 4, {'weight': 3.0})]
Edgelist with data in a list:
>>> lines = ["1 2 3", "2 3 27", "3 4 3.0"] >>> G = bipartite.parse_edgelist(lines, nodetype=int, data=(("weight", float),)) >>> sorted(G.nodes()) [1, 2, 3, 4] >>> sorted(G.edges(data=True)) [(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
See Also -------- """ from ast import literal_eval
G = nx.empty_graph(0, create_using) for line in lines: p = line.find(comments) if p >= 0: line = line[:p] if not len(line): continue # split line, should have 2 or more s = line.rstrip("\n").split(delimiter) if len(s) < 2: continue u = s.pop(0) v = s.pop(0) d = s if nodetype is not None: try: u = nodetype(u) v = nodetype(v) except BaseException as err: raise TypeError( f"Failed to convert nodes {u},{v} to type {nodetype}." ) from err
if len(d) == 0 or data is False: # no data or data type specified edgedata = {} elif data is True: # no edge types specified try: # try to evaluate as dictionary edgedata = dict(literal_eval(" ".join(d))) except BaseException as err: raise TypeError( f"Failed to convert edge data ({d}) to dictionary." ) from err else: # convert edge data to dictionary with specified keys and type if len(d) != len(data): raise IndexError( f"Edge data {d} and data_keys {data} are not the same length" ) edgedata = {} for (edge_key, edge_type), edge_value in zip(data, d): try: edge_value = edge_type(edge_value) except BaseException as err: raise TypeError( f"Failed to convert {edge_key} data " f"{edge_value} to type {edge_type}." ) from err edgedata.update({edge_key: edge_value}) G.add_node(u, bipartite=0) G.add_node(v, bipartite=1) G.add_edge(u, v, **edgedata) return G
@open_file(0, mode="rb")@nx._dispatchable(name="bipartite_read_edgelist", graphs=None, returns_graph=True)def read_edgelist( path, comments="#", delimiter=None, create_using=None, nodetype=None, data=True, edgetype=None, encoding="utf-8",): """Read a bipartite 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 decompressed. 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 : Graph container, optional, Use specified container to build graph. The default is networkx.Graph, an undirected graph. 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 -------- >>> from networkx.algorithms import bipartite >>> G = nx.path_graph(4) >>> G.add_nodes_from([0, 2], bipartite=0) >>> G.add_nodes_from([1, 3], bipartite=1) >>> bipartite.write_edgelist(G, "test.edgelist") >>> G = bipartite.read_edgelist("test.edgelist")
>>> fh = open("test.edgelist", "rb") >>> G = bipartite.read_edgelist(fh) >>> fh.close()
>>> G = bipartite.read_edgelist("test.edgelist", nodetype=int)
Edgelist with data in a list:
>>> textline = "1 2 3" >>> fh = open("test.edgelist", "w") >>> d = fh.write(textline) >>> fh.close() >>> G = bipartite.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
Notes ----- Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset - or tuples of those, etc.) """ lines = (line.decode(encoding) for line in path) return parse_edgelist( lines, comments=comments, delimiter=delimiter, create_using=create_using, nodetype=nodetype, data=data, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""Provides a function for computing the extendability of a graph which isundirected, simple, connected and bipartite and contains at least one perfect matching."""
import networkx as nxfrom networkx.utils import not_implemented_for
__all__ = ["maximal_extendability"]
@not_implemented_for("directed")@not_implemented_for("multigraph")@nx._dispatchabledef maximal_extendability(G): """Computes the extendability of a graph.
The extendability of a graph is defined as the maximum $k$ for which `G` is $k$-extendable. Graph `G` is $k$-extendable if and only if `G` has a perfect matching and every set of $k$ independent edges can be extended to a perfect matching in `G`.
Parameters ---------- G : NetworkX Graph A fully-connected bipartite graph without self-loops
Returns ------- extendability : int
Raises ------ NetworkXError If the graph `G` is disconnected. If the graph `G` is not bipartite. If the graph `G` does not contain a perfect matching. If the residual graph of `G` is not strongly connected.
Notes ----- Definition: Let `G` be a simple, connected, undirected and bipartite graph with a perfect matching M and bipartition (U,V). The residual graph of `G`, denoted by $G_M$, is the graph obtained from G by directing the edges of M from V to U and the edges that do not belong to M from U to V.
Lemma [1]_ : Let M be a perfect matching of `G`. `G` is $k$-extendable if and only if its residual graph $G_M$ is strongly connected and there are $k$ vertex-disjoint directed paths between every vertex of U and every vertex of V.
Assuming that input graph `G` is undirected, simple, connected, bipartite and contains a perfect matching M, this function constructs the residual graph $G_M$ of G and returns the minimum value among the maximum vertex-disjoint directed paths between every vertex of U and every vertex of V in $G_M$. By combining the definitions and the lemma, this value represents the extendability of the graph `G`.
Time complexity O($n^3$ $m^2$)) where $n$ is the number of vertices and $m$ is the number of edges.
References ---------- .. [1] "A polynomial algorithm for the extendability problem in bipartite graphs", J. Lakhal, L. Litzler, Information Processing Letters, 1998. .. [2] "On n-extendible graphs", M. D. Plummer, Discrete Mathematics, 31:201–210, 1980 https://doi.org/10.1016/0012-365X(80)90037-0
""" if not nx.is_connected(G): raise nx.NetworkXError("Graph G is not connected")
if not nx.bipartite.is_bipartite(G): raise nx.NetworkXError("Graph G is not bipartite")
U, V = nx.bipartite.sets(G)
maximum_matching = nx.bipartite.hopcroft_karp_matching(G)
if not nx.is_perfect_matching(G, maximum_matching): raise nx.NetworkXError("Graph G does not contain a perfect matching")
# list of edges in perfect matching, directed from V to U pm = [(node, maximum_matching[node]) for node in V & maximum_matching.keys()]
# Direct all the edges of G, from V to U if in matching, else from U to V directed_edges = [ (x, y) if (x in V and (x, y) in pm) or (x in U and (y, x) not in pm) else (y, x) for x, y in G.edges ]
# Construct the residual graph of G residual_G = nx.DiGraph() residual_G.add_nodes_from(G) residual_G.add_edges_from(directed_edges)
if not nx.is_strongly_connected(residual_G): raise nx.NetworkXError("The residual graph of G is not strongly connected")
# For node-pairs between V & U, keep min of max number of node-disjoint paths # Variable $k$ stands for the extendability of graph G k = float("inf") for u in U: for v in V: num_paths = sum(1 for _ in nx.node_disjoint_paths(residual_G, u, v)) k = k if k < num_paths else num_paths return k123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603"""Generators and functions for bipartite graphs."""
import mathimport numbersfrom functools import reduce
import networkx as nxfrom networkx.utils import nodes_or_number, py_random_state
__all__ = [ "configuration_model", "havel_hakimi_graph", "reverse_havel_hakimi_graph", "alternating_havel_hakimi_graph", "preferential_attachment_graph", "random_graph", "gnmk_random_graph", "complete_bipartite_graph",]
@nx._dispatchable(graphs=None, returns_graph=True)@nodes_or_number([0, 1])def complete_bipartite_graph(n1, n2, create_using=None): """Returns the complete bipartite graph `K_{n_1,n_2}`.
The graph is composed of two partitions with nodes 0 to (n1 - 1) in the first and nodes n1 to (n1 + n2 - 1) in the second. Each node in the first is connected to each node in the second.
Parameters ---------- n1, n2 : integer or iterable container of nodes If integers, nodes are from `range(n1)` and `range(n1, n1 + n2)`. If a container, the elements are the nodes. create_using : NetworkX graph instance, (default: nx.Graph) Return graph of this type.
Notes ----- Nodes are the integers 0 to `n1 + n2 - 1` unless either n1 or n2 are containers of nodes. If only one of n1 or n2 are integers, that integer is replaced by `range` of that integer.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.complete_bipartite_graph """ G = nx.empty_graph(0, create_using) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported")
n1, top = n1 n2, bottom = n2 if isinstance(n1, numbers.Integral) and isinstance(n2, numbers.Integral): bottom = [n1 + i for i in bottom] G.add_nodes_from(top, bipartite=0) G.add_nodes_from(bottom, bipartite=1) if len(G) != len(top) + len(bottom): raise nx.NetworkXError("Inputs n1 and n2 must contain distinct nodes") G.add_edges_from((u, v) for u in top for v in bottom) G.graph["name"] = f"complete_bipartite_graph({len(top)}, {len(bottom)})" return G
@py_random_state(3)@nx._dispatchable(name="bipartite_configuration_model", graphs=None, returns_graph=True)def configuration_model(aseq, bseq, create_using=None, seed=None): """Returns a random bipartite graph from two given degree sequences.
Parameters ---------- aseq : list Degree sequence for node set A. bseq : list Degree sequence for node set B. create_using : NetworkX graph instance, optional Return graph of this type. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1). Nodes from set A are connected to nodes in set B by choosing randomly from the possible free stubs, one in A and one in B.
Notes ----- The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting degree sequences might not be exact.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.configuration_model """ G = nx.empty_graph(0, create_using, default=nx.MultiGraph) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported")
# length and sum of each sequence lena = len(aseq) lenb = len(bseq) suma = sum(aseq) sumb = sum(bseq)
if not suma == sumb: raise nx.NetworkXError( f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}" )
G = _add_nodes_with_bipartite_label(G, lena, lenb)
if len(aseq) == 0 or max(aseq) == 0: return G # done if no edges
# build lists of degree-repeated vertex numbers stubs = [[v] * aseq[v] for v in range(lena)] astubs = [x for subseq in stubs for x in subseq]
stubs = [[v] * bseq[v - lena] for v in range(lena, lena + lenb)] bstubs = [x for subseq in stubs for x in subseq]
# shuffle lists seed.shuffle(astubs) seed.shuffle(bstubs)
G.add_edges_from([astubs[i], bstubs[i]] for i in range(suma))
G.name = "bipartite_configuration_model" return G
@nx._dispatchable(name="bipartite_havel_hakimi_graph", graphs=None, returns_graph=True)def havel_hakimi_graph(aseq, bseq, create_using=None): """Returns a bipartite graph from two given degree sequences using a Havel-Hakimi style construction.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1). Nodes from the set A are connected to nodes in the set B by connecting the highest degree nodes in set A to the highest degree nodes in set B until all stubs are connected.
Parameters ---------- aseq : list Degree sequence for node set A. bseq : list Degree sequence for node set B. create_using : NetworkX graph instance, optional Return graph of this type.
Notes ----- The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting degree sequences might not be exact.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.havel_hakimi_graph """ G = nx.empty_graph(0, create_using, default=nx.MultiGraph) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported")
# length of the each sequence naseq = len(aseq) nbseq = len(bseq)
suma = sum(aseq) sumb = sum(bseq)
if not suma == sumb: raise nx.NetworkXError( f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}" )
G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
if len(aseq) == 0 or max(aseq) == 0: return G # done if no edges
# build list of degree-repeated vertex numbers astubs = [[aseq[v], v] for v in range(naseq)] bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)] astubs.sort() while astubs: (degree, u) = astubs.pop() # take of largest degree node in the a set if degree == 0: break # done, all are zero # connect the source to largest degree nodes in the b set bstubs.sort() for target in bstubs[-degree:]: v = target[1] G.add_edge(u, v) target[0] -= 1 # note this updates bstubs too. if target[0] == 0: bstubs.remove(target)
G.name = "bipartite_havel_hakimi_graph" return G
@nx._dispatchable(graphs=None, returns_graph=True)def reverse_havel_hakimi_graph(aseq, bseq, create_using=None): """Returns a bipartite graph from two given degree sequences using a Havel-Hakimi style construction.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1). Nodes from set A are connected to nodes in the set B by connecting the highest degree nodes in set A to the lowest degree nodes in set B until all stubs are connected.
Parameters ---------- aseq : list Degree sequence for node set A. bseq : list Degree sequence for node set B. create_using : NetworkX graph instance, optional Return graph of this type.
Notes ----- The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting degree sequences might not be exact.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.reverse_havel_hakimi_graph """ G = nx.empty_graph(0, create_using, default=nx.MultiGraph) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported")
# length of the each sequence lena = len(aseq) lenb = len(bseq) suma = sum(aseq) sumb = sum(bseq)
if not suma == sumb: raise nx.NetworkXError( f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}" )
G = _add_nodes_with_bipartite_label(G, lena, lenb)
if len(aseq) == 0 or max(aseq) == 0: return G # done if no edges
# build list of degree-repeated vertex numbers astubs = [[aseq[v], v] for v in range(lena)] bstubs = [[bseq[v - lena], v] for v in range(lena, lena + lenb)] astubs.sort() bstubs.sort() while astubs: (degree, u) = astubs.pop() # take of largest degree node in the a set if degree == 0: break # done, all are zero # connect the source to the smallest degree nodes in the b set for target in bstubs[0:degree]: v = target[1] G.add_edge(u, v) target[0] -= 1 # note this updates bstubs too. if target[0] == 0: bstubs.remove(target)
G.name = "bipartite_reverse_havel_hakimi_graph" return G
@nx._dispatchable(graphs=None, returns_graph=True)def alternating_havel_hakimi_graph(aseq, bseq, create_using=None): """Returns a bipartite graph from two given degree sequences using an alternating Havel-Hakimi style construction.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes len(aseq) to (len(bseq) - 1). Nodes from the set A are connected to nodes in the set B by connecting the highest degree nodes in set A to alternatively the highest and the lowest degree nodes in set B until all stubs are connected.
Parameters ---------- aseq : list Degree sequence for node set A. bseq : list Degree sequence for node set B. create_using : NetworkX graph instance, optional Return graph of this type.
Notes ----- The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting degree sequences might not be exact.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.alternating_havel_hakimi_graph """ G = nx.empty_graph(0, create_using, default=nx.MultiGraph) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported")
# length of the each sequence naseq = len(aseq) nbseq = len(bseq) suma = sum(aseq) sumb = sum(bseq)
if not suma == sumb: raise nx.NetworkXError( f"invalid degree sequences, sum(aseq)!=sum(bseq),{suma},{sumb}" )
G = _add_nodes_with_bipartite_label(G, naseq, nbseq)
if len(aseq) == 0 or max(aseq) == 0: return G # done if no edges # build list of degree-repeated vertex numbers astubs = [[aseq[v], v] for v in range(naseq)] bstubs = [[bseq[v - naseq], v] for v in range(naseq, naseq + nbseq)] while astubs: astubs.sort() (degree, u) = astubs.pop() # take of largest degree node in the a set if degree == 0: break # done, all are zero bstubs.sort() small = bstubs[0 : degree // 2] # add these low degree targets large = bstubs[(-degree + degree // 2) :] # now high degree targets stubs = [x for z in zip(large, small) for x in z] # combine, sorry if len(stubs) < len(small) + len(large): # check for zip truncation stubs.append(large.pop()) for target in stubs: v = target[1] G.add_edge(u, v) target[0] -= 1 # note this updates bstubs too. if target[0] == 0: bstubs.remove(target)
G.name = "bipartite_alternating_havel_hakimi_graph" return G
@py_random_state(3)@nx._dispatchable(graphs=None, returns_graph=True)def preferential_attachment_graph(aseq, p, create_using=None, seed=None): """Create a bipartite graph with a preferential attachment model from a given single degree sequence.
The graph is composed of two partitions. Set A has nodes 0 to (len(aseq) - 1) and set B has nodes starting with node len(aseq). The number of nodes in set B is random.
Parameters ---------- aseq : list Degree sequence for node set A. p : float Probability that a new bottom node is added. create_using : NetworkX graph instance, optional Return graph of this type. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`.
References ---------- .. [1] Guillaume, J.L. and Latapy, M., Bipartite graphs as models of complex networks. Physica A: Statistical Mechanics and its Applications, 2006, 371(2), pp.795-813. .. [2] Jean-Loup Guillaume and Matthieu Latapy, Bipartite structure of all complex networks, Inf. Process. Lett. 90, 2004, pg. 215-221 https://doi.org/10.1016/j.ipl.2004.03.007
Notes ----- The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.preferential_attachment_graph """ G = nx.empty_graph(0, create_using, default=nx.MultiGraph) if G.is_directed(): raise nx.NetworkXError("Directed Graph not supported")
if p > 1: raise nx.NetworkXError(f"probability {p} > 1")
naseq = len(aseq) G = _add_nodes_with_bipartite_label(G, naseq, 0) vv = [[v] * aseq[v] for v in range(naseq)] while vv: while vv[0]: source = vv[0][0] vv[0].remove(source) if seed.random() < p or len(G) == naseq: target = len(G) G.add_node(target, bipartite=1) G.add_edge(source, target) else: bb = [[b] * G.degree(b) for b in range(naseq, len(G))] # flatten the list of lists into a list. bbstubs = reduce(lambda x, y: x + y, bb) # choose preferentially a bottom node. target = seed.choice(bbstubs) G.add_node(target, bipartite=1) G.add_edge(source, target) vv.remove(vv[0]) G.name = "bipartite_preferential_attachment_model" return G
@py_random_state(3)@nx._dispatchable(graphs=None, returns_graph=True)def random_graph(n, m, p, seed=None, directed=False): """Returns a bipartite random graph.
This is a bipartite version of the binomial (Erdős-Rényi) graph. The graph is composed of two partitions. Set A has nodes 0 to (n - 1) and set B has nodes n to (n + m - 1).
Parameters ---------- n : int The number of nodes in the first bipartite set. m : int The number of nodes in the second bipartite set. p : float Probability for edge creation. seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : bool, optional (default=False) If True return a directed graph
Notes ----- The bipartite random graph algorithm chooses each of the n*m (undirected) or 2*nm (directed) possible edges with probability p.
This algorithm is $O(n+m)$ where $m$ is the expected number of edges.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.random_graph
See Also -------- gnp_random_graph, configuration_model
References ---------- .. [1] Vladimir Batagelj and Ulrik Brandes, "Efficient generation of large random networks", Phys. Rev. E, 71, 036113, 2005. """ G = nx.Graph() G = _add_nodes_with_bipartite_label(G, n, m) if directed: G = nx.DiGraph(G) G.name = f"fast_gnp_random_graph({n},{m},{p})"
if p <= 0: return G if p >= 1: return nx.complete_bipartite_graph(n, m)
lp = math.log(1.0 - p)
v = 0 w = -1 while v < n: lr = math.log(1.0 - seed.random()) w = w + 1 + int(lr / lp) while w >= m and v < n: w = w - m v = v + 1 if v < n: G.add_edge(v, n + w)
if directed: # use the same algorithm to # add edges from the "m" to "n" set v = 0 w = -1 while v < n: lr = math.log(1.0 - seed.random()) w = w + 1 + int(lr / lp) while w >= m and v < n: w = w - m v = v + 1 if v < n: G.add_edge(n + w, v)
return G
@py_random_state(3)@nx._dispatchable(graphs=None, returns_graph=True)def gnmk_random_graph(n, m, k, seed=None, directed=False): """Returns a random bipartite graph G_{n,m,k}.
Produces a bipartite graph chosen randomly out of the set of all graphs with n top nodes, m bottom nodes, and k edges. The graph is composed of two sets of nodes. Set A has nodes 0 to (n - 1) and set B has nodes n to (n + m - 1).
Parameters ---------- n : int The number of nodes in the first bipartite set. m : int The number of nodes in the second bipartite set. k : int The number of edges seed : integer, random_state, or None (default) Indicator of random number generation state. See :ref:`Randomness<randomness>`. directed : bool, optional (default=False) If True return a directed graph
Examples -------- >>> G = nx.bipartite.gnmk_random_graph(10, 20, 50)
See Also -------- gnm_random_graph
Notes ----- If k > m * n then a complete bipartite graph is returned.
This graph is a bipartite version of the `G_{nm}` random graph model.
The nodes are assigned the attribute 'bipartite' with the value 0 or 1 to indicate which bipartite set the node belongs to.
This function is not imported in the main namespace. To use it use nx.bipartite.gnmk_random_graph """ G = nx.Graph() G = _add_nodes_with_bipartite_label(G, n, m) if directed: G = nx.DiGraph(G) G.name = f"bipartite_gnm_random_graph({n},{m},{k})" if n == 1 or m == 1: return G max_edges = n * m # max_edges for bipartite networks if k >= max_edges: # Maybe we should raise an exception here return nx.complete_bipartite_graph(n, m, create_using=G)
top = [n for n, d in G.nodes(data=True) if d["bipartite"] == 0] bottom = list(set(G) - set(top)) edge_count = 0 while edge_count < k: # generate random edge,u,v u = seed.choice(top) v = seed.choice(bottom) if v in G[u]: continue else: G.add_edge(u, v) edge_count += 1 return G
def _add_nodes_with_bipartite_label(G, lena, lenb): G.add_nodes_from(range(lena + lenb)) b = dict(zip(range(lena), [0] * lena)) b.update(dict(zip(range(lena, lena + lenb), [1] * lenb))) nx.set_node_attributes(G, b, "bipartite") return Glib/python3.12/site-packages/networkx/algorithms/__pycache__/bridges.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/broadcasting.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/chains.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/chordal.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/clique.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/cluster.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/communicability_alg.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/covering.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/d_separation.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/efficiency_measures.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/hybrid.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/isolate.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/link_prediction.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/moral.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/node_classification.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/non_randomness.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/perfect_graph.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/planar_drawing.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/polynomials.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/regular.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/richclub.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/similarity.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/smetric.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/structuralholes.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/triads.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/voronoi.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/walks.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/__pycache__/wiener.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__init__.pyAdded+88
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/__init__.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/basic.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/centrality.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/cluster.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/covering.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/edgelist.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/extendability.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/generators.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/link_analysis.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/matching.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/matrix.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/projection.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/redundancy.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/__pycache__/spectral.cpython-312.pycAdded
lib/python3.12/site-packages/networkx/algorithms/bipartite/basic.pyAdded+322
lib/python3.12/site-packages/networkx/algorithms/bipartite/centrality.pyAdded+290
lib/python3.12/site-packages/networkx/algorithms/bipartite/cluster.pyAdded+289
lib/python3.12/site-packages/networkx/algorithms/bipartite/covering.pyAdded+57
lib/python3.12/site-packages/networkx/algorithms/bipartite/edgelist.pyAdded+360
lib/python3.12/site-packages/networkx/algorithms/bipartite/extendability.pyAdded+105
lib/python3.12/site-packages/networkx/algorithms/bipartite/generators.pyAdded+603