ramsey.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. Ramsey numbers.
  3. """
  4. import networkx as nx
  5. from networkx.utils import not_implemented_for
  6. from ...utils import arbitrary_element
  7. __all__ = ["ramsey_R2"]
  8. @not_implemented_for("directed")
  9. @not_implemented_for("multigraph")
  10. def ramsey_R2(G):
  11. r"""Compute the largest clique and largest independent set in `G`.
  12. This can be used to estimate bounds for the 2-color
  13. Ramsey number `R(2;s,t)` for `G`.
  14. This is a recursive implementation which could run into trouble
  15. for large recursions. Note that self-loop edges are ignored.
  16. Parameters
  17. ----------
  18. G : NetworkX graph
  19. Undirected graph
  20. Returns
  21. -------
  22. max_pair : (set, set) tuple
  23. Maximum clique, Maximum independent set.
  24. Raises
  25. ------
  26. NetworkXNotImplemented
  27. If the graph is directed or is a multigraph.
  28. """
  29. if not G:
  30. return set(), set()
  31. node = arbitrary_element(G)
  32. nbrs = (nbr for nbr in nx.all_neighbors(G, node) if nbr != node)
  33. nnbrs = nx.non_neighbors(G, node)
  34. c_1, i_1 = ramsey_R2(G.subgraph(nbrs).copy())
  35. c_2, i_2 = ramsey_R2(G.subgraph(nnbrs).copy())
  36. c_1.add(node)
  37. i_2.add(node)
  38. # Choose the larger of the two cliques and the larger of the two
  39. # independent sets, according to cardinality.
  40. return max(c_1, c_2, key=len), max(i_1, i_2, key=len)