Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/generators/stochastic.py: 47%
15 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
1"""Functions for generating stochastic graphs from a given weighted directed
2graph.
4"""
6import networkx as nx
7from networkx.classes import DiGraph, MultiDiGraph
8from networkx.utils import not_implemented_for
10__all__ = ["stochastic_graph"]
13@not_implemented_for("undirected")
14@nx._dispatch(edge_attrs="weight")
15def stochastic_graph(G, copy=True, weight="weight"):
16 """Returns a right-stochastic representation of directed graph `G`.
18 A right-stochastic graph is a weighted digraph in which for each
19 node, the sum of the weights of all the out-edges of that node is
20 1. If the graph is already weighted (for example, via a 'weight'
21 edge attribute), the reweighting takes that into account.
23 Parameters
24 ----------
25 G : directed graph
26 A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.
28 copy : boolean, optional
29 If this is True, then this function returns a new graph with
30 the stochastic reweighting. Otherwise, the original graph is
31 modified in-place (and also returned, for convenience).
33 weight : edge attribute key (optional, default='weight')
34 Edge attribute key used for reading the existing weight and
35 setting the new weight. If no attribute with this key is found
36 for an edge, then the edge weight is assumed to be 1. If an edge
37 has a weight, it must be a positive number.
39 """
40 if copy:
41 G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
42 # There is a tradeoff here: the dictionary of node degrees may
43 # require a lot of memory, whereas making a call to `G.out_degree`
44 # inside the loop may be costly in computation time.
45 degree = dict(G.out_degree(weight=weight))
46 for u, v, d in G.edges(data=True):
47 if degree[u] == 0:
48 d[weight] = 0
49 else:
50 d[weight] = d.get(weight, 1) / degree[u]
51 return G