cographs.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. r"""Generators for cographs
  2. A cograph is a graph containing no path on four vertices.
  3. Cographs or $P_4$-free graphs can be obtained from a single vertex
  4. by disjoint union and complementation operations.
  5. References
  6. ----------
  7. .. [0] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
  8. "Complement reducible graphs",
  9. Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
  10. ISSN 0166-218X.
  11. """
  12. import networkx as nx
  13. from networkx.utils import py_random_state
  14. __all__ = ["random_cograph"]
  15. @py_random_state(1)
  16. def random_cograph(n, seed=None):
  17. r"""Returns a random cograph with $2 ^ n$ nodes.
  18. A cograph is a graph containing no path on four vertices.
  19. Cographs or $P_4$-free graphs can be obtained from a single vertex
  20. by disjoint union and complementation operations.
  21. This generator starts off from a single vertex and performs disjoint
  22. union and full join operations on itself.
  23. The decision on which operation will take place is random.
  24. Parameters
  25. ----------
  26. n : int
  27. The order of the cograph.
  28. seed : integer, random_state, or None (default)
  29. Indicator of random number generation state.
  30. See :ref:`Randomness<randomness>`.
  31. Returns
  32. -------
  33. G : A random graph containing no path on four vertices.
  34. See Also
  35. --------
  36. full_join
  37. union
  38. References
  39. ----------
  40. .. [1] D.G. Corneil, H. Lerchs, L.Stewart Burlingham,
  41. "Complement reducible graphs",
  42. Discrete Applied Mathematics, Volume 3, Issue 3, 1981, Pages 163-174,
  43. ISSN 0166-218X.
  44. """
  45. R = nx.empty_graph(1)
  46. for i in range(n):
  47. RR = nx.relabel_nodes(R.copy(), lambda x: x + len(R))
  48. if seed.randint(0, 1) == 0:
  49. R = nx.full_join(R, RR)
  50. else:
  51. R = nx.disjoint_union(R, RR)
  52. return R