ramsey.py 1.3 KB

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