本文整理匯總了Python中networkx.NetworkXException方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.NetworkXException方法的具體用法?Python networkx.NetworkXException怎麽用?Python networkx.NetworkXException使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.NetworkXException方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: maximum_spanning_arborescence
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def maximum_spanning_arborescence(G, attr='weight', default=1):
ed = Edmonds(G)
B = ed.find_optimum(attr, default, kind='max', style='arborescence')
if not is_arborescence(B):
msg = 'No maximum spanning arborescence in G.'
raise nx.exception.NetworkXException(msg)
return B
示例2: minimum_spanning_arborescence
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def minimum_spanning_arborescence(G, attr='weight', default=1):
ed = Edmonds(G)
B = ed.find_optimum(attr, default, kind='min', style='arborescence')
if not is_arborescence(B):
msg = 'No maximum spanning arborescence in G.'
raise nx.exception.NetworkXException(msg)
return B
示例3: test_view_pygraphviz
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def test_view_pygraphviz(self):
G = nx.Graph() # "An empty graph cannot be drawn."
assert_raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G)
G = nx.barbell_graph(4, 6)
nx.nx_agraph.view_pygraphviz(G)
示例4: test_planar_layout_non_planar_input
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def test_planar_layout_non_planar_input(self):
G = nx.complete_graph(9)
assert_raises(nx.NetworkXException, nx.planar_layout, G)
示例5: maximum_spanning_arborescence
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def maximum_spanning_arborescence(G, attr='weight', default=1,
preserve_attrs=False):
ed = Edmonds(G)
B = ed.find_optimum(attr, default, kind='max', style='arborescence',
preserve_attrs=preserve_attrs)
if not is_arborescence(B):
msg = 'No maximum spanning arborescence in G.'
raise nx.exception.NetworkXException(msg)
return B
示例6: check_embedding
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def check_embedding(G, embedding):
"""Raises an exception if the combinatorial embedding is not correct
Parameters
----------
G : NetworkX graph
embedding : a dict mapping nodes to a list of edges
This specifies the ordering of the outgoing edges from a node for
a combinatorial embedding
Notes
-----
Checks the following things:
- The type of the embedding is correct
- The nodes and edges match the original graph
- Every half edge has its matching opposite half edge
- No intersections of edges (checked by Euler's formula)
"""
if not isinstance(embedding, nx.PlanarEmbedding):
raise nx.NetworkXException(
"Bad embedding. Not of type nx.PlanarEmbedding")
# Check structure
embedding.check_structure()
# Check that graphs are equivalent
assert_equals(set(G.nodes), set(embedding.nodes),
"Bad embedding. Nodes don't match the original graph.")
# Check that the edges are equal
g_edges = set()
for edge in G.edges:
if edge[0] != edge[1]:
g_edges.add((edge[0], edge[1]))
g_edges.add((edge[1], edge[0]))
assert_equals(g_edges, set(embedding.edges),
"Bad embedding. Edges don't match the original graph.")
示例7: get_counterexample
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def get_counterexample(G):
"""Obtains a Kuratowski subgraph.
Raises nx.NetworkXException if G is planar.
The function removes edges such that the graph is still not planar.
At some point the removal of any edge would make the graph planar.
This subgraph must be a Kuratowski subgraph.
Parameters
----------
G : NetworkX graph
Returns
-------
subgraph : NetworkX graph
A Kuratowski subgraph that proves that G is not planar.
"""
# copy graph
G = nx.Graph(G)
if check_planarity(G)[0]:
raise nx.NetworkXException("G is planar - no counter example.")
# find Kuratowski subgraph
subgraph = nx.Graph()
for u in G:
nbrs = list(G[u])
for v in nbrs:
G.remove_edge(u, v)
if check_planarity(G)[0]:
G.add_edge(u, v)
subgraph.add_edge(u, v)
return subgraph
示例8: add_half_edge_ccw
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def add_half_edge_ccw(self, start_node, end_node, reference_neighbor):
"""Adds a half-edge from start_node to end_node.
The half-edge is added counter clockwise next to the existing half-edge
(start_node, reference_neighbor).
Parameters
----------
start_node : node
Start node of inserted edge.
end_node : node
End node of inserted edge.
reference_neighbor: node
End node of reference edge.
Raises
------
nx.NetworkXException
If the reference_neighbor does not exist.
See Also
--------
add_half_edge_cw
connect_components
add_half_edge_first
"""
if reference_neighbor is None:
# The start node has no neighbors
self.add_edge(start_node, end_node) # Add edge to graph
self[start_node][end_node]['cw'] = end_node
self[start_node][end_node]['ccw'] = end_node
self.nodes[start_node]['first_nbr'] = end_node
else:
ccw_reference = self[start_node][reference_neighbor]['ccw']
self.add_half_edge_cw(start_node, end_node, ccw_reference)
if reference_neighbor == self.nodes[start_node].get('first_nbr',
None):
# Update first neighbor
self.nodes[start_node]['first_nbr'] = end_node
示例9: minimum_spanning_arborescence
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def minimum_spanning_arborescence(G, attr='weight', default=1):
ed = Edmonds(G)
B = ed.find_optimum(attr, default, kind='min', style='arborescence')
if not is_arborescence(B):
msg = 'No minimum spanning arborescence in G.'
raise nx.exception.NetworkXException(msg)
return B
示例10: _init
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def _init(self, attr, default, kind, style):
if kind not in KINDS:
raise nx.NetworkXException("Unknown value for `kind`.")
# Store inputs.
self.attr = attr
self.default = default
self.kind = kind
self.style = style
# Determine how we are going to transform the weights.
if kind == 'min':
self.trans = trans = _min_weight
else:
self.trans = trans = _max_weight
if attr is None:
# Generate a random attr the graph probably won't have.
attr = random_string()
# This is the actual attribute used by the algorithm.
self._attr = attr
# The object we manipulate at each step is a multidigraph.
self.G = G = MultiDiGraph_EdgeKey()
for key, (u, v, data) in enumerate(self.G_original.edges(data=True)):
d = {attr: trans(data.get(attr, default))}
G.add_edge(u, v, key, **d)
self.level = 0
# These are the "buckets" from the paper.
#
# As in the paper, G^i are modified versions of the original graph.
# D^i and E^i are nodes and edges of the maximal edges that are
# consistent with G^i. These are dashed edges in figures A-F of the
# paper. In this implementation, we store D^i and E^i together as a
# graph B^i. So we will have strictly more B^i than the paper does.
self.B = MultiDiGraph_EdgeKey()
self.B.edge_index = {}
self.graphs = [] # G^i
self.branchings = [] # B^i
self.uf = nx.utils.UnionFind()
# A list of lists of edge indexes. Each list is a circuit for graph G^i.
# Note the edge list will not, in general, be a circuit in graph G^0.
self.circuits = []
# Stores the index of the minimum edge in the circuit found in G^i and B^i.
# The ordering of the edges seems to preserve the weight ordering from G^0.
# So even if the circuit does not form a circuit in G^0, it is still true
# that the minimum edge of the circuit in G^i is still the minimum edge
# in circuit G^0 (depsite their weights being different).
self.minedge_circuit = []
示例11: is_graphical
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def is_graphical(sequence, method='eg'):
"""Returns True if sequence is a valid degree sequence.
A degree sequence is valid if some graph can realize it.
Parameters
----------
sequence : list or iterable container
A sequence of integer node degrees
method : "eg" | "hh"
The method used to validate the degree sequence.
"eg" corresponds to the Erdős-Gallai algorithm, and
"hh" to the Havel-Hakimi algorithm.
Returns
-------
valid : bool
True if the sequence is a valid degree sequence and False if not.
Examples
--------
>>> G = nx.path_graph(4)
>>> sequence = G.degree().values()
>>> nx.is_valid_degree_sequence(sequence)
True
References
----------
Erdős-Gallai
[EG1960]_, [choudum1986]_
Havel-Hakimi
[havel1955]_, [hakimi1962]_, [CL1996]_
"""
if method == 'eg':
valid = is_valid_degree_sequence_erdos_gallai(list(sequence))
elif method == 'hh':
valid = is_valid_degree_sequence_havel_hakimi(list(sequence))
else:
msg = "`method` must be 'eg' or 'hh'"
raise nx.NetworkXException(msg)
return valid
示例12: _bidirectional_pred_succ
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def _bidirectional_pred_succ(G, source, target, exclude):
# does BFS from both source and target and meets in the middle
# excludes nodes in the container "exclude" from the search
if source is None or target is None:
raise nx.NetworkXException(\
"Bidirectional shortest path called without source or target")
if target == source:
return ({target:None},{source:None},source)
# handle either directed or undirected
if G.is_directed():
Gpred = G.predecessors_iter
Gsucc = G.successors_iter
else:
Gpred = G.neighbors_iter
Gsucc = G.neighbors_iter
# predecesssor and successors in search
pred = {source: None}
succ = {target: None}
# initialize fringes, start with forward
forward_fringe = [source]
reverse_fringe = [target]
level = 0
while forward_fringe and reverse_fringe:
# Make sure that we iterate one step forward and one step backwards
# thus source and target will only tigger "found path" when they are
# adjacent and then they can be safely included in the container 'exclude'
level += 1
if not level % 2 == 0:
this_level = forward_fringe
forward_fringe = []
for v in this_level:
for w in Gsucc(v):
if w in exclude:
continue
if w not in pred:
forward_fringe.append(w)
pred[w] = v
if w in succ:
return pred, succ, w # found path
else:
this_level = reverse_fringe
reverse_fringe = []
for v in this_level:
for w in Gpred(v):
if w in exclude:
continue
if w not in succ:
succ[w] = v
reverse_fringe.append(w)
if w in pred:
return pred, succ, w # found path
raise nx.NetworkXNoPath("No path between %s and %s." % (source, target))
示例13: planar_layout
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def planar_layout(G, scale=1, center=None, dim=2):
"""Position nodes without edge intersections.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G. If G is of type
PlanarEmbedding, the positions are selected accordingly.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G. If G is of type
nx.PlanarEmbedding, the positions are selected accordingly.
scale : number (default: 1)
Scale factor for positions.
center : array-like or None
Coordinate pair around which to center the layout.
dim : int
Dimension of layout.
Returns
-------
pos : dict
A dictionary of positions keyed by node
Raises
------
nx.NetworkXException
If G is not planar
Examples
--------
>>> G = nx.path_graph(4)
>>> pos = nx.planar_layout(G)
"""
import numpy as np
if dim != 2:
raise ValueError('can only handle 2 dimensions')
G, center = _process_params(G, center, dim)
if len(G) == 0:
return {}
if isinstance(G, nx.PlanarEmbedding):
embedding = G
else:
is_planar, embedding = nx.check_planarity(G)
if not is_planar:
raise nx.NetworkXException("G is not planar.")
pos = nx.combinatorial_embedding_to_pos(embedding)
node_list = list(embedding)
pos = np.row_stack((pos[x] for x in node_list))
pos = pos.astype(np.float64)
pos = rescale_layout(pos, scale=scale) + center
return dict(zip(node_list, pos))
示例14: make_bi_connected
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def make_bi_connected(embedding, starting_node, outgoing_node, edges_counted):
"""Triangulate a face and make it 2-connected
This method also adds all edges on the face to `edges_counted`.
Parameters
----------
embedding: nx.PlanarEmbedding
The embedding that defines the faces
starting_node : node
A node on the face
outgoing_node : node
A node such that the half edge (starting_node, outgoing_node) belongs
to the face
edges_counted: set
Set of all half-edges that belong to a face that have been visited
Returns
-------
face_nodes: list
A list of all nodes at the border of this face
"""
# Check if the face has already been calculated
if (starting_node, outgoing_node) in edges_counted:
# This face was already counted
return []
edges_counted.add((starting_node, outgoing_node))
# Add all edges to edges_counted which have this face to their left
v1 = starting_node
v2 = outgoing_node
face_list = [starting_node] # List of nodes around the face
face_set = set(face_list) # Set for faster queries
_, v3 = embedding.next_face_half_edge(v1, v2)
# Move the nodes v1, v2, v3 around the face:
while v2 != starting_node or v3 != outgoing_node:
if v1 == v2:
raise nx.NetworkXException("Invalid half-edge")
# cycle is not completed yet
if v2 in face_set:
# v2 encountered twice: Add edge to ensure 2-connectedness
embedding.add_half_edge_cw(v1, v3, v2)
embedding.add_half_edge_ccw(v3, v1, v2)
edges_counted.add((v2, v3))
edges_counted.add((v3, v1))
v2 = v1
else:
face_set.add(v2)
face_list.append(v2)
# set next edge
v1 = v2
v2, v3 = embedding.next_face_half_edge(v2, v3)
# remember that this edge has been counted
edges_counted.add((v1, v2))
return face_list
示例15: is_graphical
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import NetworkXException [as 別名]
def is_graphical(sequence, method='eg'):
"""Returns True if sequence is a valid degree sequence.
A degree sequence is valid if some graph can realize it.
Parameters
----------
sequence : list or iterable container
A sequence of integer node degrees
method : "eg" | "hh" (default: 'eg')
The method used to validate the degree sequence.
"eg" corresponds to the Erdős-Gallai algorithm, and
"hh" to the Havel-Hakimi algorithm.
Returns
-------
valid : bool
True if the sequence is a valid degree sequence and False if not.
Examples
--------
>>> G = nx.path_graph(4)
>>> sequence = (d for n, d in G.degree())
>>> nx.is_graphical(sequence)
True
References
----------
Erdős-Gallai
[EG1960]_, [choudum1986]_
Havel-Hakimi
[havel1955]_, [hakimi1962]_, [CL1996]_
"""
if method == 'eg':
valid = is_valid_degree_sequence_erdos_gallai(list(sequence))
elif method == 'hh':
valid = is_valid_degree_sequence_havel_hakimi(list(sequence))
else:
msg = "`method` must be 'eg' or 'hh'"
raise nx.NetworkXException(msg)
return valid