本文整理汇总了Python中networkx.DiGraph.remove_node方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.remove_node方法的具体用法?Python DiGraph.remove_node怎么用?Python DiGraph.remove_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.remove_node方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: merge
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def merge(self,minN):
import numpy as np
merged=[]
merged_cliq=[]
while len(DiGraph.nodes(self)):
#print(len(self.nodes()))
contcmp,ct_cliq=self.splitG(minN)
if not DiGraph.nodes(self):
break
merged=merged+contcmp
merged_cliq=merged_cliq+ct_cliq
try:
#print("point1")
cut_nodes=minimum_node_cut(self)
#print("point2")
except:
nodes=DiGraph.nodes(self)
index=np.random.randint(len(nodes))
cut_nodes=[nodes[index]]
for node in cut_nodes:
DiGraph.remove_node(self,node)
self.topics=merged
self.topic_cliq=merged_cliq
示例2: remove_node
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def remove_node(self, n):
if n not in self.nodes():
return
if self.node[n]['conn'] is not None \
and not self.node[n]['conn'].disconnected:
self.node[n]['conn'].disconnect()
DiGraph.remove_node(self, n)
示例3: filter_nodes
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def filter_nodes(self,thresh):
nodes=DiGraph.nodes(self)
for node in nodes:
if DiGraph.in_degree(self,node)<thresh:
DiGraph.remove_node(self,node)
nodes=DiGraph.nodes(self)
for node in nodes:
if DiGraph.in_degree(self,node)==0 and DiGraph.out_degree(self,node)==0:
DiGraph.remove_node(self,node)
示例4: remove_node
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def remove_node(self, n):
"""
Remove node n from graph if the deletion do not disconnect graph.
Attempting to delete a non-existent node will raise an exception.
"""
temp = self.copy()
DiGraph.remove_node(temp, n)
if temp._is_connected():
DiGraph.remove_node(self, n)
else: raise ValueError("Node %s disconnects graph" %(n, ) )
示例5: filter_edges
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def filter_edges(self,thresh):
edges=DiGraph.edges(self,data='weight')
for edge in edges:
if edge[2]<thresh:
DiGraph.remove_edge(self,edge[0],edge[1])
if DiGraph.in_degree(self,edge[0])==0 and DiGraph.out_degree(self,edge[0])==0:
DiGraph.remove_node(self,edge[0])
if DiGraph.in_degree(self,edge[1])==0 and DiGraph.out_degree(self,edge[1])==0:
DiGraph.remove_node(self,edge[1])
示例6: remove_node
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def remove_node(self, node):
if self.__debug > 0:
print "Removing node: " + str(node)
if node in self.__inputs:
self.__inputs.remove(node)
if node in self.__outputs:
self.__outputs.remove(node)
if node in self.__cells:
self.__cells.remove(node)
if node in self.__flops:
self.__flops.remove(node)
if node in self.__flopsIn:
self.__flopsIn.pop(node)
if node in self.__virtual:
self.__virtual.pop(node)
digraph.remove_node(self, node)
示例7: splitG
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def splitG(self,minN):
contcmp=[]
ct_cliq=[]
cncp=list(strongly_connected_components(self))
for item in cncp:
#print(len(item))
if len(item)<=minN and len(item)>1:
#print("topic")
tmp=set()
tmp_cliq=[]
for each in item:
tmp=tmp.union(set(self.node[each]["keywords"]))
tmp_cliq.append(each)
DiGraph.remove_node(self,each)
contcmp.append(tmp)
ct_cliq.append(tmp_cliq)
if len(item)==1:
DiGraph.remove_node(self,list(item)[0])
nodes=DiGraph.nodes(self)
for node in nodes:
if DiGraph.in_degree(self,node)==0 and DiGraph.out_degree(self,node)==0:
DiGraph.remove_node(self,node)
return contcmp,ct_cliq
示例8: deterministic_topological_ordering
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [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
示例9: remove_node
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def remove_node(self, n):
if n not in self.nodes():
return
DiGraph.remove_node(self, n)
示例10: synthesize
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [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)
#.........这里部分代码省略.........
示例11: MacroManager
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [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):
#.........这里部分代码省略.........
示例12: __init__
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
#.........这里部分代码省略.........
>>> muscle = network.findMuscle('M1')
Returns a :class:`muscle <Network.Muscle.Muscle>` or None if there are no muscles with the name.
"""
return self.findObject(Muscle, name)
def muscles(self):
"""
Return a list of all :class:`muscles <Network.Muscle.Muscle>` in the network.
>>> for muscle in network.muscles():
... display.setVisibleOpacity(muscle, 0.5)
An empty list will be returned if there are no muscles in the network.
"""
return self.objectsOfClass(Muscle)
def _updateGraph(self, objectToUpdate = None):
if objectToUpdate is None:
# Rebuild the entire graph.
objectsToUpdate = self.objects
self.graph.clear()
else:
# Just rebuild the connections to the one object.
objectsToUpdate = [objectToUpdate]
# Remove the object if it was there before. This will also delete any edges from the node.
objectId = objectToUpdate.networkId
if objectId in self.graph:
self.graph.remove_node(objectId)
# Maintain a temporary cache of weights so that rebuilding the whole graph doesn't take so long.
objectWeights = {}
def weightOfObject(weightedObject):
if weightedObject.networkId in objectWeights:
objectWeight = objectWeights[weightedObject.networkId]
else:
objectWeight = self.weightOfObject(weightedObject)
objectWeights[weightedObject.networkId] = objectWeight
return objectWeight
for objectToUpdate in objectsToUpdate:
objectId = objectToUpdate.networkId
# (Re-)Add the object to the graph.
self.graph.add_node(objectId)
# Get the weight of this object.
objectWeight = weightOfObject(objectToUpdate)
# Add the connections to other objects already in the graph.
# (Each connection to an object not in the graph will be added when that object is added.)
# The weight of each edge is the average of the weights of the two objects it connects.
inputIds = set([objectInput.networkId for objectInput in objectToUpdate.inputs(recurse = False)])
outputIds = set([objectOutput.networkId for objectOutput in objectToUpdate.outputs(recurse = False)])
unknownIds = set([objectInput.networkId for objectInput in objectToUpdate.connections(recurse = False)]).difference(inputIds).difference(outputIds)
for inputId in inputIds.union(unknownIds):
if inputId in self.graph:
otherWeight = weightOfObject(objectToUpdate)
self.graph.add_edge(inputId, objectId, weight = (objectWeight + otherWeight) / 2.0)
for outputId in outputIds.union(unknownIds):
if outputId in self.graph:
示例13: __init__
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
#.........这里部分代码省略.........
"""
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
def delete_method(self, method_name):
"""
Delete the method and update callers
:param method_name:
:return:
"""
# remove method invocation
method_info = self._method_call_graph.node[method_name]
method = method_info['method']
change_size = len(method.body)
for caller_name in self._method_call_graph.predecessors_iter(method_name):
caller_info = self._method_call_graph.node[caller_name]
caller = caller_info['method']
old_size = len(caller.body)
caller.body = [stmt for stmt in caller.body
if not Codebase.is_invocation(stmt, method_name)
]
change_size += old_size - len(caller.body)
caller_info['fitness'] = random()
class_name = method_info['class_name']
klass = self._inheritance_graph.node[class_name]['class']
klass.body.remove(method)
self._method_call_graph.remove_node(method_name)
if len(klass.body) == 0:
# remove inheritance from all subclasses
for subclass_name in self._inheritance_graph.predecessors_iter(class_name):
subclass = self._inheritance_graph.node[subclass_name]['class']
subclass.extends = None
change_size += 1
self._inheritance_graph.remove_node(class_name)
change_size += 1
return change_size
def create_class(self, superclass_name):
klass = ClassDeclaration('Class' + str(self.counter), [])
if superclass_name:
klass.extends = Type(Name(superclass_name))
self.counter += 1
self._inheritance_graph.add_node(klass.name, {'class': klass})
if superclass_name:
self._inheritance_graph.add_edge(klass.name, superclass_name)
return 1, klass.name
def add_method_call(self, caller_name, callee_name):
callee_info = self._method_call_graph.node[callee_name]
caller_info = self._method_call_graph.node[caller_name]
caller = caller_info['method']
num_params = len(callee_info['method'].parameters)
# trying to find enough variables for the method arguments
arguments = []
for p in caller.parameters:
if len(arguments) >= num_params:
break
else:
arguments.append(Name(p.variable.name))
示例14: _construct
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import remove_node [as 别名]
def _construct(self):
"""
We want to build the type of DFG that's used in "Automated Ident. of Crypto
Primitives in Binary Code with Data Flow Graph Isomorphisms." Unlike that
paper, however, we're building it on Vex IR instead of assembly instructions.
"""
cfg = self._cfg
p = self.project
dfgs = {}
l.debug("Building Vex DFG...")
for node in cfg.nodes():
try:
if node.simprocedure_name == None:
irsb = p.factory.block(node.addr).vex
else:
l.debug("Cannot process SimProcedures, ignoring %s" % node.simprocedure_name)
continue
except Exception as e:
l.debug(e)
continue
tmpsnodes = {}
storesnodes = {}
putsnodes = {}
statements = irsb.statements
dfg = DiGraph()
for stmt_idx, stmt in enumerate(statements):
# We want to skip over certain types, such as Imarks
if self._need_to_ignore(node.addr, stmt, stmt_idx):
continue
# break statement down into sub-expressions
exprs = stmt.expressions
stmt_node = stmt
dfg.add_node(stmt)
if stmt.tag == 'Ist_WrTmp':
tmpsnodes[stmt.tmp] = stmt_node
if exprs[0].tag == 'Iex_Binop':
if exprs[1].tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[exprs[1].tmp], stmt_node)
else:
dfg.add_edge(exprs[1], stmt_node)
if exprs[2].tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[exprs[2].tmp], stmt_node)
else:
dfg.add_edge(exprs[2], stmt_node)
elif exprs[0].tag == 'Iex_Unop':
dfg.remove_node(stmt_node)
if exprs[1].tag == 'Iex_RdTmp':
tmpsnodes[stmt.tmp] = copy(tmpsnodes[exprs[1].tmp])
tmpsnodes[stmt.tmp].tmp = stmt.tmp
else:
tmpsnodes[stmt.tmp] = exprs[1]
elif exprs[0].tag == 'Iex_RdTmp':
tmpsnodes[stmt.tmp] = copy(tmpsnodes[exprs[0].tmp])
tmpsnodes[stmt.tmp].tmp = stmt.tmp
elif exprs[0].tag == 'Iex_Get':
if putsnodes.has_key(exprs[0].offset):
dfg.add_edge(putsnodes[exprs[0].offset], stmt_node)
if len(exprs) > 1 and exprs[1].tag == "Iex_RdTmp":
dfg.add_edge(tmpsnodes[exprs[1].tmp], stmt_node)
elif len(exprs) > 1:
dfg.add_edge(exprs[1], stmt_node)
elif exprs[0].tag == 'Iex_Load':
if exprs[1].tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[exprs[1].tmp], stmt_node)
else:
dfg.add_edge(exprs[1], stmt_node)
else:
# Take a guess by assuming exprs[0] is the op and any other expressions are args
for e in exprs[1:]:
if e.tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[e.tmp], stmt_node)
else:
dfg.add_edge(e, stmt_node)
elif stmt.tag == 'Ist_Store':
if exprs[0].tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[exprs[0].tmp], stmt_node)
elif exprs[0].tag == 'Iex_Const':
dfg.add_edge(exprs[0], stmt_node)
if exprs[1].tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[exprs[1].tmp], stmt_node)
else:
dfg.add_edge(exprs[1], stmt_node)
elif stmt.tag == 'Ist_Put':
if exprs[0].tag == 'Iex_RdTmp':
dfg.add_edge(tmpsnodes[exprs[0].tmp], stmt_node)
elif exprs[0].tag == 'Iex_Const':
dfg.add_edge(exprs[0], stmt_node)
#.........这里部分代码省略.........