triads.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. # See https://github.com/networkx/networkx/pull/1474
  2. # Copyright 2011 Reya Group <http://www.reyagroup.com>
  3. # Copyright 2011 Alex Levenson <alex@isnotinvain.com>
  4. # Copyright 2011 Diederik van Liere <diederik.vanliere@rotman.utoronto.ca>
  5. """Functions that generate the triad graphs, that is, the possible
  6. digraphs on three nodes.
  7. """
  8. import networkx as nx
  9. from networkx.classes import DiGraph
  10. __all__ = ["triad_graph"]
  11. #: Dictionary mapping triad name to list of directed edges in the
  12. #: digraph representation of that triad (with nodes 'a', 'b', and 'c').
  13. TRIAD_EDGES = {
  14. "003": [],
  15. "012": ["ab"],
  16. "102": ["ab", "ba"],
  17. "021D": ["ba", "bc"],
  18. "021U": ["ab", "cb"],
  19. "021C": ["ab", "bc"],
  20. "111D": ["ac", "ca", "bc"],
  21. "111U": ["ac", "ca", "cb"],
  22. "030T": ["ab", "cb", "ac"],
  23. "030C": ["ba", "cb", "ac"],
  24. "201": ["ab", "ba", "ac", "ca"],
  25. "120D": ["bc", "ba", "ac", "ca"],
  26. "120U": ["ab", "cb", "ac", "ca"],
  27. "120C": ["ab", "bc", "ac", "ca"],
  28. "210": ["ab", "bc", "cb", "ac", "ca"],
  29. "300": ["ab", "ba", "bc", "cb", "ac", "ca"],
  30. }
  31. @nx._dispatchable(graphs=None, returns_graph=True)
  32. def triad_graph(triad_name):
  33. """Returns the triad graph with the given name.
  34. Each string in the following tuple is a valid triad name::
  35. (
  36. "003",
  37. "012",
  38. "102",
  39. "021D",
  40. "021U",
  41. "021C",
  42. "111D",
  43. "111U",
  44. "030T",
  45. "030C",
  46. "201",
  47. "120D",
  48. "120U",
  49. "120C",
  50. "210",
  51. "300",
  52. )
  53. Each triad name corresponds to one of the possible valid digraph on
  54. three nodes.
  55. Parameters
  56. ----------
  57. triad_name : string
  58. The name of a triad, as described above.
  59. Returns
  60. -------
  61. :class:`~networkx.DiGraph`
  62. The digraph on three nodes with the given name. The nodes of the
  63. graph are the single-character strings 'a', 'b', and 'c'.
  64. Raises
  65. ------
  66. ValueError
  67. If `triad_name` is not the name of a triad.
  68. See also
  69. --------
  70. triadic_census
  71. """
  72. if triad_name not in TRIAD_EDGES:
  73. raise ValueError(
  74. f'unknown triad name "{triad_name}"; use one of the triad names'
  75. " in the TRIAD_NAMES constant"
  76. )
  77. G = DiGraph()
  78. G.add_nodes_from("abc")
  79. G.add_edges_from(TRIAD_EDGES[triad_name])
  80. return G