本文整理汇总了Python中networkx.NetworkXError方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.NetworkXError方法的具体用法?Python networkx.NetworkXError怎么用?Python networkx.NetworkXError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.NetworkXError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _remove_history
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def _remove_history(self, h):
try:
predecessors = self._graph.predecessors(h)
successors = self._graph.successors(h)
for p,s in itertools.product(predecessors, successors):
self._graph.add_edge(p, s)
self._graph.remove_node(h)
except networkx.NetworkXError:
pass
self._leaves.discard(h)
self._twigs.discard(h)
hh = h()
if hh is not None:
hh.demote()
示例2: _transitive_rel
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def _transitive_rel(self, ns, id, rel_fun, rel_types, target=None):
source = (ns, id)
visited = {source}
queue = deque([(source,
rel_fun(*source, rel_types))])
while queue:
parent, children = queue[0]
try:
child = next(children)
if target and child == target:
return [target]
if child not in visited:
visited.add(child)
queue.append((child,
rel_fun(*child, rel_types)))
except networkx.NetworkXError as e:
logger.debug(e)
return []
except StopIteration:
queue.popleft()
return list(visited - {source})
示例3: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def __init__(self, data=None, **attr):
self.node_dict_factory = ndf = self.node_dict_factory
self.adjlist_dict_factory = self.adjlist_dict_factory
self.edge_attr_dict_factory = self.edge_attr_dict_factory
self.graph = {} # dictionary for graph attributes
self.node = ndf() # empty node attribute dict
self.adj = ndf() # empty adjacency dict
# attempt to load graph with data
if data is not None:
if isinstance(data, OrderedGraph):
try:
nx.convert.from_dict_of_dicts(
data.adj,
create_using=self,
multigraph_input=data.is_multigraph()
)
self.graph = data.graph.copy()
self.node.update((n,d.copy()) for n,d in data.node.items())
except:
raise nx.NetworkXError("Input is not a correct NetworkX graph.")
else:
nx.convert.to_networkx_graph(data, create_using=self)
示例4: successors_iter
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def successors_iter(self, n, t=None):
"""
Return an iterator over successor nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be returned the presence of the interaction on the flattened graph.
"""
try:
if t is None:
return iter(self._succ[n])
else:
return iter([i for i in self._succ[n] if self.__presence_test(n, i, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,))
示例5: predecessors_iter
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def predecessors_iter(self, n, t=None):
"""Return an iterator over predecessors nodes of n at time t (optional).
Parameters
----------
n : node
Nodes can be, for example, strings or numbers.
Nodes must be hashable (and not None) Python objects.
t : snapshot id (default=None)
If None will be returned the presence of the interaction on the flattened graph.
"""
try:
if t is None:
return iter(self._pred[n])
else:
return iter([i for i in self._pred[n] if self.__presence_test(i, n, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,))
示例6: neighbors_iter
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def neighbors_iter(self, n, t=None):
"""Return an iterator over all neighbors of node n at time t.
Parameters
----------
n : node
A node in the graph
t : snapshot id (default=None)
If None will be returned an iterator over the neighbors of the node on the flattened graph.
Examples
--------
>>> import dynetx as dn
>>> G = dn.DynGraph()
>>> G.add_path([0,1,2,3], t=0)
>>> [n for n in G.neighbors_iter(0, t=0)]
[1]
"""
try:
if t is None:
return iter(self._adj[n])
else:
return iter([i for i in self._adj[n] if self.__presence_test(n, i, t)])
except KeyError:
raise nx.NetworkXError("The node %s is not in the graph." % (n,))
示例7: test_relabel_duplicate
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def test_relabel_duplicate(self):
data = """
graph
[
label ""
directed 1
node
[
id 0
label "same"
]
node
[
id 1
label "same"
]
]
"""
fh = io.BytesIO(data.encode('UTF-8'))
fh.seek(0)
assert_raises(
nx.NetworkXError, nx.read_gml, fh, label='label')
示例8: test_directed_edge_in_undirected
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def test_directed_edge_in_undirected(self):
s="""<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.1draft" version="1.1">
<graph mode="static" defaultedgetype="undirected">
<nodes>
<node id="0" label="Hello" />
<node id="1" label="Word" />
</nodes>
<edges>
<edge id="0" source="0" target="1" type="directed"/>
</edges>
</graph>
</gexf>
"""
fh = io.BytesIO(s.encode('UTF-8'))
assert_raises(nx.NetworkXError,nx.read_gexf,fh)
示例9: test_key_error
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def test_key_error(self):
s="""<?xml version="1.0" encoding="UTF-8"?>
<gexf xmlns="http://www.gexf.net/1.1draft" version="1.1">
<graph mode="static" defaultedgetype="directed">
<nodes>
<node id="0" label="Hello">
<attvalues>
<attvalue for='0' value='1'/>
</attvalues>
</node>
<node id="1" label="Word" />
</nodes>
<edges>
<edge id="0" source="0" target="1" type="undirected"/>
</edges>
</graph>
</gexf>
"""
fh = io.BytesIO(s.encode('UTF-8'))
assert_raises(nx.NetworkXError,nx.read_gexf,fh)
示例10: _spectral
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def _spectral(A, dim=2):
# Input adjacency matrix A
# Uses dense eigenvalue solver from numpy
try:
import numpy as np
except ImportError:
raise ImportError("spectral_layout() requires numpy: http://scipy.org/ ")
try:
nnodes,_=A.shape
except AttributeError:
raise nx.NetworkXError(\
"spectral() takes an adjacency matrix as input")
# form Laplacian matrix
# make sure we have an array instead of a matrix
A=np.asarray(A)
I=np.identity(nnodes,dtype=A.dtype)
D=I*np.sum(A,axis=1) # diagonal of degrees
L=D-A
eigenvalues,eigenvectors=np.linalg.eig(L)
# sort and keep smallest nonzero
index=np.argsort(eigenvalues)[1:dim+1] # 0 index is zero eigenvalue
return np.real(eigenvectors[:,index])
示例11: test_iterators
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def test_iterators(self):
G=self.G()
G.add_edges_from([('A', 'B'), ('A', 'C'), ('B', 'D'),
('C', 'B'), ('C', 'D')])
G.add_nodes_from('GJK')
assert_equal(sorted(G.nodes_iter()),
['A', 'B', 'C', 'D', 'G', 'J', 'K'])
assert_edges_equal(G.edges_iter(),
[('A', 'B'), ('A', 'C'), ('B', 'D'), ('C', 'B'), ('C', 'D')])
assert_equal(sorted([v for k,v in G.degree_iter()]),
[0, 0, 0, 2, 2, 3, 3])
assert_equal(sorted(G.degree_iter(),key=str),
[('A', 2), ('B', 3), ('C', 3), ('D', 2),
('G', 0), ('J', 0), ('K', 0)])
assert_equal(sorted(G.neighbors_iter('A')),['B', 'C'])
assert_raises(nx.NetworkXError,G.neighbors_iter,'X')
G.clear()
assert_equal(nx.number_of_nodes(G),0)
assert_equal(nx.number_of_edges(G),0)
示例12: test_info_digraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def test_info_digraph(self):
G=nx.DiGraph(name='path_graph(5)')
G.add_path([0,1,2,3,4])
info=nx.info(G)
expected_graph_info='\n'.join(['Name: path_graph(5)',
'Type: DiGraph',
'Number of nodes: 5',
'Number of edges: 4',
'Average in degree: 0.8000',
'Average out degree: 0.8000'])
assert_equal(info,expected_graph_info)
info=nx.info(G,n=1)
expected_node_info='\n'.join(
['Node 1 has the following properties:',
'Degree: 2',
'Neighbors: 2'])
assert_equal(info,expected_node_info)
assert_raises(nx.NetworkXError,nx.info,G,n=-1)
示例13: test_is_weighted
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def test_is_weighted(self):
G = nx.Graph()
assert_false(nx.is_weighted(G))
G = nx.path_graph(4)
assert_false(nx.is_weighted(G))
assert_false(nx.is_weighted(G, (2, 3)))
G.add_node(4)
G.add_edge(3, 4, weight=4)
assert_false(nx.is_weighted(G))
assert_true(nx.is_weighted(G, (3, 4)))
G = nx.DiGraph()
G.add_weighted_edges_from([('0', '3', 3), ('0', '1', -5), ('1', '0', -5),
('0', '2', 2), ('1', '2', 4),
('2', '3', 1)])
assert_true(nx.is_weighted(G))
assert_true(nx.is_weighted(G, ('1', '0')))
G = G.to_undirected()
assert_true(nx.is_weighted(G))
assert_true(nx.is_weighted(G, ('1', '0')))
assert_raises(nx.NetworkXError, nx.is_weighted, G, (1, 2))
示例14: plot_path
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def plot_path(self, frm_node, to_node, levels=1, add_to_exsting=False):
"""Plot shortest path between two nodes"""
try:
path = nx.shortest_path(self.dataG, frm_node, to_node)
except nx.NetworkXNoPath as e:
tkm.showerror("No path", str(e))
return
except nx.NetworkXError as e:
tkm.showerror("Node not in graph", str(e))
return
graph = self.dataG.subgraph(self._neighbors(path,levels=levels))
if add_to_exsting:
self._plot_additional(graph.nodes())
else:
self.clear()
self._plot_graph(graph)
# Mark the path
if levels > 0 or add_to_exsting:
for u, v in zip(path[:-1], path[1:]):
u_disp = self._find_disp_node(u)
v_disp = self._find_disp_node(v)
for key, value in self.dispG.edge[u_disp][v_disp].items():
self.mark_edge(u_disp, v_disp, key)
示例15: add_subgraph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXError [as 别名]
def add_subgraph(self, members, topology):
"""Add subgraph from existing account vertices and given graph topology
:param members: Account vertex list
:param topology: Topology graph
:return:
"""
if len(members) != topology.number_of_nodes():
raise nx.NetworkXError("The number of account vertices does not match")
node_map = dict(zip(members, topology.nodes()))
for e in topology.edges():
src = node_map[e[0]]
dst = node_map[e[1]]
self.add_transaction(src, dst)