Goulib.graph module¶
efficient Euclidian Graphs for networkx
and related algorithms
requires: 

optional: 


class
Goulib.graph.
index
[source]¶ Bases:
object

Goulib.graph.
to_networkx_graph
(data, create_using=None, multigraph_input=False)[source]¶ Make a NetworkX graph from a known data structure. enhances networkx.convert.to_networkx_graph :param data: any type handled by convert.to_networkx_graph, plus: *
scipy.spatial.qhull.Delaunay
to enable building a graph from a delauney triangulationIf create_using is a :class:`GeoGraph`and data is a Graph where nodes have a ‘pos’ attribute, then this attribute will be used to rename nodes as (x,y,…) tuples suitable for GeoGraph.

class
Goulib.graph.
GeoGraph
(data=None, nodes=None, **kwargs)[source]¶ Bases:
Goulib.graph._Geo
,networkx.classes.multigraph.MultiGraph
Undirected graph with nodes positions can be set to non multiedges anytime with attribute multi=False
Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:

__init__
(data=None, nodes=None, **kwargs)[source]¶ Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:
 data – see
 data – see

class
Goulib.graph.
DiGraph
(data=None, nodes=None, **kwargs)[source]¶ Bases:
Goulib.graph._Geo
,networkx.classes.multidigraph.MultiDiGraph
directed graph with nodes positions can be set to non multiedges anytime with attribute multi=False
Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:

__init__
(data=None, nodes=None, **kwargs)[source]¶ Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:
 data – see
 data – see

Goulib.graph.
figure
(g, box=None, **kwargs)[source]¶ Parameters:  g – _Geo derived Graph
 box – optional interval.Box if g has no box
Returns: matplotlib axis suitable for drawing graph g

Goulib.graph.
draw_networkx
(g, pos=None, **kwargs)[source]¶ improves nx.draw_networkx :param g: NetworkX Graph :param pos: can be either :
 optional dictionary of (x,y) node positions
 function of the form lambda node:(x,y) that maps node positions.
 None. in this case, nodes are directly used as positions if graph is a GeoGraph, otherwise nx.draw_shell is used
Parameters: **kwargs – passed to nx.draw method as described in http://networkx.lanl.gov/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html with one tweak:
 if edge_color is a function of the form lambda data:color string, it is mapped over all edges

Goulib.graph.
to_drawing
(g, d=None, edges=[])[source]¶ draws Graph to a Drawing :param g:
Graph
:param d: existingDrawing
to draw onto, or None to create a new Drawing :param edges: iterable of edges (with data) that will be added, in the same order. By default all edges are drawn :return:Drawing
Graph edges with an ‘entity’ property

Goulib.graph.
write_dxf
(g, filename)[source]¶ writes
networkx.Graph
in .dxf format

Goulib.graph.
write_json
(g, filename, **kwargs)[source]¶ write a JSON file, suitable for D*.js representation

Goulib.graph.
delauney_triangulation
(nodes, qhull_options='', incremental=False, **kwargs)[source]¶ https://en.wikipedia.org/wiki/Delaunay_triangulation :param nodes: _Geo graph or list of (x,y) or (x,y,z) node positions :param qhull_options: string passed to
scipy.spatial.Delaunay()
, which passes it to Qhull ( http://www.qhull.org/ ) *’Qt’ ensures all points are connected *’Qz’ required when nodes lie on a sphere *’QJ’ solves some singularity situationsParameters: kwargs – passed to the GeoGraph
constructorReturns: GeoGraph
with delauney triangulation between nodes

Goulib.graph.
euclidean_minimum_spanning_tree
(nodes, **kwargs)[source]¶ Parameters: nodes – list of (x,y) nodes positions Returns: GeoGraph
with minimum spanning tree between nodessee https://en.wikipedia.org/wiki/Euclidean_minimum_spanning_tree
Classes¶
efficient Euclidian Graphs for networkx
and related algorithms
requires: 

optional: 


class
Goulib.graph.
index
[source] Bases:
object

class
Property
[source] Bases:
object

set_dimension
(n)[source]

__class__
¶ alias of
builtins.type

__delattr__
¶ Implement delattr(self, name).

__dir__
() → list¶ default dir() implementation

__eq__
¶ Return self==value.

__format__
()¶ default object formatter

__ge__
¶ Return self>=value.

__getattribute__
¶ Return getattr(self, name).

__gt__
¶ Return self>value.

__hash__
¶ Return hash(self).

__init__
¶ Initialize self. See help(type(self)) for accurate signature.

__le__
¶ Return self<=value.

__lt__
¶ Return self<value.

__ne__
¶ Return self!=value.

__new__
()¶ Create and return a new object. See help(type) for accurate signature.

__reduce__
()¶ helper for pickle

__reduce_ex__
()¶ helper for pickle

__repr__
¶ Return repr(self).

__setattr__
¶ Implement setattr(self, name, value).

__sizeof__
() → int¶ size of object in memory, in bytes

__str__
¶ Return str(self).


class
Index
(properties)[source] Bases:
dict
fallback for rtree.index

__init__
(properties)[source] Initialize self. See help(type(self)) for accurate signature.

count
(ignored)[source]

insert
(k, p, _)[source]

delete
(k, _)[source]

nearest
(p, num_results, objects='raw')[source] very inefficient, but remember it’s a fallback…

__class__
¶ alias of
builtins.type

__contains__
()¶ True if D has a key k, else False.

__delattr__
¶ Implement delattr(self, name).

__delitem__
¶ Delete self[key].

__dir__
() → list¶ default dir() implementation

__eq__
¶ Return self==value.

__format__
()¶ default object formatter

__ge__
¶ Return self>=value.

__getattribute__
¶ Return getattr(self, name).

__getitem__
()¶ x.__getitem__(y) <==> x[y]

__gt__
¶ Return self>value.

__hash__
= None¶

__iter__
¶ Implement iter(self).

__le__
¶ Return self<=value.

__len__
¶ Return len(self).

__lt__
¶ Return self<value.

__ne__
¶ Return self!=value.

__new__
()¶ Create and return a new object. See help(type) for accurate signature.

__reduce__
()¶ helper for pickle

__reduce_ex__
()¶ helper for pickle

__repr__
¶ Return repr(self).

__setattr__
¶ Implement setattr(self, name, value).

__setitem__
¶ Set self[key] to value.

__sizeof__
() → size of D in memory, in bytes¶

__str__
¶ Return str(self).

clear
() → None. Remove all items from D.¶

copy
() → a shallow copy of D¶

fromkeys
()¶ Returns a new dict with keys from iterable and values equal to value.

get
(k[, d]) → D[k] if k in D, else d. d defaults to None.¶

items
() → a setlike object providing a view on D's items¶

keys
() → a setlike object providing a view on D's keys¶

pop
(k[, d]) → v, remove specified key and return the corresponding value.¶ If key is not found, d is returned if given, otherwise KeyError is raised

popitem
() → (k, v), remove and return some (key, value) pair as a¶ 2tuple; but raise KeyError if D is empty.

setdefault
(k[, d]) → D.get(k,d), also set D[k]=d if k not in D¶

update
([E, ]**F) → None. Update D from dict/iterable E and F.¶ If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values
() → an object providing a view on D's values¶


__class__
¶ alias of
builtins.type

__delattr__
¶ Implement delattr(self, name).

__dir__
() → list¶ default dir() implementation

__eq__
¶ Return self==value.

__format__
()¶ default object formatter

__ge__
¶ Return self>=value.

__getattribute__
¶ Return getattr(self, name).

__gt__
¶ Return self>value.

__hash__
¶ Return hash(self).

__init__
¶ Initialize self. See help(type(self)) for accurate signature.

__le__
¶ Return self<=value.

__lt__
¶ Return self<value.

__ne__
¶ Return self!=value.

__new__
()¶ Create and return a new object. See help(type) for accurate signature.

__reduce__
()¶ helper for pickle

__reduce_ex__
()¶ helper for pickle

__repr__
¶ Return repr(self).

__setattr__
¶ Implement setattr(self, name, value).

__sizeof__
() → int¶ size of object in memory, in bytes

__str__
¶ Return str(self).

class

class
Goulib.graph.
AGraph
[source] Bases:
object

__class__
¶ alias of
builtins.type

__delattr__
¶ Implement delattr(self, name).

__dir__
() → list¶ default dir() implementation

__eq__
¶ Return self==value.

__format__
()¶ default object formatter

__ge__
¶ Return self>=value.

__getattribute__
¶ Return getattr(self, name).

__gt__
¶ Return self>value.

__hash__
¶ Return hash(self).

__init__
¶ Initialize self. See help(type(self)) for accurate signature.

__le__
¶ Return self<=value.

__lt__
¶ Return self<value.

__ne__
¶ Return self!=value.

__new__
()¶ Create and return a new object. See help(type) for accurate signature.

__reduce__
()¶ helper for pickle

__reduce_ex__
()¶ helper for pickle

__repr__
¶ Return repr(self).

__setattr__
¶ Implement setattr(self, name, value).

__sizeof__
() → int¶ size of object in memory, in bytes

__str__
¶ Return str(self).


Goulib.graph.
to_networkx_graph
(data, create_using=None, multigraph_input=False)[source] Make a NetworkX graph from a known data structure. enhances networkx.convert.to_networkx_graph :param data: any type handled by convert.to_networkx_graph, plus: *
scipy.spatial.qhull.Delaunay
to enable building a graph from a delauney triangulationIf create_using is a :class:`GeoGraph`and data is a Graph where nodes have a ‘pos’ attribute, then this attribute will be used to rename nodes as (x,y,…) tuples suitable for GeoGraph.

class
Goulib.graph.
GeoGraph
(data=None, nodes=None, **kwargs)[source] Bases:
Goulib.graph._Geo
,networkx.classes.multigraph.MultiGraph
Undirected graph with nodes positions can be set to non multiedges anytime with attribute multi=False
Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:

__init__
(data=None, nodes=None, **kwargs)[source] Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:
 data – see

__bool__
()¶ Returns: True if graph has at least one node

__class__
¶ alias of
builtins.type

__contains__
(n)¶ Return True if n is a node, False otherwise. Use: ‘n in G’.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> 1 in G True

__delattr__
¶ Implement delattr(self, name).

__dir__
() → list¶ default dir() implementation

__eq__
(other)¶ Returns: True if self and other are equal

__format__
()¶ default object formatter

__ge__
¶ Return self>=value.

__getattribute__
¶ Return getattr(self, name).

__getitem__
(n)¶ Return a dict of neighbors of node n. Use: ‘G[n]’.
 n : node
 A node in the graph.
 adj_dict : dictionary
 The adjacency dictionary for nodes connected to n.
G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G[0] AtlasView({1: {}})

__gt__
¶ Return self>value.

__hash__
= None¶

__iter__
()¶ Iterate over the nodes. Use: ‘for n in G’.
 niter : iterator
 An iterator over all nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [n for n in G] [0, 1, 2, 3] >>> list(G) [0, 1, 2, 3]

__le__
¶ Return self<=value.

__len__
()¶ Return the number of nodes. Use: ‘len(G)’.
 nnodes : int
 The number of nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> len(G) 4

__lt__
¶ Return self<value.

__ne__
¶ Return self!=value.

__new__
()¶ Create and return a new object. See help(type) for accurate signature.

__nonzero__
()¶ Returns: True if graph has at least one node

__reduce__
()¶ helper for pickle

__reduce_ex__
()¶ helper for pickle

__repr__
¶ Return repr(self).

__setattr__
¶ Implement setattr(self, name, value).

__sizeof__
() → int¶ size of object in memory, in bytes

__str__
()¶ Returns: string representation, used mainly for logging and debugging

add_cycle
(nodes, **attr)¶

add_edge
(u, v, key=None, **attr)¶ add an edge to graph
Returns: edge key

add_edge2
(u, v, key=None, **attrs)¶ add an edge to graph :return: edge data from created or existing edge

add_edges_from
(ebunch_to_add, **attr)¶ Add all the edges in ebunch_to_add.
 ebunch_to_add : container of edges
Each edge given in the container will be added to the graph. The edges can be:
 2tuples (u, v) or
 3tuples (u, v, d) for an edge data dict d, or
 3tuples (u, v, k) for not iterable key k, or
 4tuples (u, v, k, d) for an edge with data and key k
 attr : keyword arguments, optional
 Edge data (or labels or objects) can be assigned using keyword arguments.
A list of edge keys assigned to the edges in ebunch.
add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method
new_edge_key()
. This method can be overridden by subclassing the base class and providing a customnew_edge_key()
method.>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0123
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label='WN2898')

add_node
(p, **attr)¶ add a node or return one already very close :return (x,y,…) node id

add_nodes_from
(nodes, **attr)¶

add_path
(nodes, **attr)¶

add_star
(nodes, **attr)¶

add_weighted_edges_from
(ebunch_to_add, weight='weight', **attr)¶ Add weighted edges in ebunch_to_add with specified weight attr
 ebunch_to_add : container of edges
 Each edge given in the list or container will be added to the graph. The edges must be given as 3tuples (u, v, w) where w is a number.
 weight : string, optional (default= ‘weight’)
 The attribute name for the edge weights to be added.
 attr : keyword arguments, optional (default= no attributes)
 Edge attributes to add/update for all edges.
add_edge : add a single edge add_edges_from : add multiple edges
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph, duplicate edges are stored.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])

adj
¶ Graph adjacency object holding the neighbors of each node.
This object is a readonly dictlike structure with node keys and neighbordict values. The neighbordict is keyed by neighbor to the edgekeydatadict. So G.adj[3][2][0][‘color’] = ‘blue’ sets the color of the edge (3, 2, 0) to “blue”.
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, nbrdict in G.adj[n].items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.

adjacency
()¶ Return an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
 adj_iter : iterator
 An iterator over (node, adjacency dictionary) for all nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [(n, nbrdict) for n, nbrdict in G.adjacency()] [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

adjlist_inner_dict_factory
¶ alias of
builtins.dict

adjlist_outer_dict_factory
¶ alias of
builtins.dict

box
()¶ Returns: nodes bounding box as (xmin,ymin,…),(xmax,ymax,…)

box_size
()¶ Returns: (x,y) size

clear
()¶

closest_edges
(p, data=False)¶ Returns: container of edges close to p and distance

closest_nodes
(p, n=1, skip=False)¶ nodes closest to a given position :param p: (x,y) position tuple :param skip: optional bool to skip n itself :return: list of nodes, minimal distance

contiguity
(pts)¶ Returns: int number of points from pts already in graph

copy
()¶ Returns: copy of self graph

degree
¶ A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 weight : string or None, optional (default=None)
 The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
Degree of the node, if a single node is passed as argument.OR if multiple nodes are requested nd_iter : iterator
The iterator returns twotuples of (node, degree).>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1])) [(0, 1), (1, 2)]

dist
(u, v)¶ Returns: float distance between nodes u and v

draw
(**kwargs)¶ draw graph with default params

edge_attr_dict_factory
¶ alias of
builtins.dict

edge_key_dict_factory
¶ alias of
builtins.dict

edge_subgraph
(edges)¶ Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
 edges : iterable
 An iterable of edges in this graph.
 G : Graph
 An edgeinduced subgraph of this graph with the same edge attributes.
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes in the original graph. The view is readonly.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
>>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)]

edges
¶ Return an iterator over the edges.
edges(self, nbunch=None, data=False, keys=False, default=None)
The EdgeView provides setlike operations on the edgetuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide setlike operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges(data=’color’, default=’red’): iterates through all the edges yielding the color attribute.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 data : string or bool, optional (default=False)
 The edge attribute returned in 3tuple (u, v, ddict[data]). If True, return edge attribute dict in 3tuple (u, v, ddict). If False, return 2tuple (u, v).
 keys : bool, optional (default=False)
 If True, return edge keys with each edge.
 default : value, optional (default=None)
 Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.
 edges : MultiEdgeView
 A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as edges[u, v, k][‘foo’].
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the outedges.
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2]) >>> key = G.add_edge(2, 3, weight=5) >>> [e for e in G.edges()] [(0, 1), (1, 2), (2, 3)] >>> G.edges.data() # default data is {} (empty dict) MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]) >>> G.edges.data('weight', default=1) MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)]) >>> G.edges(keys=True) # default keys are integers MultiEdgeView([(0, 1, 0), (1, 2, 0), (2, 3, 0)]) >>> G.edges.data(keys=True) MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})]) >>> G.edges.data('weight', default=1, keys=True) MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)]) >>> G.edges([0, 3]) MultiEdgeDataView([(0, 1), (3, 2)]) >>> G.edges(0) MultiEdgeDataView([(0, 1)])

fresh_copy
()¶

get_edge_data
(u, v, key=None, default=None)¶ Return the attribute dictionary associated with edge (u, v).
This is identical to G[u][v][key] except the default is returned instead of an exception is the edge doesn’t exist.
u, v : nodes
 default : any Python object (default=None)
 Value to return if the edge (u, v) is not found.
 key : hashable identifier, optional (default=None)
 Return data only for the edge with specified key.
 edge_dict : dictionary
 The edge attribute dictionary.
>>> G = nx.MultiGraph() # or MultiDiGraph >>> key = G.add_edge(0, 1, key='a', weight=7) >>> G[0][1]['a'] # key='a' {'weight': 7} >>> G.edges[0, 1, 'a'] # key='a' {'weight': 7}
Warning: we protect the graph data structure by making G.edges and G[1][2] readonly dictlike structures. However, you can assign values to attributes in e.g. G.edges[1, 2, ‘a’] or G[1][2][‘a’] using an additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an edge.
>>> G[0][1]['a']['weight'] = 10 >>> G.edges[0, 1, 'a']['weight'] = 10 >>> G[0][1]['a']['weight'] 10 >>> G.edges[1, 0, 'a']['weight'] 10
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.get_edge_data(0, 1) {0: {}} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {0: {}} >>> G.get_edge_data('a', 'b', default=0) # edge not in graph, return 0 0

has_edge
(u, v, key=None)¶ Return True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
 u, v : nodes
 Nodes can be, for example, strings or numbers.
 key : hashable identifier, optional (default=None)
 If specified return True only if the edge with key is found.
 edge_ind : bool
 True if edge is in the graph, False otherwise.
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2tuple (u, v) True >>> G.add_edge(0, 1, key='a') 'a' >>> G.has_edge(0, 1, key='a') # specify key True >>> e=(0, 1, 'a') >>> G.has_edge(*e) # e is a 3tuple (u, v, 'a') True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G True

has_node
(n)¶ Return True if the graph contains the node n.
Identical to n in G
n : node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_node(0) True
It is more readable and simpler to use
>>> 0 in G True

html
(**kwargs)¶

is_directed
()¶ Return True if graph is directed, False otherwise.

is_multigraph
()¶ used internally in constructor

length
(edges=None)¶ Parameters: edges – iterator over edges either as (u,v,data) or (u,v,key,data). If None, all edges are taken Returns: sum of ‘length’ attributes of edges

multi
¶

name
¶ String identifier of the graph.
This graph attribute appears in the attribute dict G.graph keyed by the string “name”. as well as an attribute (technically a property) G.name. This is entirely user controlled.

nbunch_iter
(nbunch=None)¶ Return an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 niter : iterator
 An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate over all nodes in the graph.
 NetworkXError
 If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
Graph.__iter__
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a
NetworkXError
is raised. Also, if any object in nbunch is not hashable, aNetworkXError
is raised.

neighbors
(n)¶ Return an iterator over all neighbors of node n.
This is identical to iter(G[n])
 n : node
 A node in the graph
 neighbors : iterator
 An iterator over all neighbors of node n
 NetworkXError
 If the node n is not in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [n for n in G.neighbors(0)] [1]
It is usually more convenient (and faster) to access the adjacency dictionary as
G[n]
:>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge('a', 'b', weight=7) >>> G['a'] AtlasView({'b': {'weight': 7}}) >>> G = nx.path_graph(4) >>> [n for n in G[0]] [1]

new_edge_key
(u, v)¶ Return an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further new_edge_keys may not be in this order.
u, v : nodes
key : int

node
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for setlike operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dictlike interface as well with G.nodes.items() iterating over (node, nodedata) 2tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dictlike interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
 data : string or bool, optional (default=False)
 The node attribute returned in 2tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
 default : value, optional (default=None)
 Value used for nodes that don’t have the requested attribute. Only relevant if data is not True or False.
 NodeView
Allows setlike operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}

node_dict_factory
¶ alias of
builtins.dict

nodes
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for setlike operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dictlike interface as well with G.nodes.items() iterating over (node, nodedata) 2tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dictlike interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
 data : string or bool, optional (default=False)
 The node attribute returned in 2tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
 default : value, optional (default=None)
 Value used for nodes that don’t have the requested attribute. Only relevant if data is not True or False.
 NodeView
Allows setlike operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}

nodes_with_selfloops
()¶

number_of_edges
(u=None, v=None)¶ Return the number of edges between two nodes.
 u, v : nodes, optional (Gefault=all edges)
 If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.
 nedges : int
 The number of edges in the graph. If nodes u and v are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from u to v.
size
For undirected multigraphs, this method counts the total number of edges in the graph:
>>> G = nx.MultiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)]) [0, 1, 0] >>> G.number_of_edges() 3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1) 2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = nx.MultiDiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)]) [0, 1, 0] >>> G.number_of_edges(0, 1) 2 >>> G.number_of_edges(1, 0) 1

number_of_nodes
(doublecheck=False)¶

number_of_selfloops
()¶

order
()¶ Return the number of nodes in the graph.
 nnodes : int
 The number of nodes in the graph.
number_of_nodes, __len__ which are identical

plot
(**kwargs)¶ renders on IPython Notebook (alias to make usage more straightforward)

png
(**kwargs)¶

pos
(nodes=None)¶ Parameters: nodes – a single node, an iterator of all nodes if None Returns: the position of node(s)

remove_edge
(u, v=None, key=None, clean=False)¶ Parameters:  u – Node or Edge (Nodes tuple)
 v – Node if u is a single Node
 clean – bool removes disconnected nodes. must be False for certain nx algos to work
Result: return attributes of removed edge
remove edge from graph. NetworkX graphs do not remove unused nodes

remove_edges_from
(ebunch)¶ Remove all edges specified in ebunch.
 ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can be:
 2tuples (u, v) All edges between u and v are removed.
 3tuples (u, v, key) The edge identified by key is removed.
 4tuples (u, v, key, data) where data is ignored.
remove_edge : remove a single edge
Will fail silently if an edge in ebunch is not in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch=[(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch)
Removing multiple copies of edges
>>> G = nx.MultiGraph() >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)]) >>> G.remove_edges_from([(1, 2), (1, 2)]) >>> list(G.edges()) [(1, 2)] >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy >>> list(G.edges) # now empty graph []

remove_node
(n)¶ Parameters: n – node tuple remove node from graph and rtree

remove_nodes_from
(nodes)¶ Remove multiple nodes.
 nodes : iterable container
 A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.
remove_node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []

render
(fmt='svg', **kwargs)¶ render graph to bitmap stream :param fmt: string defining the format. ‘svg’ by default for INotepads :return: matplotlib figure as a byte stream in specified format

save
(filename, **kwargs)¶ save graph in various formats

selfloop_edges
(data=False, keys=False, default=None)¶

shortest_path
(source=None, target=None)¶

size
(weight=None)¶ Return the number of edges or total of all edge weights.
 weight : string or None, optional (default=None)
 The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
 size : numeric
The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are more general).
number_of_edges
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.size() 3
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge('a', 'b', weight=2) >>> G.add_edge('b', 'c', weight=4) >>> G.size() 2 >>> G.size(weight='weight') 6.0

stats
()¶ Returns: dict of graph data to use in __repr__ or usable otherwise

subgraph
(nodes)¶ Return a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
 nodes : list, iterable
 A container of nodes which will be iterated through once.
 G : SubGraph View
 A subgraph view of the graph. The graph structure cannot be changed but node/edge attributes can and are shared with the original graph.
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
# Create a subgraph SG based on a (possibly multigraph) G SG = G.__class__() SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc) if SG.is_multigraph: SG.add_edges_from((n, nbr, key, d) for n, nbrs in G.adj.items() if n in largest_wcc for nbr, keydict in nbrs.items() if nbr in largest_wcc for key, d in keydict.items()) else: SG.add_edges_from((n, nbr, d) for n, nbrs in G.adj.items() if n in largest_wcc for nbr, d in nbrs.items() if nbr in largest_wcc) SG.graph.update(G.graph)
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.subgraph([0, 1, 2]) >>> list(H.edges) [(0, 1), (1, 2)]

svg
(**kwargs)¶

to_directed
(as_view=False)¶ Return a directed representation of the graph.
 G : MultiDiGraph
 A directed graph with the same name, same nodes, and with each edge (u, v, data) replaced by two directed edges (u, v, data) and (v, u, data).
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed MultiGraph to use dictlike objects in the data structure, those changes do not transfer to the MultiDiGraph created by this method.
>>> G = nx.Graph() # or MultiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)]

to_directed_class
()¶ Returns the class to use for empty directed copies.
If you subclass the base classes, use this to designate what directed class to use for to_directed() copies.

to_undirected
(as_view=False)¶ Return an undirected copy of the graph.
 G : Graph/MultiGraph
 A deepcopy of the graph.
copy, add_edge, add_edges_from
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar G = nx.MultiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed MultiiGraph to use dictlike objects in the data structure, those changes do not transfer to the MultiGraph created by this method.
>>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)]

to_undirected_class
()¶ Returns the class to use for empty undirected copies.
If you subclass the base classes, use this to designate what directed class to use for to_directed() copies.

tol
¶

update
(edges=None, nodes=None)¶ Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph’s noes and edges to this graph. It can also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods. When iterated, they should yield 2tuples (u, v) or 3tuples (u, v, datadict).
 edges : Graph object, collection of edges, or None
 The first parameter can be a graph or some edges. If it has attributes nodes and edges, then it is taken to be a Graphlike object and those attributes are used as collections of nodes and edges to be added to the graph. If the first parameter does not have those attributes, it is treated as a collection of edges and added to the graph. If the first argument is None, no edges are added.
 nodes : collection of nodes, or None
 The second parameter is treated as a collection of nodes to be added to the graph unless it is None. If edges is None and nodes is None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
>>> G = nx.path_graph(5) >>> G.update(nx.complete_graph(range(4,10))) >>> from itertools import combinations >>> edges = ((u, v, {'power': u * v}) ... for u, v in combinations(range(10, 20), 2) ... if u * v < 225) >>> nodes = [1000] # for singleton, use a container >>> G.update(edges, nodes)
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from adjacency. The following examples provide common cases, your adjacency may be slightly different and require tweaks of these examples.
>>> # dictofset/list/tuple >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}} >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs] >>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph() >>> # dictofdictofattribute >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}} >>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items() ... for v, d in nbrs.items()] >>> DG.update(edges=e, nodes=adj)
>>> # dictofdictofdict >>> adj = {1: {2: {'weight': 1.3}, 3: {'color': 0.7, 'weight':1.2}}} >>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items() ... for v, d in nbrs.items()] >>> DG.update(edges=e, nodes=adj)
>>> # predecessor adjacency (dictofset) >>> pred = {1: {2, 3}, 2: {3}, 3: {3}} >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
>>> # MultiGraph dictofdictofdictofattribute >>> MDG = nx.MultiDiGraph() >>> adj = {1: {2: {0: {'weight': 1.3}, 1: {'weight': 1.2}}}, ... 3: {2: {0: {'weight': 0.7}}}} >>> e = [(u, v, ekey, d) for u, nbrs in adj.items() ... for v, keydict in nbrs.items() ... for ekey, d in keydict.items()] >>> MDG.update(edges=e)
add_edges_from: add multiple edges to a graph add_nodes_from: add multiple nodes to a graph
 data – see

class
Goulib.graph.
DiGraph
(data=None, nodes=None, **kwargs)[source] Bases:
Goulib.graph._Geo
,networkx.classes.multidigraph.MultiDiGraph
directed graph with nodes positions can be set to non multiedges anytime with attribute multi=False
Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:

__init__
(data=None, nodes=None, **kwargs)[source] Parameters:  data – see
to_networkx_graph()
for valid types  kwargs – other parameters will be copied as attributes, especially:
 data – see

__bool__
()¶ Returns: True if graph has at least one node

__class__
¶ alias of
builtins.type

__contains__
(n)¶ Return True if n is a node, False otherwise. Use: ‘n in G’.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> 1 in G True

__delattr__
¶ Implement delattr(self, name).

__dir__
() → list¶ default dir() implementation

__eq__
(other)¶ Returns: True if self and other are equal

__format__
()¶ default object formatter

__ge__
¶ Return self>=value.

__getattribute__
¶ Return getattr(self, name).

__getitem__
(n)¶ Return a dict of neighbors of node n. Use: ‘G[n]’.
 n : node
 A node in the graph.
 adj_dict : dictionary
 The adjacency dictionary for nodes connected to n.
G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G[0] AtlasView({1: {}})

__gt__
¶ Return self>value.

__hash__
= None¶

__iter__
()¶ Iterate over the nodes. Use: ‘for n in G’.
 niter : iterator
 An iterator over all nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [n for n in G] [0, 1, 2, 3] >>> list(G) [0, 1, 2, 3]

__le__
¶ Return self<=value.

__len__
()¶ Return the number of nodes. Use: ‘len(G)’.
 nnodes : int
 The number of nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> len(G) 4

__lt__
¶ Return self<value.

__ne__
¶ Return self!=value.

__new__
()¶ Create and return a new object. See help(type) for accurate signature.

__nonzero__
()¶ Returns: True if graph has at least one node

__reduce__
()¶ helper for pickle

__reduce_ex__
()¶ helper for pickle

__repr__
¶ Return repr(self).

__setattr__
¶ Implement setattr(self, name, value).

__sizeof__
() → int¶ size of object in memory, in bytes

__str__
()¶ Returns: string representation, used mainly for logging and debugging

add_cycle
(nodes, **attr)¶

add_edge
(u, v, key=None, **attr)¶ add an edge to graph
Returns: edge key

add_edge2
(u, v, key=None, **attrs)¶ add an edge to graph :return: edge data from created or existing edge

add_edges_from
(ebunch_to_add, **attr)¶ Add all the edges in ebunch_to_add.
 ebunch_to_add : container of edges
Each edge given in the container will be added to the graph. The edges can be:
 2tuples (u, v) or
 3tuples (u, v, d) for an edge data dict d, or
 3tuples (u, v, k) for not iterable key k, or
 4tuples (u, v, k, d) for an edge with data and key k
 attr : keyword arguments, optional
 Edge data (or labels or objects) can be assigned using keyword arguments.
A list of edge keys assigned to the edges in ebunch.
add_edge : add a single edge add_weighted_edges_from : convenient way to add weighted edges
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method
new_edge_key()
. This method can be overridden by subclassing the base class and providing a customnew_edge_key()
method.>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples >>> e = zip(range(0, 3), range(1, 4)) >>> G.add_edges_from(e) # Add the path graph 0123
Associate data to edges
>>> G.add_edges_from([(1, 2), (2, 3)], weight=3) >>> G.add_edges_from([(3, 4), (1, 4)], label='WN2898')

add_node
(p, **attr)¶ add a node or return one already very close :return (x,y,…) node id

add_nodes_from
(nodes, **attr)¶

add_path
(nodes, **attr)¶

add_star
(nodes, **attr)¶

add_weighted_edges_from
(ebunch_to_add, weight='weight', **attr)¶ Add weighted edges in ebunch_to_add with specified weight attr
 ebunch_to_add : container of edges
 Each edge given in the list or container will be added to the graph. The edges must be given as 3tuples (u, v, w) where w is a number.
 weight : string, optional (default= ‘weight’)
 The attribute name for the edge weights to be added.
 attr : keyword arguments, optional (default= no attributes)
 Edge attributes to add/update for all edges.
add_edge : add a single edge add_edges_from : add multiple edges
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph, duplicate edges are stored.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])

adj
¶ Graph adjacency object holding the neighbors of each node.
This object is a readonly dictlike structure with node keys and neighbordict values. The neighbordict is keyed by neighbor to the edgekeydict. So G.adj[3][2][0][‘color’] = ‘blue’ sets the color of the edge (3, 2, 0) to “blue”.
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.

adjacency
()¶ Return an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
 adj_iter : iterator
 An iterator over (node, adjacency dictionary) for all nodes in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> [(n, nbrdict) for n, nbrdict in G.adjacency()] [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]

adjlist_inner_dict_factory
¶ alias of
builtins.dict

adjlist_outer_dict_factory
¶ alias of
builtins.dict

box
()¶ Returns: nodes bounding box as (xmin,ymin,…),(xmax,ymax,…)

box_size
()¶ Returns: (x,y) size

clear
()¶

closest_edges
(p, data=False)¶ Returns: container of edges close to p and distance

closest_nodes
(p, n=1, skip=False)¶ nodes closest to a given position :param p: (x,y) position tuple :param skip: optional bool to skip n itself :return: list of nodes, minimal distance

contiguity
(pts)¶ Returns: int number of points from pts already in graph

copy
()¶ Returns: copy of self graph

degree
¶ A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 weight : string or None, optional (default=None)
 The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single nodes is requested deg : int
Degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns twotuples of (node, degree).out_degree, in_degree
>>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.degree(0) # node 0 with degree 1 1 >>> list(G.degree([0, 1, 2])) [(0, 1), (1, 2), (2, 2)]

dist
(u, v)¶ Returns: float distance between nodes u and v

draw
(**kwargs)¶ draw graph with default params

edge_attr_dict_factory
¶ alias of
builtins.dict

edge_key_dict_factory
¶ alias of
builtins.dict

edge_subgraph
(edges)¶ Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
 edges : iterable
 An iterable of edges in this graph.
 G : Graph
 An edgeinduced subgraph of this graph with the same edge attributes.
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes in the original graph. The view is readonly.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
>>> G = nx.path_graph(5) >>> H = G.edge_subgraph([(0, 1), (3, 4)]) >>> list(H.nodes) [0, 1, 3, 4] >>> list(H.edges) [(0, 1), (3, 4)]

edges
¶ An OutMultiEdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides setlike operations on the edgetuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide setlike operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges(data=’color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 data : string or bool, optional (default=False)
 The edge attribute returned in 3tuple (u, v, ddict[data]). If True, return edge attribute dict in 3tuple (u, v, ddict). If False, return 2tuple (u, v).
 keys : bool, optional (default=False)
 If True, return edge keys with each edge.
 default : value, optional (default=None)
 Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.
 edges : EdgeView
 A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as edges[u, v, k][‘foo’].
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the outedges.
>>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2]) >>> key = G.add_edge(2, 3, weight=5) >>> [e for e in G.edges()] [(0, 1), (1, 2), (2, 3)] >>> list(G.edges(data=True)) # default data is {} (empty dict) [(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})] >>> list(G.edges(data='weight', default=1)) [(0, 1, 1), (1, 2, 1), (2, 3, 5)] >>> list(G.edges(keys=True)) # default keys are integers [(0, 1, 0), (1, 2, 0), (2, 3, 0)] >>> list(G.edges(data=True, keys=True)) [(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})] >>> list(G.edges(data='weight', default=1, keys=True)) [(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)] >>> list(G.edges([0, 2])) [(0, 1), (2, 3)] >>> list(G.edges(0)) [(0, 1)]
in_edges, out_edges

fresh_copy
()¶

get_edge_data
(u, v, key=None, default=None)¶ Return the attribute dictionary associated with edge (u, v).
This is identical to G[u][v][key] except the default is returned instead of an exception is the edge doesn’t exist.
u, v : nodes
 default : any Python object (default=None)
 Value to return if the edge (u, v) is not found.
 key : hashable identifier, optional (default=None)
 Return data only for the edge with specified key.
 edge_dict : dictionary
 The edge attribute dictionary.
>>> G = nx.MultiGraph() # or MultiDiGraph >>> key = G.add_edge(0, 1, key='a', weight=7) >>> G[0][1]['a'] # key='a' {'weight': 7} >>> G.edges[0, 1, 'a'] # key='a' {'weight': 7}
Warning: we protect the graph data structure by making G.edges and G[1][2] readonly dictlike structures. However, you can assign values to attributes in e.g. G.edges[1, 2, ‘a’] or G[1][2][‘a’] using an additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an edge.
>>> G[0][1]['a']['weight'] = 10 >>> G.edges[0, 1, 'a']['weight'] = 10 >>> G[0][1]['a']['weight'] 10 >>> G.edges[1, 0, 'a']['weight'] 10
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.get_edge_data(0, 1) {0: {}} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {0: {}} >>> G.get_edge_data('a', 'b', default=0) # edge not in graph, return 0 0

has_edge
(u, v, key=None)¶ Return True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
 u, v : nodes
 Nodes can be, for example, strings or numbers.
 key : hashable identifier, optional (default=None)
 If specified return True only if the edge with key is found.
 edge_ind : bool
 True if edge is in the graph, False otherwise.
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G = nx.MultiGraph() # or MultiDiGraph >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2tuple (u, v) True >>> G.add_edge(0, 1, key='a') 'a' >>> G.has_edge(0, 1, key='a') # specify key True >>> e=(0, 1, 'a') >>> G.has_edge(*e) # e is a 3tuple (u, v, 'a') True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G True

has_node
(n)¶ Return True if the graph contains the node n.
Identical to n in G
n : node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.has_node(0) True
It is more readable and simpler to use
>>> 0 in G True

has_predecessor
(u, v)[source]¶ Return True if node u has predecessor v.
This is true if graph has the edge u<v.

has_successor
(u, v)[source]¶ Return True if node u has successor v.
This is true if graph has the edge u>v.

html
(**kwargs)¶

in_degree
¶ A DegreeView for (node, in_degree) or in_degree for single node.
The node indegree is the number of edges pointing in to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 weight : string or None, optional (default=None)
 The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
If a single node is requested deg : int
Degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns twotuples of (node, indegree).degree, out_degree
>>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.in_degree(0) # node 0 with degree 0 0 >>> list(G.in_degree([0, 1, 2])) [(0, 0), (1, 1), (2, 1)]

in_edges
¶ An InMultiEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, keys=False, default=None)
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 data : string or bool, optional (default=False)
 The edge attribute returned in 3tuple (u, v, ddict[data]). If True, return edge attribute dict in 3tuple (u, v, ddict). If False, return 2tuple (u, v).
 keys : bool, optional (default=False)
 If True, return edge keys with each edge.
 default : value, optional (default=None)
 Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.
 in_edges : InMultiEdgeView
 A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as edges[u, v, k][‘foo’].
edges

is_directed
()¶ Return True if graph is directed, False otherwise.

is_multigraph
()¶ used internally in constructor

length
(edges=None)¶ Parameters: edges – iterator over edges either as (u,v,data) or (u,v,key,data). If None, all edges are taken Returns: sum of ‘length’ attributes of edges

multi
¶

name
¶ String identifier of the graph.
This graph attribute appears in the attribute dict G.graph keyed by the string “name”. as well as an attribute (technically a property) G.name. This is entirely user controlled.

nbunch_iter
(nbunch=None)¶ Return an iterator over nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 niter : iterator
 An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate over all nodes in the graph.
 NetworkXError
 If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
Graph.__iter__
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a
NetworkXError
is raised. Also, if any object in nbunch is not hashable, aNetworkXError
is raised.

neighbors
(n)¶ Return an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
 n : node
 A node in the graph
 NetworkXError
 If n is not in the graph.
predecessors
neighbors() and successors() are the same.

new_edge_key
(u, v)¶ Return an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further new_edge_keys may not be in this order.
u, v : nodes
key : int

node
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for setlike operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dictlike interface as well with G.nodes.items() iterating over (node, nodedata) 2tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dictlike interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
 data : string or bool, optional (default=False)
 The node attribute returned in 2tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
 default : value, optional (default=None)
 Value used for nodes that don’t have the requested attribute. Only relevant if data is not True or False.
 NodeView
Allows setlike operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}

node_dict_factory
¶ alias of
builtins.dict

nodes
¶ A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for setlike operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dictlike interface as well with G.nodes.items() iterating over (node, nodedata) 2tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dictlike interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.
 data : string or bool, optional (default=False)
 The node attribute returned in 2tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.
 default : value, optional (default=None)
 Value used for nodes that don’t have the requested attribute. Only relevant if data is not True or False.
 NodeView
Allows setlike operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.
If your node data is not needed, it is simpler and equivalent to use the expression
for n in G
, orlist(G)
.There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3) >>> list(G.nodes) [0, 1, 2] >>> list(G) [0, 1, 2]
To get the node data along with the nodes:
>>> G.add_node(1, time='5pm') >>> G.nodes[0]['foo'] = 'bar' >>> list(G.nodes(data=True)) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})] >>> list(G.nodes.data()) [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data='foo')) [(0, 'bar'), (1, None), (2, None)] >>> list(G.nodes.data('foo')) [(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time')) [(0, None), (1, '5pm'), (2, None)] >>> list(G.nodes.data('time')) [(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data='time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')] >>> list(G.nodes.data('time', default='Not Available')) [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:
>>> G = nx.Graph() >>> G.add_node(0) >>> G.add_node(1, weight=2) >>> G.add_node(2, weight=3) >>> dict(G.nodes(data='weight', default=1)) {0: 1, 1: 2, 2: 3}

nodes_with_selfloops
()¶

number_of_edges
(u=None, v=None)¶ Return the number of edges between two nodes.
 u, v : nodes, optional (Gefault=all edges)
 If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.
 nedges : int
 The number of edges in the graph. If nodes u and v are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from u to v.
size
For undirected multigraphs, this method counts the total number of edges in the graph:
>>> G = nx.MultiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)]) [0, 1, 0] >>> G.number_of_edges() 3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1) 2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = nx.MultiDiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)]) [0, 1, 0] >>> G.number_of_edges(0, 1) 2 >>> G.number_of_edges(1, 0) 1

number_of_nodes
(doublecheck=False)¶

number_of_selfloops
()¶

order
()¶ Return the number of nodes in the graph.
 nnodes : int
 The number of nodes in the graph.
number_of_nodes, __len__ which are identical

out_degree
¶ Return an iterator for (node, outdegree) or outdegree for single node.
out_degree(self, nbunch=None, weight=None)
The node outdegree is the number of edges pointing out of the node. This function returns the outdegree for a single node or an iterator for a bunch of nodes or if nothing is passed as argument.
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 weight : string or None, optional (default=None)
 The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights.
If a single node is requested deg : int
Degree of the nodeOR if multiple nodes are requested nd_iter : iterator
The iterator returns twotuples of (node, outdegree).degree, in_degree
>>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2, 3]) >>> G.out_degree(0) # node 0 with degree 1 1 >>> list(G.out_degree([0, 1, 2])) [(0, 1), (1, 1), (2, 1)]

out_edges
¶ An OutMultiEdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides setlike operations on the edgetuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide setlike operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges(data=’color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
 nbunch : single node, container, or all nodes (default= all nodes)
 The view will only report edges incident to these nodes.
 data : string or bool, optional (default=False)
 The edge attribute returned in 3tuple (u, v, ddict[data]). If True, return edge attribute dict in 3tuple (u, v, ddict). If False, return 2tuple (u, v).
 keys : bool, optional (default=False)
 If True, return edge keys with each edge.
 default : value, optional (default=None)
 Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.
 edges : EdgeView
 A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples of edges, but can also be used for attribute lookup as edges[u, v, k][‘foo’].
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the outedges.
>>> G = nx.MultiDiGraph() >>> nx.add_path(G, [0, 1, 2]) >>> key = G.add_edge(2, 3, weight=5) >>> [e for e in G.edges()] [(0, 1), (1, 2), (2, 3)] >>> list(G.edges(data=True)) # default data is {} (empty dict) [(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})] >>> list(G.edges(data='weight', default=1)) [(0, 1, 1), (1, 2, 1), (2, 3, 5)] >>> list(G.edges(keys=True)) # default keys are integers [(0, 1, 0), (1, 2, 0), (2, 3, 0)] >>> list(G.edges(data=True, keys=True)) [(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})] >>> list(G.edges(data='weight', default=1, keys=True)) [(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)] >>> list(G.edges([0, 2])) [(0, 1), (2, 3)] >>> list(G.edges(0)) [(0, 1)]
in_edges, out_edges

plot
(**kwargs)¶ renders on IPython Notebook (alias to make usage more straightforward)

png
(**kwargs)¶

pos
(nodes=None)¶ Parameters: nodes – a single node, an iterator of all nodes if None Returns: the position of node(s)

pred
¶ Graph adjacency object holding the predecessors of each node.
This object is a readonly dictlike structure with node keys and neighbordict values. The neighbordict is keyed by neighbor to the edgekeydict. So G.adj[3][2][0][‘color’] = ‘blue’ sets the color of the edge (3, 2, 0) to “blue”.
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].items():.

predecessors
(n)[source]¶ Return an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
 n : node
 A node in the graph
 NetworkXError
 If n is not in the graph.
successors

remove_edge
(u, v=None, key=None, clean=False)¶ Parameters:  u – Node or Edge (Nodes tuple)
 v – Node if u is a single Node
 clean – bool removes disconnected nodes. must be False for certain nx algos to work
Result: return attributes of removed edge
remove edge from graph. NetworkX graphs do not remove unused nodes

remove_edges_from
(ebunch)¶ Remove all edges specified in ebunch.
 ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can be:
 2tuples (u, v) All edges between u and v are removed.
 3tuples (u, v, key) The edge identified by key is removed.
 4tuples (u, v, key, data) where data is ignored.
remove_edge : remove a single edge
Will fail silently if an edge in ebunch is not in the graph.
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> ebunch=[(1, 2), (2, 3)] >>> G.remove_edges_from(ebunch)
Removing multiple copies of edges
>>> G = nx.MultiGraph() >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)]) >>> G.remove_edges_from([(1, 2), (1, 2)]) >>> list(G.edges()) [(1, 2)] >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy >>> list(G.edges) # now empty graph []

remove_node
(n)¶ Parameters: n – node tuple remove node from graph and rtree

remove_nodes_from
(nodes)[source]¶ Remove multiple nodes.
 nodes : iterable container
 A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.
remove_node
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []

render
(fmt='svg', **kwargs)¶ render graph to bitmap stream :param fmt: string defining the format. ‘svg’ by default for INotepads :return: matplotlib figure as a byte stream in specified format

reverse
(copy=True)¶ Return the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
 copy : bool optional (default=True)
 If True, return a new DiGraph holding the reversed edges. If False, the reverse graph is created using a view of the original graph.

save
(filename, **kwargs)¶ save graph in various formats

selfloop_edges
(data=False, keys=False, default=None)¶

shortest_path
(source=None, target=None)¶

size
(weight=None)¶ Return the number of edges or total of all edge weights.
 weight : string or None, optional (default=None)
 The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.
 size : numeric
The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are more general).
number_of_edges
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.size() 3
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge('a', 'b', weight=2) >>> G.add_edge('b', 'c', weight=4) >>> G.size() 2 >>> G.size(weight='weight') 6.0

stats
()¶ Returns: dict of graph data to use in __repr__ or usable otherwise

subgraph
(nodes)¶ Return a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
 nodes : list, iterable
 A container of nodes which will be iterated through once.
 G : SubGraph View
 A subgraph view of the graph. The graph structure cannot be changed but node/edge attributes can and are shared with the original graph.
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
# Create a subgraph SG based on a (possibly multigraph) G SG = G.__class__() SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc) if SG.is_multigraph: SG.add_edges_from((n, nbr, key, d) for n, nbrs in G.adj.items() if n in largest_wcc for nbr, keydict in nbrs.items() if nbr in largest_wcc for key, d in keydict.items()) else: SG.add_edges_from((n, nbr, d) for n, nbrs in G.adj.items() if n in largest_wcc for nbr, d in nbrs.items() if nbr in largest_wcc) SG.graph.update(G.graph)
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.subgraph([0, 1, 2]) >>> list(H.edges) [(0, 1), (1, 2)]

succ
¶ Graph adjacency object holding the successors of each node.
This object is a readonly dictlike structure with node keys and neighbordict values. The neighbordict is keyed by neighbor to the edgekeydict. So G.adj[3][2][0][‘color’] = ‘blue’ sets the color of the edge (3, 2, 0) to “blue”.
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.
For directed graphs, G.succ is identical to G.adj.

successors
(n)[source]¶ Return an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
 n : node
 A node in the graph
 NetworkXError
 If n is not in the graph.
predecessors
neighbors() and successors() are the same.

svg
(**kwargs)¶

to_directed
(as_view=False)¶ Return a directed representation of the graph.
 G : MultiDiGraph
 A directed graph with the same name, same nodes, and with each edge (u, v, data) replaced by two directed edges (u, v, data) and (v, u, data).
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed MultiGraph to use dictlike objects in the data structure, those changes do not transfer to the MultiDiGraph created by this method.
>>> G = nx.Graph() # or MultiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)]
If already directed, return a (deep) copy
>>> G = nx.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)]

to_directed_class
()¶ Returns the class to use for empty directed copies.
If you subclass the base classes, use this to designate what directed class to use for to_directed() copies.

to_undirected
(reciprocal=False, as_view=False)¶ Return an undirected representation of the digraph.
 reciprocal : bool (optional)
 If True only keep edges that appear in both directions in the original digraph.
 as_view : bool (optional, default=False)
 If True return an undirected view of the original directed graph.
 G : MultiGraph
 An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is different, only one edge is created with an arbitrary choice of which edge data to use. You must check and correct for this manually if desired.
MultiGraph, copy, add_edge, add_edges_from
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.
This is in contrast to the similar D=MultiiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/copy.html.
Warning: If you have subclassed MultiDiGraph to use dictlike objects in the data structure, those changes do not transfer to the MultiGraph created by this method.
>>> G = nx.path_graph(2) # or MultiGraph, etc >>> H = G.to_directed() >>> list(H.edges) [(0, 1), (1, 0)] >>> G2 = H.to_undirected() >>> list(G2.edges) [(0, 1)]

to_undirected_class
()¶ Returns the class to use for empty undirected copies.
If you subclass the base classes, use this to designate what directed class to use for to_directed() copies.

tol
¶

update
(edges=None, nodes=None)¶ Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph’s noes and edges to this graph. It can also take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods. When iterated, they should yield 2tuples (u, v) or 3tuples (u, v, datadict).
 edges : Graph object, collection of edges, or None
 The first parameter can be a graph or some edges. If it has attributes nodes and edges, then it is taken to be a Graphlike object and those attributes are used as collections of nodes and edges to be added to the graph. If the first parameter does not have those attributes, it is treated as a collection of edges and added to the graph. If the first argument is None, no edges are added.
 nodes : collection of nodes, or None
 The second parameter is treated as a collection of nodes to be added to the graph unless it is None. If edges is None and nodes is None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
>>> G = nx.path_graph(5) >>> G.update(nx.complete_graph(range(4,10))) >>> from itertools import combinations >>> edges = ((u, v, {'power': u * v}) ... for u, v in combinations(range(10, 20), 2) ... if u * v < 225) >>> nodes = [1000] # for singleton, use a container >>> G.update(edges, nodes)
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from adjacency. The following examples provide common cases, your adjacency may be slightly different and require tweaks of these examples.
>>> # dictofset/list/tuple >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}} >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs] >>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph() >>> # dictofdictofattribute >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}} >>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items() ... for v, d in nbrs.items()] >>> DG.update(edges=e, nodes=adj)
>>> # dictofdictofdict >>> adj = {1: {2: {'weight': 1.3}, 3: {'color': 0.7, 'weight':1.2}}} >>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items() ... for v, d in nbrs.items()] >>> DG.update(edges=e, nodes=adj)
>>> # predecessor adjacency (dictofset) >>> pred = {1: {2, 3}, 2: {3}, 3: {3}} >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
>>> # MultiGraph dictofdictofdictofattribute >>> MDG = nx.MultiDiGraph() >>> adj = {1: {2: {0: {'weight': 1.3}, 1: {'weight': 1.2}}}, ... 3: {2: {0: {'weight': 0.7}}}} >>> e = [(u, v, ekey, d) for u, nbrs in adj.items() ... for v, keydict in nbrs.items() ... for ekey, d in keydict.items()] >>> MDG.update(edges=e)
add_edges_from: add multiple edges to a graph add_nodes_from: add multiple nodes to a graph
 data – see

Goulib.graph.
figure
(g, box=None, **kwargs)[source] Parameters:  g – _Geo derived Graph
 box – optional interval.Box if g has no box
Returns: matplotlib axis suitable for drawing graph g

Goulib.graph.
draw_networkx
(g, pos=None, **kwargs)[source] improves nx.draw_networkx :param g: NetworkX Graph :param pos: can be either :
 optional dictionary of (x,y) node positions
 function of the form lambda node:(x,y) that maps node positions.
 None. in this case, nodes are directly used as positions if graph is a GeoGraph, otherwise nx.draw_shell is used
Parameters: **kwargs – passed to nx.draw method as described in http://networkx.lanl.gov/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html with one tweak:
 if edge_color is a function of the form lambda data:color string, it is mapped over all edges

Goulib.graph.
to_drawing
(g, d=None, edges=[])[source] draws Graph to a Drawing :param g:
Graph
:param d: existingDrawing
to draw onto, or None to create a new Drawing :param edges: iterable of edges (with data) that will be added, in the same order. By default all edges are drawn :return:Drawing
Graph edges with an ‘entity’ property

Goulib.graph.
write_dxf
(g, filename)[source] writes
networkx.Graph
in .dxf format

Goulib.graph.
write_dot
(g, filename)[source]

Goulib.graph.
to_json
(g, **kwargs)[source] Returns: string JSON representation of a graph

Goulib.graph.
write_json
(g, filename, **kwargs)[source] write a JSON file, suitable for D*.js representation

Goulib.graph.
read_json
(filename, directed=False, multigraph=True, attrs=None)[source]

Goulib.graph.
delauney_triangulation
(nodes, qhull_options='', incremental=False, **kwargs)[source] https://en.wikipedia.org/wiki/Delaunay_triangulation :param nodes: _Geo graph or list of (x,y) or (x,y,z) node positions :param qhull_options: string passed to
scipy.spatial.Delaunay()
, which passes it to Qhull ( http://www.qhull.org/ ) *’Qt’ ensures all points are connected *’Qz’ required when nodes lie on a sphere *’QJ’ solves some singularity situationsParameters: kwargs – passed to the GeoGraph
constructorReturns: GeoGraph
with delauney triangulation between nodes

Goulib.graph.
euclidean_minimum_spanning_tree
(nodes, **kwargs)[source] Parameters: nodes – list of (x,y) nodes positions Returns: GeoGraph
with minimum spanning tree between nodessee https://en.wikipedia.org/wiki/Euclidean_minimum_spanning_tree

Goulib.graph.
points_on_sphere
(N)[source]