covering.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """ Functions related to graph covers."""
  2. from functools import partial
  3. from itertools import chain
  4. import networkx as nx
  5. from networkx.utils import arbitrary_element, not_implemented_for
  6. __all__ = ["min_edge_cover", "is_edge_cover"]
  7. @not_implemented_for("directed")
  8. @not_implemented_for("multigraph")
  9. def min_edge_cover(G, matching_algorithm=None):
  10. """Returns the min cardinality edge cover of the graph as a set of edges.
  11. A smallest edge cover can be found in polynomial time by finding
  12. a maximum matching and extending it greedily so that all nodes
  13. are covered. This function follows that process. A maximum matching
  14. algorithm can be specified for the first step of the algorithm.
  15. The resulting set may return a set with one 2-tuple for each edge,
  16. (the usual case) or with both 2-tuples `(u, v)` and `(v, u)` for
  17. each edge. The latter is only done when a bipartite matching algorithm
  18. is specified as `matching_algorithm`.
  19. Parameters
  20. ----------
  21. G : NetworkX graph
  22. An undirected graph.
  23. matching_algorithm : function
  24. A function that returns a maximum cardinality matching for `G`.
  25. The function must take one input, the graph `G`, and return
  26. either a set of edges (with only one direction for the pair of nodes)
  27. or a dictionary mapping each node to its mate. If not specified,
  28. :func:`~networkx.algorithms.matching.max_weight_matching` is used.
  29. Common bipartite matching functions include
  30. :func:`~networkx.algorithms.bipartite.matching.hopcroft_karp_matching`
  31. or
  32. :func:`~networkx.algorithms.bipartite.matching.eppstein_matching`.
  33. Returns
  34. -------
  35. min_cover : set
  36. A set of the edges in a minimum edge cover in the form of tuples.
  37. It contains only one of the equivalent 2-tuples `(u, v)` and `(v, u)`
  38. for each edge. If a bipartite method is used to compute the matching,
  39. the returned set contains both the 2-tuples `(u, v)` and `(v, u)`
  40. for each edge of a minimum edge cover.
  41. Examples
  42. --------
  43. >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
  44. >>> sorted(nx.min_edge_cover(G))
  45. [(2, 1), (3, 0)]
  46. Notes
  47. -----
  48. An edge cover of a graph is a set of edges such that every node of
  49. the graph is incident to at least one edge of the set.
  50. The minimum edge cover is an edge covering of smallest cardinality.
  51. Due to its implementation, the worst-case running time of this algorithm
  52. is bounded by the worst-case running time of the function
  53. ``matching_algorithm``.
  54. Minimum edge cover for `G` can also be found using the `min_edge_covering`
  55. function in :mod:`networkx.algorithms.bipartite.covering` which is
  56. simply this function with a default matching algorithm of
  57. :func:`~networkx.algorithms.bipartite.matching.hopcraft_karp_matching`
  58. """
  59. if len(G) == 0:
  60. return set()
  61. if nx.number_of_isolates(G) > 0:
  62. # ``min_cover`` does not exist as there is an isolated node
  63. raise nx.NetworkXException(
  64. "Graph has a node with no edge incident on it, " "so no edge cover exists."
  65. )
  66. if matching_algorithm is None:
  67. matching_algorithm = partial(nx.max_weight_matching, maxcardinality=True)
  68. maximum_matching = matching_algorithm(G)
  69. # ``min_cover`` is superset of ``maximum_matching``
  70. try:
  71. # bipartite matching algs return dict so convert if needed
  72. min_cover = set(maximum_matching.items())
  73. bipartite_cover = True
  74. except AttributeError:
  75. min_cover = maximum_matching
  76. bipartite_cover = False
  77. # iterate for uncovered nodes
  78. uncovered_nodes = set(G) - {v for u, v in min_cover} - {u for u, v in min_cover}
  79. for v in uncovered_nodes:
  80. # Since `v` is uncovered, each edge incident to `v` will join it
  81. # with a covered node (otherwise, if there were an edge joining
  82. # uncovered nodes `u` and `v`, the maximum matching algorithm
  83. # would have found it), so we can choose an arbitrary edge
  84. # incident to `v`. (This applies only in a simple graph, not a
  85. # multigraph.)
  86. u = arbitrary_element(G[v])
  87. min_cover.add((u, v))
  88. if bipartite_cover:
  89. min_cover.add((v, u))
  90. return min_cover
  91. @not_implemented_for("directed")
  92. def is_edge_cover(G, cover):
  93. """Decides whether a set of edges is a valid edge cover of the graph.
  94. Given a set of edges, whether it is an edge covering can
  95. be decided if we just check whether all nodes of the graph
  96. has an edge from the set, incident on it.
  97. Parameters
  98. ----------
  99. G : NetworkX graph
  100. An undirected bipartite graph.
  101. cover : set
  102. Set of edges to be checked.
  103. Returns
  104. -------
  105. bool
  106. Whether the set of edges is a valid edge cover of the graph.
  107. Examples
  108. --------
  109. >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
  110. >>> cover = {(2, 1), (3, 0)}
  111. >>> nx.is_edge_cover(G, cover)
  112. True
  113. Notes
  114. -----
  115. An edge cover of a graph is a set of edges such that every node of
  116. the graph is incident to at least one edge of the set.
  117. """
  118. return set(G) <= set(chain.from_iterable(cover))