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
⌀ |
---|---|---|---|---|---|
30,930 | networkx.drawing.layout | multipartite_layout | Position nodes in layers of straight lines.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G.
subset_key : string or dict (default='subset')
If a string, the key of node data in G that holds the node subset.
If a dict, keyed by layer number to the nodes in that layer/subset.
align : string (default='vertical')
The alignment of nodes. Vertical or horizontal.
scale : number (default: 1)
Scale factor for positions.
center : array-like or None
Coordinate pair around which to center the layout.
Returns
-------
pos : dict
A dictionary of positions keyed by node.
Examples
--------
>>> G = nx.complete_multipartite_graph(28, 16, 10)
>>> pos = nx.multipartite_layout(G)
or use a dict to provide the layers of the layout
>>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
>>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
>>> pos = nx.multipartite_layout(G, subset_key=layers)
Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.
Network does not need to be a complete multipartite graph. As long as nodes
have subset_key data, they will be placed in the corresponding layers.
| def multipartite_layout(G, subset_key="subset", align="vertical", scale=1, center=None):
"""Position nodes in layers of straight lines.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G.
subset_key : string or dict (default='subset')
If a string, the key of node data in G that holds the node subset.
If a dict, keyed by layer number to the nodes in that layer/subset.
align : string (default='vertical')
The alignment of nodes. Vertical or horizontal.
scale : number (default: 1)
Scale factor for positions.
center : array-like or None
Coordinate pair around which to center the layout.
Returns
-------
pos : dict
A dictionary of positions keyed by node.
Examples
--------
>>> G = nx.complete_multipartite_graph(28, 16, 10)
>>> pos = nx.multipartite_layout(G)
or use a dict to provide the layers of the layout
>>> G = nx.Graph([(0, 1), (1, 2), (1, 3), (3, 4)])
>>> layers = {"a": [0], "b": [1], "c": [2, 3], "d": [4]}
>>> pos = nx.multipartite_layout(G, subset_key=layers)
Notes
-----
This algorithm currently only works in two dimensions and does not
try to minimize edge crossings.
Network does not need to be a complete multipartite graph. As long as nodes
have subset_key data, they will be placed in the corresponding layers.
"""
import numpy as np
if align not in ("vertical", "horizontal"):
msg = "align must be either vertical or horizontal."
raise ValueError(msg)
G, center = _process_params(G, center=center, dim=2)
if len(G) == 0:
return {}
try:
# check if subset_key is dict-like
if len(G) != sum(len(nodes) for nodes in subset_key.values()):
raise nx.NetworkXError(
"all nodes must be in one subset of `subset_key` dict"
)
except AttributeError:
# subset_key is not a dict, hence a string
node_to_subset = nx.get_node_attributes(G, subset_key)
if len(node_to_subset) != len(G):
raise nx.NetworkXError(
f"all nodes need a subset_key attribute: {subset_key}"
)
subset_key = nx.utils.groups(node_to_subset)
# Sort by layer, if possible
try:
layers = dict(sorted(subset_key.items()))
except TypeError:
layers = subset_key
pos = None
nodes = []
width = len(layers)
for i, layer in enumerate(layers.values()):
height = len(layer)
xs = np.repeat(i, height)
ys = np.arange(0, height, dtype=float)
offset = ((width - 1) / 2, (height - 1) / 2)
layer_pos = np.column_stack([xs, ys]) - offset
if pos is None:
pos = layer_pos
else:
pos = np.concatenate([pos, layer_pos])
nodes.extend(layer)
pos = rescale_layout(pos, scale=scale) + center
if align == "horizontal":
pos = pos[:, ::-1] # swap x and y coords
pos = dict(zip(nodes, pos))
return pos
| (G, subset_key='subset', align='vertical', scale=1, center=None) |
30,932 | networkx.generators.mycielski | mycielski_graph | Generator for the n_th Mycielski Graph.
The Mycielski family of graphs is an infinite set of graphs.
:math:`M_1` is the singleton graph, :math:`M_2` is two vertices with an
edge, and, for :math:`i > 2`, :math:`M_i` is the Mycielskian of
:math:`M_{i-1}`.
More information can be found at
http://mathworld.wolfram.com/MycielskiGraph.html
Parameters
----------
n : int
The desired Mycielski Graph.
Returns
-------
M : graph
The n_th Mycielski Graph
Notes
-----
The first graph in the Mycielski sequence is the singleton graph.
The Mycielskian of this graph is not the :math:`P_2` graph, but rather the
:math:`P_2` graph with an extra, isolated vertex. The second Mycielski
graph is the :math:`P_2` graph, so the first two are hard coded.
The remaining graphs are generated using the Mycielski operation.
| null | (n, *, backend=None, **backend_kwargs) |
30,933 | networkx.generators.mycielski | mycielskian | Returns the Mycielskian of a simple, undirected graph G
The Mycielskian of graph preserves a graph's triangle free
property while increasing the chromatic number by 1.
The Mycielski Operation on a graph, :math:`G=(V, E)`, constructs a new
graph with :math:`2|V| + 1` nodes and :math:`3|E| + |V|` edges.
The construction is as follows:
Let :math:`V = {0, ..., n-1}`. Construct another vertex set
:math:`U = {n, ..., 2n}` and a vertex, `w`.
Construct a new graph, `M`, with vertices :math:`U \bigcup V \bigcup w`.
For edges, :math:`(u, v) \in E` add edges :math:`(u, v), (u, v + n)`, and
:math:`(u + n, v)` to M. Finally, for all vertices :math:`u \in U`, add
edge :math:`(u, w)` to M.
The Mycielski Operation can be done multiple times by repeating the above
process iteratively.
More information can be found at https://en.wikipedia.org/wiki/Mycielskian
Parameters
----------
G : graph
A simple, undirected NetworkX graph
iterations : int
The number of iterations of the Mycielski operation to
perform on G. Defaults to 1. Must be a non-negative integer.
Returns
-------
M : graph
The Mycielskian of G after the specified number of iterations.
Notes
-----
Graph, node, and edge data are not necessarily propagated to the new graph.
| null | (G, iterations=1, *, backend=None, **backend_kwargs) |
30,934 | networkx.generators.geometric | navigable_small_world_graph | Returns a navigable small-world graph.
A navigable small-world graph is a directed grid with additional long-range
connections that are chosen randomly.
[...] we begin with a set of nodes [...] that are identified with the set
of lattice points in an $n \times n$ square,
$\{(i, j): i \in \{1, 2, \ldots, n\}, j \in \{1, 2, \ldots, n\}\}$,
and we define the *lattice distance* between two nodes $(i, j)$ and
$(k, l)$ to be the number of "lattice steps" separating them:
$d((i, j), (k, l)) = |k - i| + |l - j|$.
For a universal constant $p >= 1$, the node $u$ has a directed edge to
every other node within lattice distance $p$---these are its *local
contacts*. For universal constants $q >= 0$ and $r >= 0$ we also
construct directed edges from $u$ to $q$ other nodes (the *long-range
contacts*) using independent random trials; the $i$th directed edge from
$u$ has endpoint $v$ with probability proportional to $[d(u,v)]^{-r}$.
-- [1]_
Parameters
----------
n : int
The length of one side of the lattice; the number of nodes in
the graph is therefore $n^2$.
p : int
The diameter of short range connections. Each node is joined with every
other node within this lattice distance.
q : int
The number of long-range connections for each node.
r : float
Exponent for decaying probability of connections. The probability of
connecting to a node at lattice distance $d$ is $1/d^r$.
dim : int
Dimension of grid
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
References
----------
.. [1] J. Kleinberg. The small-world phenomenon: An algorithmic
perspective. Proc. 32nd ACM Symposium on Theory of Computing, 2000.
| 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, p=1, q=1, r=2, dim=2, seed=None, *, backend=None, **backend_kwargs) |
30,935 | networkx.algorithms.shortest_paths.weighted | negative_edge_cycle | Returns True if there exists a negative edge cycle anywhere in G.
Parameters
----------
G : NetworkX graph
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.
heuristic : bool
Determines whether to use a heuristic to early detect negative
cycles at a negligible cost. In case of graphs with a negative cycle,
the performance of detection increases by at least an order of magnitude.
Returns
-------
negative_cycle : bool
True if a negative edge cycle exists, otherwise False.
Examples
--------
>>> G = nx.cycle_graph(5, create_using=nx.DiGraph())
>>> print(nx.negative_edge_cycle(G))
False
>>> G[1][2]["weight"] = -7
>>> print(nx.negative_edge_cycle(G))
True
Notes
-----
Edge weight attributes must be numerical.
Distances are calculated as sums of weighted edges traversed.
This algorithm uses bellman_ford_predecessor_and_distance() but finds
negative cycles on any component by first adding a new node connected to
every node, and starting bellman_ford_predecessor_and_distance on that
node. It then removes that extra node.
| 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, weight='weight', heuristic=True, *, backend=None, **backend_kwargs) |
30,937 | networkx.classes.function | neighbors | Returns an iterator over all neighbors of node n.
This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
| def neighbors(G, n):
"""Returns an iterator over all neighbors of node n.
This function wraps the :func:`G.neighbors <networkx.Graph.neighbors>` function.
"""
return G.neighbors(n)
| (G, n) |
30,938 | networkx.algorithms.flow.networksimplex | network_simplex | Find a minimum cost flow satisfying all demands in digraph G.
This is a primal network simplex algorithm that uses the leaving
arc rule to prevent cycling.
G is a digraph with edge costs and capacities and in which nodes
have demand, i.e., they want to send or receive some amount of
flow. A negative demand means that the node wants to send flow, a
positive demand means that the node want to receive flow. A flow on
the digraph G satisfies all demand if the net flow into each node
is equal to the demand of that node.
Parameters
----------
G : NetworkX graph
DiGraph on which a minimum cost flow satisfying all demands is
to be found.
demand : string
Nodes of the graph G are expected to have an attribute demand
that indicates how much flow a node wants to send (negative
demand) or receive (positive demand). Note that the sum of the
demands should be 0 otherwise the problem in not feasible. If
this attribute is not present, a node is considered to have 0
demand. Default value: 'demand'.
capacity : string
Edges of the graph G are expected to have an attribute capacity
that indicates how much flow the edge can support. If this
attribute is not present, the edge is considered to have
infinite capacity. Default value: 'capacity'.
weight : string
Edges of the graph G are expected to have an attribute weight
that indicates the cost incurred by sending one unit of flow on
that edge. If not present, the weight is considered to be 0.
Default value: 'weight'.
Returns
-------
flowCost : integer, float
Cost of a minimum cost flow satisfying all demands.
flowDict : dictionary
Dictionary of dictionaries keyed by nodes such that
flowDict[u][v] is the flow edge (u, v).
Raises
------
NetworkXError
This exception is raised if the input graph is not directed or
not connected.
NetworkXUnfeasible
This exception is raised in the following situations:
* The sum of the demands is not zero. Then, there is no
flow satisfying all demands.
* There is no flow satisfying all demand.
NetworkXUnbounded
This exception is raised if the digraph G has a cycle of
negative cost and infinite capacity. Then, the cost of a flow
satisfying all demands is unbounded below.
Notes
-----
This algorithm is not guaranteed to work if edge weights or demands
are floating point numbers (overflows and roundoff errors can
cause problems). As a workaround you can use integer numbers by
multiplying the relevant edge attributes by a convenient
constant factor (eg 100).
See also
--------
cost_of_flow, max_flow_min_cost, min_cost_flow, min_cost_flow_cost
Examples
--------
A simple example of a min cost flow problem.
>>> G = nx.DiGraph()
>>> G.add_node("a", demand=-5)
>>> G.add_node("d", demand=5)
>>> G.add_edge("a", "b", weight=3, capacity=4)
>>> G.add_edge("a", "c", weight=6, capacity=10)
>>> G.add_edge("b", "d", weight=1, capacity=9)
>>> G.add_edge("c", "d", weight=2, capacity=5)
>>> flowCost, flowDict = nx.network_simplex(G)
>>> flowCost
24
>>> flowDict
{'a': {'b': 4, 'c': 1}, 'd': {}, 'b': {'d': 4}, 'c': {'d': 1}}
The mincost flow algorithm can also be used to solve shortest path
problems. To find the shortest path between two nodes u and v,
give all edges an infinite capacity, give node u a demand of -1 and
node v a demand a 1. Then run the network simplex. The value of a
min cost flow will be the distance between u and v and edges
carrying positive flow will indicate the path.
>>> G = nx.DiGraph()
>>> G.add_weighted_edges_from(
... [
... ("s", "u", 10),
... ("s", "x", 5),
... ("u", "v", 1),
... ("u", "x", 2),
... ("v", "y", 1),
... ("x", "u", 3),
... ("x", "v", 5),
... ("x", "y", 2),
... ("y", "s", 7),
... ("y", "v", 6),
... ]
... )
>>> G.add_node("s", demand=-1)
>>> G.add_node("v", demand=1)
>>> flowCost, flowDict = nx.network_simplex(G)
>>> flowCost == nx.shortest_path_length(G, "s", "v", weight="weight")
True
>>> sorted([(u, v) for u in flowDict for v in flowDict[u] if flowDict[u][v] > 0])
[('s', 'x'), ('u', 'v'), ('x', 'u')]
>>> nx.shortest_path(G, "s", "v", weight="weight")
['s', 'x', 'u', 'v']
It is possible to change the name of the attributes used for the
algorithm.
>>> G = nx.DiGraph()
>>> G.add_node("p", spam=-4)
>>> G.add_node("q", spam=2)
>>> G.add_node("a", spam=-2)
>>> G.add_node("d", spam=-1)
>>> G.add_node("t", spam=2)
>>> G.add_node("w", spam=3)
>>> G.add_edge("p", "q", cost=7, vacancies=5)
>>> G.add_edge("p", "a", cost=1, vacancies=4)
>>> G.add_edge("q", "d", cost=2, vacancies=3)
>>> G.add_edge("t", "q", cost=1, vacancies=2)
>>> G.add_edge("a", "t", cost=2, vacancies=4)
>>> G.add_edge("d", "w", cost=3, vacancies=4)
>>> G.add_edge("t", "w", cost=4, vacancies=1)
>>> flowCost, flowDict = nx.network_simplex(
... G, demand="spam", capacity="vacancies", weight="cost"
... )
>>> flowCost
37
>>> flowDict
{'p': {'q': 2, 'a': 2}, 'q': {'d': 1}, 'a': {'t': 4}, 'd': {'w': 2}, 't': {'q': 1, 'w': 1}, 'w': {}}
References
----------
.. [1] Z. Kiraly, P. Kovacs.
Efficient implementation of minimum-cost flow algorithms.
Acta Universitatis Sapientiae, Informatica 4(1):67--118. 2012.
.. [2] R. Barr, F. Glover, D. Klingman.
Enhancement of spanning tree labeling procedures for network
optimization.
INFOR 17(1):16--34. 1979.
| null | (G, demand='demand', capacity='capacity', weight='weight', *, backend=None, **backend_kwargs) |
30,939 | networkx.generators.random_graphs | newman_watts_strogatz_graph | Returns a Newman–Watts–Strogatz small-world graph.
Parameters
----------
n : int
The number of nodes.
k : int
Each node is joined with its `k` nearest neighbors in a ring
topology.
p : float
The probability of adding a new edge for each edge.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Notes
-----
First create a ring over $n$ nodes [1]_. Then each node in the ring is
connected with its $k$ nearest neighbors (or $k - 1$ neighbors if $k$
is odd). Then shortcuts are created by adding new edges as follows: for
each edge $(u, v)$ in the underlying "$n$-ring with $k$ nearest
neighbors" with probability $p$ add a new edge $(u, w)$ with
randomly-chosen existing node $w$. In contrast with
:func:`watts_strogatz_graph`, no edges are removed.
See Also
--------
watts_strogatz_graph
References
----------
.. [1] M. E. J. Newman and D. J. Watts,
Renormalization group analysis of the small-world network model,
Physics Letters A, 263, 341, 1999.
https://doi.org/10.1016/S0375-9601(99)00757-4
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (n, k, p, seed=None, *, backend=None, **backend_kwargs) |
30,940 | networkx.algorithms.assortativity.pairs | node_attribute_xy | Returns iterator of node-attribute pairs for all edges in G.
Parameters
----------
G: NetworkX graph
attribute: key
The node attribute key.
nodes: list or iterable (optional)
Use only edges that are incident to specified nodes.
The default is all nodes.
Returns
-------
(x, y): 2-tuple
Generates 2-tuple of (attribute, attribute) values.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_node(1, color="red")
>>> G.add_node(2, color="blue")
>>> G.add_edge(1, 2)
>>> list(nx.node_attribute_xy(G, "color"))
[('red', 'blue')]
Notes
-----
For undirected graphs each edge is produced twice, once for each edge
representation (u, v) and (v, u), with the exception of self-loop edges
which only appear once.
| null | (G, attribute, nodes=None, *, backend=None, **backend_kwargs) |
30,941 | networkx.algorithms.boundary | node_boundary | Returns the node boundary of `nbunch1`.
The *node boundary* of a set *S* with respect to a set *T* is the
set of nodes *v* in *T* such that for some *u* in *S*, there is an
edge joining *u* to *v*. If *T* is not specified, it is assumed to
be the set of all nodes not in *S*.
Parameters
----------
G : NetworkX graph
nbunch1 : iterable
Iterable of nodes in the graph representing the set of nodes
whose node boundary will be returned. (This is the set *S* from
the definition above.)
nbunch2 : iterable
Iterable of nodes representing the target (or "exterior") set of
nodes. (This is the set *T* from the definition above.) If not
specified, this is assumed to be the set of all nodes in `G`
not in `nbunch1`.
Returns
-------
set
The node boundary of `nbunch1` with respect to `nbunch2`.
Examples
--------
>>> G = nx.wheel_graph(6)
When nbunch2=None:
>>> list(nx.node_boundary(G, (3, 4)))
[0, 2, 5]
When nbunch2 is given:
>>> list(nx.node_boundary(G, (3, 4), (0, 1, 5)))
[0, 5]
Notes
-----
Any element of `nbunch` that is not in the graph `G` will be
ignored.
`nbunch1` and `nbunch2` are usually meant to be disjoint, but in
the interest of speed and generality, that is not required here.
| null | (G, nbunch1, nbunch2=None, *, backend=None, **backend_kwargs) |
30,943 | networkx.algorithms.clique | node_clique_number | Returns the size of the largest maximal clique containing each given node.
Returns a single or list depending on input nodes.
An optional list of cliques can be input if already computed.
Parameters
----------
G : NetworkX graph
An undirected graph.
cliques : list, optional (default=None)
A list of cliques, each of which is itself a list of nodes.
If not specified, the list of all cliques will be computed
using :func:`find_cliques`.
Returns
-------
int or dict
If `nodes` is a single node, returns the size of the
largest maximal clique in `G` containing that node.
Otherwise return a dict keyed by node to the size
of the largest maximal clique containing that node.
See Also
--------
find_cliques
find_cliques yields the maximal cliques of G.
It accepts a `nodes` argument which restricts consideration to
maximal cliques containing all the given `nodes`.
The search for the cliques is optimized for `nodes`.
| null | (G, nodes=None, cliques=None, separate_nodes=False, *, backend=None, **backend_kwargs) |
30,944 | networkx.algorithms.components.connected | node_connected_component | Returns the set of nodes in the component of graph containing node n.
Parameters
----------
G : NetworkX Graph
An undirected graph.
n : node label
A node in G
Returns
-------
comp : set
A set of nodes in the component of G containing node n.
Raises
------
NetworkXNotImplemented
If G is directed.
Examples
--------
>>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
>>> nx.node_connected_component(G, 0) # nodes of component that contains node 0
{0, 1, 2}
See Also
--------
connected_components
Notes
-----
For undirected graphs only.
| null | (G, n, *, backend=None, **backend_kwargs) |
30,945 | networkx.algorithms.connectivity.connectivity | node_connectivity | Returns node connectivity for a graph or digraph G.
Node connectivity is equal to the minimum number of nodes that
must be removed to disconnect G or render it trivial. If source
and target nodes are provided, this function returns the local node
connectivity: the minimum number of nodes that must be removed to break
all paths from source to target in G.
Parameters
----------
G : NetworkX graph
Undirected graph
s : node
Source node. Optional. Default value: None.
t : node
Target node. Optional. Default value: None.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The
choice of the default function may change from version
to version and should not be relied on. Default value: None.
Returns
-------
K : integer
Node connectivity of G, or local node connectivity if source
and target are provided.
Examples
--------
>>> # Platonic icosahedral graph is 5-node-connected
>>> G = nx.icosahedral_graph()
>>> nx.node_connectivity(G)
5
You can use alternative flow algorithms for the underlying maximum
flow computation. In dense networks the algorithm
:meth:`shortest_augmenting_path` will usually perform better
than the default :meth:`edmonds_karp`, which is faster for
sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> nx.node_connectivity(G, flow_func=shortest_augmenting_path)
5
If you specify a pair of nodes (source and target) as parameters,
this function returns the value of local node connectivity.
>>> nx.node_connectivity(G, 3, 7)
5
If you need to perform several local computations among different
pairs of nodes on the same graph, it is recommended that you reuse
the data structures used in the maximum flow computations. See
:meth:`local_node_connectivity` for details.
Notes
-----
This is a flow based implementation of node connectivity. The
algorithm works by solving $O((n-\delta-1+\delta(\delta-1)/2))$
maximum flow problems on an auxiliary digraph. Where $\delta$
is the minimum degree of G. For details about the auxiliary
digraph and the computation of local node connectivity see
:meth:`local_node_connectivity`. This implementation is based
on algorithm 11 in [1]_.
See also
--------
:meth:`local_node_connectivity`
:meth:`edge_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
References
----------
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
| @nx._dispatchable
def edge_connectivity(G, s=None, t=None, flow_func=None, cutoff=None):
r"""Returns the edge connectivity of the graph or digraph G.
The edge connectivity is equal to the minimum number of edges that
must be removed to disconnect G or render it trivial. If source
and target nodes are provided, this function returns the local edge
connectivity: the minimum number of edges that must be removed to
break all paths from source to target in G.
Parameters
----------
G : NetworkX graph
Undirected or directed graph
s : node
Source node. Optional. Default value: None.
t : node
Target node. Optional. Default value: None.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The
choice of the default function may change from version
to version and should not be relied on. Default value: None.
cutoff : integer, float, or None (default: None)
If specified, the maximum flow algorithm will terminate when the
flow value reaches or exceeds the cutoff. This only works for flows
that support the cutoff parameter (most do) and is ignored otherwise.
Returns
-------
K : integer
Edge connectivity for G, or local edge connectivity if source
and target were provided
Examples
--------
>>> # Platonic icosahedral graph is 5-edge-connected
>>> G = nx.icosahedral_graph()
>>> nx.edge_connectivity(G)
5
You can use alternative flow algorithms for the underlying
maximum flow computation. In dense networks the algorithm
:meth:`shortest_augmenting_path` will usually perform better
than the default :meth:`edmonds_karp`, which is faster for
sparse networks with highly skewed degree distributions.
Alternative flow functions have to be explicitly imported
from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
5
If you specify a pair of nodes (source and target) as parameters,
this function returns the value of local edge connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different
pairs of nodes on the same graph, it is recommended that you reuse
the data structures used in the maximum flow computations. See
:meth:`local_edge_connectivity` for details.
Notes
-----
This is a flow based implementation of global edge connectivity.
For undirected graphs the algorithm works by finding a 'small'
dominating set of nodes of G (see algorithm 7 in [1]_ ) and
computing local maximum flow (see :meth:`local_edge_connectivity`)
between an arbitrary node in the dominating set and the rest of
nodes in it. This is an implementation of algorithm 6 in [1]_ .
For directed graphs, the algorithm does n calls to the maximum
flow function. This is an implementation of algorithm 8 in [1]_ .
See also
--------
:meth:`local_edge_connectivity`
:meth:`local_node_connectivity`
:meth:`node_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
:meth:`k_edge_components`
:meth:`k_edge_subgraphs`
References
----------
.. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms.
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
"""
if (s is not None and t is None) or (s is None and t is not None):
raise nx.NetworkXError("Both source and target must be specified.")
# Local edge connectivity
if s is not None and t is not None:
if s not in G:
raise nx.NetworkXError(f"node {s} not in graph")
if t not in G:
raise nx.NetworkXError(f"node {t} not in graph")
return local_edge_connectivity(G, s, t, flow_func=flow_func, cutoff=cutoff)
# Global edge connectivity
# reuse auxiliary digraph and residual network
H = build_auxiliary_edge_connectivity(G)
R = build_residual_network(H, "capacity")
kwargs = {"flow_func": flow_func, "auxiliary": H, "residual": R}
if G.is_directed():
# Algorithm 8 in [1]
if not nx.is_weakly_connected(G):
return 0
# initial value for \lambda is minimum degree
L = min(d for n, d in G.degree())
nodes = list(G)
n = len(nodes)
if cutoff is not None:
L = min(cutoff, L)
for i in range(n):
kwargs["cutoff"] = L
try:
L = min(L, local_edge_connectivity(G, nodes[i], nodes[i + 1], **kwargs))
except IndexError: # last node!
L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs))
return L
else: # undirected
# Algorithm 6 in [1]
if not nx.is_connected(G):
return 0
# initial value for \lambda is minimum degree
L = min(d for n, d in G.degree())
if cutoff is not None:
L = min(cutoff, L)
# A dominating set is \lambda-covering
# We need a dominating set with at least two nodes
for node in G:
D = nx.dominating_set(G, start_with=node)
v = D.pop()
if D:
break
else:
# in complete graphs the dominating sets will always be of one node
# thus we return min degree
return L
for w in D:
kwargs["cutoff"] = L
L = min(L, local_edge_connectivity(G, v, w, **kwargs))
return L
| (G, s=None, t=None, flow_func=None, *, backend=None, **backend_kwargs) |
30,946 | networkx.algorithms.assortativity.pairs | node_degree_xy | Generate node degree-degree pairs for edges in G.
Parameters
----------
G: NetworkX graph
x: string ('in','out')
The degree type for source node (directed graphs only).
y: string ('in','out')
The degree type for target node (directed graphs only).
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.
nodes: list or iterable (optional)
Use only edges that are adjacency to specified nodes.
The default is all nodes.
Returns
-------
(x, y): 2-tuple
Generates 2-tuple of (degree, degree) values.
Examples
--------
>>> G = nx.DiGraph()
>>> G.add_edge(1, 2)
>>> list(nx.node_degree_xy(G, x="out", y="in"))
[(1, 1)]
>>> list(nx.node_degree_xy(G, x="in", y="out"))
[(0, 0)]
Notes
-----
For undirected graphs each edge is produced twice, once for each edge
representation (u, v) and (v, u), with the exception of self-loop edges
which only appear once.
| null | (G, x='out', y='in', weight=None, nodes=None, *, backend=None, **backend_kwargs) |
30,947 | networkx.algorithms.connectivity.disjoint_paths | node_disjoint_paths | Computes node disjoint paths between source and target.
Node disjoint paths are paths that only share their first and last
nodes. The number of node independent paths between two nodes is
equal to their local node connectivity.
Parameters
----------
G : NetworkX graph
s : node
Source node.
t : node
Target node.
flow_func : function
A function for computing the maximum flow among a pair of nodes.
The function has to accept at least three parameters: a Digraph,
a source node, and a target node. And return a residual network
that follows NetworkX conventions (see :meth:`maximum_flow` for
details). If flow_func is None, the default maximum flow function
(:meth:`edmonds_karp`) is used. See below for details. The choice
of the default function may change from version to version and
should not be relied on. Default value: None.
cutoff : integer or None (default: None)
Maximum number of paths to yield. If specified, the maximum flow
algorithm will terminate when the flow value reaches or exceeds the
cutoff. This only works for flows that support the cutoff parameter
(most do) and is ignored otherwise.
auxiliary : NetworkX DiGraph
Auxiliary digraph to compute flow based node connectivity. It has
to have a graph attribute called mapping with a dictionary mapping
node names in G and in the auxiliary digraph. If provided
it will be reused instead of recreated. Default value: None.
residual : NetworkX DiGraph
Residual network to compute maximum flow. If provided it will be
reused instead of recreated. Default value: None.
Returns
-------
paths : generator
Generator of node disjoint paths.
Raises
------
NetworkXNoPath
If there is no path between source and target.
NetworkXError
If source or target are not in the graph G.
Examples
--------
We use in this example the platonic icosahedral graph, which has node
connectivity 5, thus there are 5 node disjoint paths between any pair
of non neighbor nodes.
>>> G = nx.icosahedral_graph()
>>> len(list(nx.node_disjoint_paths(G, 0, 6)))
5
If you need to compute node disjoint paths between several pairs of
nodes in the same graph, it is recommended that you reuse the
data structures that NetworkX uses in the computation: the
auxiliary digraph for node connectivity and node cuts, and the
residual network for the underlying maximum flow computation.
Example of how to compute node disjoint paths reusing the data
structures:
>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from networkx.algorithms.connectivity import build_auxiliary_node_connectivity
>>> H = build_auxiliary_node_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from networkx.algorithms.flow import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, "capacity")
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as arguments
>>> len(list(nx.node_disjoint_paths(G, 0, 6, auxiliary=H, residual=R)))
5
You can also use alternative flow algorithms for computing node disjoint
paths. For instance, in dense networks the algorithm
:meth:`shortest_augmenting_path` will usually perform better than
the default :meth:`edmonds_karp` which is faster for sparse
networks with highly skewed degree distributions. Alternative flow
functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> len(list(nx.node_disjoint_paths(G, 0, 6, flow_func=shortest_augmenting_path)))
5
Notes
-----
This is a flow based implementation of node disjoint paths. We compute
the maximum flow between source and target on an auxiliary directed
network. The saturated edges in the residual network after running the
maximum flow algorithm correspond to node disjoint paths between source
and target in the original network. This function handles both directed
and undirected graphs, and can use all flow algorithms from NetworkX flow
package.
See also
--------
:meth:`edge_disjoint_paths`
:meth:`node_connectivity`
:meth:`maximum_flow`
:meth:`edmonds_karp`
:meth:`preflow_push`
:meth:`shortest_augmenting_path`
| null | (G, s, t, flow_func=None, cutoff=None, auxiliary=None, residual=None, *, backend=None, **backend_kwargs) |
30,948 | networkx.algorithms.cuts | node_expansion | Returns the node expansion of the set `S`.
The *node expansion* is the quotient of the size of the node
boundary of *S* and the cardinality of *S*. [1]
Parameters
----------
G : NetworkX graph
S : collection
A collection of nodes in `G`.
Returns
-------
number
The node expansion of the set `S`.
See also
--------
boundary_expansion
edge_expansion
mixing_expansion
References
----------
.. [1] Vadhan, Salil P.
"Pseudorandomness."
*Foundations and Trends
in Theoretical Computer Science* 7.1–3 (2011): 1–336.
<https://doi.org/10.1561/0400000010>
| null | (G, S, *, backend=None, **backend_kwargs) |
30,950 | networkx.readwrite.json_graph.node_link | node_link_data | Returns data in node-link format that is suitable for JSON serialization
and use in JavaScript documents.
Parameters
----------
G : NetworkX graph
source : string
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
target : string
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
name : string
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
key : string
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
link : string
A string that provides the 'link' attribute name for storing NetworkX-internal graph data.
Returns
-------
data : dict
A dictionary with node-link formatted data.
Raises
------
NetworkXError
If the values of 'source', 'target' and 'key' are not unique.
Examples
--------
>>> G = nx.Graph([("A", "B")])
>>> data1 = nx.node_link_data(G)
>>> data1
{'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]}
To serialize with JSON
>>> import json
>>> s1 = json.dumps(data1)
>>> s1
'{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
A graph can also be serialized by passing `node_link_data` as an encoder function. The two methods are equivalent.
>>> s1 = json.dumps(G, default=nx.node_link_data)
>>> s1
'{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
The attribute names for storing NetworkX-internal graph data can
be specified as keyword options.
>>> H = nx.gn_graph(2)
>>> data2 = nx.node_link_data(H, link="edges", source="from", target="to")
>>> data2
{'directed': True, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 0}, {'id': 1}], 'edges': [{'from': 1, 'to': 0}]}
Notes
-----
Graph, node, and link attributes are stored in this format. Note that
attribute keys will be converted to strings in order to comply with JSON.
Attribute 'key' is only used for multigraphs.
To use `node_link_data` in conjunction with `node_link_graph`,
the keyword names for the attributes must match.
See Also
--------
node_link_graph, adjacency_data, tree_data
| def node_link_data(
G,
*,
source="source",
target="target",
name="id",
key="key",
link="links",
):
"""Returns data in node-link format that is suitable for JSON serialization
and use in JavaScript documents.
Parameters
----------
G : NetworkX graph
source : string
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
target : string
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
name : string
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
key : string
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
link : string
A string that provides the 'link' attribute name for storing NetworkX-internal graph data.
Returns
-------
data : dict
A dictionary with node-link formatted data.
Raises
------
NetworkXError
If the values of 'source', 'target' and 'key' are not unique.
Examples
--------
>>> G = nx.Graph([("A", "B")])
>>> data1 = nx.node_link_data(G)
>>> data1
{'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]}
To serialize with JSON
>>> import json
>>> s1 = json.dumps(data1)
>>> s1
'{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
A graph can also be serialized by passing `node_link_data` as an encoder function. The two methods are equivalent.
>>> s1 = json.dumps(G, default=nx.node_link_data)
>>> s1
'{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "A"}, {"id": "B"}], "links": [{"source": "A", "target": "B"}]}'
The attribute names for storing NetworkX-internal graph data can
be specified as keyword options.
>>> H = nx.gn_graph(2)
>>> data2 = nx.node_link_data(H, link="edges", source="from", target="to")
>>> data2
{'directed': True, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 0}, {'id': 1}], 'edges': [{'from': 1, 'to': 0}]}
Notes
-----
Graph, node, and link attributes are stored in this format. Note that
attribute keys will be converted to strings in order to comply with JSON.
Attribute 'key' is only used for multigraphs.
To use `node_link_data` in conjunction with `node_link_graph`,
the keyword names for the attributes must match.
See Also
--------
node_link_graph, adjacency_data, tree_data
"""
multigraph = G.is_multigraph()
# Allow 'key' to be omitted from attrs if the graph is not a multigraph.
key = None if not multigraph else key
if len({source, target, key}) < 3:
raise nx.NetworkXError("Attribute names are not unique.")
data = {
"directed": G.is_directed(),
"multigraph": multigraph,
"graph": G.graph,
"nodes": [{**G.nodes[n], name: n} for n in G],
}
if multigraph:
data[link] = [
{**d, source: u, target: v, key: k}
for u, v, k, d in G.edges(keys=True, data=True)
]
else:
data[link] = [{**d, source: u, target: v} for u, v, d in G.edges(data=True)]
return data
| (G, *, source='source', target='target', name='id', key='key', link='links') |
30,951 | networkx.readwrite.json_graph.node_link | node_link_graph | Returns graph from node-link data format.
Useful for de-serialization from JSON.
Parameters
----------
data : dict
node-link formatted graph data
directed : bool
If True, and direction not specified in data, return a directed graph.
multigraph : bool
If True, and multigraph not specified in data, return a multigraph.
source : string
A string that provides the 'source' attribute name for storing NetworkX-internal graph data.
target : string
A string that provides the 'target' attribute name for storing NetworkX-internal graph data.
name : string
A string that provides the 'name' attribute name for storing NetworkX-internal graph data.
key : string
A string that provides the 'key' attribute name for storing NetworkX-internal graph data.
link : string
A string that provides the 'link' attribute name for storing NetworkX-internal graph data.
Returns
-------
G : NetworkX graph
A NetworkX graph object
Examples
--------
Create data in node-link format by converting a graph.
>>> G = nx.Graph([("A", "B")])
>>> data = nx.node_link_data(G)
>>> data
{'directed': False, 'multigraph': False, 'graph': {}, 'nodes': [{'id': 'A'}, {'id': 'B'}], 'links': [{'source': 'A', 'target': 'B'}]}
Revert data in node-link format to a graph.
>>> H = nx.node_link_graph(data)
>>> print(H.edges)
[('A', 'B')]
To serialize and deserialize a graph with JSON,
>>> import json
>>> d = json.dumps(node_link_data(G))
>>> H = node_link_graph(json.loads(d))
>>> print(G.edges, H.edges)
[('A', 'B')] [('A', 'B')]
Notes
-----
Attribute 'key' is only used for multigraphs.
To use `node_link_data` in conjunction with `node_link_graph`,
the keyword names for the attributes must match.
See Also
--------
node_link_data, adjacency_data, tree_data
| null | (data, directed=False, multigraph=True, *, source='source', target='target', name='id', key='key', link='links', backend=None, **backend_kwargs) |
30,952 | networkx.classes.function | nodes | Returns a NodeView over the graph nodes.
This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
| def nodes(G):
"""Returns a NodeView over the graph nodes.
This function wraps the :func:`G.nodes <networkx.Graph.nodes>` property.
"""
return G.nodes()
| (G) |
30,953 | networkx.classes.function | nodes_with_selfloops | Returns an iterator over nodes with self loops.
A node with a self loop has an edge with both ends adjacent
to that node.
Returns
-------
nodelist : iterator
A iterator over nodes with self loops.
See Also
--------
selfloop_edges, number_of_selfloops
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge(1, 1)
>>> G.add_edge(1, 2)
>>> list(nx.nodes_with_selfloops(G))
[1]
| def nodes_with_selfloops(G):
"""Returns an iterator over nodes with self loops.
A node with a self loop has an edge with both ends adjacent
to that node.
Returns
-------
nodelist : iterator
A iterator over nodes with self loops.
See Also
--------
selfloop_edges, number_of_selfloops
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge(1, 1)
>>> G.add_edge(1, 2)
>>> list(nx.nodes_with_selfloops(G))
[1]
"""
return (n for n, nbrs in G._adj.items() if n in nbrs)
| (G) |
30,954 | networkx.classes.function | non_edges | Returns the nonexistent edges in the graph.
Parameters
----------
graph : NetworkX graph.
Graph to find nonexistent edges.
Returns
-------
non_edges : iterator
Iterator of edges that are not in the graph.
| def non_edges(graph):
"""Returns the nonexistent edges in the graph.
Parameters
----------
graph : NetworkX graph.
Graph to find nonexistent edges.
Returns
-------
non_edges : iterator
Iterator of edges that are not in the graph.
"""
if graph.is_directed():
for u in graph:
for v in non_neighbors(graph, u):
yield (u, v)
else:
nodes = set(graph)
while nodes:
u = nodes.pop()
for v in nodes - set(graph[u]):
yield (u, v)
| (graph) |
30,955 | networkx.classes.function | non_neighbors | Returns the non-neighbors of the node in the graph.
Parameters
----------
graph : NetworkX graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
Returns
-------
non_neighbors : set
Set of nodes in the graph that are not neighbors of the node.
| def non_neighbors(graph, node):
"""Returns the non-neighbors of the node in the graph.
Parameters
----------
graph : NetworkX graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
Returns
-------
non_neighbors : set
Set of nodes in the graph that are not neighbors of the node.
"""
return graph._adj.keys() - graph._adj[node].keys() - {node}
| (graph, node) |
30,956 | networkx.algorithms.non_randomness | non_randomness | Compute the non-randomness of graph G.
The first returned value nr is the sum of non-randomness values of all
edges within the graph (where the non-randomness of an edge tends to be
small when the two nodes linked by that edge are from two different
communities).
The second computed value nr_rd is a relative measure that indicates
to what extent graph G is different from random graphs in terms
of probability. When it is close to 0, the graph tends to be more
likely generated by an Erdos Renyi model.
Parameters
----------
G : NetworkX graph
Graph must be symmetric, connected, and without self-loops.
k : int
The number of communities in G.
If k is not set, the function will use a default community
detection algorithm to set it.
weight : string or None, optional (default=None)
The name of an edge attribute that holds the numerical value used
as a weight. If None, then each edge has weight 1, i.e., the graph is
binary.
Returns
-------
non-randomness : (float, float) tuple
Non-randomness, Relative non-randomness w.r.t.
Erdos Renyi random graphs.
Raises
------
NetworkXException
if the input graph is not connected.
NetworkXError
if the input graph contains self-loops.
Examples
--------
>>> G = nx.karate_club_graph()
>>> nr, nr_rd = nx.non_randomness(G, 2)
>>> nr, nr_rd = nx.non_randomness(G, 2, "weight")
Notes
-----
This computes Eq. (4.4) and (4.5) in Ref. [1]_.
If a weight field is passed, this algorithm will use the eigenvalues
of the weighted adjacency matrix to compute Eq. (4.4) and (4.5).
References
----------
.. [1] Xiaowei Ying and Xintao Wu,
On Randomness Measures for Social Networks,
SIAM International Conference on Data Mining. 2009
| null | (G, k=None, weight='weight', *, backend=None, **backend_kwargs) |
30,957 | networkx.generators.nonisomorphic_trees | nonisomorphic_trees | Generates lists of nonisomorphic trees
Parameters
----------
order : int
order of the desired tree(s)
create : one of {"graph", "matrix"} (default="graph")
If ``"graph"`` is selected a list of ``Graph`` instances will be returned,
if matrix is selected a list of adjacency matrices will be returned.
.. deprecated:: 3.3
The `create` argument is deprecated and will be removed in NetworkX
version 3.5. In the future, `nonisomorphic_trees` will yield graph
instances by default. To generate adjacency matrices, call
``nx.to_numpy_array`` on the output, e.g.::
[nx.to_numpy_array(G) for G in nx.nonisomorphic_trees(N)]
Yields
------
list
A list of nonisomorphic trees, in one of two formats depending on the
value of the `create` parameter:
- ``create="graph"``: yields a list of `networkx.Graph` instances
- ``create="matrix"``: yields a list of list-of-lists representing adjacency matrices
| null | (order, create='graph', *, backend=None, **backend_kwargs) |
30,958 | networkx.algorithms.cuts | normalized_cut_size | Returns the normalized size of the cut between two sets of nodes.
The *normalized cut size* is the cut size times the sum of the
reciprocal sizes of the volumes of the two sets. [1]
Parameters
----------
G : NetworkX graph
S : collection
A collection of nodes in `G`.
T : collection
A collection of nodes in `G`.
weight : object
Edge attribute key to use as weight. If not specified, edges
have weight one.
Returns
-------
number
The normalized cut size between the two sets `S` and `T`.
Notes
-----
In a multigraph, the cut size is the total weight of edges including
multiplicity.
See also
--------
conductance
cut_size
edge_expansion
volume
References
----------
.. [1] David Gleich.
*Hierarchical Directed Spectral Graph Partitioning*.
<https://www.cs.purdue.edu/homes/dgleich/publications/Gleich%202005%20-%20hierarchical%20directed%20spectral.pdf>
| null | (G, S, T=None, weight=None, *, backend=None, **backend_kwargs) |
30,959 | networkx.linalg.laplacianmatrix | normalized_laplacian_matrix | Returns the normalized Laplacian matrix of G.
The normalized graph Laplacian is the matrix
.. math::
N = D^{-1/2} L D^{-1/2}
where `L` is the graph Laplacian and `D` is the diagonal matrix of
node degrees [1]_.
Parameters
----------
G : graph
A NetworkX graph
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().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
Returns
-------
N : SciPy sparse array
The normalized Laplacian matrix of G.
Notes
-----
For MultiGraph, the edges weights are summed.
See :func:`to_numpy_array` for other options.
If the Graph contains selfloops, D is defined as ``diag(sum(A, 1))``, where A is
the adjacency matrix [2]_.
This calculation uses the out-degree of the graph `G`. To use the
in-degree for calculations instead, use `G.reverse(copy=False)` and
take the transpose.
For an unnormalized output, use `laplacian_matrix`.
Examples
--------
>>> import numpy as np
>>> edges = [
... (1, 2),
... (2, 1),
... (2, 4),
... (4, 3),
... (3, 4),
... ]
>>> DiG = nx.DiGraph(edges)
>>> print(nx.normalized_laplacian_matrix(DiG).toarray())
[[ 1. -0.70710678 0. 0. ]
[-0.70710678 1. -0.70710678 0. ]
[ 0. 0. 1. -1. ]
[ 0. 0. -1. 1. ]]
Notice that node 4 is represented by the third column and row. This is because
by default the row/column order is the order of `G.nodes` (i.e. the node added
order -- in the edgelist, 4 first appears in (2, 4), before node 3 in edge (4, 3).)
To control the node order of the matrix, use the `nodelist` argument.
>>> print(nx.normalized_laplacian_matrix(DiG, nodelist=[1, 2, 3, 4]).toarray())
[[ 1. -0.70710678 0. 0. ]
[-0.70710678 1. 0. -0.70710678]
[ 0. 0. 1. -1. ]
[ 0. 0. -1. 1. ]]
>>> G = nx.Graph(edges)
>>> print(nx.normalized_laplacian_matrix(G).toarray())
[[ 1. -0.70710678 0. 0. ]
[-0.70710678 1. -0.5 0. ]
[ 0. -0.5 1. -0.70710678]
[ 0. 0. -0.70710678 1. ]]
See Also
--------
laplacian_matrix
normalized_laplacian_spectrum
directed_laplacian_matrix
directed_combinatorial_laplacian_matrix
References
----------
.. [1] Fan Chung-Graham, Spectral Graph Theory,
CBMS Regional Conference Series in Mathematics, Number 92, 1997.
.. [2] Steve Butler, Interlacing For Weighted Graphs Using The Normalized
Laplacian, Electronic Journal of Linear Algebra, Volume 16, pp. 90-98,
March 2007.
.. [3] Langville, Amy N., and Carl D. Meyer. Google’s PageRank and Beyond:
The Science of Search Engine Rankings. Princeton University Press, 2006.
| null | (G, nodelist=None, weight='weight', *, backend=None, **backend_kwargs) |
30,960 | networkx.linalg.spectrum | normalized_laplacian_spectrum | Return eigenvalues of the normalized Laplacian of G
Parameters
----------
G : graph
A NetworkX graph
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
Returns
-------
evals : NumPy array
Eigenvalues
Notes
-----
For MultiGraph/MultiDiGraph, the edges weights are summed.
See to_numpy_array for other options.
See Also
--------
normalized_laplacian_matrix
| null | (G, weight='weight', *, backend=None, **backend_kwargs) |
30,961 | networkx.generators.classic | null_graph | Returns the Null graph with no nodes or edges.
See empty_graph for the use of create_using.
| 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
| (create_using=None, *, backend=None, **backend_kwargs) |
30,962 | networkx.algorithms.components.attracting | number_attracting_components | Returns the number of attracting components in `G`.
Parameters
----------
G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns
-------
n : int
The number of attracting components in G.
Raises
------
NetworkXNotImplemented
If the input graph is undirected.
See Also
--------
attracting_components
is_attracting_component
| null | (G, *, backend=None, **backend_kwargs) |
30,963 | networkx.algorithms.components.connected | number_connected_components | Returns the number of connected components.
Parameters
----------
G : NetworkX graph
An undirected graph.
Returns
-------
n : integer
Number of connected components
Raises
------
NetworkXNotImplemented
If G is directed.
Examples
--------
>>> G = nx.Graph([(0, 1), (1, 2), (5, 6), (3, 4)])
>>> nx.number_connected_components(G)
3
See Also
--------
connected_components
number_weakly_connected_components
number_strongly_connected_components
Notes
-----
For undirected graphs only.
| null | (G, *, backend=None, **backend_kwargs) |
30,964 | networkx.algorithms.clique | number_of_cliques | Returns the number of maximal cliques for each node.
Returns a single or list depending on input nodes.
Optional list of cliques can be input if already computed.
| def number_of_cliques(G, nodes=None, cliques=None):
"""Returns the number of maximal cliques for each node.
Returns a single or list depending on input nodes.
Optional list of cliques can be input if already computed.
"""
if cliques is None:
cliques = list(find_cliques(G))
if nodes is None:
nodes = list(G.nodes()) # none, get entire graph
if not isinstance(nodes, list): # check for a list
v = nodes
# assume it is a single value
numcliq = len([1 for c in cliques if v in c])
else:
numcliq = {}
for v in nodes:
numcliq[v] = len([1 for c in cliques if v in c])
return numcliq
| (G, nodes=None, cliques=None) |
30,965 | networkx.classes.function | number_of_edges | Returns the number of edges in the graph.
This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
| def number_of_edges(G):
"""Returns the number of edges in the graph.
This function wraps the :func:`G.number_of_edges <networkx.Graph.number_of_edges>` function.
"""
return G.number_of_edges()
| (G) |
30,966 | networkx.algorithms.isolate | number_of_isolates | Returns the number of isolates in the graph.
An *isolate* is a node with no neighbors (that is, with degree
zero). For directed graphs, this means no in-neighbors and no
out-neighbors.
Parameters
----------
G : NetworkX graph
Returns
-------
int
The number of degree zero nodes in the graph `G`.
| null | (G, *, backend=None, **backend_kwargs) |
30,967 | networkx.classes.function | number_of_nodes | Returns the number of nodes in the graph.
This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
| def number_of_nodes(G):
"""Returns the number of nodes in the graph.
This function wraps the :func:`G.number_of_nodes <networkx.Graph.number_of_nodes>` function.
"""
return G.number_of_nodes()
| (G) |
30,968 | networkx.generators.nonisomorphic_trees | number_of_nonisomorphic_trees | Returns the number of nonisomorphic trees
Parameters
----------
order : int
order of the desired tree(s)
Returns
-------
length : Number of nonisomorphic graphs for the given order
References
----------
| null | (order, *, backend=None, **backend_kwargs) |
30,969 | networkx.classes.function | number_of_selfloops | Returns the number of selfloop edges.
A selfloop edge has the same node at both ends.
Returns
-------
nloops : int
The number of selfloops.
See Also
--------
nodes_with_selfloops, selfloop_edges
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge(1, 1)
>>> G.add_edge(1, 2)
>>> nx.number_of_selfloops(G)
1
| def number_of_selfloops(G):
"""Returns the number of selfloop edges.
A selfloop edge has the same node at both ends.
Returns
-------
nloops : int
The number of selfloops.
See Also
--------
nodes_with_selfloops, selfloop_edges
Examples
--------
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge(1, 1)
>>> G.add_edge(1, 2)
>>> nx.number_of_selfloops(G)
1
"""
return sum(1 for _ in nx.selfloop_edges(G))
| (G) |
30,970 | networkx.algorithms.tree.mst | number_of_spanning_trees | Returns the number of spanning trees in `G`.
A spanning tree for an undirected graph is a tree that connects
all nodes in the graph. For a directed graph, the analog of a
spanning tree is called a (spanning) arborescence. The arborescence
includes a unique directed path from the `root` node to each other node.
The graph must be weakly connected, and the root must be a node
that includes all nodes as successors [3]_. Note that to avoid
discussing sink-roots and reverse-arborescences, we have reversed
the edge orientation from [3]_ and use the in-degree laplacian.
This function (when `weight` is `None`) returns the number of
spanning trees for an undirected graph and the number of
arborescences from a single root node for a directed graph.
When `weight` is the name of an edge attribute which holds the
weight value of each edge, the function returns the sum over
all trees of the multiplicative weight of each tree. That is,
the weight of the tree is the product of its edge weights.
Kirchoff's Tree Matrix Theorem states that any cofactor of the
Laplacian matrix of a graph is the number of spanning trees in the
graph. (Here we use cofactors for a diagonal entry so that the
cofactor becomes the determinant of the matrix with one row
and its matching column removed.) For a weighted Laplacian matrix,
the cofactor is the sum across all spanning trees of the
multiplicative weight of each tree. That is, the weight of each
tree is the product of its edge weights. The theorem is also
known as Kirchhoff's theorem [1]_ and the Matrix-Tree theorem [2]_.
For directed graphs, a similar theorem (Tutte's Theorem) holds with
the cofactor chosen to be the one with row and column removed that
correspond to the root. The cofactor is the number of arborescences
with the specified node as root. And the weighted version gives the
sum of the arborescence weights with root `root`. The arborescence
weight is the product of its edge weights.
Parameters
----------
G : NetworkX graph
root : node
A node in the directed graph `G` that has all nodes as descendants.
(This is ignored for undirected graphs.)
weight : string or None, optional (default=None)
The name of the edge attribute holding the edge weight.
If `None`, then each edge is assumed to have a weight of 1.
Returns
-------
Number
Undirected graphs:
The number of spanning trees of the graph `G`.
Or the sum of all spanning tree weights of the graph `G`
where the weight of a tree is the product of its edge weights.
Directed graphs:
The number of arborescences of `G` rooted at node `root`.
Or the sum of all arborescence weights of the graph `G` with
specified root where the weight of an arborescence is the product
of its edge weights.
Raises
------
NetworkXPointlessConcept
If `G` does not contain any nodes.
NetworkXError
If the graph `G` is directed and the root node
is not specified or is not in G.
Examples
--------
>>> G = nx.complete_graph(5)
>>> round(nx.number_of_spanning_trees(G))
125
>>> G = nx.Graph()
>>> G.add_edge(1, 2, weight=2)
>>> G.add_edge(1, 3, weight=1)
>>> G.add_edge(2, 3, weight=1)
>>> round(nx.number_of_spanning_trees(G, weight="weight"))
5
Notes
-----
Self-loops are excluded. Multi-edges are contracted in one edge
equal to the sum of the weights.
References
----------
.. [1] Wikipedia
"Kirchhoff's theorem."
https://en.wikipedia.org/wiki/Kirchhoff%27s_theorem
.. [2] Kirchhoff, G. R.
Über die Auflösung der Gleichungen, auf welche man
bei der Untersuchung der linearen Vertheilung
Galvanischer Ströme geführt wird
Annalen der Physik und Chemie, vol. 72, pp. 497-508, 1847.
.. [3] Margoliash, J.
"Matrix-Tree Theorem for Directed Graphs"
https://www.math.uchicago.edu/~may/VIGRE/VIGRE2010/REUPapers/Margoliash.pdf
| def random_spanning_tree(G, weight=None, *, multiplicative=True, seed=None):
"""
Sample a random spanning tree using the edges weights of `G`.
This function supports two different methods for determining the
probability of the graph. If ``multiplicative=True``, the probability
is based on the product of edge weights, and if ``multiplicative=False``
it is based on the sum of the edge weight. However, since it is
easier to determine the total weight of all spanning trees for the
multiplicative version, that is significantly faster and should be used if
possible. Additionally, setting `weight` to `None` will cause a spanning tree
to be selected with uniform probability.
The function uses algorithm A8 in [1]_ .
Parameters
----------
G : nx.Graph
An undirected version of the original graph.
weight : string
The edge key for the edge attribute holding edge weight.
multiplicative : bool, default=True
If `True`, the probability of each tree is the product of its edge weight
over the sum of the product of all the spanning trees in the graph. If
`False`, the probability is the sum of its edge weight over the sum of
the sum of weights for all spanning trees in the graph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
nx.Graph
A spanning tree using the distribution defined by the weight of the tree.
References
----------
.. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
Algorithms, 11 (1990), pp. 185–207
"""
def find_node(merged_nodes, node):
"""
We can think of clusters of contracted nodes as having one
representative in the graph. Each node which is not in merged_nodes
is still its own representative. Since a representative can be later
contracted, we need to recursively search though the dict to find
the final representative, but once we know it we can use path
compression to speed up the access of the representative for next time.
This cannot be replaced by the standard NetworkX union_find since that
data structure will merge nodes with less representing nodes into the
one with more representing nodes but this function requires we merge
them using the order that contract_edges contracts using.
Parameters
----------
merged_nodes : dict
The dict storing the mapping from node to representative
node
The node whose representative we seek
Returns
-------
The representative of the `node`
"""
if node not in merged_nodes:
return node
else:
rep = find_node(merged_nodes, merged_nodes[node])
merged_nodes[node] = rep
return rep
def prepare_graph():
"""
For the graph `G`, remove all edges not in the set `V` and then
contract all edges in the set `U`.
Returns
-------
A copy of `G` which has had all edges not in `V` removed and all edges
in `U` contracted.
"""
# The result is a MultiGraph version of G so that parallel edges are
# allowed during edge contraction
result = nx.MultiGraph(incoming_graph_data=G)
# Remove all edges not in V
edges_to_remove = set(result.edges()).difference(V)
result.remove_edges_from(edges_to_remove)
# Contract all edges in U
#
# Imagine that you have two edges to contract and they share an
# endpoint like this:
# [0] ----- [1] ----- [2]
# If we contract (0, 1) first, the contraction function will always
# delete the second node it is passed so the resulting graph would be
# [0] ----- [2]
# and edge (1, 2) no longer exists but (0, 2) would need to be contracted
# in its place now. That is why I use the below dict as a merge-find
# data structure with path compression to track how the nodes are merged.
merged_nodes = {}
for u, v in U:
u_rep = find_node(merged_nodes, u)
v_rep = find_node(merged_nodes, v)
# We cannot contract a node with itself
if u_rep == v_rep:
continue
nx.contracted_nodes(result, u_rep, v_rep, self_loops=False, copy=False)
merged_nodes[v_rep] = u_rep
return merged_nodes, result
def spanning_tree_total_weight(G, weight):
"""
Find the sum of weights of the spanning trees of `G` using the
appropriate `method`.
This is easy if the chosen method is 'multiplicative', since we can
use Kirchhoff's Tree Matrix Theorem directly. However, with the
'additive' method, this process is slightly more complex and less
computationally efficient as we have to find the number of spanning
trees which contain each possible edge in the graph.
Parameters
----------
G : NetworkX Graph
The graph to find the total weight of all spanning trees on.
weight : string
The key for the weight edge attribute of the graph.
Returns
-------
float
The sum of either the multiplicative or additive weight for all
spanning trees in the graph.
"""
if multiplicative:
return nx.total_spanning_tree_weight(G, weight)
else:
# There are two cases for the total spanning tree additive weight.
# 1. There is one edge in the graph. Then the only spanning tree is
# that edge itself, which will have a total weight of that edge
# itself.
if G.number_of_edges() == 1:
return G.edges(data=weight).__iter__().__next__()[2]
# 2. There are no edges or two or more edges in the graph. Then, we find the
# total weight of the spanning trees using the formula in the
# reference paper: take the weight of each edge and multiply it by
# the number of spanning trees which include that edge. This
# can be accomplished by contracting the edge and finding the
# multiplicative total spanning tree weight if the weight of each edge
# is assumed to be 1, which is conveniently built into networkx already,
# by calling total_spanning_tree_weight with weight=None.
# Note that with no edges the returned value is just zero.
else:
total = 0
for u, v, w in G.edges(data=weight):
total += w * nx.total_spanning_tree_weight(
nx.contracted_edge(G, edge=(u, v), self_loops=False), None
)
return total
if G.number_of_nodes() < 2:
# no edges in the spanning tree
return nx.empty_graph(G.nodes)
U = set()
st_cached_value = 0
V = set(G.edges())
shuffled_edges = list(G.edges())
seed.shuffle(shuffled_edges)
for u, v in shuffled_edges:
e_weight = G[u][v][weight] if weight is not None else 1
node_map, prepared_G = prepare_graph()
G_total_tree_weight = spanning_tree_total_weight(prepared_G, weight)
# Add the edge to U so that we can compute the total tree weight
# assuming we include that edge
# Now, if (u, v) cannot exist in G because it is fully contracted out
# of existence, then it by definition cannot influence G_e's Kirchhoff
# value. But, we also cannot pick it.
rep_edge = (find_node(node_map, u), find_node(node_map, v))
# Check to see if the 'representative edge' for the current edge is
# in prepared_G. If so, then we can pick it.
if rep_edge in prepared_G.edges:
prepared_G_e = nx.contracted_edge(
prepared_G, edge=rep_edge, self_loops=False
)
G_e_total_tree_weight = spanning_tree_total_weight(prepared_G_e, weight)
if multiplicative:
threshold = e_weight * G_e_total_tree_weight / G_total_tree_weight
else:
numerator = (
st_cached_value + e_weight
) * nx.total_spanning_tree_weight(prepared_G_e) + G_e_total_tree_weight
denominator = (
st_cached_value * nx.total_spanning_tree_weight(prepared_G)
+ G_total_tree_weight
)
threshold = numerator / denominator
else:
threshold = 0.0
z = seed.uniform(0.0, 1.0)
if z > threshold:
# Remove the edge from V since we did not pick it.
V.remove((u, v))
else:
# Add the edge to U since we picked it.
st_cached_value += e_weight
U.add((u, v))
# If we decide to keep an edge, it may complete the spanning tree.
if len(U) == G.number_of_nodes() - 1:
spanning_tree = nx.Graph()
spanning_tree.add_edges_from(U)
return spanning_tree
raise Exception(f"Something went wrong! Only {len(U)} edges in the spanning tree!")
| (G, *, root=None, weight=None, backend=None, **backend_kwargs) |
30,971 | networkx.algorithms.walks | number_of_walks | Returns the number of walks connecting each pair of nodes in `G`
A *walk* is a sequence of nodes in which each adjacent pair of nodes
in the sequence is adjacent in the graph. A walk can repeat the same
edge and go in the opposite direction just as people can walk on a
set of paths, but standing still is not counted as part of the walk.
This function only counts the walks with `walk_length` edges. Note that
the number of nodes in the walk sequence is one more than `walk_length`.
The number of walks can grow very quickly on a larger graph
and with a larger walk length.
Parameters
----------
G : NetworkX graph
walk_length : int
A nonnegative integer representing the length of a walk.
Returns
-------
dict
A dictionary of dictionaries in which outer keys are source
nodes, inner keys are target nodes, and inner values are the
number of walks of length `walk_length` connecting those nodes.
Raises
------
ValueError
If `walk_length` is negative
Examples
--------
>>> G = nx.Graph([(0, 1), (1, 2)])
>>> walks = nx.number_of_walks(G, 2)
>>> walks
{0: {0: 1, 1: 0, 2: 1}, 1: {0: 0, 1: 2, 2: 0}, 2: {0: 1, 1: 0, 2: 1}}
>>> total_walks = sum(sum(tgts.values()) for _, tgts in walks.items())
You can also get the number of walks from a specific source node using the
returned dictionary. For example, number of walks of length 1 from node 0
can be found as follows:
>>> walks = nx.number_of_walks(G, 1)
>>> walks[0]
{0: 0, 1: 1, 2: 0}
>>> sum(walks[0].values()) # walks from 0 of length 1
1
Similarly, a target node can also be specified:
>>> walks[0][1]
1
| null | (G, walk_length, *, backend=None, **backend_kwargs) |
30,972 | networkx.algorithms.components.strongly_connected | number_strongly_connected_components | Returns number of strongly connected components in graph.
Parameters
----------
G : NetworkX graph
A directed graph.
Returns
-------
n : integer
Number of strongly connected components
Raises
------
NetworkXNotImplemented
If G is undirected.
Examples
--------
>>> G = nx.DiGraph(
... [(0, 1), (1, 2), (2, 0), (2, 3), (4, 5), (3, 4), (5, 6), (6, 3), (6, 7)]
... )
>>> nx.number_strongly_connected_components(G)
3
See Also
--------
strongly_connected_components
number_connected_components
number_weakly_connected_components
Notes
-----
For directed graphs only.
| null | (G, *, backend=None, **backend_kwargs) |
30,973 | networkx.algorithms.components.weakly_connected | number_weakly_connected_components | Returns the number of weakly connected components in G.
Parameters
----------
G : NetworkX graph
A directed graph.
Returns
-------
n : integer
Number of weakly connected components
Raises
------
NetworkXNotImplemented
If G is undirected.
Examples
--------
>>> G = nx.DiGraph([(0, 1), (2, 1), (3, 4)])
>>> nx.number_weakly_connected_components(G)
2
See Also
--------
weakly_connected_components
number_connected_components
number_strongly_connected_components
Notes
-----
For directed graphs only.
| null | (G, *, backend=None, **backend_kwargs) |
30,974 | networkx.algorithms.assortativity.correlation | numeric_assortativity_coefficient | Compute assortativity for numerical node attributes.
Assortativity measures the similarity of connections
in the graph with respect to the given numeric attribute.
Parameters
----------
G : NetworkX graph
attribute : string
Node attribute key.
nodes: list or iterable (optional)
Compute numeric assortativity only for attributes of nodes in
container. The default is all nodes.
Returns
-------
r: float
Assortativity of graph for given attribute
Examples
--------
>>> G = nx.Graph()
>>> G.add_nodes_from([0, 1], size=2)
>>> G.add_nodes_from([2, 3], size=3)
>>> G.add_edges_from([(0, 1), (2, 3)])
>>> print(nx.numeric_assortativity_coefficient(G, "size"))
1.0
Notes
-----
This computes Eq. (21) in Ref. [1]_ , which is the Pearson correlation
coefficient of the specified (scalar valued) attribute across edges.
References
----------
.. [1] M. E. J. Newman, Mixing patterns in networks
Physical Review E, 67 026126, 2003
| null | (G, attribute, nodes=None, *, backend=None, **backend_kwargs) |
30,979 | networkx.generators.small | octahedral_graph |
Returns the Platonic Octahedral graph.
The octahedral graph is the 6-node 12-edge Platonic graph having the
connectivity of the octahedron [1]_. If 6 couples go to a party,
and each person shakes hands with every person except his or her partner,
then this graph describes the set of handshakes that take place;
for this reason it is also called the cocktail party graph [2]_.
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
Octahedral graph
References
----------
.. [1] https://mathworld.wolfram.com/OctahedralGraph.html
.. [2] https://en.wikipedia.org/wiki/Tur%C3%A1n_graph#Special_cases
| def _raise_on_directed(func):
"""
A decorator which inspects the `create_using` argument and raises a
NetworkX exception when `create_using` is a DiGraph (class or instance) for
graph generators that do not support directed outputs.
"""
@wraps(func)
def wrapper(*args, **kwargs):
if kwargs.get("create_using") is not None:
G = nx.empty_graph(create_using=kwargs["create_using"])
if G.is_directed():
raise NetworkXError("Directed Graph not supported")
return func(*args, **kwargs)
return wrapper
| (create_using=None, *, backend=None, **backend_kwargs) |
30,980 | networkx.algorithms.smallworld | omega | Returns the small-world coefficient (omega) of a graph
The small-world coefficient of a graph G is:
omega = Lr/L - C/Cl
where C and L are respectively the average clustering coefficient and
average shortest path length of G. Lr is the average shortest path length
of an equivalent random graph and Cl is the average clustering coefficient
of an equivalent lattice graph.
The small-world coefficient (omega) measures how much G is like a lattice
or a random graph. Negative values mean G is similar to a lattice whereas
positive values mean G is a random graph.
Values close to 0 mean that G has small-world characteristics.
Parameters
----------
G : NetworkX graph
An undirected graph.
niter: integer (optional, default=5)
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 maximal 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
-------
omega : float
The small-world coefficient (omega)
Notes
-----
The implementation is adapted from the algorithm by Telesford et al. [1]_.
References
----------
.. [1] Telesford, Joyce, Hayasaka, Burdette, and Laurienti (2011).
"The Ubiquity of Small-World Networks".
Brain Connectivity. 1 (0038): 367-75. PMC 3604768. PMID 22432451.
doi:10.1089/brain.2011.0038.
| null | (G, niter=5, nrand=10, seed=None, *, backend=None, **backend_kwargs) |
30,981 | networkx.algorithms.core | onion_layers | Returns the layer of each vertex in an onion decomposition of the graph.
The onion decomposition refines the k-core decomposition by providing
information on the internal organization of each k-shell. It is usually
used alongside the `core numbers`.
Parameters
----------
G : NetworkX graph
An undirected graph without self loops.
Returns
-------
od_layers : dictionary
A dictionary keyed by node to the onion layer. The layers are
contiguous integers starting at 1.
Raises
------
NetworkXNotImplemented
If `G` is a multigraph or directed graph or if it contains self loops.
Examples
--------
>>> degrees = [0, 1, 2, 2, 2, 2, 3]
>>> H = nx.havel_hakimi_graph(degrees)
>>> H.degree
DegreeView({0: 1, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 0})
>>> nx.onion_layers(H)
{6: 1, 0: 2, 4: 3, 1: 4, 2: 4, 3: 4, 5: 4}
See Also
--------
core_number
References
----------
.. [1] Multi-scale structure and topological anomaly detection via a new
network statistic: The onion decomposition
L. Hébert-Dufresne, J. A. Grochow, and A. Allard
Scientific Reports 6, 31708 (2016)
http://doi.org/10.1038/srep31708
.. [2] Percolation and the effective structure of complex networks
A. Allard and L. Hébert-Dufresne
Physical Review X 9, 011023 (2019)
http://doi.org/10.1103/PhysRevX.9.011023
| null | (G, *, backend=None, **backend_kwargs) |
30,983 | networkx.algorithms.similarity | optimal_edit_paths | Returns all minimum-cost edit paths transforming G1 to G2.
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.
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.
Returns
-------
edit_paths : list of tuples (node_edit_path, edge_edit_path)
node_edit_path : list of tuples (u, v)
edge_edit_path : list of tuples ((u1, v1), (u2, v2))
cost : numeric
Optimal edit path cost (graph edit distance). When the cost
is zero, it indicates that `G1` and `G2` are isomorphic.
Examples
--------
>>> G1 = nx.cycle_graph(4)
>>> G2 = nx.wheel_graph(5)
>>> paths, cost = nx.optimal_edit_paths(G1, G2)
>>> len(paths)
40
>>> cost
5.0
Notes
-----
To transform `G1` into a graph isomorphic to `G2`, apply the node
and edge edits in the returned ``edit_paths``.
In the case of isomorphic graphs, the cost is zero, and the paths
represent different isomorphic mappings (isomorphisms). That is, the
edits involve renaming nodes and edges to match the structure of `G2`.
See Also
--------
graph_edit_distance, optimize_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
| 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)
| (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, *, backend=None, **backend_kwargs) |
30,984 | networkx.algorithms.similarity | optimize_edit_paths | 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
| 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)
| (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, *, backend=None, **backend_kwargs) |
30,985 | networkx.algorithms.similarity | optimize_graph_edit_distance | Returns consecutive approximations of GED (graph edit distance)
between graphs G1 and G2.
Graph edit distance is a graph similarity measure analogous to
Levenshtein distance for strings. It is defined as minimum cost
of edit path (sequence of node and edge edit operations)
transforming graph G1 to graph isomorphic to G2.
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.
Returns
-------
Generator of consecutive approximations of graph edit distance.
Examples
--------
>>> G1 = nx.cycle_graph(6)
>>> G2 = nx.wheel_graph(7)
>>> for v in nx.optimize_graph_edit_distance(G1, G2):
... minv = v
>>> minv
7.0
See Also
--------
graph_edit_distance, optimize_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
| 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)
| (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, *, backend=None, **backend_kwargs) |
30,986 | networkx.algorithms.centrality.degree_alg | out_degree_centrality | Compute the out-degree centrality for nodes.
The out-degree centrality for a node v is the fraction of nodes its
outgoing edges are connected to.
Parameters
----------
G : graph
A NetworkX graph
Returns
-------
nodes : dictionary
Dictionary of nodes with out-degree centrality as values.
Raises
------
NetworkXNotImplemented
If G is undirected.
Examples
--------
>>> G = nx.DiGraph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
>>> nx.out_degree_centrality(G)
{0: 1.0, 1: 0.6666666666666666, 2: 0.0, 3: 0.0}
See Also
--------
degree_centrality, in_degree_centrality
Notes
-----
The degree centrality values are normalized by dividing by the maximum
possible degree in a simple graph n-1 where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might
be higher than n-1 and values of degree centrality greater than 1
are possible.
| null | (G, *, backend=None, **backend_kwargs) |
30,987 | networkx.algorithms.reciprocity | overall_reciprocity | Compute the reciprocity for the whole graph.
See the doc of reciprocity for the definition.
Parameters
----------
G : graph
A networkx graph
| null | (G, *, backend=None, **backend_kwargs) |
30,988 | networkx.algorithms.link_analysis.pagerank_alg | pagerank | Returns the PageRank of the nodes in the graph.
PageRank computes a ranking of the nodes in the graph G based on
the structure of the incoming links. It was originally designed as
an algorithm to rank web pages.
Parameters
----------
G : graph
A NetworkX graph. Undirected graphs will be converted to a directed
graph with two directed edges for each undirected edge.
alpha : float, optional
Damping parameter for PageRank, default=0.85.
personalization: dict, optional
The "personalization vector" consisting of a dictionary with a
key some subset of graph nodes and personalization value each of those.
At least one personalization value must be non-zero.
If not specified, a nodes personalization value will be zero.
By default, a uniform distribution is used.
max_iter : integer, optional
Maximum number of iterations in power method eigenvalue solver.
tol : float, optional
Error tolerance used to check convergence in power method solver.
The iteration will stop after a tolerance of ``len(G) * tol`` is reached.
nstart : dictionary, optional
Starting value of PageRank iteration for each node.
weight : key, optional
Edge data key to use as weight. If None weights are set to 1.
dangling: dict, optional
The outedges to be assigned to any "dangling" nodes, i.e., nodes without
any outedges. The dict key is the node the outedge points to and the dict
value is the weight of that outedge. By default, dangling nodes are given
outedges according to the personalization vector (uniform if not
specified). This must be selected to result in an irreducible transition
matrix (see notes under google_matrix). It may be common to have the
dangling dict to be the same as the personalization dict.
Returns
-------
pagerank : dictionary
Dictionary of nodes with PageRank as value
Examples
--------
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank(G, alpha=0.9)
Notes
-----
The eigenvector calculation is done by the power iteration method
and has no guarantee of convergence. The iteration will stop after
an error tolerance of ``len(G) * tol`` has been reached. If the
number of iterations exceed `max_iter`, a
:exc:`networkx.exception.PowerIterationFailedConvergence` exception
is raised.
The PageRank algorithm was designed for directed graphs but this
algorithm does not check if the input graph is directed and will
execute on undirected graphs by converting each edge in the
directed graph to two edges.
See Also
--------
google_matrix
Raises
------
PowerIterationFailedConvergence
If the algorithm fails to converge to the specified tolerance
within the specified number of iterations of the power iteration
method.
References
----------
.. [1] A. Langville and C. Meyer,
"A survey of eigenvector methods of web information retrieval."
http://citeseer.ist.psu.edu/713792.html
.. [2] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry,
The PageRank citation ranking: Bringing order to the Web. 1999
http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-66&format=pdf
| null | (G, alpha=0.85, personalization=None, max_iter=100, tol=1e-06, nstart=None, weight='weight', dangling=None, *, backend=None, **backend_kwargs) |
30,992 | networkx.generators.expanders | paley_graph | Returns the Paley $\frac{(p-1)}{2}$ -regular graph on $p$ nodes.
The returned graph is a graph on $\mathbb{Z}/p\mathbb{Z}$ with edges between $x$ and $y$
if and only if $x-y$ is a nonzero square in $\mathbb{Z}/p\mathbb{Z}$.
If $p \equiv 1 \pmod 4$, $-1$ is a square in $\mathbb{Z}/p\mathbb{Z}$ and therefore $x-y$ is a square if and
only if $y-x$ is also a square, i.e the edges in the Paley graph are symmetric.
If $p \equiv 3 \pmod 4$, $-1$ is not a square in $\mathbb{Z}/p\mathbb{Z}$ and therefore either $x-y$ or $y-x$
is a square in $\mathbb{Z}/p\mathbb{Z}$ but not both.
Note that a more general definition of Paley graphs extends this construction
to graphs over $q=p^n$ vertices, by using the finite field $F_q$ instead of $\mathbb{Z}/p\mathbb{Z}$.
This construction requires to compute squares in general finite fields and is
not what is implemented here (i.e `paley_graph(25)` does not return the true
Paley graph associated with $5^2$).
Parameters
----------
p : int, an odd prime number.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
Returns
-------
G : graph
The constructed directed graph.
Raises
------
NetworkXError
If the graph is a multigraph.
References
----------
Chapter 13 in B. Bollobas, Random Graphs. Second edition.
Cambridge Studies in Advanced Mathematics, 73.
Cambridge University Press, Cambridge (2001).
| null | (p, create_using=None, *, backend=None, **backend_kwargs) |
30,993 | networkx.algorithms.similarity | panther_similarity | Returns the Panther similarity of nodes in the graph `G` to node ``v``.
Panther is a similarity metric that says "two objects are considered
to be similar if they frequently appear on the same paths." [1]_.
Parameters
----------
G : NetworkX graph
A NetworkX graph
source : node
Source node for which to find the top `k` similar other nodes
k : int (default = 5)
The number of most similar nodes to return.
path_length : int (default = 5)
How long the randomly generated paths should be (``T`` in [1]_)
c : float (default = 0.5)
A universal positive constant used to scale the number
of sample random paths to generate.
delta : float (default = 0.1)
The probability that the similarity $S$ is not an epsilon-approximation to (R, phi),
where $R$ is the number of random paths and $\phi$ is the probability
that an element sampled from a set $A \subseteq D$, where $D$ is the domain.
eps : float or None (default = None)
The error bound. Per [1]_, a good value is ``sqrt(1/|E|)``. Therefore,
if no value is provided, the recommended computed value will be used.
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
-------
similarity : dictionary
Dictionary of nodes to similarity scores (as floats). Note:
the self-similarity (i.e., ``v``) will not be included in
the returned dictionary. So, for ``k = 5``, a dictionary of
top 4 nodes and their similarity scores will be returned.
Raises
------
NetworkXUnfeasible
If `source` is an isolated node.
NodeNotFound
If `source` is not in `G`.
Notes
-----
The isolated nodes in `G` are ignored.
Examples
--------
>>> G = nx.star_graph(10)
>>> sim = nx.panther_similarity(G, 0)
References
----------
.. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.
Panther: Fast top-k similarity search on large networks.
In Proceedings of the ACM SIGKDD International Conference
on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).
Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
| 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, k=5, path_length=5, c=0.5, delta=0.1, eps=None, weight='weight', *, backend=None, **backend_kwargs) |
30,994 | networkx.generators.small | pappus_graph |
Returns the Pappus graph.
The Pappus graph is a cubic symmetric distance-regular graph with 18 nodes
and 27 edges. It is Hamiltonian and can be represented in LCF notation as
[5,7,-7,7,-7,-5]^3 [1]_.
Returns
-------
G : networkx Graph
Pappus graph
References
----------
.. [1] https://en.wikipedia.org/wiki/Pappus_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
| (*, backend=None, **backend_kwargs) |
30,995 | networkx.readwrite.adjlist | parse_adjlist | Parse lines of a graph adjacency list representation.
Parameters
----------
lines : list or iterator of strings
Input data in adjlist format
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
--------
>>> lines = ["1 2 5", "2 3 4", "3 5", "4", "5"]
>>> G = nx.parse_adjlist(lines, nodetype=int)
>>> nodes = [1, 2, 3, 4, 5]
>>> all(node in G for node in nodes)
True
>>> edges = [(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)]
>>> all((u, v) in G.edges() or (v, u) in G.edges() for (u, v) in edges)
True
See Also
--------
read_adjlist
| null | (lines, comments='#', delimiter=None, create_using=None, nodetype=None, *, backend=None, **backend_kwargs) |
30,996 | networkx.readwrite.edgelist | parse_edgelist | Parse lines of an edge list representation of a graph.
Parameters
----------
lines : list or iterator of strings
Input data in edgelist format
comments : string, optional
Marker for comment lines. Default is `'#'`. To specify that no character
should be treated as a comment, use ``comments=None``.
delimiter : string, optional
Separator for node labels. Default is `None`, meaning any whitespace.
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. Default is `None`, meaning no conversion is
performed.
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 graph corresponding to lines
Examples
--------
Edgelist with no data:
>>> lines = ["1 2", "2 3", "3 4"]
>>> G = nx.parse_edgelist(lines, nodetype=int)
>>> list(G)
[1, 2, 3, 4]
>>> list(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 = nx.parse_edgelist(lines, nodetype=int)
>>> list(G)
[1, 2, 3, 4]
>>> list(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 = nx.parse_edgelist(lines, nodetype=int, data=(("weight", float),))
>>> list(G)
[1, 2, 3, 4]
>>> list(G.edges(data=True))
[(1, 2, {'weight': 3.0}), (2, 3, {'weight': 27.0}), (3, 4, {'weight': 3.0})]
See Also
--------
read_weighted_edgelist
| null | (lines, comments='#', delimiter=None, create_using=None, nodetype=None, data=True, *, backend=None, **backend_kwargs) |
30,997 | networkx.readwrite.gml | parse_gml | Parse GML graph from a string or iterable.
Parameters
----------
lines : string or iterable of strings
Data in GML format.
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, read_gml
Notes
-----
This stores nested GML attributes as dictionaries in the NetworkX graph,
node, and edge attribute structures.
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.
| 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 "]"
| (lines, label='label', destringizer=None, *, backend=None, **backend_kwargs) |
30,998 | networkx.readwrite.graphml | parse_graphml | Read graph in GraphML format from string.
Parameters
----------
graphml_string : string
String containing graphml information
(e.g., contents of a graphml file).
node_type: Python type (default: str)
Convert node ids to this type
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 no parallel edges are found a Graph or DiGraph is returned.
Otherwise a MultiGraph or MultiDiGraph is returned.
Examples
--------
>>> G = nx.path_graph(4)
>>> linefeed = chr(10) # linefeed =
>>> s = linefeed.join(nx.generate_graphml(G))
>>> H = nx.parse_graphml(s)
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.
| 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
| (graphml_string, node_type=<class 'str'>, edge_key_type=<class 'int'>, force_multigraph=False, *, backend=None, **backend_kwargs) |
30,999 | networkx.readwrite.leda | parse_leda | Read graph in LEDA format from string or iterable.
Parameters
----------
lines : string or iterable
Data in LEDA format.
Returns
-------
G : NetworkX graph
Examples
--------
G=nx.parse_leda(string)
References
----------
.. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
| null | (lines, *, backend=None, **backend_kwargs) |
31,000 | networkx.readwrite.multiline_adjlist | parse_multiline_adjlist | Parse lines of a multiline adjacency list representation of a graph.
Parameters
----------
lines : list or iterator of strings
Input data in multiline adjlist format
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 edges 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 multiline adjacency list format.
Examples
--------
>>> lines = [
... "1 2",
... "2 {'weight':3, 'name': 'Frodo'}",
... "3 {}",
... "2 1",
... "5 {'weight':6, 'name': 'Saruman'}",
... ]
>>> G = nx.parse_multiline_adjlist(iter(lines), nodetype=int)
>>> list(G)
[1, 2, 3, 5]
| null | (lines, comments='#', delimiter=None, create_using=None, nodetype=None, edgetype=None, *, backend=None, **backend_kwargs) |
31,001 | networkx.readwrite.pajek | parse_pajek | Parse Pajek format graph from string or iterable.
Parameters
----------
lines : string or iterable
Data in Pajek format.
Returns
-------
G : NetworkX graph
See Also
--------
read_pajek
| null | (lines, *, backend=None, **backend_kwargs) |
31,002 | networkx.generators.duplication | partial_duplication_graph | Returns a random graph using the partial duplication model.
Parameters
----------
N : int
The total number of nodes in the final graph.
n : int
The number of nodes in the initial clique.
p : float
The probability of joining each neighbor of a node to the
duplicate node. Must be a number in the between zero and one,
inclusive.
q : float
The probability of joining the source node to the duplicate
node. Must be a number in the between zero and one, inclusive.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Notes
-----
A graph of nodes is grown by creating a fully connected graph
of size `n`. The following procedure is then repeated until
a total of `N` nodes have been reached.
1. A random node, *u*, is picked and a new node, *v*, is created.
2. For each neighbor of *u* an edge from the neighbor to *v* is created
with probability `p`.
3. An edge from *u* to *v* is created with probability `q`.
This algorithm appears in [1].
This implementation allows the possibility of generating
disconnected graphs.
References
----------
.. [1] Knudsen Michael, and Carsten Wiuf. "A Markov chain approach to
randomly grown graphs." Journal of Applied Mathematics 2008.
<https://doi.org/10.1155/2008/190836>
| null | (N, n, p, q, seed=None, *, backend=None, **backend_kwargs) |
31,003 | networkx.algorithms.tree.mst | partition_spanning_tree |
Find a spanning tree while respecting a partition of edges.
Edges can be flagged as either `INCLUDED` which are required to be in the
returned tree, `EXCLUDED`, which cannot be in the returned tree and `OPEN`.
This is used in the SpanningTreeIterator to create new partitions following
the algorithm of Sörensen and Janssens [1]_.
Parameters
----------
G : undirected graph
An undirected graph.
minimum : bool (default: True)
Determines whether the returned tree is the minimum spanning tree of
the partition of the maximum one.
weight : str
Data key to use for edge weights.
partition : str
The key for the edge attribute containing the partition
data on the graph. Edges can be included, excluded or open using the
`EdgePartition` enum.
ignore_nan : bool (default: False)
If a NaN is found as an edge weight normally an exception is raised.
If `ignore_nan is True` then that edge is ignored instead.
Returns
-------
G : NetworkX Graph
A minimum spanning tree using all of the included edges in the graph and
none of the excluded edges.
References
----------
.. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning
trees in order of increasing cost, Pesquisa Operacional, 2005-08,
Vol. 25 (2), p. 219-229,
https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en
| def random_spanning_tree(G, weight=None, *, multiplicative=True, seed=None):
"""
Sample a random spanning tree using the edges weights of `G`.
This function supports two different methods for determining the
probability of the graph. If ``multiplicative=True``, the probability
is based on the product of edge weights, and if ``multiplicative=False``
it is based on the sum of the edge weight. However, since it is
easier to determine the total weight of all spanning trees for the
multiplicative version, that is significantly faster and should be used if
possible. Additionally, setting `weight` to `None` will cause a spanning tree
to be selected with uniform probability.
The function uses algorithm A8 in [1]_ .
Parameters
----------
G : nx.Graph
An undirected version of the original graph.
weight : string
The edge key for the edge attribute holding edge weight.
multiplicative : bool, default=True
If `True`, the probability of each tree is the product of its edge weight
over the sum of the product of all the spanning trees in the graph. If
`False`, the probability is the sum of its edge weight over the sum of
the sum of weights for all spanning trees in the graph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
nx.Graph
A spanning tree using the distribution defined by the weight of the tree.
References
----------
.. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
Algorithms, 11 (1990), pp. 185–207
"""
def find_node(merged_nodes, node):
"""
We can think of clusters of contracted nodes as having one
representative in the graph. Each node which is not in merged_nodes
is still its own representative. Since a representative can be later
contracted, we need to recursively search though the dict to find
the final representative, but once we know it we can use path
compression to speed up the access of the representative for next time.
This cannot be replaced by the standard NetworkX union_find since that
data structure will merge nodes with less representing nodes into the
one with more representing nodes but this function requires we merge
them using the order that contract_edges contracts using.
Parameters
----------
merged_nodes : dict
The dict storing the mapping from node to representative
node
The node whose representative we seek
Returns
-------
The representative of the `node`
"""
if node not in merged_nodes:
return node
else:
rep = find_node(merged_nodes, merged_nodes[node])
merged_nodes[node] = rep
return rep
def prepare_graph():
"""
For the graph `G`, remove all edges not in the set `V` and then
contract all edges in the set `U`.
Returns
-------
A copy of `G` which has had all edges not in `V` removed and all edges
in `U` contracted.
"""
# The result is a MultiGraph version of G so that parallel edges are
# allowed during edge contraction
result = nx.MultiGraph(incoming_graph_data=G)
# Remove all edges not in V
edges_to_remove = set(result.edges()).difference(V)
result.remove_edges_from(edges_to_remove)
# Contract all edges in U
#
# Imagine that you have two edges to contract and they share an
# endpoint like this:
# [0] ----- [1] ----- [2]
# If we contract (0, 1) first, the contraction function will always
# delete the second node it is passed so the resulting graph would be
# [0] ----- [2]
# and edge (1, 2) no longer exists but (0, 2) would need to be contracted
# in its place now. That is why I use the below dict as a merge-find
# data structure with path compression to track how the nodes are merged.
merged_nodes = {}
for u, v in U:
u_rep = find_node(merged_nodes, u)
v_rep = find_node(merged_nodes, v)
# We cannot contract a node with itself
if u_rep == v_rep:
continue
nx.contracted_nodes(result, u_rep, v_rep, self_loops=False, copy=False)
merged_nodes[v_rep] = u_rep
return merged_nodes, result
def spanning_tree_total_weight(G, weight):
"""
Find the sum of weights of the spanning trees of `G` using the
appropriate `method`.
This is easy if the chosen method is 'multiplicative', since we can
use Kirchhoff's Tree Matrix Theorem directly. However, with the
'additive' method, this process is slightly more complex and less
computationally efficient as we have to find the number of spanning
trees which contain each possible edge in the graph.
Parameters
----------
G : NetworkX Graph
The graph to find the total weight of all spanning trees on.
weight : string
The key for the weight edge attribute of the graph.
Returns
-------
float
The sum of either the multiplicative or additive weight for all
spanning trees in the graph.
"""
if multiplicative:
return nx.total_spanning_tree_weight(G, weight)
else:
# There are two cases for the total spanning tree additive weight.
# 1. There is one edge in the graph. Then the only spanning tree is
# that edge itself, which will have a total weight of that edge
# itself.
if G.number_of_edges() == 1:
return G.edges(data=weight).__iter__().__next__()[2]
# 2. There are no edges or two or more edges in the graph. Then, we find the
# total weight of the spanning trees using the formula in the
# reference paper: take the weight of each edge and multiply it by
# the number of spanning trees which include that edge. This
# can be accomplished by contracting the edge and finding the
# multiplicative total spanning tree weight if the weight of each edge
# is assumed to be 1, which is conveniently built into networkx already,
# by calling total_spanning_tree_weight with weight=None.
# Note that with no edges the returned value is just zero.
else:
total = 0
for u, v, w in G.edges(data=weight):
total += w * nx.total_spanning_tree_weight(
nx.contracted_edge(G, edge=(u, v), self_loops=False), None
)
return total
if G.number_of_nodes() < 2:
# no edges in the spanning tree
return nx.empty_graph(G.nodes)
U = set()
st_cached_value = 0
V = set(G.edges())
shuffled_edges = list(G.edges())
seed.shuffle(shuffled_edges)
for u, v in shuffled_edges:
e_weight = G[u][v][weight] if weight is not None else 1
node_map, prepared_G = prepare_graph()
G_total_tree_weight = spanning_tree_total_weight(prepared_G, weight)
# Add the edge to U so that we can compute the total tree weight
# assuming we include that edge
# Now, if (u, v) cannot exist in G because it is fully contracted out
# of existence, then it by definition cannot influence G_e's Kirchhoff
# value. But, we also cannot pick it.
rep_edge = (find_node(node_map, u), find_node(node_map, v))
# Check to see if the 'representative edge' for the current edge is
# in prepared_G. If so, then we can pick it.
if rep_edge in prepared_G.edges:
prepared_G_e = nx.contracted_edge(
prepared_G, edge=rep_edge, self_loops=False
)
G_e_total_tree_weight = spanning_tree_total_weight(prepared_G_e, weight)
if multiplicative:
threshold = e_weight * G_e_total_tree_weight / G_total_tree_weight
else:
numerator = (
st_cached_value + e_weight
) * nx.total_spanning_tree_weight(prepared_G_e) + G_e_total_tree_weight
denominator = (
st_cached_value * nx.total_spanning_tree_weight(prepared_G)
+ G_total_tree_weight
)
threshold = numerator / denominator
else:
threshold = 0.0
z = seed.uniform(0.0, 1.0)
if z > threshold:
# Remove the edge from V since we did not pick it.
V.remove((u, v))
else:
# Add the edge to U since we picked it.
st_cached_value += e_weight
U.add((u, v))
# If we decide to keep an edge, it may complete the spanning tree.
if len(U) == G.number_of_nodes() - 1:
spanning_tree = nx.Graph()
spanning_tree.add_edges_from(U)
return spanning_tree
raise Exception(f"Something went wrong! Only {len(U)} edges in the spanning tree!")
| (G, minimum=True, weight='weight', partition='partition', ignore_nan=False, *, backend=None, **backend_kwargs) |
31,004 | networkx.generators.classic | path_graph | Returns the Path graph `P_n` of linearly connected nodes.
.. plot::
>>> nx.draw(nx.path_graph(5))
Parameters
----------
n : int or iterable
If an integer, nodes are 0 to n - 1.
If an iterable of nodes, in the order they appear in the path.
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.
| 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,005 | networkx.classes.function | path_weight | Returns total cost associated with specified path and weight
Parameters
----------
G : graph
A NetworkX graph.
path: list
A list of node labels which defines the path to traverse
weight: string
A string indicating which edge attribute to use for path cost
Returns
-------
cost: int or float
An integer or a float representing the total cost with respect to the
specified weight of the specified path
Raises
------
NetworkXNoPath
If the specified edge does not exist.
| def path_weight(G, path, weight):
"""Returns total cost associated with specified path and weight
Parameters
----------
G : graph
A NetworkX graph.
path: list
A list of node labels which defines the path to traverse
weight: string
A string indicating which edge attribute to use for path cost
Returns
-------
cost: int or float
An integer or a float representing the total cost with respect to the
specified weight of the specified path
Raises
------
NetworkXNoPath
If the specified edge does not exist.
"""
multigraph = G.is_multigraph()
cost = 0
if not nx.is_path(G, path):
raise nx.NetworkXNoPath("path does not exist")
for node, nbr in nx.utils.pairwise(path):
if multigraph:
cost += min(v[weight] for v in G._adj[node][nbr].values())
else:
cost += G._adj[node][nbr][weight]
return cost
| (G, path, weight) |
31,007 | networkx.algorithms.centrality.percolation | percolation_centrality | Compute the percolation centrality for nodes.
Percolation centrality of a node $v$, at a given time, is defined
as the proportion of ‘percolated paths’ that go through that node.
This measure quantifies relative impact of nodes based on their
topological connectivity, as well as their percolation states.
Percolation states of nodes are used to depict network percolation
scenarios (such as during infection transmission in a social network
of individuals, spreading of computer viruses on computer networks, or
transmission of disease over a network of towns) over time. In this
measure usually the percolation state is expressed as a decimal
between 0.0 and 1.0.
When all nodes are in the same percolated state this measure is
equivalent to betweenness centrality.
Parameters
----------
G : graph
A NetworkX graph.
attribute : None or string, optional (default='percolation')
Name of the node attribute to use for percolation state, used
if `states` is None. If a node does not set the attribute the
state of that node will be set to the default value of 1.
If all nodes do not have the attribute all nodes will be set to
1 and the centrality measure will be equivalent to betweenness centrality.
states : None or dict, optional (default=None)
Specify percolation states for the nodes, nodes as keys states
as values.
weight : None or string, optional (default=None)
If None, all edge weights are considered equal.
Otherwise holds the name of the edge attribute used as weight.
The weight of an edge is treated as the length or distance between the two sides.
Returns
-------
nodes : dictionary
Dictionary of nodes with percolation centrality as the value.
See Also
--------
betweenness_centrality
Notes
-----
The algorithm is from Mahendra Piraveenan, Mikhail Prokopenko, and
Liaquat Hossain [1]_
Pair dependencies are calculated and accumulated using [2]_
For weighted graphs the edge weights must be greater than zero.
Zero edge weights can produce an infinite number of equal length
paths between pairs of nodes.
References
----------
.. [1] Mahendra Piraveenan, Mikhail Prokopenko, Liaquat Hossain
Percolation Centrality: Quantifying Graph-Theoretic Impact of Nodes
during Percolation in Networks
http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0053095
.. [2] Ulrik Brandes:
A Faster Algorithm for Betweenness Centrality.
Journal of Mathematical Sociology 25(2):163-177, 2001.
https://doi.org/10.1080/0022250X.2001.9990249
| null | (G, attribute='percolation', states=None, weight=None, *, backend=None, **backend_kwargs) |
31,008 | networkx.algorithms.distance_measures | periphery | Returns the periphery of the graph G.
The periphery is the set of nodes with eccentricity equal to the diameter.
Parameters
----------
G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
weight : string, function, or None
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.
If this is None, every edge has weight/distance/cost 1.
Weights stored as floating point values can lead to small round-off
errors in distances. Use integer weights to avoid this.
Weights should be positive, since they are distances.
Returns
-------
p : list
List of nodes in periphery
Examples
--------
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
>>> nx.periphery(G)
[2, 5]
See Also
--------
barycenter
center
| 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, e=None, usebounds=False, weight=None, *, backend=None, **backend_kwargs) |
31,009 | networkx.generators.small | petersen_graph |
Returns the Petersen graph.
The Peterson graph is a cubic, undirected graph with 10 nodes and 15 edges [1]_.
Julius Petersen constructed the graph as the smallest counterexample
against the claim that a connected bridgeless cubic graph
has an edge colouring with three colours [2]_.
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
Petersen graph
References
----------
.. [1] https://en.wikipedia.org/wiki/Petersen_graph
.. [2] https://www.win.tue.nl/~aeb/drg/graphs/Petersen.html
| def _raise_on_directed(func):
"""
A decorator which inspects the `create_using` argument and raises a
NetworkX exception when `create_using` is a DiGraph (class or instance) for
graph generators that do not support directed outputs.
"""
@wraps(func)
def wrapper(*args, **kwargs):
if kwargs.get("create_using") is not None:
G = nx.empty_graph(create_using=kwargs["create_using"])
if G.is_directed():
raise NetworkXError("Directed Graph not supported")
return func(*args, **kwargs)
return wrapper
| (create_using=None, *, backend=None, **backend_kwargs) |
31,011 | networkx.drawing.layout | planar_layout | Position nodes without edge intersections.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G. If G is of type
nx.PlanarEmbedding, the positions are selected accordingly.
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
Raises
------
NetworkXException
If G is not planar
Examples
--------
>>> G = nx.path_graph(4)
>>> pos = nx.planar_layout(G)
| def planar_layout(G, scale=1, center=None, dim=2):
"""Position nodes without edge intersections.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G. If G is of type
nx.PlanarEmbedding, the positions are selected accordingly.
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
Raises
------
NetworkXException
If G is not planar
Examples
--------
>>> G = nx.path_graph(4)
>>> pos = nx.planar_layout(G)
"""
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 isinstance(G, nx.PlanarEmbedding):
embedding = G
else:
is_planar, embedding = nx.check_planarity(G)
if not is_planar:
raise nx.NetworkXException("G is not planar.")
pos = nx.combinatorial_embedding_to_pos(embedding)
node_list = list(embedding)
pos = np.vstack([pos[x] for x in node_list])
pos = pos.astype(np.float64)
pos = rescale_layout(pos, scale=scale) + center
return dict(zip(node_list, pos))
| (G, scale=1, center=None, dim=2) |
31,013 | networkx.generators.community | planted_partition_graph | Returns the planted l-partition graph.
This model partitions a graph with n=l*k vertices in
l groups with k vertices each. Vertices of the same
group are linked with a probability p_in, and vertices
of different groups are linked with probability p_out.
Parameters
----------
l : int
Number of groups
k : int
Number of vertices in each group
p_in : float
probability of connecting vertices within a group
p_out : float
probability of connected vertices between groups
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
Returns
-------
G : NetworkX Graph or DiGraph
planted l-partition graph
Raises
------
NetworkXError
If `p_in`, `p_out` are not in `[0, 1]`
Examples
--------
>>> G = nx.planted_partition_graph(4, 3, 0.5, 0.1, seed=42)
See Also
--------
random_partition_model
References
----------
.. [1] A. Condon, R.M. Karp, Algorithms for graph partitioning
on the planted partition model,
Random Struct. Algor. 18 (2001) 116-140.
.. [2] Santo Fortunato 'Community Detection in Graphs' Physical Reports
Volume 486, Issue 3-5 p. 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_in, p_out, seed=None, directed=False, *, backend=None, **backend_kwargs) |
31,015 | networkx.algorithms.operators.product | power | Returns the specified power of a graph.
The $k$th power of a simple graph $G$, denoted $G^k$, is a
graph on the same set of nodes in which two distinct nodes $u$ and
$v$ are adjacent in $G^k$ if and only if the shortest path
distance between $u$ and $v$ in $G$ is at most $k$.
Parameters
----------
G : graph
A NetworkX simple graph object.
k : positive integer
The power to which to raise the graph `G`.
Returns
-------
NetworkX simple graph
`G` to the power `k`.
Raises
------
ValueError
If the exponent `k` is not positive.
NetworkXNotImplemented
If `G` is not a simple graph.
Examples
--------
The number of edges will never decrease when taking successive
powers:
>>> G = nx.path_graph(4)
>>> list(nx.power(G, 2).edges)
[(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
>>> list(nx.power(G, 3).edges)
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
The `k` th power of a cycle graph on *n* nodes is the complete graph
on *n* nodes, if `k` is at least ``n // 2``:
>>> G = nx.cycle_graph(5)
>>> H = nx.complete_graph(5)
>>> nx.is_isomorphic(nx.power(G, 2), H)
True
>>> G = nx.cycle_graph(8)
>>> H = nx.complete_graph(8)
>>> nx.is_isomorphic(nx.power(G, 4), H)
True
References
----------
.. [1] J. A. Bondy, U. S. R. Murty, *Graph Theory*. Springer, 2008.
Notes
-----
This definition of "power graph" comes from Exercise 3.1.6 of
*Graph Theory* by Bondy and Murty [1]_.
| null | (G, k, *, backend=None, **backend_kwargs) |
31,016 | networkx.generators.random_graphs | powerlaw_cluster_graph | Holme and Kim algorithm for growing graphs with powerlaw
degree distribution and approximate average clustering.
Parameters
----------
n : int
the number of nodes
m : int
the number of random edges to add for each new node
p : float,
Probability of adding a triangle after adding a random edge
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Notes
-----
The average clustering has a hard time getting above a certain
cutoff that depends on `m`. This cutoff is often quite low. The
transitivity (fraction of triangles to possible triangles) seems to
decrease with network size.
It is essentially the Barabási–Albert (BA) growth model with an
extra step that each random edge is followed by a chance of
making an edge to one of its neighbors too (and thus a triangle).
This algorithm improves on BA in the sense that it enables a
higher average clustering to be attained if desired.
It seems possible to have a disconnected graph with this algorithm
since the initial `m` nodes may not be all linked to a new node
on the first iteration like the BA model.
Raises
------
NetworkXError
If `m` does not satisfy ``1 <= m <= n`` or `p` does not
satisfy ``0 <= p <= 1``.
References
----------
.. [1] P. Holme and B. J. Kim,
"Growing scale-free networks with tunable clustering",
Phys. Rev. E, 65, 026107, 2002.
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (n, m, p, seed=None, *, backend=None, **backend_kwargs) |
31,017 | networkx.algorithms.shortest_paths.unweighted | predecessor | Returns dict of predecessors for the path from source to all nodes in G.
Parameters
----------
G : NetworkX graph
source : node label
Starting node for path
target : node label, optional
Ending node for path. If provided only predecessors between
source and target are returned
cutoff : integer, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
return_seen : bool, optional (default=None)
Whether to return a dictionary, keyed by node, of the level (number of
hops) to reach the node (as seen during breadth-first-search).
Returns
-------
pred : dictionary
Dictionary, keyed by node, of predecessors in the shortest path.
(pred, seen): tuple of dictionaries
If `return_seen` argument is set to `True`, then a tuple of dictionaries
is returned. The first element is the dictionary, keyed by node, of
predecessors in the shortest path. The second element is the dictionary,
keyed by node, of the level (number of hops) to reach the node (as seen
during breadth-first-search).
Examples
--------
>>> G = nx.path_graph(4)
>>> list(G)
[0, 1, 2, 3]
>>> nx.predecessor(G, 0)
{0: [], 1: [0], 2: [1], 3: [2]}
>>> nx.predecessor(G, 0, return_seen=True)
({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})
| null | (G, source, target=None, cutoff=None, return_seen=None, *, backend=None, **backend_kwargs) |
31,018 | networkx.algorithms.link_prediction | preferential_attachment | Compute the preferential attachment score of all node pairs in ebunch.
Preferential attachment score of `u` and `v` is defined as
.. math::
|\Gamma(u)| |\Gamma(v)|
where $\Gamma(u)$ denotes the set of neighbors of $u$.
Parameters
----------
G : graph
NetworkX undirected graph.
ebunch : iterable of node pairs, optional (default = None)
Preferential attachment score 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 preferential attachment score.
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.preferential_attachment(G, [(0, 1), (2, 3)])
>>> for u, v, p in preds:
... print(f"({u}, {v}) -> {p}")
(0, 1) -> 16
(2, 3) -> 16
References
----------
.. [1] D. Liben-Nowell, J. Kleinberg.
The Link Prediction Problem for Social Networks (2004).
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
| null | (G, ebunch=None, *, backend=None, **backend_kwargs) |
31,019 | networkx.generators.trees | prefix_tree | Creates a directed prefix tree from a list of paths.
Usually the paths are described as strings or lists of integers.
A "prefix tree" represents the prefix structure of the strings.
Each node represents a prefix of some string. The root represents
the empty prefix with children for the single letter prefixes which
in turn have children for each double letter prefix starting with
the single letter corresponding to the parent node, and so on.
More generally the prefixes do not need to be strings. A prefix refers
to the start of a sequence. The root has children for each one element
prefix and they have children for each two element prefix that starts
with the one element sequence of the parent, and so on.
Note that this implementation uses integer nodes with an attribute.
Each node has an attribute "source" whose value is the original element
of the path to which this node corresponds. For example, suppose `paths`
consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
this path have "source" values "c", "a" and "n".
All the descendants of a node have a common prefix in the sequence/path
associated with that node. From the returned tree, the prefix for each
node can be constructed by traversing the tree up to the root and
accumulating the "source" values along the way.
The root node is always `0` and has "source" attribute `None`.
The root is the only node with in-degree zero.
The nil node is always `-1` and has "source" attribute `"NIL"`.
The nil node is the only node with out-degree zero.
Parameters
----------
paths: iterable of paths
An iterable of paths which are themselves sequences.
Matching prefixes among these sequences are identified with
nodes of the prefix tree. One leaf of the tree is associated
with each path. (Identical paths are associated with the same
leaf of the tree.)
Returns
-------
tree: DiGraph
A directed graph representing an arborescence consisting of the
prefix tree generated by `paths`. Nodes are directed "downward",
from parent to child. A special "synthetic" root node is added
to be the parent of the first node in each path. A special
"synthetic" leaf node, the "nil" node `-1`, is added to be the child
of all nodes representing the last element in a path. (The
addition of this nil node technically makes this not an
arborescence but a directed acyclic graph; removing the nil node
makes it an arborescence.)
Notes
-----
The prefix tree is also known as a *trie*.
Examples
--------
Create a prefix tree from a list of strings with common prefixes::
>>> paths = ["ab", "abs", "ad"]
>>> T = nx.prefix_tree(paths)
>>> list(T.edges)
[(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]
The leaf nodes can be obtained as predecessors of the nil node::
>>> root, NIL = 0, -1
>>> list(T.predecessors(NIL))
[2, 3, 4]
To recover the original paths that generated the prefix tree,
traverse up the tree from the node `-1` to the node `0`::
>>> recovered = []
>>> for v in T.predecessors(NIL):
... prefix = ""
... while v != root:
... prefix = str(T.nodes[v]["source"]) + prefix
... v = next(T.predecessors(v)) # only one predecessor
... recovered.append(prefix)
>>> sorted(recovered)
['ab', 'abs', 'ad']
| 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)
]
| (paths, *, backend=None, **backend_kwargs) |
31,020 | networkx.generators.trees | prefix_tree_recursive | Recursively creates a directed prefix tree from a list of paths.
The original recursive version of prefix_tree for comparison. It is
the same algorithm but the recursion is unrolled onto a stack.
Usually the paths are described as strings or lists of integers.
A "prefix tree" represents the prefix structure of the strings.
Each node represents a prefix of some string. The root represents
the empty prefix with children for the single letter prefixes which
in turn have children for each double letter prefix starting with
the single letter corresponding to the parent node, and so on.
More generally the prefixes do not need to be strings. A prefix refers
to the start of a sequence. The root has children for each one element
prefix and they have children for each two element prefix that starts
with the one element sequence of the parent, and so on.
Note that this implementation uses integer nodes with an attribute.
Each node has an attribute "source" whose value is the original element
of the path to which this node corresponds. For example, suppose `paths`
consists of one path: "can". Then the nodes `[1, 2, 3]` which represent
this path have "source" values "c", "a" and "n".
All the descendants of a node have a common prefix in the sequence/path
associated with that node. From the returned tree, ehe prefix for each
node can be constructed by traversing the tree up to the root and
accumulating the "source" values along the way.
The root node is always `0` and has "source" attribute `None`.
The root is the only node with in-degree zero.
The nil node is always `-1` and has "source" attribute `"NIL"`.
The nil node is the only node with out-degree zero.
Parameters
----------
paths: iterable of paths
An iterable of paths which are themselves sequences.
Matching prefixes among these sequences are identified with
nodes of the prefix tree. One leaf of the tree is associated
with each path. (Identical paths are associated with the same
leaf of the tree.)
Returns
-------
tree: DiGraph
A directed graph representing an arborescence consisting of the
prefix tree generated by `paths`. Nodes are directed "downward",
from parent to child. A special "synthetic" root node is added
to be the parent of the first node in each path. A special
"synthetic" leaf node, the "nil" node `-1`, is added to be the child
of all nodes representing the last element in a path. (The
addition of this nil node technically makes this not an
arborescence but a directed acyclic graph; removing the nil node
makes it an arborescence.)
Notes
-----
The prefix tree is also known as a *trie*.
Examples
--------
Create a prefix tree from a list of strings with common prefixes::
>>> paths = ["ab", "abs", "ad"]
>>> T = nx.prefix_tree(paths)
>>> list(T.edges)
[(0, 1), (1, 2), (1, 4), (2, -1), (2, 3), (3, -1), (4, -1)]
The leaf nodes can be obtained as predecessors of the nil node.
>>> root, NIL = 0, -1
>>> list(T.predecessors(NIL))
[2, 3, 4]
To recover the original paths that generated the prefix tree,
traverse up the tree from the node `-1` to the node `0`::
>>> recovered = []
>>> for v in T.predecessors(NIL):
... prefix = ""
... while v != root:
... prefix = str(T.nodes[v]["source"]) + prefix
... v = next(T.predecessors(v)) # only one predecessor
... recovered.append(prefix)
>>> sorted(recovered)
['ab', 'abs', 'ad']
| 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)
]
| (paths, *, backend=None, **backend_kwargs) |
31,022 | networkx.algorithms.bipartite.projection | projected_graph | Returns the projection of B onto one of its node sets.
Returns the graph G that is the projection of the bipartite graph B
onto the specified nodes. They retain their attributes and are connected
in G if they have a common neighbor in B.
Parameters
----------
B : NetworkX graph
The input graph should be bipartite.
nodes : list or iterable
Nodes to project onto (the "bottom" nodes).
multigraph: bool (default=False)
If True return a multigraph where the multiple edges represent multiple
shared neighbors. They edge key in the multigraph is assigned to the
label of the neighbor.
Returns
-------
Graph : NetworkX graph or multigraph
A graph that is the projection onto the given nodes.
Examples
--------
>>> from networkx.algorithms import bipartite
>>> B = nx.path_graph(4)
>>> G = bipartite.projected_graph(B, [1, 3])
>>> list(G)
[1, 3]
>>> list(G.edges())
[(1, 3)]
If nodes `a`, and `b` are connected through both nodes 1 and 2 then
building a multigraph results in two edges in the projection onto
[`a`, `b`]:
>>> B = nx.Graph()
>>> B.add_edges_from([("a", 1), ("b", 1), ("a", 2), ("b", 2)])
>>> G = bipartite.projected_graph(B, ["a", "b"], multigraph=True)
>>> print([sorted((u, v)) for u, v in G.edges()])
[['a', 'b'], ['a', 'b']]
Notes
-----
No attempt is made to verify that the input graph B is bipartite.
Returns a simple graph that is the projection of the bipartite graph B
onto the set of nodes given in list nodes. If multigraph=True then
a multigraph is returned with an edge for every shared neighbor.
Directed graphs are allowed as input. The output will also then
be a directed graph with edges if there is a directed path between
the nodes.
The graph and node properties are (shallow) copied to the projected graph.
See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
for further details on how bipartite graphs are handled in NetworkX.
See Also
--------
is_bipartite,
is_bipartite_node_set,
sets,
weighted_projected_graph,
collaboration_weighted_projected_graph,
overlap_weighted_projected_graph,
generic_weighted_projected_graph
| null | (B, nodes, multigraph=False, *, backend=None, **backend_kwargs) |
31,023 | networkx.algorithms.centrality.group | prominent_group | Find the prominent group of size $k$ in graph $G$. The prominence of the
group is evaluated by the group betweenness centrality.
Group betweenness centrality of a group of nodes $C$ is the sum of the
fraction of all-pairs shortest paths that pass through any vertex in $C$
.. math::
c_B(v) =\sum_{s,t \in V} \frac{\sigma(s, t|v)}{\sigma(s, t)}
where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
shortest $(s, t)$-paths, and $\sigma(s, t|C)$ is the number of
those paths passing through some node in group $C$. Note that
$(s, t)$ are not members of the group ($V-C$ is the set of nodes
in $V$ that are not in $C$).
Parameters
----------
G : graph
A NetworkX graph.
k : int
The number of nodes in the group.
normalized : bool, optional (default=True)
If True, group betweenness is normalized by ``1/((|V|-|C|)(|V|-|C|-1))``
where ``|V|`` is the number of nodes in G and ``|C|`` is the number of
nodes in C.
weight : None or string, optional (default=None)
If None, all edge weights are considered equal.
Otherwise holds the name of the edge attribute used as weight.
The weight of an edge is treated as the length or distance between the two sides.
endpoints : bool, optional (default=False)
If True include the endpoints in the shortest path counts.
C : list or set, optional (default=None)
list of nodes which won't be candidates of the prominent group.
greedy : bool, optional (default=False)
Using a naive greedy algorithm in order to find non-optimal prominent
group. For scale free networks the results are negligibly below the optimal
results.
Raises
------
NodeNotFound
If node(s) in C are not present in G.
Returns
-------
max_GBC : float
The group betweenness centrality of the prominent group.
max_group : list
The list of nodes in the prominent group.
See Also
--------
betweenness_centrality, group_betweenness_centrality
Notes
-----
Group betweenness centrality is described in [1]_ and its importance discussed in [3]_.
The algorithm is described in [2]_ and is based on techniques mentioned in [4]_.
The number of nodes in the group must be a maximum of ``n - 2`` where ``n``
is the total number of nodes in the graph.
For weighted graphs the edge weights must be greater than zero.
Zero edge weights can produce an infinite number of equal length
paths between pairs of nodes.
The total number of paths between source and target is counted
differently for directed and undirected graphs. Directed paths
between "u" and "v" are counted as two possible paths (one each
direction) while undirected paths between "u" and "v" are counted
as one path. Said another way, the sum in the expression above is
over all ``s != t`` for directed graphs and for ``s < t`` for undirected graphs.
References
----------
.. [1] M G Everett and S P Borgatti:
The Centrality of Groups and Classes.
Journal of Mathematical Sociology. 23(3): 181-201. 1999.
http://www.analytictech.com/borgatti/group_centrality.htm
.. [2] Rami Puzis, Yuval Elovici, and Shlomi Dolev:
"Finding the Most Prominent Group in Complex Networks"
AI communications 20(4): 287-296, 2007.
https://www.researchgate.net/profile/Rami_Puzis2/publication/220308855
.. [3] Sourav Medya et. al.:
Group Centrality Maximization via Network Design.
SIAM International Conference on Data Mining, SDM 2018, 126–134.
https://sites.cs.ucsb.edu/~arlei/pubs/sdm18.pdf
.. [4] Rami Puzis, Yuval Elovici, and Shlomi Dolev.
"Fast algorithm for successive computation of group betweenness centrality."
https://journals.aps.org/pre/pdf/10.1103/PhysRevE.76.056709
| null | (G, k, weight=None, C=None, endpoints=False, normalized=True, greedy=False, *, backend=None, **backend_kwargs) |
31,024 | networkx.algorithms.minors.contraction | quotient_graph | Returns the quotient graph of `G` under the specified equivalence
relation on nodes.
Parameters
----------
G : NetworkX graph
The graph for which to return the quotient graph with the
specified node relation.
partition : function, or dict or list of lists, tuples or sets
If a function, this function must represent an equivalence
relation on the nodes of `G`. It must take two arguments *u*
and *v* and return True exactly when *u* and *v* are in the
same equivalence class. The equivalence classes form the nodes
in the returned graph.
If a dict of lists/tuples/sets, the keys can be any meaningful
block labels, but the values must be the block lists/tuples/sets
(one list/tuple/set per block), and the blocks must form a valid
partition of the nodes of the graph. That is, each node must be
in exactly one block of the partition.
If a list of sets, the list must form a valid partition of
the nodes of the graph. That is, each node must be in exactly
one block of the partition.
edge_relation : Boolean function with two arguments
This function must represent an edge relation on the *blocks* of
the `partition` of `G`. It must take two arguments, *B* and *C*,
each one a set of nodes, and return True exactly when there should be
an edge joining block *B* to block *C* in the returned graph.
If `edge_relation` is not specified, it is assumed to be the
following relation. Block *B* is related to block *C* if and
only if some node in *B* is adjacent to some node in *C*,
according to the edge set of `G`.
node_data : function
This function takes one argument, *B*, a set of nodes in `G`,
and must return a dictionary representing the node data
attributes to set on the node representing *B* in the quotient graph.
If None, the following node attributes will be set:
* 'graph', the subgraph of the graph `G` that this block
represents,
* 'nnodes', the number of nodes in this block,
* 'nedges', the number of edges within this block,
* 'density', the density of the subgraph of `G` that this
block represents.
edge_data : function
This function takes two arguments, *B* and *C*, each one a set
of nodes, and must return a dictionary representing the edge
data attributes to set on the edge joining *B* and *C*, should
there be an edge joining *B* and *C* in the quotient graph (if
no such edge occurs in the quotient graph as determined by
`edge_relation`, then the output of this function is ignored).
If the quotient graph would be a multigraph, this function is
not applied, since the edge data from each edge in the graph
`G` appears in the edges of the quotient 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.
relabel : bool
If True, relabel the nodes of the quotient graph to be
nonnegative integers. Otherwise, the nodes are identified with
:class:`frozenset` instances representing the blocks given in
`partition`.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
Returns
-------
NetworkX graph
The quotient graph of `G` under the equivalence relation
specified by `partition`. If the partition were given as a
list of :class:`set` instances and `relabel` is False,
each node will be a :class:`frozenset` corresponding to the same
:class:`set`.
Raises
------
NetworkXException
If the given partition is not a valid partition of the nodes of
`G`.
Examples
--------
The quotient graph of the complete bipartite graph under the "same
neighbors" equivalence relation is `K_2`. Under this relation, two nodes
are equivalent if they are not adjacent but have the same neighbor set.
>>> G = nx.complete_bipartite_graph(2, 3)
>>> same_neighbors = lambda u, v: (u not in G[v] and v not in G[u] and G[u] == G[v])
>>> Q = nx.quotient_graph(G, same_neighbors)
>>> K2 = nx.complete_graph(2)
>>> nx.is_isomorphic(Q, K2)
True
The quotient graph of a directed graph under the "same strongly connected
component" equivalence relation is the condensation of the graph (see
:func:`condensation`). This example comes from the Wikipedia article
*`Strongly connected component`_*.
>>> G = nx.DiGraph()
>>> edges = [
... "ab",
... "be",
... "bf",
... "bc",
... "cg",
... "cd",
... "dc",
... "dh",
... "ea",
... "ef",
... "fg",
... "gf",
... "hd",
... "hf",
... ]
>>> G.add_edges_from(tuple(x) for x in edges)
>>> components = list(nx.strongly_connected_components(G))
>>> sorted(sorted(component) for component in components)
[['a', 'b', 'e'], ['c', 'd', 'h'], ['f', 'g']]
>>>
>>> C = nx.condensation(G, components)
>>> component_of = C.graph["mapping"]
>>> same_component = lambda u, v: component_of[u] == component_of[v]
>>> Q = nx.quotient_graph(G, same_component)
>>> nx.is_isomorphic(C, Q)
True
Node identification can be represented as the quotient of a graph under the
equivalence relation that places the two nodes in one block and each other
node in its own singleton block.
>>> K24 = nx.complete_bipartite_graph(2, 4)
>>> K34 = nx.complete_bipartite_graph(3, 4)
>>> C = nx.contracted_nodes(K34, 1, 2)
>>> nodes = {1, 2}
>>> is_contracted = lambda u, v: u in nodes and v in nodes
>>> Q = nx.quotient_graph(K34, is_contracted)
>>> nx.is_isomorphic(Q, C)
True
>>> nx.is_isomorphic(Q, K24)
True
The blockmodeling technique described in [1]_ can be implemented as a
quotient graph.
>>> G = nx.path_graph(6)
>>> partition = [{0, 1}, {2, 3}, {4, 5}]
>>> M = nx.quotient_graph(G, partition, relabel=True)
>>> list(M.edges())
[(0, 1), (1, 2)]
Here is the sample example but using partition as a dict of block sets.
>>> G = nx.path_graph(6)
>>> partition = {0: {0, 1}, 2: {2, 3}, 4: {4, 5}}
>>> M = nx.quotient_graph(G, partition, relabel=True)
>>> list(M.edges())
[(0, 1), (1, 2)]
Partitions can be represented in various ways:
0. a list/tuple/set of block lists/tuples/sets
1. a dict with block labels as keys and blocks lists/tuples/sets as values
2. a dict with block lists/tuples/sets as keys and block labels as values
3. a function from nodes in the original iterable to block labels
4. an equivalence relation function on the target iterable
As `quotient_graph` is designed to accept partitions represented as (0), (1) or
(4) only, the `equivalence_classes` function can be used to get the partitions
in the right form, in order to call `quotient_graph`.
.. _Strongly connected component: https://en.wikipedia.org/wiki/Strongly_connected_component
References
----------
.. [1] Patrick Doreian, Vladimir Batagelj, and Anuska Ferligoj.
*Generalized Blockmodeling*.
Cambridge University Press, 2004.
| null | (G, partition, edge_relation=None, node_data=None, edge_data=None, weight='weight', relabel=False, create_using=None, *, backend=None, **backend_kwargs) |
31,025 | networkx.algorithms.link_prediction | ra_index_soundarajan_hopcroft | Compute the resource allocation index of all node pairs in
ebunch using community information.
For two nodes $u$ and $v$, this function computes the resource
allocation index considering only common neighbors belonging to the
same community as $u$ and $v$. Mathematically,
.. math::
\sum_{w \in \Gamma(u) \cap \Gamma(v)} \frac{f(w)}{|\Gamma(w)|}
where $f(w)$ equals 1 if $w$ belongs to the same community as $u$
and $v$ or 0 otherwise and $\Gamma(u)$ denotes the set of
neighbors of $u$.
Parameters
----------
G : graph
A NetworkX undirected graph.
ebunch : iterable of node pairs, optional (default = None)
The score 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.
community : string, optional (default = 'community')
Nodes attribute name containing the community information.
G[u][community] identifies which community u belongs to. Each
node belongs to at most one community. Default value: 'community'.
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 score.
Raises
------
NetworkXNotImplemented
If `G` is a `DiGraph`, a `Multigraph` or a `MultiDiGraph`.
NetworkXAlgorithmError
If no community information is available for a node in `ebunch` or in `G` (if `ebunch` is `None`).
NodeNotFound
If `ebunch` has a node that is not in `G`.
Examples
--------
>>> G = nx.Graph()
>>> G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3)])
>>> G.nodes[0]["community"] = 0
>>> G.nodes[1]["community"] = 0
>>> G.nodes[2]["community"] = 1
>>> G.nodes[3]["community"] = 0
>>> preds = nx.ra_index_soundarajan_hopcroft(G, [(0, 3)])
>>> for u, v, p in preds:
... print(f"({u}, {v}) -> {p:.8f}")
(0, 3) -> 0.50000000
References
----------
.. [1] Sucheta Soundarajan and John Hopcroft.
Using community information to improve the precision of link
prediction methods.
In Proceedings of the 21st international conference companion on
World Wide Web (WWW '12 Companion). ACM, New York, NY, USA, 607-608.
http://doi.acm.org/10.1145/2187980.2188150
| null | (G, ebunch=None, community='community', *, backend=None, **backend_kwargs) |
31,026 | networkx.algorithms.distance_measures | radius | Returns the radius of the graph G.
The radius is the minimum eccentricity.
Parameters
----------
G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
weight : string, function, or None
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.
If this is None, every edge has weight/distance/cost 1.
Weights stored as floating point values can lead to small round-off
errors in distances. Use integer weights to avoid this.
Weights should be positive, since they are distances.
Returns
-------
r : integer
Radius of graph
Examples
--------
>>> G = nx.Graph([(1, 2), (1, 3), (1, 4), (3, 4), (3, 5), (4, 5)])
>>> nx.radius(G)
2
| 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, e=None, usebounds=False, weight=None, *, backend=None, **backend_kwargs) |
31,028 | networkx.generators.random_clustered | random_clustered_graph | Generate a random graph with the given joint independent edge degree and
triangle degree sequence.
This uses a configuration model-like approach to generate a random graph
(with parallel edges and self-loops) by randomly assigning edges to match
the given joint degree sequence.
The joint degree sequence is a list of pairs of integers of the form
$[(d_{1,i}, d_{1,t}), \dotsc, (d_{n,i}, d_{n,t})]$. According to this list,
vertex $u$ is a member of $d_{u,t}$ triangles and has $d_{u, i}$ other
edges. The number $d_{u,t}$ is the *triangle degree* of $u$ and the number
$d_{u,i}$ is the *independent edge degree*.
Parameters
----------
joint_degree_sequence : list of integer pairs
Each list entry corresponds to the independent edge degree and
triangle degree of a node.
create_using : NetworkX graph constructor, optional (default MultiGraph)
Graph type to create. If graph instance, then cleared before populated.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : MultiGraph
A graph with the specified degree sequence. Nodes are labeled
starting at 0 with an index corresponding to the position in
deg_sequence.
Raises
------
NetworkXError
If the independent edge degree sequence sum is not even
or the triangle degree sequence sum is not divisible by 3.
Notes
-----
As described by Miller [1]_ (see also Newman [2]_ for an equivalent
description).
A non-graphical degree sequence (not realizable by some simple
graph) is allowed since this function returns graphs with self
loops and parallel edges. An exception is raised if the
independent degree sequence does not have an even sum or the
triangle degree sequence sum is not divisible by 3.
This configuration model-like construction process can lead to
duplicate edges and loops. You can remove the self-loops and
parallel edges (see below) which will likely result in a graph
that doesn't have the exact degree sequence specified. This
"finite-size effect" decreases as the size of the graph increases.
References
----------
.. [1] Joel C. Miller. "Percolation and epidemics in random clustered
networks". In: Physical review. E, Statistical, nonlinear, and soft
matter physics 80 (2 Part 1 August 2009).
.. [2] M. E. J. Newman. "Random Graphs with Clustering".
In: Physical Review Letters 103 (5 July 2009)
Examples
--------
>>> deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)]
>>> G = nx.random_clustered_graph(deg)
To remove parallel edges:
>>> G = nx.Graph(G)
To remove self loops:
>>> G.remove_edges_from(nx.selfloop_edges(G))
| null | (joint_degree_sequence, create_using=None, seed=None, *, backend=None, **backend_kwargs) |
31,029 | networkx.generators.cographs | random_cograph | Returns a random cograph with $2 ^ n$ nodes.
A cograph is a graph containing no path on four vertices.
Cographs or $P_4$-free graphs can be obtained from a single vertex
by disjoint union and complementation operations.
This generator starts off from a single vertex and performs disjoint
union and full join operations on itself.
The decision on which operation will take place is random.
Parameters
----------
n : int
The order of the cograph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : A random graph containing no path on four vertices.
See Also
--------
full_join
union
References
----------
.. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
"Complement reducible graphs",
Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
ISSN 0166-218X.
| null | (n, seed=None, *, backend=None, **backend_kwargs) |
31,030 | networkx.generators.degree_seq | random_degree_sequence_graph | Returns a simple random graph with the given degree sequence.
If the maximum degree $d_m$ in the sequence is $O(m^{1/4})$ then the
algorithm produces almost uniform random graphs in $O(m d_m)$ time
where $m$ is the number of edges.
Parameters
----------
sequence : list of integers
Sequence of degrees
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
tries : int, optional
Maximum number of tries to create a graph
Returns
-------
G : Graph
A graph with the specified degree sequence.
Nodes are labeled starting at 0 with an index
corresponding to the position in the sequence.
Raises
------
NetworkXUnfeasible
If the degree sequence is not graphical.
NetworkXError
If a graph is not produced in specified number of tries
See Also
--------
is_graphical, configuration_model
Notes
-----
The generator algorithm [1]_ is not guaranteed to produce a graph.
References
----------
.. [1] Moshen Bayati, Jeong Han Kim, and Amin Saberi,
A sequential algorithm for generating random graphs.
Algorithmica, Volume 58, Number 4, 860-910,
DOI: 10.1007/s00453-009-9340-1
Examples
--------
>>> sequence = [1, 2, 2, 3]
>>> G = nx.random_degree_sequence_graph(sequence, seed=42)
>>> sorted(d for n, d in G.degree())
[1, 2, 2, 3]
| def generate(self):
# remaining_degree is mapping from int->remaining degree
self.remaining_degree = dict(enumerate(self.degree))
# add all nodes to make sure we get isolated nodes
self.graph = nx.Graph()
self.graph.add_nodes_from(self.remaining_degree)
# remove zero degree nodes
for n, d in list(self.remaining_degree.items()):
if d == 0:
del self.remaining_degree[n]
if len(self.remaining_degree) > 0:
# build graph in three phases according to how many unmatched edges
self.phase1()
self.phase2()
self.phase3()
return self.graph
| (sequence, seed=None, tries=10, *, backend=None, **backend_kwargs) |
31,031 | networkx.generators.geometric | random_geometric_graph | Returns a random geometric graph in the unit cube of dimensions `dim`.
The random geometric graph model places `n` nodes uniformly at
random in the unit cube. Two nodes are joined by an edge if the
distance between the nodes is at most `radius`.
Edges are determined using a KDTree when SciPy is available.
This reduces the time complexity from $O(n^2)$ to $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.
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 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
--------
Create a random geometric graph on twenty nodes where nodes are joined by
an edge if their distance is at most 0.1::
>>> G = nx.random_geometric_graph(20, 0.1)
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::
>>> import random
>>> n = 20
>>> pos = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)}
>>> G = nx.random_geometric_graph(n, 0.2, pos=pos)
References
----------
.. [1] Penrose, Mathew, *Random Geometric Graphs*,
Oxford Studies in Probability, 5, 2003.
| 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, seed=None, *, pos_name='pos', backend=None, **backend_kwargs) |
31,033 | networkx.generators.internet_as_graphs | random_internet_as_graph | Generates a random undirected graph resembling the Internet AS network
Parameters
----------
n: integer in [1000, 10000]
Number of graph nodes
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G: Networkx Graph object
A randomly generated undirected graph
Notes
-----
This algorithm returns an undirected graph resembling the Internet
Autonomous System (AS) network, it uses the approach by Elmokashfi et al.
[1]_ and it grants the properties described in the related paper [1]_.
Each node models an autonomous system, with an attribute 'type' specifying
its kind; tier-1 (T), mid-level (M), customer (C) or content-provider (CP).
Each edge models an ADV communication link (hence, bidirectional) with
attributes:
- type: transit|peer, the kind of commercial agreement between nodes;
- customer: <node id>, the identifier of the node acting as customer
('none' if type is peer).
References
----------
.. [1] A. Elmokashfi, A. Kvalbein and C. Dovrolis, "On the Scalability of
BGP: The Role of Topology Growth," in IEEE Journal on Selected Areas
in Communications, vol. 28, no. 8, pp. 1250-1261, October 2010.
| null | (n, seed=None, *, backend=None, **backend_kwargs) |
31,034 | networkx.generators.directed | random_k_out_graph | Returns a random `k`-out graph with preferential attachment.
A random `k`-out graph with preferential attachment is a
multidigraph generated by the following algorithm.
1. Begin with an empty digraph, and initially set each node to have
weight `alpha`.
2. Choose a node `u` with out-degree less than `k` uniformly at
random.
3. Choose a node `v` from with probability proportional to its
weight.
4. Add a directed edge from `u` to `v`, and increase the weight
of `v` by one.
5. If each node has out-degree `k`, halt, otherwise repeat from
step 2.
For more information on this model of random graph, see [1].
Parameters
----------
n : int
The number of nodes in the returned graph.
k : int
The out-degree of each node in the returned graph.
alpha : float
A positive :class:`float` representing the initial weight of
each vertex. A higher number means that in step 3 above, nodes
will be chosen more like a true uniformly random sample, and a
lower number means that nodes are more likely to be chosen as
their in-degree increases. If this parameter is not positive, a
:exc:`ValueError` is raised.
self_loops : bool
If True, self-loops are allowed when generating the graph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
:class:`~networkx.classes.MultiDiGraph`
A `k`-out-regular multidigraph generated according to the above
algorithm.
Raises
------
ValueError
If `alpha` is not positive.
Notes
-----
The returned multidigraph may not be strongly connected, or even
weakly connected.
References
----------
[1]: Peterson, Nicholas R., and Boris Pittel.
"Distance between two random `k`-out digraphs, with and without
preferential attachment."
arXiv preprint arXiv:1311.5961 (2013).
<https://arxiv.org/abs/1311.5961>
| null | (n, k, alpha, self_loops=True, seed=None, *, backend=None, **backend_kwargs) |
31,035 | networkx.generators.random_graphs | random_kernel_graph | Returns an random graph based on the specified kernel.
The algorithm chooses each of the $[n(n-1)]/2$ possible edges with
probability specified by a kernel $\kappa(x,y)$ [1]_. The kernel
$\kappa(x,y)$ must be a symmetric (in $x,y$), non-negative,
bounded function.
Parameters
----------
n : int
The number of nodes
kernel_integral : function
Function that returns the definite integral of the kernel $\kappa(x,y)$,
$F(y,a,b) := \int_a^b \kappa(x,y)dx$
kernel_root: function (optional)
Function that returns the root $b$ of the equation $F(y,a,b) = r$.
If None, the root is found using :func:`scipy.optimize.brentq`
(this requires SciPy).
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Notes
-----
The kernel is specified through its definite integral which must be
provided as one of the arguments. If the integral and root of the
kernel integral can be found in $O(1)$ time then this algorithm runs in
time $O(n+m)$ where m is the expected number of edges [2]_.
The nodes are set to integers from $0$ to $n-1$.
Examples
--------
Generate an Erdős–Rényi random graph $G(n,c/n)$, with kernel
$\kappa(x,y)=c$ where $c$ is the mean expected degree.
>>> def integral(u, w, z):
... return c * (z - w)
>>> def root(u, w, r):
... return r / c + w
>>> c = 1
>>> graph = nx.random_kernel_graph(1000, integral, root)
See Also
--------
gnp_random_graph
expected_degree_graph
References
----------
.. [1] Bollobás, Béla, Janson, S. and Riordan, O.
"The phase transition in inhomogeneous random graphs",
*Random Structures Algorithms*, 31, 3--122, 2007.
.. [2] Hagberg A, Lemons N (2015),
"Fast Generation of Sparse Random Kernel Graphs".
PLoS ONE 10(9): e0135177, 2015. doi:10.1371/journal.pone.0135177
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (n, kernel_integral, kernel_root=None, seed=None, *, backend=None, **backend_kwargs) |
31,036 | networkx.generators.trees | random_labeled_rooted_forest | Returns a labeled rooted forest with `n` nodes.
The returned forest is chosen uniformly at random using a
generalization of Prüfer sequences [1]_ in the form described in [2]_.
Parameters
----------
n : int
The number of nodes.
seed : random_state
See :ref:`Randomness<randomness>`.
Returns
-------
:class:`networkx.Graph`
A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
The "roots" graph attribute is a set of integers containing the roots.
References
----------
.. [1] Knuth, Donald E. "Another Enumeration of Trees."
Canadian Journal of Mathematics, 20 (1968): 1077-1086.
https://doi.org/10.4153/CJM-1968-104-8
.. [2] Rubey, Martin. "Counting Spanning Trees". Diplomarbeit
zur Erlangung des akademischen Grades Magister der
Naturwissenschaften an der Formal- und Naturwissenschaftlichen
Fakultät der Universität Wien. Wien, May 2000.
| 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, backend=None, **backend_kwargs) |
31,037 | networkx.generators.trees | random_labeled_rooted_tree | Returns a labeled rooted tree with `n` nodes.
The returned tree is chosen uniformly at random from all labeled rooted trees.
Parameters
----------
n : int
The number of nodes
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
:class:`networkx.Graph`
A `networkx.Graph` with integer nodes 0 <= node <= `n` - 1.
The root of the tree is selected uniformly from the nodes.
The "root" graph attribute identifies the root of the tree.
Notes
-----
This function returns the result of :func:`random_labeled_tree`
with a randomly selected root.
Raises
------
NetworkXPointlessConcept
If `n` is zero (because the null graph is not a tree).
| 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, backend=None, **backend_kwargs) |
31,038 | networkx.generators.trees | random_labeled_tree | Returns a labeled tree on `n` nodes chosen uniformly at random.
Generating uniformly distributed random Prüfer sequences and
converting them into the corresponding trees is a straightforward
method of generating uniformly distributed random labeled trees.
This function implements this method.
Parameters
----------
n : int
The number of nodes, greater than zero.
seed : random_state
Indicator of random number generation state.
See :ref:`Randomness<randomness>`
Returns
-------
:class:`networkx.Graph`
A `networkx.Graph` with nodes in the set {0, …, *n* - 1}.
Raises
------
NetworkXPointlessConcept
If `n` is zero (because the null graph is not a tree).
| 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, backend=None, **backend_kwargs) |
31,039 | networkx.drawing.layout | random_layout | Position nodes uniformly at random in the unit square.
For every node, a position is generated by choosing each of dim
coordinates uniformly at random on the interval [0.0, 1.0).
NumPy (http://scipy.org) is required for this function.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G.
center : array-like or None
Coordinate pair around which to center the layout.
dim : int
Dimension of layout.
seed : int, RandomState instance or None optional (default=None)
Set the random state for deterministic node layouts.
If int, `seed` is the seed used by the random number generator,
if numpy.random.RandomState instance, `seed` is the random
number generator,
if None, the random number generator is the RandomState instance used
by numpy.random.
Returns
-------
pos : dict
A dictionary of positions keyed by node
Examples
--------
>>> G = nx.lollipop_graph(4, 3)
>>> pos = nx.random_layout(G)
| 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, center=None, dim=2, seed=None) |
31,040 | networkx.generators.random_graphs | random_lobster | Returns a random lobster graph.
A lobster is a tree that reduces to a caterpillar when pruning all
leaf nodes. A caterpillar is a tree that reduces to a path graph
when pruning all leaf nodes; setting `p2` to zero produces a caterpillar.
This implementation iterates on the probabilities `p1` and `p2` to add
edges at levels 1 and 2, respectively. Graphs are therefore constructed
iteratively with uniform randomness at each level rather than being selected
uniformly at random from the set of all possible lobsters.
Parameters
----------
n : int
The expected number of nodes in the backbone
p1 : float
Probability of adding an edge to the backbone
p2 : float
Probability of adding an edge one level beyond backbone
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Raises
------
NetworkXError
If `p1` or `p2` parameters are >= 1 because the while loops would never finish.
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (n, p1, p2, seed=None, *, backend=None, **backend_kwargs) |
31,041 | networkx.generators.community | random_partition_graph | Returns the random partition graph with a partition of sizes.
A partition graph is a graph of communities with sizes defined by
s in sizes. Nodes in the same group are connected with probability
p_in and nodes of different groups are connected with probability
p_out.
Parameters
----------
sizes : list of ints
Sizes of groups
p_in : float
probability of edges with in groups
p_out : float
probability of edges between groups
directed : boolean optional, default=False
Whether to create a directed graph
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : NetworkX Graph or DiGraph
random partition graph of size sum(gs)
Raises
------
NetworkXError
If p_in or p_out is not in [0,1]
Examples
--------
>>> G = nx.random_partition_graph([10, 10, 10], 0.25, 0.01)
>>> len(G)
30
>>> partition = G.graph["partition"]
>>> len(partition)
3
Notes
-----
This is a generalization of the planted-l-partition described in
[1]_. It allows for the creation of groups of any size.
The partition is store as a graph attribute 'partition'.
References
----------
.. [1] Santo Fortunato 'Community Detection in Graphs' Physical Reports
Volume 486, Issue 3-5 p. 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)
| (sizes, p_in, p_out, seed=None, directed=False, *, backend=None, **backend_kwargs) |
31,042 | networkx.generators.random_graphs | random_powerlaw_tree | Returns a tree with a power law degree distribution.
Parameters
----------
n : int
The number of nodes.
gamma : float
Exponent of the power law.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
tries : int
Number of attempts to adjust the sequence to make it a tree.
Raises
------
NetworkXError
If no valid sequence is found within the maximum number of
attempts.
Notes
-----
A trial power law degree sequence is chosen and then elements are
swapped with new elements from a powerlaw distribution until the
sequence makes a tree (by checking, for example, that the number of
edges is one smaller than the number of nodes).
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (n, gamma=3, seed=None, tries=100, *, backend=None, **backend_kwargs) |
31,043 | networkx.generators.random_graphs | random_powerlaw_tree_sequence | Returns a degree sequence for a tree with a power law distribution.
Parameters
----------
n : int,
The number of nodes.
gamma : float
Exponent of the power law.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
tries : int
Number of attempts to adjust the sequence to make it a tree.
Raises
------
NetworkXError
If no valid sequence is found within the maximum number of
attempts.
Notes
-----
A trial power law degree sequence is chosen and then elements are
swapped with new elements from a power law distribution until
the sequence makes a tree (by checking, for example, that the number of
edges is one smaller than the number of nodes).
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (n, gamma=3, seed=None, tries=100, *, backend=None, **backend_kwargs) |
31,044 | networkx.algorithms.smallworld | random_reference | Compute a random graph by swapping edges of a given graph.
Parameters
----------
G : graph
An undirected graph with 4 or more nodes.
niter : integer (optional, default=1)
An edge is rewired approximately `niter` times.
connectivity : boolean (optional, default=True)
When True, ensure connectivity for the randomized graph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
G : graph
The randomized graph.
Raises
------
NetworkXError
If there are fewer than 4 nodes or 2 edges in `G`
Notes
-----
The implementation is adapted from the algorithm by Maslov and Sneppen
(2002) [1]_.
References
----------
.. [1] Maslov, Sergei, and Kim Sneppen.
"Specificity and stability in topology of protein networks."
Science 296.5569 (2002): 910-913.
| null | (G, niter=1, connectivity=True, seed=None, *, backend=None, **backend_kwargs) |
31,045 | networkx.generators.expanders | random_regular_expander_graph | Returns a random regular expander graph on $n$ nodes with degree $d$.
An expander graph is a sparse graph with strong connectivity properties. [1]_
More precisely the returned graph is a $(n, d, \lambda)$-expander with
$\lambda = 2 \sqrt{d - 1} + \epsilon$, close to the Alon-Boppana bound. [2]_
In the case where $\epsilon = 0$ it returns a Ramanujan graph.
A Ramanujan graph has spectral gap almost as large as possible,
which makes them excellent expanders. [3]_
Parameters
----------
n : int
The number of nodes.
d : int
The degree of each node.
epsilon : int, float, default=0
max_tries : int, (default: 100)
The number of allowed loops, also used in the maybe_regular_expander utility
seed : (default: None)
Seed used to set random number generation state. See :ref`Randomness<randomness>`.
Raises
------
NetworkXError
If max_tries is reached
Examples
--------
>>> G = nx.random_regular_expander_graph(20, 4)
>>> nx.is_regular_expander(G)
True
Notes
-----
This loops over `maybe_regular_expander` and can be slow when
$n$ is too big or $\epsilon$ too small.
See Also
--------
maybe_regular_expander
is_regular_expander
References
----------
.. [1] Expander graph, https://en.wikipedia.org/wiki/Expander_graph
.. [2] Alon-Boppana bound, https://en.wikipedia.org/wiki/Alon%E2%80%93Boppana_bound
.. [3] Ramanujan graphs, https://en.wikipedia.org/wiki/Ramanujan_graph
| null | (n, d, *, epsilon=0, create_using=None, max_tries=100, seed=None, backend=None, **backend_kwargs) |
31,046 | networkx.generators.random_graphs | random_regular_graph | Returns a random $d$-regular graph on $n$ nodes.
A regular graph is a graph where each node has the same number of neighbors.
The resulting graph has no self-loops or parallel edges.
Parameters
----------
d : int
The degree of each node.
n : integer
The number of nodes. The value of $n \times d$ must be even.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Notes
-----
The nodes are numbered from $0$ to $n - 1$.
Kim and Vu's paper [2]_ shows that this algorithm samples in an
asymptotically uniform way from the space of random graphs when
$d = O(n^{1 / 3 - \epsilon})$.
Raises
------
NetworkXError
If $n \times d$ is odd or $d$ is greater than or equal to $n$.
References
----------
.. [1] A. Steger and N. Wormald,
Generating random regular graphs quickly,
Probability and Computing 8 (1999), 377-396, 1999.
https://doi.org/10.1017/S0963548399003867
.. [2] Jeong Han Kim and Van H. Vu,
Generating random regular graphs,
Proceedings of the thirty-fifth ACM symposium on Theory of computing,
San Diego, CA, USA, pp 213--222, 2003.
http://portal.acm.org/citation.cfm?id=780542.780576
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (d, n, seed=None, *, backend=None, **backend_kwargs) |
31,047 | networkx.generators.random_graphs | random_shell_graph | Returns a random shell graph for the constructor given.
Parameters
----------
constructor : list of three-tuples
Represents the parameters for a shell, starting at the center
shell. Each element of the list must be of the form `(n, m,
d)`, where `n` is the number of nodes in the shell, `m` is
the number of edges in the shell, and `d` is the ratio of
inter-shell (next) edges to intra-shell edges. If `d` is zero,
there will be no intra-shell edges, and if `d` is one there
will be all possible intra-shell edges.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Examples
--------
>>> constructor = [(10, 20, 0.8), (20, 40, 0.8)]
>>> G = nx.random_shell_graph(constructor)
| def dual_barabasi_albert_graph(n, m1, m2, p, seed=None, initial_graph=None):
"""Returns a random graph using dual Barabási–Albert preferential attachment
A graph of $n$ nodes is grown by attaching new nodes each with either $m_1$
edges (with probability $p$) or $m_2$ edges (with probability $1-p$) that
are preferentially attached to existing nodes with high degree.
Parameters
----------
n : int
Number of nodes
m1 : int
Number of edges to link each new node to existing nodes with probability $p$
m2 : int
Number of edges to link each new node to existing nodes with probability $1-p$
p : float
The probability of attaching $m_1$ edges (as opposed to $m_2$ edges)
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
initial_graph : Graph or None (default)
Initial network for Barabási–Albert algorithm.
A copy of `initial_graph` is used.
It should be connected for most use cases.
If None, starts from an star graph on max(m1, m2) + 1 nodes.
Returns
-------
G : Graph
Raises
------
NetworkXError
If `m1` and `m2` do not satisfy ``1 <= m1,m2 < n``, or
`p` does not satisfy ``0 <= p <= 1``, or
the initial graph number of nodes m0 does not satisfy m1, m2 <= m0 <= n.
References
----------
.. [1] N. Moshiri "The dual-Barabasi-Albert model", arXiv:1810.10538.
"""
if m1 < 1 or m1 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m1 >= 1 and m1 < n, m1 = {m1}, n = {n}"
)
if m2 < 1 or m2 >= n:
raise nx.NetworkXError(
f"Dual Barabási–Albert must have m2 >= 1 and m2 < n, m2 = {m2}, n = {n}"
)
if p < 0 or p > 1:
raise nx.NetworkXError(
f"Dual Barabási–Albert network must have 0 <= p <= 1, p = {p}"
)
# For simplicity, if p == 0 or 1, just return BA
if p == 1:
return barabasi_albert_graph(n, m1, seed)
elif p == 0:
return barabasi_albert_graph(n, m2, seed)
if initial_graph is None:
# Default initial graph : empty graph on max(m1, m2) nodes
G = star_graph(max(m1, m2))
else:
if len(initial_graph) < max(m1, m2) or len(initial_graph) > n:
raise nx.NetworkXError(
f"Barabási–Albert initial graph must have between "
f"max(m1, m2) = {max(m1, m2)} and n = {n} nodes"
)
G = initial_graph.copy()
# Target nodes for new edges
targets = list(G)
# List of existing nodes, with nodes repeated once for each adjacent edge
repeated_nodes = [n for n, d in G.degree() for _ in range(d)]
# Start adding the remaining nodes.
source = len(G)
while source < n:
# Pick which m to use (m1 or m2)
if seed.random() < p:
m = m1
else:
m = m2
# Now choose m unique nodes from the existing nodes
# Pick uniformly from repeated_nodes (preferential attachment)
targets = _random_subset(repeated_nodes, m, seed)
# Add edges to m nodes from the source.
G.add_edges_from(zip([source] * m, targets))
# Add one node to the list for each new edge just created.
repeated_nodes.extend(targets)
# And the new node "source" has m edges to add to the list.
repeated_nodes.extend([source] * m)
source += 1
return G
| (constructor, seed=None, *, backend=None, **backend_kwargs) |
31,048 | networkx.algorithms.tree.mst | random_spanning_tree |
Sample a random spanning tree using the edges weights of `G`.
This function supports two different methods for determining the
probability of the graph. If ``multiplicative=True``, the probability
is based on the product of edge weights, and if ``multiplicative=False``
it is based on the sum of the edge weight. However, since it is
easier to determine the total weight of all spanning trees for the
multiplicative version, that is significantly faster and should be used if
possible. Additionally, setting `weight` to `None` will cause a spanning tree
to be selected with uniform probability.
The function uses algorithm A8 in [1]_ .
Parameters
----------
G : nx.Graph
An undirected version of the original graph.
weight : string
The edge key for the edge attribute holding edge weight.
multiplicative : bool, default=True
If `True`, the probability of each tree is the product of its edge weight
over the sum of the product of all the spanning trees in the graph. If
`False`, the probability is the sum of its edge weight over the sum of
the sum of weights for all spanning trees in the graph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
nx.Graph
A spanning tree using the distribution defined by the weight of the tree.
References
----------
.. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
Algorithms, 11 (1990), pp. 185–207
| def random_spanning_tree(G, weight=None, *, multiplicative=True, seed=None):
"""
Sample a random spanning tree using the edges weights of `G`.
This function supports two different methods for determining the
probability of the graph. If ``multiplicative=True``, the probability
is based on the product of edge weights, and if ``multiplicative=False``
it is based on the sum of the edge weight. However, since it is
easier to determine the total weight of all spanning trees for the
multiplicative version, that is significantly faster and should be used if
possible. Additionally, setting `weight` to `None` will cause a spanning tree
to be selected with uniform probability.
The function uses algorithm A8 in [1]_ .
Parameters
----------
G : nx.Graph
An undirected version of the original graph.
weight : string
The edge key for the edge attribute holding edge weight.
multiplicative : bool, default=True
If `True`, the probability of each tree is the product of its edge weight
over the sum of the product of all the spanning trees in the graph. If
`False`, the probability is the sum of its edge weight over the sum of
the sum of weights for all spanning trees in the graph.
seed : integer, random_state, or None (default)
Indicator of random number generation state.
See :ref:`Randomness<randomness>`.
Returns
-------
nx.Graph
A spanning tree using the distribution defined by the weight of the tree.
References
----------
.. [1] V. Kulkarni, Generating random combinatorial objects, Journal of
Algorithms, 11 (1990), pp. 185–207
"""
def find_node(merged_nodes, node):
"""
We can think of clusters of contracted nodes as having one
representative in the graph. Each node which is not in merged_nodes
is still its own representative. Since a representative can be later
contracted, we need to recursively search though the dict to find
the final representative, but once we know it we can use path
compression to speed up the access of the representative for next time.
This cannot be replaced by the standard NetworkX union_find since that
data structure will merge nodes with less representing nodes into the
one with more representing nodes but this function requires we merge
them using the order that contract_edges contracts using.
Parameters
----------
merged_nodes : dict
The dict storing the mapping from node to representative
node
The node whose representative we seek
Returns
-------
The representative of the `node`
"""
if node not in merged_nodes:
return node
else:
rep = find_node(merged_nodes, merged_nodes[node])
merged_nodes[node] = rep
return rep
def prepare_graph():
"""
For the graph `G`, remove all edges not in the set `V` and then
contract all edges in the set `U`.
Returns
-------
A copy of `G` which has had all edges not in `V` removed and all edges
in `U` contracted.
"""
# The result is a MultiGraph version of G so that parallel edges are
# allowed during edge contraction
result = nx.MultiGraph(incoming_graph_data=G)
# Remove all edges not in V
edges_to_remove = set(result.edges()).difference(V)
result.remove_edges_from(edges_to_remove)
# Contract all edges in U
#
# Imagine that you have two edges to contract and they share an
# endpoint like this:
# [0] ----- [1] ----- [2]
# If we contract (0, 1) first, the contraction function will always
# delete the second node it is passed so the resulting graph would be
# [0] ----- [2]
# and edge (1, 2) no longer exists but (0, 2) would need to be contracted
# in its place now. That is why I use the below dict as a merge-find
# data structure with path compression to track how the nodes are merged.
merged_nodes = {}
for u, v in U:
u_rep = find_node(merged_nodes, u)
v_rep = find_node(merged_nodes, v)
# We cannot contract a node with itself
if u_rep == v_rep:
continue
nx.contracted_nodes(result, u_rep, v_rep, self_loops=False, copy=False)
merged_nodes[v_rep] = u_rep
return merged_nodes, result
def spanning_tree_total_weight(G, weight):
"""
Find the sum of weights of the spanning trees of `G` using the
appropriate `method`.
This is easy if the chosen method is 'multiplicative', since we can
use Kirchhoff's Tree Matrix Theorem directly. However, with the
'additive' method, this process is slightly more complex and less
computationally efficient as we have to find the number of spanning
trees which contain each possible edge in the graph.
Parameters
----------
G : NetworkX Graph
The graph to find the total weight of all spanning trees on.
weight : string
The key for the weight edge attribute of the graph.
Returns
-------
float
The sum of either the multiplicative or additive weight for all
spanning trees in the graph.
"""
if multiplicative:
return nx.total_spanning_tree_weight(G, weight)
else:
# There are two cases for the total spanning tree additive weight.
# 1. There is one edge in the graph. Then the only spanning tree is
# that edge itself, which will have a total weight of that edge
# itself.
if G.number_of_edges() == 1:
return G.edges(data=weight).__iter__().__next__()[2]
# 2. There are no edges or two or more edges in the graph. Then, we find the
# total weight of the spanning trees using the formula in the
# reference paper: take the weight of each edge and multiply it by
# the number of spanning trees which include that edge. This
# can be accomplished by contracting the edge and finding the
# multiplicative total spanning tree weight if the weight of each edge
# is assumed to be 1, which is conveniently built into networkx already,
# by calling total_spanning_tree_weight with weight=None.
# Note that with no edges the returned value is just zero.
else:
total = 0
for u, v, w in G.edges(data=weight):
total += w * nx.total_spanning_tree_weight(
nx.contracted_edge(G, edge=(u, v), self_loops=False), None
)
return total
if G.number_of_nodes() < 2:
# no edges in the spanning tree
return nx.empty_graph(G.nodes)
U = set()
st_cached_value = 0
V = set(G.edges())
shuffled_edges = list(G.edges())
seed.shuffle(shuffled_edges)
for u, v in shuffled_edges:
e_weight = G[u][v][weight] if weight is not None else 1
node_map, prepared_G = prepare_graph()
G_total_tree_weight = spanning_tree_total_weight(prepared_G, weight)
# Add the edge to U so that we can compute the total tree weight
# assuming we include that edge
# Now, if (u, v) cannot exist in G because it is fully contracted out
# of existence, then it by definition cannot influence G_e's Kirchhoff
# value. But, we also cannot pick it.
rep_edge = (find_node(node_map, u), find_node(node_map, v))
# Check to see if the 'representative edge' for the current edge is
# in prepared_G. If so, then we can pick it.
if rep_edge in prepared_G.edges:
prepared_G_e = nx.contracted_edge(
prepared_G, edge=rep_edge, self_loops=False
)
G_e_total_tree_weight = spanning_tree_total_weight(prepared_G_e, weight)
if multiplicative:
threshold = e_weight * G_e_total_tree_weight / G_total_tree_weight
else:
numerator = (
st_cached_value + e_weight
) * nx.total_spanning_tree_weight(prepared_G_e) + G_e_total_tree_weight
denominator = (
st_cached_value * nx.total_spanning_tree_weight(prepared_G)
+ G_total_tree_weight
)
threshold = numerator / denominator
else:
threshold = 0.0
z = seed.uniform(0.0, 1.0)
if z > threshold:
# Remove the edge from V since we did not pick it.
V.remove((u, v))
else:
# Add the edge to U since we picked it.
st_cached_value += e_weight
U.add((u, v))
# If we decide to keep an edge, it may complete the spanning tree.
if len(U) == G.number_of_nodes() - 1:
spanning_tree = nx.Graph()
spanning_tree.add_edges_from(U)
return spanning_tree
raise Exception(f"Something went wrong! Only {len(U)} edges in the spanning tree!")
| (G, weight=None, *, multiplicative=True, seed=None, backend=None, **backend_kwargs) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.