unary.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """Unary operations on graphs"""
  2. import networkx as nx
  3. __all__ = ["complement", "reverse"]
  4. def complement(G):
  5. """Returns the graph complement of G.
  6. Parameters
  7. ----------
  8. G : graph
  9. A NetworkX graph
  10. Returns
  11. -------
  12. GC : A new graph.
  13. Notes
  14. -----
  15. Note that `complement` does not create self-loops and also
  16. does not produce parallel edges for MultiGraphs.
  17. Graph, node, and edge data are not propagated to the new graph.
  18. Examples
  19. --------
  20. >>> G = nx.Graph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
  21. >>> G_complement = nx.complement(G)
  22. >>> G_complement.edges() # This shows the edges of the complemented graph
  23. EdgeView([(1, 4), (1, 5), (2, 4), (2, 5), (4, 5)])
  24. """
  25. R = G.__class__()
  26. R.add_nodes_from(G)
  27. R.add_edges_from(
  28. ((n, n2) for n, nbrs in G.adjacency() for n2 in G if n2 not in nbrs if n != n2)
  29. )
  30. return R
  31. def reverse(G, copy=True):
  32. """Returns the reverse directed graph of G.
  33. Parameters
  34. ----------
  35. G : directed graph
  36. A NetworkX directed graph
  37. copy : bool
  38. If True, then a new graph is returned. If False, then the graph is
  39. reversed in place.
  40. Returns
  41. -------
  42. H : directed graph
  43. The reversed G.
  44. Raises
  45. ------
  46. NetworkXError
  47. If graph is undirected.
  48. Examples
  49. --------
  50. >>> G = nx.DiGraph([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5)])
  51. >>> G_reversed = nx.reverse(G)
  52. >>> G_reversed.edges()
  53. OutEdgeView([(2, 1), (3, 1), (3, 2), (4, 3), (5, 3)])
  54. """
  55. if not G.is_directed():
  56. raise nx.NetworkXError("Cannot reverse an undirected graph.")
  57. else:
  58. return G.reverse(copy=copy)