本文整理汇总了Python中networkx.NetworkXUnfeasible方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.NetworkXUnfeasible方法的具体用法?Python networkx.NetworkXUnfeasible怎么用?Python networkx.NetworkXUnfeasible使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.NetworkXUnfeasible方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def __init__(self, config: Dict, recipe_folder: str,
exclude: List[str] = None, nocatch: bool=False) ->None:
self.config = config
self.recipe_folder = recipe_folder
self.skip = self.load_skips()
self.exclude = exclude or []
self.nocatch = nocatch
self._messages = []
dag = nx.DiGraph()
dag.add_nodes_from(str(check) for check in get_checks())
dag.add_edges_from(
(str(check), str(check_dep))
for check in get_checks()
for check_dep in check.requires
)
self.checks_dag = dag
try:
self.checks_ordered = nx.topological_sort(dag, reverse=True)
except nx.NetworkXUnfeasible:
raise RunTimeError("Cycle in LintCheck requirements!")
self.reload_checks()
示例2: bridge_augmentation
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def bridge_augmentation(G, avail=None, weight=None):
"""Finds the a set of edges that bridge connects G.
Adding these edges to G will make it 2-edge-connected.
If no constraints are specified the returned set of edges is minimum an
optimal, otherwise the solution is approximated.
Notes
-----
If there are no constraints the solution can be computed in linear time
using :func:`unconstrained_bridge_augmentation`. Otherwise, the problem
becomes NP-hard and is the solution is approximated by
:func:`weighted_bridge_augmentation`.
"""
if G.number_of_nodes() < 3:
raise nx.NetworkXUnfeasible(
'impossible to bridge connect less than 3 nodes')
if avail is None:
return unconstrained_bridge_augmentation(G)
else:
return weighted_bridge_augmentation(G, avail, weight=weight)
# --- Algorithms and Helpers ---
示例3: sorted_nodes
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def sorted_nodes(self):
"""Returns a topological sort of the resource graph.
Notes
-----
Topological sorts are not stable. Be wary of depending on order
where you shouldn't.
"""
if self._sorted_nodes is None:
try:
self._sorted_nodes = list(nx.algorithms.topological_sort(self.graph))
except nx.NetworkXUnfeasible:
raise ResourceError(f'The resource pool contains at least one cycle: '
f'{nx.find_cycle(self.graph)}.')
return self._sorted_nodes
示例4: resolve_hook_order
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def resolve_hook_order(self, hook_tuples: List[HookTuple]) -> List[HookTuple]:
dag = nx.DiGraph()
for hook_tuple in hook_tuples:
dag.add_node(hook_tuple.Hook.name, hook_tuple=hook_tuple)
for dep_name in hook_tuple.Hook.run_after:
dag.add_edge(hook_tuple.Hook.name, dep_name)
for successor_name in hook_tuple.Hook.run_before:
dag.add_edge(successor_name, hook_tuple.Hook.name)
try:
order = reversed(list(nx.topological_sort(dag)))
except nx.NetworkXUnfeasible:
msg = 'Circular dependency detected between hooks'
problem_graph = ', '.join(f'{a} -> {b}'
for a, b in nx.find_cycle(dag))
raise Exception(f'{msg}: {problem_graph}')
rv = []
for hook_name in order:
hook_tuple = dag.nodes[hook_name].get('hook_tuple')
if hook_tuple:
rv.append(hook_tuple)
return rv
示例5: is_directed_acyclic_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def is_directed_acyclic_graph(G):
"""Return True if the graph G is a directed acyclic graph (DAG) or
False if not.
Parameters
----------
G : NetworkX graph
A graph
Returns
-------
is_dag : bool
True if G is a DAG, false otherwise
"""
if not G.is_directed():
return False
try:
topological_sort(G, reverse=True)
return True
except nx.NetworkXUnfeasible:
return False
示例6: test_reverse_topological_sort1
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def test_reverse_topological_sort1(self):
DG = nx.DiGraph()
DG.add_edges_from([(1, 2), (1, 3), (2, 3)])
assert_equal(nx.topological_sort(DG, reverse=True), [3, 2, 1])
assert_equal(
nx.topological_sort_recursive(DG, reverse=True), [3, 2, 1])
DG.add_edge(3, 2)
assert_raises(nx.NetworkXUnfeasible,
nx.topological_sort, DG, reverse=True)
assert_raises(nx.NetworkXUnfeasible,
nx.topological_sort_recursive, DG, reverse=True)
DG.remove_edge(2, 3)
assert_equal(nx.topological_sort(DG, reverse=True), [2, 3, 1])
assert_equal(
nx.topological_sort_recursive(DG, reverse=True), [2, 3, 1])
示例7: test_topological_sort3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def test_topological_sort3(self):
DG = nx.DiGraph()
DG.add_edges_from([(1, i) for i in range(2, 5)])
DG.add_edges_from([(2, i) for i in range(5, 9)])
DG.add_edges_from([(6, i) for i in range(9, 12)])
DG.add_edges_from([(4, i) for i in range(12, 15)])
def validate(order):
ok_(isinstance(order, list))
assert_equal(set(order), set(DG))
for u, v in combinations(order, 2):
assert_false(nx.has_path(DG, v, u))
validate(nx.topological_sort_recursive(DG))
validate(nx.topological_sort(DG))
DG.add_edge(14, 1)
assert_raises(nx.NetworkXUnfeasible, nx.topological_sort, DG)
assert_raises(nx.NetworkXUnfeasible, nx.topological_sort_recursive, DG)
示例8: phase3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def phase3(self):
# build potential remaining edges and choose with rejection sampling
potential_edges = combinations(self.remaining_degree, 2)
# build auxilliary graph of potential edges not already in graph
H = nx.Graph([(u,v) for (u,v) in potential_edges
if not self.graph.has_edge(u,v)])
while self.remaining_degree:
if not self.suitable_edge():
raise nx.NetworkXUnfeasible('no suitable edges left')
while True:
u,v = sorted(random.choice(H.edges()))
if random.random() < self.q(u,v):
break
if random.random() < self.p(u,v): # accept edge
self.graph.add_edge(u,v)
self.update_remaining(u,v, aux_graph=H)
示例9: test_topological_sort1
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def test_topological_sort1(self):
DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
for algorithm in [nx.topological_sort,
nx.lexicographical_topological_sort]:
assert_equal(tuple(algorithm(DG)), (1, 2, 3))
DG.add_edge(3, 2)
for algorithm in [nx.topological_sort,
nx.lexicographical_topological_sort]:
assert_raises(nx.NetworkXUnfeasible, consume, algorithm(DG))
DG.remove_edge(2, 3)
for algorithm in [nx.topological_sort,
nx.lexicographical_topological_sort]:
assert_equal(tuple(algorithm(DG)), (1, 3, 2))
DG.remove_edge(3, 2)
assert_in(tuple(nx.topological_sort(DG)), {(1, 2, 3), (1, 3, 2)})
assert_equal(tuple(nx.lexicographical_topological_sort(DG)), (1, 2, 3))
示例10: test_topological_sort3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def test_topological_sort3(self):
DG = nx.DiGraph()
DG.add_edges_from([(1, i) for i in range(2, 5)])
DG.add_edges_from([(2, i) for i in range(5, 9)])
DG.add_edges_from([(6, i) for i in range(9, 12)])
DG.add_edges_from([(4, i) for i in range(12, 15)])
def validate(order):
ok_(isinstance(order, list))
assert_equal(set(order), set(DG))
for u, v in combinations(order, 2):
assert_false(nx.has_path(DG, v, u))
validate(list(nx.topological_sort(DG)))
DG.add_edge(14, 1)
assert_raises(nx.NetworkXUnfeasible, consume, nx.topological_sort(DG))
示例11: test_all_topological_sorts_3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def test_all_topological_sorts_3(self):
def unfeasible():
DG = nx.DiGraph([(1, 2), (2, 3), (3, 4), (4, 2), (4, 5)])
# convert to list to execute generator
list(nx.all_topological_sorts(DG))
def not_implemented():
G = nx.Graph([(1, 2), (2, 3)])
# convert to list to execute generator
list(nx.all_topological_sorts(G))
def not_implemted_2():
G = nx.MultiGraph([(1, 2), (1, 2), (2, 3)])
list(nx.all_topological_sorts(G))
assert_raises(nx.NetworkXUnfeasible, unfeasible)
assert_raises(nx.NetworkXNotImplemented, not_implemented)
assert_raises(nx.NetworkXNotImplemented, not_implemted_2)
示例12: phase3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def phase3(self):
# build potential remaining edges and choose with rejection sampling
potential_edges = combinations(self.remaining_degree, 2)
# build auxiliary graph of potential edges not already in graph
H = nx.Graph([(u, v) for (u, v) in potential_edges
if not self.graph.has_edge(u, v)])
rng = self.rng
while self.remaining_degree:
if not self.suitable_edge():
raise nx.NetworkXUnfeasible('no suitable edges left')
while True:
u, v = sorted(rng.choice(list(H.edges())))
if rng.random() < self.q(u, v):
break
if rng.random() < self.p(u, v): # accept edge
self.graph.add_edge(u, v)
self.update_remaining(u, v, aux_graph=H)
示例13: is_directed_acyclic_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def is_directed_acyclic_graph(G):
"""Return True if the graph `G` is a directed acyclic graph (DAG) or
False if not.
Parameters
----------
G : NetworkX graph
Returns
-------
bool
True if `G` is a DAG, False otherwise
"""
if not G.is_directed():
return False
try:
consume(topological_sort(G))
return True
except nx.NetworkXUnfeasible:
return False
示例14: weighted_one_edge_augmentation
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def weighted_one_edge_augmentation(G, avail, weight=None, partial=False):
"""Finds the minimum weight set of edges to connect G if one exists.
This is a variant of the weighted MST problem.
Example
-------
>>> G = nx.Graph([(1, 2), (2, 3), (4, 5)])
>>> G.add_nodes_from([6, 7, 8])
>>> # any edge not in avail has an implicit weight of infinity
>>> avail = [(1, 3), (1, 5), (4, 7), (4, 8), (6, 1), (8, 1), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 1)]
>>> # find another solution by giving large weights to edges in the
>>> # previous solution (note some of the old edges must be used)
>>> avail = [(1, 3), (1, 5, 99), (4, 7, 9), (6, 1, 99), (8, 1, 99), (8, 2)]
>>> sorted(weighted_one_edge_augmentation(G, avail))
[(1, 5), (4, 7), (6, 1), (8, 2)]
"""
avail_uv, avail_w = _unpack_available_edges(avail, weight=weight, G=G)
# Collapse CCs in the original graph into nodes in a metagraph
# Then find an MST of the metagraph instead of the original graph
C = collapse(G, nx.connected_components(G))
mapping = C.graph['mapping']
# Assign each available edge to an edge in the metagraph
candidate_mapping = _lightest_meta_edges(mapping, avail_uv, avail_w)
# nx.set_edge_attributes(C, name='weight', values=0)
C.add_edges_from(
(mu, mv, {'weight': w, 'generator': uv})
for (mu, mv), uv, w in candidate_mapping
)
# Find MST of the meta graph
meta_mst = nx.minimum_spanning_tree(C)
if not partial and not nx.is_connected(meta_mst):
raise nx.NetworkXUnfeasible(
'Not possible to connect G with available edges')
# Yield the edge that generated the meta-edge
for mu, mv, d in meta_mst.edges(data=True):
if 'generator' in d:
edge = d['generator']
yield edge
示例15: find_pos_augment_edges
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import NetworkXUnfeasible [as 别名]
def find_pos_augment_edges(infr, pcc, k=None):
"""
# [[1, 0], [0, 2], [1, 2], [3, 1]]
pos_sub = nx.Graph([[0, 1], [1, 2], [0, 2], [1, 3]])
"""
if k is None:
pos_k = infr.params['redun.pos']
else:
pos_k = k
pos_sub = infr.pos_graph.subgraph(pcc)
# TODO:
# weight by pairs most likely to be comparable
# First try to augment only with unreviewed existing edges
unrev_avail = list(nxu.edges_inside(infr.unreviewed_graph, pcc))
try:
check_edges = list(nxu.k_edge_augmentation(
pos_sub, k=pos_k, avail=unrev_avail, partial=False))
except nx.NetworkXUnfeasible:
check_edges = None
if not check_edges:
# Allow new edges to be introduced
full_sub = infr.graph.subgraph(pcc).copy()
new_avail = ut.estarmap(infr.e_, nx.complement(full_sub).edges())
full_avail = unrev_avail + new_avail
n_max = (len(pos_sub) * (len(pos_sub) - 1)) // 2
n_complement = n_max - pos_sub.number_of_edges()
if len(full_avail) == n_complement:
# can use the faster algorithm
check_edges = list(nxu.k_edge_augmentation(
pos_sub, k=pos_k, partial=True))
else:
# have to use the slow approximate algo
check_edges = list(nxu.k_edge_augmentation(
pos_sub, k=pos_k, avail=full_avail, partial=True))
check_edges = set(it.starmap(e_, check_edges))
return check_edges