1 """Unary operations on graphs""" 2 # Copyright (C) 2004-2012 by 3 # Aric Hagberg <hagberg (at] lanl.gov> 4 # Dan Schult <dschult (at] colgate.edu> 5 # Pieter Swart <swart (at] lanl.gov> 6 # All rights reserved. 7 # BSD license. 8 import networkx as nx 9 from networkx.utils import is_string_like 10 __author__ = """\n""".join(['Aric Hagberg (hagberg (at] lanl.gov)', 11 'Pieter Swart (swart (at] lanl.gov)', 12 'Dan Schult(dschult (at] colgate.edu)']) 13 __all__ = ['complement', 'reverse'] 14 15 def complement(G, name=None): 16 """Return the graph complement of G. 17 18 Parameters 19 ---------- 20 G : graph 21 A NetworkX graph 22 23 name : string 24 Specify name for new graph 25 26 Returns 27 ------- 28 GC : A new graph. 29 30 Notes 31 ------ 32 Note that complement() does not create self-loops and also 33 does not produce parallel edges for MultiGraphs. 34 35 Graph, node, and edge data are not propagated to the new graph. 36 """ 37 if name is None: 38 name="complement(%s)"%(G.name) 39 R=G.__class__() 40 R.name=name 41 R.add_nodes_from(G) 42 R.add_edges_from( ((n,n2) 43 for n,nbrs in G.adjacency_iter() 44 for n2 in G if n2 not in nbrs 45 if n != n2) ) 46 return R 47 48 def reverse(G, copy=True): 49 """Return the reverse directed graph of G. 50 51 Parameters 52 ---------- 53 G : directed graph 54 A NetworkX directed graph 55 copy : bool 56 If True, then a new graph is returned. If False, then the graph is 57 reversed in place. 58 59 Returns 60 ------- 61 H : directed graph 62 The reversed G. 63 64 """ 65 if not G.is_directed(): 66 raise nx.NetworkXError("Cannot reverse an undirected graph.") 67 else: 68 return G.reverse(copy=copy) 69 70