本文整理汇总了Python中networkx.DiGraph.nodes_iter方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.nodes_iter方法的具体用法?Python DiGraph.nodes_iter怎么用?Python DiGraph.nodes_iter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.nodes_iter方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import nodes_iter [as 别名]
def build_graph(self):
new_graph = DiGraph()
# Rebuild the graph from the LSDB
for lsa in chain(self.routers.values(),
self.networks.values(),
self.ext_networks.values()):
lsa.apply(new_graph, self)
# Contract all IPs to their respective router-id
for lsa in self.routers.values():
lsa.contract_graph(new_graph, self.router_private_address.get(
lsa.routerid, []))
# Figure out the controllers layout
base_net = ip_network(CFG.get(DEFAULTSECT, 'base_net'))
controller_prefix = CFG.getint(DEFAULTSECT, 'controller_prefixlen')
# Group by controller and log them
for ip in new_graph.nodes_iter():
addr = ip_address(ip)
if addr in base_net:
"""1. Compute address diff to remove base_net
2. Right shift to remove host bits
3. Mask with controller mask
"""
id = (((int(addr) - int(base_net.network_address)) >>
base_net.max_prefixlen - controller_prefix) &
((1 << controller_prefix) - 1))
self.controllers[id].append(ip)
# Contract them on the graph
for id, ips in self.controllers.iteritems():
contract_graph(new_graph, ips, 'C_%s' % id)
# Remove generated self loops
new_graph.remove_edges_from(new_graph.selfloop_edges())
self.apply_secondary_addresses(new_graph)
return new_graph
示例2: ts_from_expr
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import nodes_iter [as 别名]
def ts_from_expr(symtab, exprtab):
"""
symtab and exprtab are as produced by form.util.gen_expr().
"""
envtrans = dict()
systrans = list()
num_uncontrolled = len([i for i in range(len(symtab)) if symtab[i]['uncontrolled']])
identifiers = [v['name'] for v in symtab]
next_identifiers = [v['name']+'_next' for v in symtab]
evalglobals = {'__builtins__': None, 'True': True, 'False': False}
envtrans_formula = '(' + ') and ('.join(exprtab['ENVTRANS']) + ')'
for state in stategen(symtab):
stated = dict(zip(identifiers, state))
envtrans[state] = []
for next_state in stategen([v for v in symtab if v['uncontrolled']]):
stated.update(dict(zip(next_identifiers, next_state)))
if eval(envtrans_formula, evalglobals, stated):
envtrans[state].append(next_state)
systrans_formula = '(' + ') and ('.join(exprtab['SYSTRANS']) + ')'
for state in stategen(symtab):
stated = dict(zip(identifiers, state))
for next_state in stategen(symtab):
stated.update(dict(zip(next_identifiers, next_state)))
if eval(systrans_formula, evalglobals, stated):
systrans.append((state, next_state))
G = DiGraph()
G.add_edges_from(systrans)
for nd in G.nodes_iter():
G.node[nd]['sat'] = list()
stated = dict(zip(identifiers, nd))
for subformula in ['ENVINIT', 'SYSINIT']:
if eval(exprtab[subformula], evalglobals, stated):
G.node[nd]['sat'].append(subformula)
for subformula in ['ENVGOAL', 'SYSGOAL']:
for (i, goalexpr) in enumerate(exprtab[subformula]):
if eval(goalexpr, evalglobals, stated):
G.node[nd]['sat'].append(subformula+str(i))
return AnnTransitionSystem(symtab, G, envtrans,
num_egoals=len(exprtab['ENVGOAL']),
num_sgoals=len(exprtab['SYSGOAL']))
示例3: synthesize
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import nodes_iter [as 别名]
def synthesize(tsys, exprtab, init_flags='ALL_ENV_EXIST_SYS_INIT'):
assert init_flags.upper() == 'ALL_ENV_EXIST_SYS_INIT', 'Only the initial condition interpretation ALL_ENV_EXIST_SYS_INIT is supported.'
W, Y_list, X_list = get_winning_set(tsys, return_intermediates=True)
initial_states = get_initial_states(W, tsys, exprtab, init_flags)
if initial_states is None:
return None
goalnames = ['SYSGOAL'+str(i) for i in range(tsys.num_sgoals)]
for goalmode in range(tsys.num_sgoals):
Y_list[goalmode][0] = set([s for s in W if goalnames[goalmode] in tsys.G.node[s]['sat']])
strategy = DiGraph()
next_id = len(initial_states)
workset = list(range(next_id))
strategy.add_nodes_from([(i, {'state': s, 'mode': 0, 'initial': True})
for (i,s) in enumerate(initial_states)])
while len(workset) > 0:
nd = workset.pop()
j = 0
while j < len(Y_list[strategy.node[nd]['mode']]):
if strategy.node[nd]['state'] in Y_list[strategy.node[nd]['mode']][j]:
break
j += 1
if j == 0:
assert goalnames[strategy.node[nd]['mode']] in tsys.G.node[strategy.node[nd]['state']]['sat']
original_mode = strategy.node[nd]['mode']
while goalnames[strategy.node[nd]['mode']] in tsys.G.node[strategy.node[nd]['state']]['sat']:
strategy.node[nd]['mode'] = (strategy.node[nd]['mode'] + 1) % tsys.num_sgoals
if strategy.node[nd]['mode'] == original_mode:
break
if strategy.node[nd]['mode'] != original_mode:
repeat_found = False
for possible_repeat, attr in strategy.nodes_iter(data=True):
if (possible_repeat != nd
and attr['mode'] == strategy.node[nd]['mode']
and attr['state'] == strategy.node[nd]['state']):
repeat_found = True
for (u,v) in strategy.in_edges_iter(nd):
strategy.add_edge(u, possible_repeat)
strategy.remove_edges_from(strategy.in_edges(nd))
strategy.remove_node(nd)
break
if repeat_found:
continue
j = 0
while j < len(Y_list[strategy.node[nd]['mode']]):
if strategy.node[nd]['state'] in Y_list[strategy.node[nd]['mode']][j]:
break
j += 1
if j == 0:
assert goalnames[strategy.node[nd]['mode']] in tsys.G.node[strategy.node[nd]['state']]['sat']
for envpost in tsys.envtrans[strategy.node[nd]['state']]:
next_state = None
for succ_nd in tsys.G.successors(strategy.node[nd]['state']):
if (tuple([succ_nd[i] for i in tsys.ind_uncontrolled]) == envpost
and ((j > 0 and succ_nd in Y_list[strategy.node[nd]['mode']][j-1])
or (j == 0 and succ_nd in W))):
next_state = succ_nd
break
if next_state is None:
assert j > 0
if j == 0:
import pdb; pdb.set_trace()
blocking_index = None
blocking_sets = X_list[strategy.node[nd]['mode']][j-1]
for k in range(len(blocking_sets)):
if strategy.node[nd]['state'] in blocking_sets[k]:
blocking_index = k
break
assert blocking_index is not None
for succ_nd in tsys.G.successors(strategy.node[nd]['state']):
if (tuple([succ_nd[i] for i in tsys.ind_uncontrolled]) == envpost
and succ_nd in blocking_sets[blocking_index]):
next_state = succ_nd
break
assert next_state is not None
foundmatch = False
for candidate, cattr in strategy.nodes_iter(data=True):
if cattr['state'] == next_state and cattr['mode'] == strategy.node[nd]['mode']:
strategy.add_edge(nd, candidate)
foundmatch = True
break
if not foundmatch:
if j == 0:
new_mode = (strategy.node[nd]['mode'] + 1) % tsys.num_sgoals
else:
new_mode = strategy.node[nd]['mode']
workset.append(next_id)
strategy.add_node(next_id, {'state': next_state,
'mode': new_mode,
'initial': False})
strategy.add_edge(nd, next_id)
#.........这里部分代码省略.........
示例4: __init__
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import nodes_iter [as 别名]
class Codebase:
def __init__(self):
self.counter = 0
self._revisions = []
with open(path.join(path.dirname(__file__), '..', 'App.java')) as java_file:
parser = Parser()
tree = parser.parse_file(java_file)
initial_classes = tree.type_declarations
self._inheritance_graph = DiGraph()
self._method_call_graph = DiGraph()
for c in initial_classes:
self._inheritance_graph.add_node(c.name, {'class': c})
for m in c.body:
if isinstance(m, MethodDeclaration):
self._method_call_graph.add_node(m.name,
{'method': m,
'class_name': c.name,
'fitness': random()
})
def get_class_name(self, method_name):
return self._method_call_graph.node[method_name]['class_name']
def size_of(self, method_name):
return len(self._method_call_graph.node[method_name]['method'].body)
def number_of_methods(self):
return len(self._method_call_graph)
def number_of_classes(self):
return len(self._inheritance_graph)
def has_method(self, method_name):
return self._method_call_graph.has_node(method_name)
def choose_random_method(self):
"""
Choose a random method, weighted by its size
:return: the method name
"""
return sample([(method_name, len(data['method'].body) + 1)
for method_name, data in self._method_call_graph.nodes_iter(True)])
def choose_random_class(self):
"""
Choose a random class, weighted by its size
:return: the class name
"""
return sample([(class_name, len(data['class'].body) + 1)
for class_name, data in self._inheritance_graph.nodes_iter(data=True)])
def least_fit_methods(self, n=1):
"""
:return: the name of the method with smallest fitness value
"""
return nsmallest(n, self._method_call_graph,
key=lambda method_name: self._method_call_graph.node[method_name]['fitness'])
def choose_random_neighbor(self, method_name):
neighbors = self._method_call_graph.neighbors(method_name)
num_neighbors = len(neighbors)
if num_neighbors > 0:
return neighbors[floor(random() * num_neighbors)]
else:
return None
def caller_names(self, method_name):
"""
:param method_name:
:return: caller method names iterator
"""
return self._method_call_graph.predecessors_iter(method_name)
def method_invocations(self, method_name):
"""
Generator for MethodInvocation instances of method_name
:param method_name:
:return:
"""
for caller_name in self._method_call_graph.predecessors_iter(method_name):
caller = self._method_call_graph.node[caller_name]['method']
for stmt in caller.body:
if Codebase.is_invocation(stmt, method_name):
yield stmt.expression
def create_method(self, class_name):
"""
The created methods are static methods for now
"""
klass = self._inheritance_graph.node[class_name]['class']
method = MethodDeclaration(
'method' + str(self.counter),
body=[], modifiers=['static'])
self.counter += 1
klass.body.append(method)
method_info = {'method': method, 'class_name': class_name, 'fitness': random()}
self._method_call_graph.add_node(method.name, method_info)
return 1, method.name
#.........这里部分代码省略.........