test_mis.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. """
  2. Tests for maximal (not maximum) independent sets.
  3. """
  4. import random
  5. import pytest
  6. import networkx as nx
  7. def test_random_seed():
  8. G = nx.empty_graph(5)
  9. assert nx.maximal_independent_set(G, seed=1) == [1, 0, 3, 2, 4]
  10. @pytest.mark.parametrize("graph", [nx.complete_graph(5), nx.complete_graph(55)])
  11. def test_K5(graph):
  12. """Maximal independent set for complete graphs"""
  13. assert all(nx.maximal_independent_set(graph, [n]) == [n] for n in graph)
  14. def test_exceptions():
  15. """Bad input should raise exception."""
  16. G = nx.florentine_families_graph()
  17. pytest.raises(nx.NetworkXUnfeasible, nx.maximal_independent_set, G, ["Smith"])
  18. pytest.raises(
  19. nx.NetworkXUnfeasible, nx.maximal_independent_set, G, ["Salviati", "Pazzi"]
  20. )
  21. # MaximalIndependantSet is not implemented for directed graphs
  22. pytest.raises(nx.NetworkXNotImplemented, nx.maximal_independent_set, nx.DiGraph(G))
  23. def test_florentine_family():
  24. G = nx.florentine_families_graph()
  25. indep = nx.maximal_independent_set(G, ["Medici", "Bischeri"])
  26. assert set(indep) == {
  27. "Medici",
  28. "Bischeri",
  29. "Castellani",
  30. "Pazzi",
  31. "Ginori",
  32. "Lamberteschi",
  33. }
  34. def test_bipartite():
  35. G = nx.complete_bipartite_graph(12, 34)
  36. indep = nx.maximal_independent_set(G, [4, 5, 9, 10])
  37. assert sorted(indep) == list(range(12))
  38. def test_random_graphs():
  39. """Generate 5 random graphs of different types and sizes and
  40. make sure that all sets are independent and maximal."""
  41. for i in range(0, 50, 10):
  42. G = nx.erdos_renyi_graph(i * 10 + 1, random.random())
  43. IS = nx.maximal_independent_set(G)
  44. assert G.subgraph(IS).number_of_edges() == 0
  45. neighbors_of_MIS = set.union(*(set(G.neighbors(v)) for v in IS))
  46. assert all(v in neighbors_of_MIS for v in set(G.nodes()).difference(IS))