desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Approximate current-flow betweenness centrality: K4'
| def test_K4(self):
| G = nx.complete_graph(4)
b = nx.current_flow_betweenness_centrality(G, normalized=False)
epsilon = 0.1
ba = approximate_cfbc(G, normalized=False, epsilon=(0.5 * epsilon))
for n in sorted(G):
assert_allclose(b[n], ba[n], atol=(epsilon * (len(G) ** 2)))
|
'Approximate current-flow betweenness centrality: star'
| def test_star(self):
| G = nx.Graph()
nx.add_star(G, ['a', 'b', 'c', 'd'])
b = nx.current_flow_betweenness_centrality(G, normalized=True)
epsilon = 0.1
ba = approximate_cfbc(G, normalized=True, epsilon=(0.5 * epsilon))
for n in sorted(G):
assert_allclose(b[n], ba[n], atol=epsilon)
|
'Approximate current-flow betweenness centrality: 2d grid'
| def test_grid(self):
| G = nx.grid_2d_graph(4, 4)
b = nx.current_flow_betweenness_centrality(G, normalized=True)
epsilon = 0.1
ba = approximate_cfbc(G, normalized=True, epsilon=(0.5 * epsilon))
for n in sorted(G):
assert_allclose(b[n], ba[n], atol=epsilon)
|
'Approximate current-flow betweenness centrality: solvers'
| def test_solvers(self):
| G = nx.complete_graph(4)
epsilon = 0.1
for solver in ['full', 'lu', 'cg']:
b = approximate_cfbc(G, normalized=False, solver=solver, epsilon=(0.5 * epsilon))
b_answer = {0: 0.75, 1: 0.75, 2: 0.75, 3: 0.75}
for n in sorted(G):
assert_allclose(b[n], b_answer[n], atol=epsilon... |
'Edge flow betweenness centrality: K4'
| def test_K4(self):
| G = nx.complete_graph(4)
b = edge_current_flow(G, normalized=True)
b_answer = dict.fromkeys(G.edges(), 0.25)
for ((s, t), v1) in b_answer.items():
v2 = b.get((s, t), b.get((t, s)))
assert_almost_equal(v1, v2)
|
'Edge flow betweenness centrality: K4'
| def test_K4_normalized(self):
| G = nx.complete_graph(4)
b = edge_current_flow(G, normalized=False)
b_answer = dict.fromkeys(G.edges(), 0.75)
for ((s, t), v1) in b_answer.items():
v2 = b.get((s, t), b.get((t, s)))
assert_almost_equal(v1, v2)
|
'Edge flow betweenness centrality: C4'
| def test_C4(self):
| G = nx.cycle_graph(4)
b = edge_current_flow(G, normalized=False)
b_answer = {(0, 1): 1.25, (0, 3): 1.25, (1, 2): 1.25, (2, 3): 1.25}
for ((s, t), v1) in b_answer.items():
v2 = b.get((s, t), b.get((t, s)))
assert_almost_equal(v1, v2)
|
'Edge betweenness centrality: P4'
| def test_P4(self):
| G = nx.path_graph(4)
b = edge_current_flow(G, normalized=False)
b_answer = {(0, 1): 1.5, (1, 2): 2.0, (2, 3): 1.5}
for ((s, t), v1) in b_answer.items():
v2 = b.get((s, t), b.get((t, s)))
assert_almost_equal(v1, v2)
|
'Initialize a graph with edges, name, graph attributes.
Parameters
data : input graph
Data to initialize graph. If data=None (default) an empty
graph is created. The data can be an edge list, or any
NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix... | def __init__(self, data=None, **attr):
| self.node_dict_factory = ndf = self.node_dict_factory
self.adjlist_outer_dict_factory = self.adjlist_outer_dict_factory
self.adjlist_inner_dict_factory = self.adjlist_inner_dict_factory
self.edge_attr_dict_factory = self.edge_attr_dict_factory
self.graph = {}
self._node = ndf()
self._adj = n... |
'Add a single node n and update node attributes.
Parameters
n : node
A node can be any hashable Python object except None.
attr : keyword arguments, optional
Set or change node attributes using key=value.
See Also
add_nodes_from
Examples
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_node(1)... | def add_node(self, n, **attr):
| if (n not in self._succ):
self._succ[n] = self.adjlist_inner_dict_factory()
self._pred[n] = self.adjlist_inner_dict_factory()
self._node[n] = attr
else:
self._node[n].update(attr)
|
'Add multiple nodes.
Parameters
nodes : iterable container
A container of nodes (list, dict, set, etc.).
OR
A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes.
Node attri... | def add_nodes_from(self, nodes, **attr):
| for n in nodes:
try:
if (n not in self._succ):
self._succ[n] = self.adjlist_inner_dict_factory()
self._pred[n] = self.adjlist_inner_dict_factory()
self._node[n] = attr.copy()
else:
self._node[n].update(attr)
exce... |
'Remove node n.
Removes the node n and all adjacent edges.
Attempting to remove a non-existent node will raise an exception.
Parameters
n : node
A node in the graph
Raises
NetworkXError
If n is not in the graph.
See Also
remove_nodes_from
Examples
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>... | def remove_node(self, n):
| try:
nbrs = self._succ[n]
del self._node[n]
except KeyError:
raise NetworkXError(('The node %s is not in the digraph.' % (n,)))
for u in nbrs:
del self._pred[u][n]
del self._succ[n]
for u in self._pred[n]:
del self._succ[u][n]
del self... |
'Remove multiple nodes.
Parameters
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.
See Also
remove_node
Examples
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> e = list(G.nodes())
>>> e
[0, 1, 2]
... | def remove_nodes_from(self, nbunch):
| for n in nbunch:
try:
succs = self._succ[n]
del self._node[n]
for u in succs:
del self._pred[u][n]
del self._succ[n]
for u in self._pred[n]:
del self._succ[u][n]
del self._pred[n]
except KeyError:... |
'Add an edge between u and v.
The nodes u and v will be automatically added if they are
not already in the graph.
Edge attributes can be specified with keywords or by directly
accessing the edge\'s attribute dictionary. See examples below.
Parameters
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes mus... | def add_edge(self, u, v, **attr):
| if (u not in self._succ):
self._succ[u] = self.adjlist_inner_dict_factory()
self._pred[u] = self.adjlist_inner_dict_factory()
self._node[u] = {}
if (v not in self._succ):
self._succ[v] = self.adjlist_inner_dict_factory()
self._pred[v] = self.adjlist_inner_dict_factory()
... |
'Add all the edges in ebunch.
Parameters
ebunch : container of edges
Each edge given in the container will be added to the
graph. The edges must be given as 2-tuples (u, v) or
3-tuples (u, v, d) where d is a dictionary containing edge data.
attr : keyword arguments, optional
Edge data (or labels or objects) can be assi... | def add_edges_from(self, ebunch, **attr):
| for e in ebunch:
ne = len(e)
if (ne == 3):
(u, v, dd) = e
elif (ne == 2):
(u, v) = e
dd = {}
else:
raise NetworkXError(('Edge tuple %s must be a 2-tuple or 3-tuple.' % (e,)))
if (u not in self._succ):
... |
'Remove the edge between u and v.
Parameters
u, v : nodes
Remove the edge between nodes u and v.
Raises
NetworkXError
If there is not an edge between u and v.
See Also
remove_edges_from : remove a collection of edges
Examples
>>> G = nx.Graph() # or DiGraph, etc
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1... | def remove_edge(self, u, v):
| try:
del self._succ[u][v]
del self._pred[v][u]
except KeyError:
raise NetworkXError(('The edge %s-%s not in graph.' % (u, v)))
|
'Remove all edges specified in ebunch.
Parameters
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:
- 2-tuples (u, v) edge between u and v.
- 3-tuples (u, v, k) where k is ignored.
See Also
remove_edge : remove a single edge
Notes
Will fa... | def remove_edges_from(self, ebunch):
| for e in ebunch:
(u, v) = e[:2]
if ((u in self._succ) and (v in self._succ[u])):
del self._succ[u][v]
del self._pred[v][u]
|
'Return True if node u has successor v.
This is true if graph has the edge u->v.'
| def has_successor(self, u, v):
| return ((u in self._succ) and (v in self._succ[u]))
|
'Return True if node u has predecessor v.
This is true if graph has the edge u<-v.'
| def has_predecessor(self, u, v):
| return ((u in self._pred) and (v in self._pred[u]))
|
'Return an iterator over successor nodes of n.
neighbors() and successors() are the same.'
| def successors(self, n):
| try:
return iter(self._succ[n])
except KeyError:
raise NetworkXError(('The node %s is not in the digraph.' % (n,)))
|
'Return an iterator over predecessor nodes of n.'
| def predecessors(self, n):
| try:
return iter(self._pred[n])
except KeyError:
raise NetworkXError(('The node %s is not in the digraph.' % (n,)))
|
'Return an iterator over the edges.
Edges are returned as tuples with optional data
in the order (node, neighbor, data).
edges(self, nbunch=None, data=False, default=None)
Parameters
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
through once.
data : str... | @property
def edges(self):
| self.__dict__['edges'] = edges = OutEdgeView(self)
self.__dict__['out_edges'] = edges
return edges
|
'Return an iterator over the incoming edges.
in_edges(self, nbunch=None, data=False, default=None):
Parameters
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated
through once.
data : string or bool, optional (default=False)
The edge attribute returned in 3-t... | @property
def in_edges(self):
| self.__dict__['in_edges'] = in_edges = InEdgeView(self)
return in_edges
|
'Return an iterator for (node, degree) or degree for single node.
degree(self, nbunch=None, weight=None)
The node degree is the number of edges adjacent to the node.
This function returns the degree for a single node or an iterator
for a bunch of nodes or if nothing is passed as argument.
Parameters
nbunch : iterable c... | @property
def degree(self):
| self.__dict__['degree'] = degree = DiDegreeView(self)
return degree
|
'Return an iterator for (node, in-degree) or in-degree for single node.
in_degree(self, nbunch=None, weight=None)
The node in-degree is the number of edges pointing in to the node.
This function returns the in-degree for a single node or an iterator
for a bunch of nodes or if nothing is passed as argument.
Parameters
n... | @property
def in_degree(self):
| self.__dict__['in_degree'] = in_degree = InDegreeView(self)
return in_degree
|
'Return an iterator for (node, out-degree) or out-degree for single node.
out_degree(self, nbunch=None, weight=None)
The node out-degree is the number of edges pointing out of the node.
This function returns the out-degree for a single node or an iterator
for a bunch of nodes or if nothing is passed as argument.
Parame... | @property
def out_degree(self):
| self.__dict__['out_degree'] = out_degree = OutDegreeView(self)
return out_degree
|
'Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.clear()
>>> list(G.nodes())
>>> list(G.edges())'
| def clear(self):
| self._succ.clear()
self._pred.clear()
self._node.clear()
self.graph.clear()
|
'Return True if graph is a multigraph, False otherwise.'
| def is_multigraph(self):
| return False
|
'Return True if graph is directed, False otherwise.'
| def is_directed(self):
| return True
|
'Return a directed copy of the graph.
Returns
G : DiGraph
A deepcopy of the graph.
Notes
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 P... | def to_directed(self):
| return deepcopy(self)
|
'Return an undirected representation of the digraph.
Parameters
reciprocal : bool (optional)
If True only keep edges that appear in both directions
in the original digraph.
Returns
G : Graph
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 digr... | def to_undirected(self, reciprocal=False):
| H = Graph()
H.name = self.name
H.add_nodes_from(self)
if (reciprocal is True):
H.add_edges_from(((u, v, deepcopy(d)) for (u, nbrs) in self.adjacency() for (v, d) in nbrs.items() if (v in self._pred[u])))
else:
H.add_edges_from(((u, v, deepcopy(d)) for (u, nbrs) in self.adjacency() fo... |
'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.
Parameters
copy : bool optional (default=True)
If True, return a new DiGraph holding the reversed edges.
If False, reverse the reverse graph is created using
the original graph (this cha... | def reverse(self, copy=True):
| if copy:
H = self.__class__(name=('Reverse of (%s)' % self.name))
H.add_nodes_from(self)
H.add_edges_from(((v, u, deepcopy(d)) for (u, v, d) in self.edges(data=True)))
H.graph = deepcopy(self.graph)
for n in self._node:
H._node[n] = deepcopy(self._node[n])
... |
'Return the subgraph induced on nodes in nbunch.
The induced subgraph of the graph contains the nodes in nbunch
and the edges between those nodes.
Parameters
nbunch : list, iterable
A container of nodes which will be iterated through once.
Returns
G : Graph
A subgraph of the graph with the same edge attributes.
Notes
T... | def subgraph(self, nbunch):
| bunch = self.nbunch_iter(nbunch)
H = self.__class__()
for n in bunch:
H._node[n] = self._node[n]
H_succ = H._succ
H_pred = H._pred
self_succ = self._succ
for n in H:
H_succ[n] = H.adjlist_inner_dict_factory()
H_pred[n] = H.adjlist_inner_dict_factory()
for u in H_s... |
'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.
Parameters
edges : iterable
An iterable of edges in this graph.
Returns
G : Graph
An edge-induced subgraph of this graph with the same edge
attributes.
Notes
The gra... | def edge_subgraph(self, edges):
| H = self.__class__()
succ = self._succ
edges = ((u, v) for (u, v) in edges if ((u in succ) and (v in succ[u])))
for (u, v) in edges:
if (u not in H.node):
H._node[u] = self._node[u]
H._pred[u] = H.adjlist_inner_dict_factory()
H._succ[u] = H.adjlist_inner_dict_... |
'Tests that the subgraph has the correct nodes.'
| def test_correct_nodes(self):
| assert_equal([0, 1, 3, 4], sorted(self.H.nodes()))
|
'Tests that the subgraph has the correct edges.'
| def test_correct_edges(self):
| assert_equal([(0, 1, 0, 'edge010'), (3, 4, 1, 'edge341')], sorted(self.H.edges(keys=True, data='name')))
|
'Tests that adding a node to the original graph does not
affect the nodes of the subgraph.'
| def test_add_node(self):
| self.G.add_node(5)
assert_equal([0, 1, 3, 4], sorted(self.H.nodes()))
|
'Tests that removing a node in the original graph does not
affect the nodes of the subgraph.'
| def test_remove_node(self):
| self.G.remove_node(0)
assert_equal([0, 1, 3, 4], sorted(self.H.nodes()))
|
'Tests that the node attribute dictionary of the two graphs is
the same object.'
| def test_node_attr_dict(self):
| for v in self.H:
assert_equal(self.G.node[v], self.H.node[v])
self.G.node[0]['name'] = 'foo'
assert_equal(self.G.node[0], self.H.node[0])
self.H.node[1]['name'] = 'bar'
assert_equal(self.G.node[1], self.H.node[1])
|
'Tests that the edge attribute dictionary of the two graphs is
the same object.'
| def test_edge_attr_dict(self):
| for (u, v, k) in self.H.edges(keys=True):
assert_equal(self.G._adj[u][v][k], self.H._adj[u][v][k])
self.G._adj[0][1][0]['name'] = 'foo'
assert_equal(self.G._adj[0][1][0]['name'], self.H._adj[0][1][0]['name'])
self.H._adj[3][4][1]['name'] = 'bar'
assert_equal(self.G._adj[3][4][1]['name'], sel... |
'Tests that the graph attribute dictionary of the two graphs
is the same object.'
| def test_graph_attr_dict(self):
| assert_is(self.G.graph, self.H.graph)
|
'Tests that the subgraph has the correct nodes.'
| def test_correct_nodes(self):
| assert_equal([0, 1, 3, 4], sorted(self.H.nodes()))
|
'Tests that the subgraph has the correct edges.'
| def test_correct_edges(self):
| assert_equal([(0, 1, 'edge01'), (3, 4, 'edge34')], sorted(self.H.edges(data='name')))
|
'Tests that adding a node to the original graph does not
affect the nodes of the subgraph.'
| def test_add_node(self):
| self.G.add_node(5)
assert_equal([0, 1, 3, 4], sorted(self.H.nodes()))
|
'Tests that removing a node in the original graph does not
affect the nodes of the subgraph.'
| def test_remove_node(self):
| self.G.remove_node(0)
assert_equal([0, 1, 3, 4], sorted(self.H.nodes()))
|
'Tests that the node attribute dictionary of the two graphs is
the same object.'
| def test_node_attr_dict(self):
| for v in self.H:
assert_equal(self.G.node[v], self.H.node[v])
self.G.node[0]['name'] = 'foo'
assert_equal(self.G.node[0], self.H.node[0])
self.H.node[1]['name'] = 'bar'
assert_equal(self.G.node[1], self.H.node[1])
|
'Tests that the edge attribute dictionary of the two graphs is
the same object.'
| def test_edge_attr_dict(self):
| for (u, v) in self.H.edges():
assert_equal(self.G.edge[(u, v)], self.H.edge[(u, v)])
self.G.edge[(0, 1)]['name'] = 'foo'
assert_equal(self.G.edge[(0, 1)]['name'], self.H.edge[(0, 1)]['name'])
self.H.edge[(3, 4)]['name'] = 'bar'
assert_equal(self.G.edge[(3, 4)]['name'], self.H.edge[(3, 4)]['n... |
'Tests that the graph attribute dictionary of the two graphs
is the same object.'
| def test_graph_attr_dict(self):
| assert_is(self.G.graph, self.H.graph)
|
'Test that nodes are added to predecessors and successors.
For more information, see GitHub issue #2370.'
| def test_pred_succ(self):
| G = nx.DiGraph()
G.add_edge(0, 1)
H = G.edge_subgraph([(0, 1)])
assert_equal(list(H.predecessors(0)), [])
assert_equal(list(H.successors(0)), [1])
assert_equal(list(H.predecessors(1)), [0])
assert_equal(list(H.successors(1)), [])
|
'Case of no common neighbors.'
| def test_custom1(self):
| G = nx.Graph()
G.add_nodes_from([0, 1])
self.test(G, 0, 1, [])
|
'Case of equal nodes.'
| def test_custom2(self):
| G = nx.complete_graph(4)
self.test(G, 0, 0, [1, 2, 3])
|
'Tests that the subgraph has the correct nodes.'
| def test_correct_nodes(self):
| assert_equal([0, 1, 3, 4], sorted(self.H.nodes))
|
'Tests that the subgraph has the correct edges.'
| def test_correct_edges(self):
| assert_equal([(0, 1, 'edge01'), (3, 4, 'edge34')], sorted(self.H.edges(data='name')))
|
'Tests that adding a node to the original graph does not
affect the nodes of the subgraph.'
| def test_add_node(self):
| self.G.add_node(5)
assert_equal([0, 1, 3, 4], sorted(self.H.nodes))
self.G.remove_node(5)
|
'Tests that removing a node in the original graph
removes the nodes of the subgraph.'
| def test_remove_node(self):
| self.G.remove_node(0)
assert_equal([1, 3, 4], sorted(self.H.nodes))
self.G.add_edge(0, 1)
|
'Tests that the node attribute dictionary of the two graphs is
the same object.'
| def test_node_attr_dict(self):
| for v in self.H:
assert_equal(self.G.node[v], self.H.node[v])
self.G.node[0]['name'] = 'foo'
assert_equal(self.G.node[0], self.H.node[0])
self.H.node[1]['name'] = 'bar'
assert_equal(self.G.node[1], self.H.node[1])
|
'Tests that the edge attribute dictionary of the two graphs is
the same object.'
| def test_edge_attr_dict(self):
| for (u, v) in self.H.edges():
assert_equal(self.G.edge[(u, v)], self.H.edge[(u, v)])
self.G.edge[(0, 1)]['name'] = 'foo'
assert_equal(self.G.edge[(0, 1)]['name'], self.H.edge[(0, 1)]['name'])
self.H.edge[(3, 4)]['name'] = 'bar'
assert_equal(self.G.edge[(3, 4)]['name'], self.H.edge[(3, 4)]['n... |
'Tests that the graph attribute dictionary of the two graphs
is the same object.'
| def test_graph_attr_dict(self):
| assert_is(self.G.graph, self.H.graph)
|
'Tests that the subgraph cannot change the graph structure'
| def test_readonly(self):
| assert_raises(nx.NetworkXError, self.H.add_node, 5)
assert_raises(nx.NetworkXError, self.H.remove_node, 0)
assert_raises(nx.NetworkXError, self.H.add_edge, 5, 6)
assert_raises(nx.NetworkXError, self.H.remove_edge, 0, 1)
|
'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.
Notes
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 ed... | def new_edge_key(self, u, v):
| try:
keydict = self._adj[u][v]
except KeyError:
return 0
key = len(keydict)
while (key in keydict):
key += 1
return key
|
'Add an edge between u and v.
The nodes u and v will be automatically added if they are
not already in the graph.
Edge attributes can be specified with keywords or by directly
accessing the edge\'s attribute dictionary. See examples below.
Parameters
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes mus... | def add_edge(self, u, v, key=None, **attr):
| if (u not in self._adj):
self._adj[u] = self.adjlist_inner_dict_factory()
self._node[u] = {}
if (v not in self._adj):
self._adj[v] = self.adjlist_inner_dict_factory()
self._node[v] = {}
if (key is None):
key = self.new_edge_key(u, v)
if (v in self._adj[u]):
... |
'Add all the edges in ebunch.
Parameters
ebunch : container of edges
Each edge given in the container will be added to the
graph. The edges can be:
- 2-tuples (u, v) or
- 3-tuples (u, v, d) for an edge data dict d, or
- 3-tuples (u, v, k) for not iterable key k, or
- 4-tuples (u, v, k, d) for an edge with data and key ... | def add_edges_from(self, ebunch, **attr):
| keylist = []
for e in ebunch:
ne = len(e)
if (ne == 4):
(u, v, key, dd) = e
elif (ne == 3):
(u, v, dd) = e
key = None
elif (ne == 2):
(u, v) = e
dd = {}
key = None
else:
msg = 'Edge tup... |
'Remove an edge between u and v.
Parameters
u, v : nodes
Remove an edge between nodes u and v.
key : hashable identifier, optional (default=None)
Used to distinguish multiple edges between a pair of nodes.
If None remove a single (arbitrary) edge between u and v.
Raises
NetworkXError
If there is not an edge between u a... | def remove_edge(self, u, v, key=None):
| try:
d = self._adj[u][v]
except KeyError:
raise NetworkXError(('The edge %s-%s is not in the graph.' % (u, v)))
if (key is None):
d.popitem()
else:
try:
del d[key]
except KeyError:
msg = 'The edge %s-%s with ... |
'Remove all edges specified in ebunch.
Parameters
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:
- 2-tuples (u, v) All edges between u and v are removed.
- 3-tuples (u, v, key) The edge identified by key is removed.
- 4-tuples (u, v, k... | def remove_edges_from(self, ebunch):
| for e in ebunch:
try:
self.remove_edge(*e[:3])
except NetworkXError:
pass
|
'Return True if the graph has an edge between nodes u and v.
Parameters
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.
Returns
edge_ind : bool
True if edge is in the graph, False otherwise.
Examp... | def has_edge(self, u, v, key=None):
| try:
if (key is None):
return (v in self._adj[u])
else:
return (key in self._adj[u][v])
except KeyError:
return False
|
'Return an iterator over the edges.
edges(self, nbunch=None, data=False, keys=False, default=None)
Edges are returned as tuples with optional data and keys
in the order (node, neighbor, key, data).
Parameters
nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterate... | @property
def edges(self):
| self.__dict__['edges'] = edges = MultiEdgeView(self)
return edges
|
'Return the attribute dictionary associated with edge (u, v).
Parameters
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.
Returns
edge_dict : dictionary
The edge ... | def get_edge_data(self, u, v, key=None, default=None):
| try:
if (key is None):
return self._adj[u][v]
else:
return self._adj[u][v][key]
except KeyError:
return default
|
'Return an iterator for (node, degree) or degree for single node.
degree(self, nbunch=None, weight=None)
The node degree is the number of edges adjacent to the node.
This function returns the degree for a single node or an iterator
for a bunch of nodes or if nothing is passed as argument.
Parameters
nbunch : iterable c... | @property
def degree(self):
| self.__dict__['degree'] = degree = MultiDegreeView(self)
return degree
|
'Return True if graph is a multigraph, False otherwise.'
| def is_multigraph(self):
| return True
|
'Return True if graph is directed, False otherwise.'
| def is_directed(self):
| return False
|
'Return a directed representation of the graph.
Returns
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).
Notes
This returns a "deepcopy" of the edge, node, and
graph attributes which attempts to completely cop... | def to_directed(self):
| from networkx.classes.multidigraph import MultiDiGraph
G = MultiDiGraph()
G.add_nodes_from(self)
G.add_edges_from(((u, v, key, deepcopy(datadict)) for (u, nbrs) in self.adjacency() for (v, keydict) in nbrs.items() for (key, datadict) in keydict.items()))
G.graph = deepcopy(self.graph)
G._node = ... |
'Return a list of selfloop edges.
A selfloop edge has the same node at both ends.
Parameters
data : bool, optional (default=False)
Return selfloop edges as two tuples (u, v) (data=False)
or three-tuples (u, v, datadict) (data=True)
or three-tuples (u, v, datavalue) (data=\'attrname\')
default : value, optional (default... | def selfloop_edges(self, data=False, keys=False, default=None):
| if (data is True):
if keys:
return ((n, n, k, d) for (n, nbrs) in self._adj.items() if (n in nbrs) for (k, d) in nbrs[n].items())
else:
return ((n, n, d) for (n, nbrs) in self._adj.items() if (n in nbrs) for d in nbrs[n].values())
elif (data is not False):
if keys... |
'Return the number of edges between two nodes.
Parameters
u, v : nodes, optional (default=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.
Returns
nedges : int
The number of edges in the graph. If nodes `u` and `v` are
specified return the... | def number_of_edges(self, u=None, v=None):
| if (u is None):
return self.size()
try:
edgedata = self._adj[u][v]
except KeyError:
return 0
return len(edgedata)
|
'Return the subgraph induced on nodes in nbunch.
The induced subgraph of the graph contains the nodes in nbunch
and the edges between those nodes.
Parameters
nbunch : list, iterable
A container of nodes which will be iterated through once.
Returns
G : Graph
A subgraph of the graph with the same edge attributes.
Notes
T... | def subgraph(self, nbunch):
| bunch = self.nbunch_iter(nbunch)
H = self.__class__()
for n in bunch:
H._node[n] = self._node[n]
H_adj = H._adj
self_adj = self._adj
for n in H:
Hnbrs = H.adjlist_inner_dict_factory()
H_adj[n] = Hnbrs
for (nbr, edgedict) in self_adj[n].items():
if (nbr... |
'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.
Parameters
edges : iterable
An iterable of edges in this graph.
Returns
G : Graph
An edge-induced subgraph of this graph with the same edge
attributes.
Notes
The gra... | def edge_subgraph(self, edges):
| H = self.__class__()
adj = self._adj
def is_in_graph(u, v, k):
return ((u in adj) and (v in adj[u]) and (k in adj[u][v]))
edges = (e for e in edges if is_in_graph(*e))
for (u, v, k) in edges:
if (u not in H._node):
H._node[u] = self._node[u]
H._adj[u] = H.adjl... |
'Initialize a graph with edges, name, graph attributes.
Parameters
data : input graph
Data to initialize graph. If data=None (default) an empty
graph is created. The data can be an edge list, or any
NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix... | def __init__(self, data=None, **attr):
| self.node_dict_factory = ndf = self.node_dict_factory
self.adjlist_outer_dict_factory = self.adjlist_outer_dict_factory
self.adjlist_inner_dict_factory = self.adjlist_inner_dict_factory
self.edge_attr_dict_factory = self.edge_attr_dict_factory
self.graph = {}
self._node = ndf()
self._adj = s... |
'Return the graph name.
Returns
name : string
The name of the graph.
Examples
>>> G = nx.Graph(name=\'foo\')
>>> str(G)
\'foo\''
| def __str__(self):
| return self.name
|
'Iterate over the nodes. Use the expression \'for n in G\'.
Returns
niter : iterator
An iterator over all nodes in the graph.
Examples
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> [n for n in G]
[0, 1, 2, 3]'
| def __iter__(self):
| return iter(self._node)
|
'Return True if n is a node, False otherwise. Use the expression
\'n in G\'.
Examples
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> 1 in G
True'
| def __contains__(self, n):
| try:
return (n in self._node)
except TypeError:
return False
|
'Return the number of nodes. Use the expression \'len(G)\'.
Returns
nnodes : int
The number of nodes in the graph.
Examples
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> len(G)
4'
| def __len__(self):
| return len(self._node)
|
'Return a dict of neighbors of node n. Use the expression \'G[n]\'.
Parameters
n : node
A node in the graph.
Returns
adj_dict : dictionary
The adjacency dictionary for nodes connected to n.
Notes
G[n] is similar to G.neighbors(n) but the internal data dictionary
is returned instead of an iterator.
Assigning G[n] will ... | def __getitem__(self, n):
| return self.adj[n]
|
'Add a single node n and update node attributes.
Parameters
n : node
A node can be any hashable Python object except None.
attr : keyword arguments, optional
Set or change node attributes using key=value.
See Also
add_nodes_from
Examples
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_node(1)
... | def add_node(self, n, **attr):
| if (n not in self._node):
self._adj[n] = self.adjlist_inner_dict_factory()
self._node[n] = attr
else:
self._node[n].update(attr)
|
'Add multiple nodes.
Parameters
nodes : iterable container
A container of nodes (list, dict, set, etc.).
OR
A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes.
Node attri... | def add_nodes_from(self, nodes, **attr):
| for n in nodes:
try:
if (n not in self._node):
self._adj[n] = self.adjlist_inner_dict_factory()
self._node[n] = attr.copy()
else:
self._node[n].update(attr)
except TypeError:
(nn, ndict) = n
if (nn not in... |
'Remove node n.
Removes the node n and all adjacent edges.
Attempting to remove a non-existent node will raise an exception.
Parameters
n : node
A node in the graph
Raises
NetworkXError
If n is not in the graph.
See Also
remove_nodes_from
Examples
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>... | def remove_node(self, n):
| adj = self._adj
try:
nbrs = list(adj[n])
del self._node[n]
except KeyError:
raise NetworkXError(('The node %s is not in the graph.' % (n,)))
for u in nbrs:
del adj[u][n]
del adj[n]
|
'Remove multiple nodes.
Parameters
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.
See Also
remove_node
Examples
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> e = list(G.nodes())
>>> e
[0, 1, 2]
... | def remove_nodes_from(self, nodes):
| adj = self._adj
for n in nodes:
try:
del self._node[n]
for u in list(adj[n]):
del adj[u][n]
del adj[n]
except KeyError:
pass
|
'A NodeView of the Graph as G.nodes or G.nodes().
Can be used as `G.nodes` for data lookup and for set-like operations.
Can also be used as `G.nodes(data=False, default=None)` to return a
NodeDataView which allows control over node data but no set operations.
Parameters
data : string or bool, optional (default=False)
T... | @property
def nodes(self):
| nodes = NodeView(self)
self.__dict__['nodes'] = nodes
return nodes
|
'Return the number of nodes in the graph.
Returns
nnodes : int
The number of nodes in the graph.
See Also
order, __len__ which are identical
Examples
>>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> len(G)
3'
| def number_of_nodes(self):
| return len(self._node)
|
'Return the number of nodes in the graph.
Returns
nnodes : int
The number of nodes in the graph.
See Also
number_of_nodes, __len__ which are identical'
| def order(self):
| return len(self._node)
|
'Return True if the graph contains the node n.
Parameters
n : node
Examples
>>> 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'
| def has_node(self, n):
| try:
return (n in self._node)
except TypeError:
return False
|
'Add an edge between u and v.
The nodes u and v will be automatically added if they are
not already in the graph.
Edge attributes can be specified with keywords or by directly
accessing the edge\'s attribute dictionary. See examples below.
Parameters
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes mus... | def add_edge(self, u, v, **attr):
| if (u not in self._node):
self._adj[u] = self.adjlist_inner_dict_factory()
self._node[u] = {}
if (v not in self._node):
self._adj[v] = self.adjlist_inner_dict_factory()
self._node[v] = {}
datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
datadict.update(attr)
... |
'Add all the edges in ebunch.
Parameters
ebunch : container of edges
Each edge given in the container will be added to the
graph. The edges must be given as as 2-tuples (u, v) or
3-tuples (u, v, d) where d is a dictionary containing edge data.
attr : keyword arguments, optional
Edge data (or labels or objects) can be a... | def add_edges_from(self, ebunch, **attr):
| for e in ebunch:
ne = len(e)
if (ne == 3):
(u, v, dd) = e
elif (ne == 2):
(u, v) = e
dd = {}
else:
raise NetworkXError(('Edge tuple %s must be a 2-tuple or 3-tuple.' % (e,)))
if (u not in self._node):
... |
'Add all the edges in ebunch as weighted edges with specified
weights.
Parameters
ebunch : container of edges
Each edge given in the list or container will be added
to the graph. The edges must be given as 3-tuples (u, v, w)
where w is a number.
weight : string, optional (default= \'weight\')
The attribute name for the... | def add_weighted_edges_from(self, ebunch, weight='weight', **attr):
| self.add_edges_from(((u, v, {weight: d}) for (u, v, d) in ebunch), **attr)
|
'Remove the edge between u and v.
Parameters
u, v : nodes
Remove the edge between nodes u and v.
Raises
NetworkXError
If there is not an edge between u and v.
See Also
remove_edges_from : remove a collection of edges
Examples
>>> G = nx.path_graph(4) # or DiGraph, etc
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remov... | def remove_edge(self, u, v):
| try:
del self._adj[u][v]
if (u != v):
del self._adj[v][u]
except KeyError:
raise NetworkXError(('The edge %s-%s is not in the graph' % (u, v)))
|
'Remove all edges specified in ebunch.
Parameters
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:
- 2-tuples (u, v) edge between u and v.
- 3-tuples (u, v, k) where k is ignored.
See Also
remove_edge : remove a single edge
Notes
Will fa... | def remove_edges_from(self, ebunch):
| adj = self._adj
for e in ebunch:
(u, v) = e[:2]
if ((u in adj) and (v in adj[u])):
del adj[u][v]
if (u != v):
del adj[v][u]
|
'Return True if the edge (u, v) is in the graph.
Parameters
u, v : nodes
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
Returns
edge_ind : bool
True if edge is in the graph, False otherwise.
Examples
Can be called either using two nodes u, v or edge tuple (u, v)
>>>... | def has_edge(self, u, v):
| try:
return (v in self._adj[u])
except KeyError:
return False
|
'Return an iterator over all neighbors of node n.
Parameters
n : node
A node in the graph
Returns
neighbors : iterator
An iterator over all neighbors of node n
Raises
NetworkXError
If the node n is not in the graph.
Examples
>>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> [n for n in G.neighbo... | def neighbors(self, n):
| try:
return iter(self._adj[n])
except KeyError:
raise NetworkXError(('The node %s is not in the graph.' % (n,)))
|
'An EdgeView of the Graph as G.edges or G.edges().
The EdgeView provides set-like operations on the edge-tuples
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 set-like operations).
Hence, `G.edges[u, v][\'col... | @property
def edges(self):
| self.__dict__['edges'] = edges = EdgeView(self)
return edges
|
'Return the attribute dictionary associated with edge (u, v).
Parameters
u, v : nodes
default: any Python object (default=None)
Value to return if the edge (u, v) is not found.
Returns
edge_dict : dictionary
The edge attribute dictionary.
Notes
It is faster to use G[u][v].
>>> G = nx.path_graph(4) # or DiGraph, Multi... | def get_edge_data(self, u, v, default=None):
| try:
return self._adj[u][v]
except KeyError:
return default
|
'Return an iterator over (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge.
For directed graphs, only outgoing adjacencies are included.
Returns
adj_iter : iterator
An iterator over (node, adjacency dictionary) for all nodes in
the graph.
Examples
>>> G = nx.path_graph(4) # or ... | def adjacency(self):
| return iter(self._adj.items())
|
'A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node.
This object provides an iterator for (node, degree) or
the degree for a single node.
Parameters
nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be itera... | @property
def degree(self):
| self.__dict__['degree'] = degree = DegreeView(self)
return degree
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.