triads.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. from networkx.classes import DiGraph
  9. __all__ = ["triad_graph"]
  10. #: Dictionary mapping triad name to list of directed edges in the
  11. #: digraph representation of that triad (with nodes 'a', 'b', and 'c').
  12. TRIAD_EDGES = {
  13. "003": [],
  14. "012": ["ab"],
  15. "102": ["ab", "ba"],
  16. "021D": ["ba", "bc"],
  17. "021U": ["ab", "cb"],
  18. "021C": ["ab", "bc"],
  19. "111D": ["ac", "ca", "bc"],
  20. "111U": ["ac", "ca", "cb"],
  21. "030T": ["ab", "cb", "ac"],
  22. "030C": ["ba", "cb", "ac"],
  23. "201": ["ab", "ba", "ac", "ca"],
  24. "120D": ["bc", "ba", "ac", "ca"],
  25. "120U": ["ab", "cb", "ac", "ca"],
  26. "120C": ["ab", "bc", "ac", "ca"],
  27. "210": ["ab", "bc", "cb", "ac", "ca"],
  28. "300": ["ab", "ba", "bc", "cb", "ac", "ca"],
  29. }
  30. def triad_graph(triad_name):
  31. """Returns the triad graph with the given name.
  32. Each string in the following tuple is a valid triad name::
  33. ('003', '012', '102', '021D', '021U', '021C', '111D', '111U',
  34. '030T', '030C', '201', '120D', '120U', '120C', '210', '300')
  35. Each triad name corresponds to one of the possible valid digraph on
  36. three nodes.
  37. Parameters
  38. ----------
  39. triad_name : string
  40. The name of a triad, as described above.
  41. Returns
  42. -------
  43. :class:`~networkx.DiGraph`
  44. The digraph on three nodes with the given name. The nodes of the
  45. graph are the single-character strings 'a', 'b', and 'c'.
  46. Raises
  47. ------
  48. ValueError
  49. If `triad_name` is not the name of a triad.
  50. See also
  51. --------
  52. triadic_census
  53. """
  54. if triad_name not in TRIAD_EDGES:
  55. raise ValueError(
  56. f'unknown triad name "{triad_name}"; use one of the triad names'
  57. " in the TRIAD_NAMES constant"
  58. )
  59. G = DiGraph()
  60. G.add_nodes_from("abc")
  61. G.add_edges_from(TRIAD_EDGES[triad_name])
  62. return G