mis.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """
  2. Algorithm to find a maximal (not maximum) independent set.
  3. """
  4. import networkx as nx
  5. from networkx.utils import not_implemented_for, py_random_state
  6. __all__ = ["maximal_independent_set"]
  7. @py_random_state(2)
  8. @not_implemented_for("directed")
  9. def maximal_independent_set(G, nodes=None, seed=None):
  10. """Returns a random maximal independent set guaranteed to contain
  11. a given set of nodes.
  12. An independent set is a set of nodes such that the subgraph
  13. of G induced by these nodes contains no edges. A maximal
  14. independent set is an independent set such that it is not possible
  15. to add a new node and still get an independent set.
  16. Parameters
  17. ----------
  18. G : NetworkX graph
  19. nodes : list or iterable
  20. Nodes that must be part of the independent set. This set of nodes
  21. must be independent.
  22. seed : integer, random_state, or None (default)
  23. Indicator of random number generation state.
  24. See :ref:`Randomness<randomness>`.
  25. Returns
  26. -------
  27. indep_nodes : list
  28. List of nodes that are part of a maximal independent set.
  29. Raises
  30. ------
  31. NetworkXUnfeasible
  32. If the nodes in the provided list are not part of the graph or
  33. do not form an independent set, an exception is raised.
  34. NetworkXNotImplemented
  35. If `G` is directed.
  36. Examples
  37. --------
  38. >>> G = nx.path_graph(5)
  39. >>> nx.maximal_independent_set(G) # doctest: +SKIP
  40. [4, 0, 2]
  41. >>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP
  42. [1, 3]
  43. Notes
  44. -----
  45. This algorithm does not solve the maximum independent set problem.
  46. """
  47. if not nodes:
  48. nodes = {seed.choice(list(G))}
  49. else:
  50. nodes = set(nodes)
  51. if not nodes.issubset(G):
  52. raise nx.NetworkXUnfeasible(f"{nodes} is not a subset of the nodes of G")
  53. neighbors = set.union(*[set(G.adj[v]) for v in nodes])
  54. if set.intersection(neighbors, nodes):
  55. raise nx.NetworkXUnfeasible(f"{nodes} is not an independent set of G")
  56. indep_nodes = list(nodes)
  57. available_nodes = set(G.nodes()).difference(neighbors.union(nodes))
  58. while available_nodes:
  59. node = seed.choice(list(available_nodes))
  60. indep_nodes.append(node)
  61. available_nodes.difference_update(list(G.adj[node]) + [node])
  62. return indep_nodes