本文整理汇总了Python中networkx.simple_cycles方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.simple_cycles方法的具体用法?Python networkx.simple_cycles怎么用?Python networkx.simple_cycles使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.simple_cycles方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: remove_cycles
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def remove_cycles(dag, name2recipes, failed, skip_dependent):
nodes_in_cycles = set()
for cycle in list(nx.simple_cycles(dag)):
logger.error('BUILD ERROR: dependency cycle found: %s', cycle)
nodes_in_cycles.update(cycle)
for name in sorted(nodes_in_cycles):
cycle_fail_recipes = sorted(name2recipes[name])
logger.error('BUILD ERROR: cannot build recipes for %s since '
'it cyclically depends on other packages in the '
'current build job. Failed recipes: %s',
name, cycle_fail_recipes)
failed.extend(cycle_fail_recipes)
for node in nx.algorithms.descendants(dag, name):
if node not in nodes_in_cycles:
skip_dependent[node].extend(cycle_fail_recipes)
return dag.subgraph(name for name in dag if name not in nodes_in_cycles)
示例2: remove_cc_with_cycles
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def remove_cc_with_cycles(DG):
# remove pairend links and unitig links (unoriented)
edges_to_remove = []
for edge in DG.edges.data():
if edge[2]['type'] == '-1M':
edges_to_remove.append(edge)
for edge in edges_to_remove:
DG.remove_edge(edge[0],edge[1])
cycles = list(nx.simple_cycles(DG))
# sys.stderr.write(f" removed {len(cycles)} cycles\n") #DEB
# tmpnb=0 #DEB
G=nx.Graph(DG)
for nodes in cycles:
first_node_in_cycle = nodes[0] # get the first node, the other ones in the cycle are in the same CC
# remove the whole CC:
CC_with_cycle = nx.node_connected_component(G, first_node_in_cycle)
for node_id in CC_with_cycle:
if node_id in DG.nodes():
# tmpnb+=1 #DEB
DG.remove_node(node_id)
# sys.stderr.write(f" removed {tmpnb} nodes\n") #DEB
示例3: _validate
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def _validate(G):
'''
Validates dependency graph to ensure it has no missing or cyclic dependencies
'''
for name in G.nodes():
if 'value' not in G.node[name] and 'template' not in G.node[name]:
msg = 'Dependency unsatisfied in variable "%s"' % name
raise ParamException(msg)
if not nx.is_directed_acyclic_graph(G):
graph_cycles = nx.simple_cycles(G)
variable_names = []
for cycle in graph_cycles:
try:
variable_name = cycle[0]
except IndexError:
continue
variable_names.append(variable_name)
variable_names = ', '.join(sorted(variable_names))
msg = ('Cyclic dependency found in the following variables: %s. Likely the variable is '
'referencing itself' % (variable_names))
raise ParamException(msg)
示例4: dagify_min_edge
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def dagify_min_edge(g):
"""Input a graph and output a DAG.
The heuristic is to reverse the edge with the lowest score of the cycle
if possible, else remove it.
Args:
g (networkx.DiGraph): Graph to modify to output a DAG
Returns:
networkx.DiGraph: DAG made out of the input graph.
Example:
>>> from cdt.utils.graph import dagify_min_edge
>>> import networkx as nx
>>> import numpy as np
>>> # Generate sample data
>>> graph = nx.DiGraph((np.ones(4) - np.eye(4)) *
np.random.uniform(size=(4,4)))
>>> output = dagify_min_edge(graph)
"""
ncycles = len(list(nx.simple_cycles(g)))
while not nx.is_directed_acyclic_graph(g):
cycle = next(nx.simple_cycles(g))
edges = [(cycle[-1], cycle[0])]
scores = [(g[cycle[-1]][cycle[0]]['weight'])]
for i, j in zip(cycle[:-1], cycle[1:]):
edges.append((i, j))
scores.append(g[i][j]['weight'])
i, j = edges[scores.index(min(scores))]
gc = deepcopy(g)
gc.remove_edge(i, j)
gc.add_edge(j, i)
ngc = len(list(nx.simple_cycles(gc)))
if ngc < ncycles:
g.add_edge(j, i, weight=min(scores))
g.remove_edge(i, j)
ncycles = ngc
return g
示例5: test_simple_graph_with_reported_bug
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def test_simple_graph_with_reported_bug(self):
G=nx.DiGraph()
edges = [(0, 2), (0, 3), (1, 0), (1, 3), (2, 1), (2, 4), \
(3, 2), (3, 4), (4, 0), (4, 1), (4, 5), (5, 0), \
(5, 1), (5, 2), (5, 3)]
G.add_edges_from(edges)
cc=sorted(nx.simple_cycles(G))
assert_equal(len(cc),26)
rcc=sorted(nx.recursive_simple_cycles(G))
assert_equal(len(cc),len(rcc))
for c in cc:
assert_true(any(self.is_cyclic_permutation(c,rc) for rc in rcc))
for rc in rcc:
assert_true(any(self.is_cyclic_permutation(rc,c) for c in cc))
# These tests might fail with hash randomization since they depend on
# edge_dfs. For more information, see the comments in:
# networkx/algorithms/traversal/tests/test_edgedfs.py
示例6: test_simple_graph_with_reported_bug
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def test_simple_graph_with_reported_bug(self):
G = nx.DiGraph()
edges = [(0, 2), (0, 3), (1, 0), (1, 3), (2, 1), (2, 4),
(3, 2), (3, 4), (4, 0), (4, 1), (4, 5), (5, 0),
(5, 1), (5, 2), (5, 3)]
G.add_edges_from(edges)
cc = sorted(nx.simple_cycles(G))
assert_equal(len(cc), 26)
rcc = sorted(nx.recursive_simple_cycles(G))
assert_equal(len(cc), len(rcc))
for c in cc:
assert_true(any(self.is_cyclic_permutation(c, rc) for rc in rcc))
for rc in rcc:
assert_true(any(self.is_cyclic_permutation(rc, c) for c in cc))
# These tests might fail with hash randomization since they depend on
# edge_dfs. For more information, see the comments in:
# networkx/algorithms/traversal/tests/test_edgedfs.py
示例7: is_cycle
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def is_cycle(alert_sub_g: nx.DiGraph, is_ordered: bool = True):
alert_id = alert_sub_g.graph["alert_id"]
edges = alert_sub_g.edges(data=True)
cycles = list(nx.simple_cycles(alert_sub_g)) # Use simple_cycles function directly (subgraph is small enough)
if len(cycles) != 1:
logging.info("Alert %s is not a cycle pattern" % alert_id)
return False
if is_ordered:
edges.sort(key=lambda e: e[2]["date"])
next_orig = None
next_amt = sys.float_info.max
next_date = datetime.strptime("1970-01-01", "%Y-%m-%d")
for orig, bene, attr in edges:
if next_orig is not None and orig != next_orig:
logging.info("Alert %s is not a cycle pattern" % alert_id)
return False
else:
next_orig = bene
amount = attr["amount"]
if amount == next_amt:
logging.info("Alert %s cycle transaction amounts are unordered" % alert_id)
return False
else:
next_amt = amount
date = attr["date"]
if date < next_date:
logging.info("Alert %s cycle transactions are chronologically unordered" % alert_id)
return False
else:
next_date = date
return True
示例8: getNetProp
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def getNetProp(inGraph):
'''
Function to compute properties
of a given network.
'''
# number of weakly connected components in
# reference network
numCC = len(list(nx.weakly_connected_components(inGraph)))
# number of feedback loop
# in reference network
allCyc = nx.simple_cycles(inGraph)
cycSet = set()
for cyc in allCyc:
if len(cyc) == 3:
cycSet.add(frozenset(cyc))
numFB = len(cycSet)
# number of feedfwd loops
# in reference network
allPaths = []
allPathsSet = set()
for u,v in inGraph.edges():
allPaths = nx.all_simple_paths(inGraph, u, v, cutoff=2)
for p in allPaths:
if len(p) > 2:
allPathsSet.add(frozenset(p))
numFF= len(allPathsSet)
# number of mutual interactions
numMI = 0.0
for u,v in inGraph.edges():
if (v,u) in inGraph.edges():
numMI += 0.5
return numCC, numFB, numFF, numMI
示例9: checkInstructionGraphCycles
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def checkInstructionGraphCycles(instructions):
import networkx as nx
g = nx.DiGraph()
for i in instructions:
g.add_node(i)
for ix in range(i.flowsToCount()):
flowsTo = i.flowsTo(ix)
if flowsTo in instructions:
g.add_edge(i, flowsTo)
cycles = nx.simple_cycles(g)
for c in cycles:
if not checkCycleHasEntrypoint(c):
print "************************************"
print "No entrypoint in the following cycle: "
for i in c:
print i
print "children:"
for sub in i.children():
print "\t", repr(sub)
print "************************************"
else:
print "************************************"
print "cycle with ", len(c), " is OK"
for i in c:
if i.getTypedJumpTarget():
print "*** ",
else:
print " ",
print repr(i)
print "************************************"
示例10: _detect_loops
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def _detect_loops(self):
temp_graph = networkx.DiGraph()
for source, target_list in self._cfg._edge_map.items():
for target in target_list:
temp_graph.add_edge(source, target)
ctr = 0
for loop_lst in networkx.simple_cycles(temp_graph):
l.debug("A loop is found. %d", ctr)
ctr += 1
loop = (tuple([x[-1] for x in loop_lst]))
print(" => ".join(["0x%08x" % x for x in loop]))
self.add_loop(loop)
示例11: cmd_cycles
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def cmd_cycles(handle, args):
g = retrieve_filtered_graph(handle, args)
cycles = nx.simple_cycles(g)
print(list(cycles))
示例12: _validate
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def _validate(self):
# graph is acyclic
cycles = nx.simple_cycles(self.nx_graph)
try:
cycle = next(cycles)
except StopIteration:
pass
else:
raise GraphCyclicError(
'Graph is not acyclic, contains a cycle {}'.format(cycle))
示例13: find_memcmp_like
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def find_memcmp_like(p, cfg):
memcpy_like = [f.addr for f in cfg.functions.values() if 'memcmp' in f.name]
tots = []
for fun in cfg.functions.values():
css = []
try:
no = cfg.get_any_node(fun.addr)
css = [pred for pred in no.predecessors]
except:
pass
if css == []:
continue
cs = css[0]
args = get_ord_arguments_call(p, cs.addr)
if len(args) > 3 or len(args) < 2:
continue
for loop in [x for x in networkx.simple_cycles(fun.graph)]:
# CMPNE or CMPEQ
if any([op for l in loop for op in p.factory.block(l.addr).vex.operations if 'cmpeq' in op.lower() or 'cmpne' in op.lower()]):
tots.append(hex(fun.addr))
# INCREMENT
wr_tmp = [st for l in loop for st in p.factory.block(l.addr).vex.statements if st.tag == 'Ist_WrTmp']
cons = [w.constants for w in wr_tmp if hasattr(w, 'data') and hasattr(w.data, 'op') and w.data.op == 'Iop_Add64']
if cons:
cons = [c.value for cs in cons for c in cs]
# using BootStomp thresholds
if 1 in cons and len([x for x in fun.blocks]) <= 8:
memcpy_like.append(fun.addr)
return list(set(memcpy_like))
# FIXME: to finish
示例14: find_memcpy_like
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def find_memcpy_like(p, cfg=None):
memcpy_like = [f.addr for f in p.kb.functions.values() if 'memcpy' in f.name]
if cfg is None:
return memcpy_like
tots = []
for fun in cfg.functions.values():
css = []
try:
no = cfg.get_any_node(fun.addr)
css = [pred for pred in no.predecessors]
except:
pass
if css == []:
continue
cs = css[0]
args = get_ord_arguments_call(p, cs.addr)
if len(args) > 3 or len(args) < 2:
continue
for loop in [x for x in networkx.simple_cycles(fun.graph)]:
# CMPNE or CMPEQ
if any([op for l in loop for op in p.factory.block(l.addr).vex.operations if 'cmpeq' in op.lower() or 'cmpne' in op.lower()]):
tots.append(hex(fun.addr))
# INCREMENT
wr_tmp = [st for l in loop for st in p.factory.block(l.addr).vex.statements if st.tag == 'Ist_WrTmp']
cons = [w.constants for w in wr_tmp if hasattr(w, 'data') and hasattr(w.data, 'op') and w.data.op == 'Iop_Add64']
if cons:
cons = [c.value for cs in cons for c in cs]
# using BootStomp thresholds
if 1 in cons and len([x for x in fun.blocks]) <= 8:
memcpy_like.append(fun.addr)
return list(set(memcpy_like))
示例15: find_cycles
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import simple_cycles [as 别名]
def find_cycles(self):
duplicate_cycles = list(nx.simple_cycles(self.digraph))
all_cycles = set()
final_cycles = []
for i in duplicate_cycles:
sorted = []
for node in i:
sorted.append(node)
sorted.sort()
sorted = tuple(sorted)
if not (sorted in all_cycles):
all_cycles.add(sorted)
final_cycles.append(i)
return final_cycles