本文整理汇总了Python中networkx.DiGraph.successors方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.successors方法的具体用法?Python DiGraph.successors怎么用?Python DiGraph.successors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.successors方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: deterministic_topological_ordering
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import successors [as 别名]
def deterministic_topological_ordering(nodes, links, start_node):
"""
Topological sort that is deterministic because it sorts (alphabetically)
candidates to check
"""
graph = DiGraph()
graph.add_nodes_from(nodes)
for link in links:
graph.add_edge(*link)
if not is_directed_acyclic_graph(graph):
raise NetworkXUnfeasible
task_names = sorted(graph.successors(start_node))
task_set = set(task_names)
graph.remove_node(start_node)
result = [start_node]
while task_names:
for name in task_names:
if graph.in_degree(name) == 0:
result.append(name)
# it is OK to modify task_names because we break out
# of loop below
task_names.remove(name)
new_successors = [t for t in graph.successors(name)
if t not in task_set]
task_names.extend(new_successors)
task_names.sort()
task_set.update(set(new_successors))
graph.remove_node(name)
break
return result
示例2: VerseGenerator
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import successors [as 别名]
class VerseGenerator(object):
def __init__(self, text=None, pos_tags=True, rhyme_table=True):
self.rhyme_table = rhyme_table
self.pos_tags = pos_tags
self.chain = DiGraph()
self.rhymes = {}
if text:
self.load_text(text)
def __getitem__(self, item):
return self.chain[item]
def load_text(self, text):
'''Add the given text to the Markov chain
'''
for sentence in tokenise(text):
if self.pos_tags:
tagged = pos_tag(sentence, tagset=TAGSET)
else:
tagged = ((w, None) for w in sentence)
previous = None
for w, tag in tagged:
current = Word(w, tag)
# Add connection between word and previous to the graph,
# or increment the edge counter if it already exists
if previous:
try:
self.chain[previous][current]['count'] += 1
except KeyError:
self.chain.add_edge(previous, current, count=1)
previous = current
if self.rhyme_table:
rhymes = {w: self.rhymes_for_word(w) for w in self.chain.nodes()}
self.rhymes = rhymes
def load_corpus(self, folder):
'''Load text files in given folder and any subfolders into the
markov chain.
'''
for root, _, fpaths in os.walk(folder):
for path in fpaths:
fullpath = os.path.join(root, path)
with codecs.open(fullpath, 'r', 'utf-8-sig') as f:
try:
text = f.read()
self.load_text(text)
except UnicodeDecodeError as e:
msg = '{} is not utf-8'.format(fullpath)
raise IOError(msg) from e
def dump_chain(self, path):
'''
Serialize the markov chain digraph to a file
'''
with open(path, 'wb') as f:
pickle.dump(self.chain, f)
def load_chain(self, path):
'''
Load a pickled markov chain. Wipes any existing data
'''
with open(path, 'rb') as f:
self.chain = pickle.load(f)
def roulette_select(self, node, pred=False):
'''
A generator which returns successors or predecessors to the
given node in roulette-wheel selected random order.
'''
r = random.random()
current_sum = 0
if pred:
adjacent = self.chain.pred[node]
else:
adjacent = self.chain.succ[node]
for node, props in adjacent.items():
count = props['count']
prob = count / len(adjacent)
current_sum += prob
if r <= current_sum:
return node
return None
def shuffled_successors(self, word, order='roulette'):
'''
Return successor words for given word in random order
proportional to their frequency.
'''
if order is 'roulette':
succ = self.chain.succ[word].items()
key = lambda kv: random.expovariate(1/0.5) * kv[1]['count']
return [pair[0] for pair in sorted(succ, key=key)]
elif order is 'random':
#.........这里部分代码省略.........
示例3: __init__
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import successors [as 别名]
#.........这里部分代码省略.........
name, access_flag, descriptor = _analysis.get_like_field()
_vm.insert_field( self.__field.get_class_name(), name, [ access_flag, descriptor ] )
fields[ i ] = Field( _vm, _analysis, _vm_generate, _vm.get_field_descriptor( self.__field.get_class_name(), name, descriptor ), self )
# degree of the field, prefix must be add if the protection is for a real field
fields[ i ].run( self.__G.degree()[i] )
########## Add all fields initialisation into the final list ############
for i in fields :
print "FIELD ->", i,
fields[ i ].show()
x = fields[ i ].insert_init()
if x != None :
try :
list_OB[ x[0] ].append( (x[1], x[2]) )
except KeyError :
list_OB[ x[0] ] = []
list_OB[ x[0] ].append( (x[1], x[2]) )
############ Create the depedency ############
############################################################################
# Integer variables :
# X -> Y
# - a depth into the calcul
# Y = { LV + LLV + NLV } x { &, -, +, |, *, /, ^ } x { &&, || }
# if (Y != ?) {
# X = ..... ;
# }
#############################################################################
# get a local variable
# - used into a loop
# - a parameter
# - a new one
############################################################################
find = False
print "F -->", self.__G.successors( self.__field.get_name() )
taint_field = _analysis.get_tainted_field( self.__field.get_class_name(), self.__field.get_name(), self.__field.get_descriptor() )
for path in taint_field.get_paths() :
continue
print "\t", path.get_access_flag(), "%s (%d-%d)" % (path.get_bb().get_name(), path.get_bb().get_start(), path.get_bb().get_end()) , path.get_bb().get_start() + path.get_idx(),
x = _analysis.get( path.get_bb().get_method() )
bb = x.get_break_block( path.get_bb().get_start() + path.get_idx() )
print "\t\t", x.get_local_variables()
if path.get_access_flag() == "R" and find == False :
o = self.add_offset( _analysis.prev_free_block_offset( path.get_method(), bb.get_start() ) )
val = _analysis.next_free_block_offset( path.get_method(), o.get_idx() )
if o.get_idx() == -1 or val == -1 :
raise("ooop")
#try :
# list_OB[ path.get_method() ].append( o, [ [ "iload_3" ], [ "iconst_0" ], [ "if_icmpge", val - o.get_idx() + 3 ] ] )
#except KeyError :
# list_OB[ path.get_method() ] = []
# list_OB[ path.get_method() ].append( (o, [ [ "iload_3" ], [ "iconst_0" ], [ "if_icmpge", val - o.get_idx() + 3 ] ] ) )
find = True
##### Insert all modifications
for m in list_OB :
code = m.get_code()
i = 0
while i < len( list_OB[ m ] ) :
v = list_OB[ m ][ i ]
print "INSERT ", v[0].get_idx(), v[1]
size_r = code.inserts_at( code.get_relative_idx( v[0].get_idx() ), v[1] )
#code.show()
j = i + 1
while j < len( list_OB[ m ] ) :
v1 = list_OB[ m ][ j ]
if v1[0].get_idx() >= v[0].get_idx() :
v1[0].add_idx( size_r )
j = j + 1
i = i + 1
def _new_node(self, G) :
return "X%d" % (len(G.node))
def _current_node(self, G) :
return len(G.node) - 1
def __random(self, G, depth) :
if depth >= self.__depth :
return
for i in range( random.randint(1, self.__width) ) :
nd = self._new_node(G)
G.add_edge( "X%d" % depth, nd )
self.__random( G, self._current_node(G) )
示例4: MacroManager
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import successors [as 别名]
class MacroManager(object):
"""This class manages the macros specified in the configuration file.
The parameters of each section, along with their dependencies are passed to
the class. Then, it verifies that the dependencies are correct (they form a
DAG and respect the sections dependencies) and creates an ordered list of
the macros to be used when replacing their actual values in a given
combination.
"""
def __init__(self):
"""Create a new MacroManager object."""
self.dep_graph = DiGraph()
self.ds_macros = set([])
self.xp_macros = set([])
self.__define_test_macros()
def __define_test_macros(self):
"""Define values and dependencies of test macros.
A set of macros are defined by default, including input and output
directories of datasets and experiments and their identifiers.
"""
self.test_macros = {
"data_base_dir": "/tests/data",
"out_base_dir": "/tests/out",
"data_dir": "/tests/data/0", # data_base_dir/ds_id
"out_dir": "/tests/out/0", # data_base_dir/comb_id
"comb_id": 0,
"ds_id": 0,
"xp.input": "/tests/data/0", # data_dir
"xp.output": "/tests/out/0" # out_dir
}
self.ds_params = set([])
self.xp_params = set([])
self.dep_graph.add_nodes_from(self.test_macros.keys())
self.add_dependency("data_base_dir", "data_dir")
self.add_dependency("ds_id", "data_dir")
self.add_dependency("data_dir", "xp.input")
self.add_dependency("out_base_dir", "out_dir")
self.add_dependency("comb_id", "out_dir")
self.add_dependency("out_dir", "xp.output")
self.sorted_test_macros = topological_sort(self.dep_graph)
def update_test_macros(self, ds_id=None, comb_id=None):
"""Update test macros with dataset and/or combination ids.
Args:
ds_id (int, optional):
The dataset identifier.
comb_id (int, optional):
The combination identifier.
"""
if ds_id:
if "data_dir" in self.test_macros:
self.test_macros["data_dir"] = \
self.test_macros["data_base_dir"] + "/" + str(ds_id)
if "xp.input" in self.test_macros:
self.test_macros["xp.input"] = \
self.test_macros["data_dir"]
if comb_id:
if "out_dir" in self.test_macros:
self.test_macros["out_dir"] = \
self.test_macros["out_base_dir"] + "/" + str(comb_id)
if "xp.output" in self.test_macros:
self.test_macros["xp.output"] = \
self.test_macros["out_dir"]
def __filter_unused_test_macros(self):
for m in reversed(self.sorted_test_macros):
if not self.dep_graph.successors(m):
self.dep_graph.remove_node(m)
self.sorted_test_macros.remove(m)
del self.test_macros[m]
def add_ds_params(self, params):
"""Add the list of dataset parameters.
Args:
params (dict):
The list of dataset parameters.
"""
self.ds_params = self.ds_params.union(params)
def add_xp_params(self, params):
"""Add the list of experiment parameters.
Args:
params (dict):
#.........这里部分代码省略.........
示例5: add_clases
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import successors [as 别名]
def add_clases(self, uml_pool, classes,
detalization_level = 0,
detalization_levels= {},
with_generalizations = True,
with_interfaces = True,
group_interfaces = True,
with_associations = False,
auto_aggregation = False,
forced_relationships = False,
):
"""
@param level detalization level
| level | Description |
|-----------------------------------------------|
| 0 | hide class |
| 1 | details suppressed |
| 2 | analysis level details |
| 3 | implementation level details |
| 4 | maximum details |
@return dictionary with node settings for graphviz
"""
for uml_class in classes:
uml_class = uml_pool.Class[uml_class]
self.add_class(uml_class, detalization_levels.get(uml_class.id, detalization_level))
if with_generalizations and uml_pool:
for uml_relationship in uml_pool.generalizations_iter():
self.add_relationship(uml_relationship, forced_relationships)
if with_associations: pass
if auto_aggregation:
self.extract_aggregations()
self._relationships = []
self.interface_groups = []
if with_interfaces:
if group_interfaces:
from networkx import DiGraph
from sets import Set
graph = DiGraph()
for uml_class in uml_pool.Class.values():
for iname in uml_class.usages:
graph.add_edge(iname, uml_class.id)
for iname in uml_class.realizations:
graph.add_edge(uml_class.id, iname)
inames = uml_pool.Interface.keys()
ivisited = [False]*len(inames)
iface_groups = []
for i1 in xrange(len(inames)-1):
iname1 = inames[i1]
if not ivisited[i1]:
uml_ifaces = Set([iname1])
for i2 in xrange(i1, len(inames)):
iname2 = inames[i2]
if not ivisited[i2] and \
graph.successors(iname1) == graph.successors(iname2) and \
graph.predecessors(iname1) == graph.predecessors(iname2) :
uml_ifaces.add(iname2)
ivisited[i2] = True
iface_groups.append(uml_ifaces)
ivisited[i1] = True
#self.interface_groups = map(lambda group: UMLInterfaceGroup(group, uml_pool), iface_groups)
for group in iface_groups:
iname = list(group)[0]
if True:
# if len(graph.successors(iname)) > 0 and \
# len(graph.predecessors(iname)) > 0:
group_id = len(self.interface_groups)
uml_igroup = UMLInterfaceGroup(group, uml_pool, group_id)
self.interface_groups.append(uml_igroup)
self.add_node(group_id)
for class_id in graph.successors(iname):
self.add_relationship(UMLUsage(uml_igroup, uml_pool.Class[class_id]))
for class_id in graph.predecessors(iname):
self.add_relationship(UMLRealization(uml_pool.Class[class_id], uml_igroup))