stochastic.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. """Functions for generating stochastic graphs from a given weighted directed
  2. graph.
  3. """
  4. from networkx.classes import DiGraph, MultiDiGraph
  5. from networkx.utils import not_implemented_for
  6. __all__ = ["stochastic_graph"]
  7. @not_implemented_for("undirected")
  8. def stochastic_graph(G, copy=True, weight="weight"):
  9. """Returns a right-stochastic representation of directed graph `G`.
  10. A right-stochastic graph is a weighted digraph in which for each
  11. node, the sum of the weights of all the out-edges of that node is
  12. 1. If the graph is already weighted (for example, via a 'weight'
  13. edge attribute), the reweighting takes that into account.
  14. Parameters
  15. ----------
  16. G : directed graph
  17. A :class:`~networkx.DiGraph` or :class:`~networkx.MultiDiGraph`.
  18. copy : boolean, optional
  19. If this is True, then this function returns a new graph with
  20. the stochastic reweighting. Otherwise, the original graph is
  21. modified in-place (and also returned, for convenience).
  22. weight : edge attribute key (optional, default='weight')
  23. Edge attribute key used for reading the existing weight and
  24. setting the new weight. If no attribute with this key is found
  25. for an edge, then the edge weight is assumed to be 1. If an edge
  26. has a weight, it must be a positive number.
  27. """
  28. if copy:
  29. G = MultiDiGraph(G) if G.is_multigraph() else DiGraph(G)
  30. # There is a tradeoff here: the dictionary of node degrees may
  31. # require a lot of memory, whereas making a call to `G.out_degree`
  32. # inside the loop may be costly in computation time.
  33. degree = dict(G.out_degree(weight=weight))
  34. for u, v, d in G.edges(data=True):
  35. if degree[u] == 0:
  36. d[weight] = 0
  37. else:
  38. d[weight] = d.get(weight, 1) / degree[u]
  39. return G