test_stochastic.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """Unit tests for the :mod:`networkx.generators.stochastic` module."""
  2. import pytest
  3. import networkx as nx
  4. class TestStochasticGraph:
  5. """Unit tests for the :func:`~networkx.stochastic_graph` function."""
  6. def test_default_weights(self):
  7. G = nx.DiGraph()
  8. G.add_edge(0, 1)
  9. G.add_edge(0, 2)
  10. S = nx.stochastic_graph(G)
  11. assert nx.is_isomorphic(G, S)
  12. assert sorted(S.edges(data=True)) == [
  13. (0, 1, {"weight": 0.5}),
  14. (0, 2, {"weight": 0.5}),
  15. ]
  16. def test_in_place(self):
  17. """Tests for an in-place reweighting of the edges of the graph."""
  18. G = nx.DiGraph()
  19. G.add_edge(0, 1, weight=1)
  20. G.add_edge(0, 2, weight=1)
  21. nx.stochastic_graph(G, copy=False)
  22. assert sorted(G.edges(data=True)) == [
  23. (0, 1, {"weight": 0.5}),
  24. (0, 2, {"weight": 0.5}),
  25. ]
  26. def test_arbitrary_weights(self):
  27. G = nx.DiGraph()
  28. G.add_edge(0, 1, weight=1)
  29. G.add_edge(0, 2, weight=1)
  30. S = nx.stochastic_graph(G)
  31. assert sorted(S.edges(data=True)) == [
  32. (0, 1, {"weight": 0.5}),
  33. (0, 2, {"weight": 0.5}),
  34. ]
  35. def test_multidigraph(self):
  36. G = nx.MultiDiGraph()
  37. G.add_edges_from([(0, 1), (0, 1), (0, 2), (0, 2)])
  38. S = nx.stochastic_graph(G)
  39. d = {"weight": 0.25}
  40. assert sorted(S.edges(data=True)) == [
  41. (0, 1, d),
  42. (0, 1, d),
  43. (0, 2, d),
  44. (0, 2, d),
  45. ]
  46. def test_zero_weights(self):
  47. """Smoke test: ensure ZeroDivisionError is not raised."""
  48. G = nx.DiGraph()
  49. G.add_edge(0, 1, weight=0)
  50. G.add_edge(0, 2, weight=0)
  51. S = nx.stochastic_graph(G)
  52. assert sorted(S.edges(data=True)) == [
  53. (0, 1, {"weight": 0}),
  54. (0, 2, {"weight": 0}),
  55. ]
  56. def test_graph_disallowed(self):
  57. with pytest.raises(nx.NetworkXNotImplemented):
  58. nx.stochastic_graph(nx.Graph())
  59. def test_multigraph_disallowed(self):
  60. with pytest.raises(nx.NetworkXNotImplemented):
  61. nx.stochastic_graph(nx.MultiGraph())