test_covering.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import pytest
  2. import networkx as nx
  3. class TestMinEdgeCover:
  4. """Tests for :func:`networkx.algorithms.min_edge_cover`"""
  5. def test_empty_graph(self):
  6. G = nx.Graph()
  7. assert nx.min_edge_cover(G) == set()
  8. def test_graph_with_loop(self):
  9. G = nx.Graph()
  10. G.add_edge(0, 0)
  11. assert nx.min_edge_cover(G) == {(0, 0)}
  12. def test_graph_with_isolated_v(self):
  13. G = nx.Graph()
  14. G.add_node(1)
  15. with pytest.raises(
  16. nx.NetworkXException,
  17. match="Graph has a node with no edge incident on it, so no edge cover exists.",
  18. ):
  19. nx.min_edge_cover(G)
  20. def test_graph_single_edge(self):
  21. G = nx.Graph([(0, 1)])
  22. assert nx.min_edge_cover(G) in ({(0, 1)}, {(1, 0)})
  23. def test_graph_two_edge_path(self):
  24. G = nx.path_graph(3)
  25. min_cover = nx.min_edge_cover(G)
  26. assert len(min_cover) == 2
  27. for u, v in G.edges:
  28. assert (u, v) in min_cover or (v, u) in min_cover
  29. def test_bipartite_explicit(self):
  30. G = nx.Graph()
  31. G.add_nodes_from([1, 2, 3, 4], bipartite=0)
  32. G.add_nodes_from(["a", "b", "c"], bipartite=1)
  33. G.add_edges_from([(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c"), (4, "a")])
  34. # Use bipartite method by prescribing the algorithm
  35. min_cover = nx.min_edge_cover(
  36. G, nx.algorithms.bipartite.matching.eppstein_matching
  37. )
  38. assert nx.is_edge_cover(G, min_cover)
  39. assert len(min_cover) == 8
  40. # Use the default method which is not specialized for bipartite
  41. min_cover2 = nx.min_edge_cover(G)
  42. assert nx.is_edge_cover(G, min_cover2)
  43. assert len(min_cover2) == 4
  44. def test_complete_graph_even(self):
  45. G = nx.complete_graph(10)
  46. min_cover = nx.min_edge_cover(G)
  47. assert nx.is_edge_cover(G, min_cover)
  48. assert len(min_cover) == 5
  49. def test_complete_graph_odd(self):
  50. G = nx.complete_graph(11)
  51. min_cover = nx.min_edge_cover(G)
  52. assert nx.is_edge_cover(G, min_cover)
  53. assert len(min_cover) == 6
  54. class TestIsEdgeCover:
  55. """Tests for :func:`networkx.algorithms.is_edge_cover`"""
  56. def test_empty_graph(self):
  57. G = nx.Graph()
  58. assert nx.is_edge_cover(G, set())
  59. def test_graph_with_loop(self):
  60. G = nx.Graph()
  61. G.add_edge(1, 1)
  62. assert nx.is_edge_cover(G, {(1, 1)})
  63. def test_graph_single_edge(self):
  64. G = nx.Graph()
  65. G.add_edge(0, 1)
  66. assert nx.is_edge_cover(G, {(0, 0), (1, 1)})
  67. assert nx.is_edge_cover(G, {(0, 1), (1, 0)})
  68. assert nx.is_edge_cover(G, {(0, 1)})
  69. assert not nx.is_edge_cover(G, {(0, 0)})