本文整理汇总了Python中networkx.DiGraph.copy方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.copy方法的具体用法?Python DiGraph.copy怎么用?Python DiGraph.copy使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.copy方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import copy [as 别名]
def __init__(self, path, version="0"):
g = DiGraph()
gaged_reaches = []
db = openFile(path, "r")
table = db.getNode("/", "networks/network" + str(version))
reaches = {}
# read data out of file
for row in table:
if str(row["ComID"]) != "-1":
reaches[row["ComID"]] = Reach(self, row)
else:
reaches[row["ComID"]] = "-1"
g.add_edge(Reach(self, row), "-1")
if row["MonitoredFlag"] == "1":
gaged_reaches.append(row["ComID"])
db.close()
# make network
for comid in reaches.keys():
to_comID = reaches[comid]._ToComID
if to_comID != "-1":
g.add_edge(reaches[comid], reaches[to_comID])
else:
g.add_edge(reaches[comid], -1)
self._g_unbroken = g.copy()
self._g_unbroken_reverse = self._g_unbroken.reverse()
# break upstream of monitored reaches
for i in gaged_reaches:
if i != "-1":
up = g.predecessors(reaches[i])
for j in up:
if j != "-1":
g.delete_edge(j, reaches[i])
else:
g.delete_edge(j, "-1")
self._g = g
self._g_rev = g.reverse()
self._version = str(version)
self._path = str(path)
self._reaches = reaches
db.close()
示例2: VariableDictionary
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import copy [as 别名]
class VariableDictionary(SequenceDict):
"""Ordered Dictionary to hold variable values. It maintains a dependency graph
to check for cycles and to recalculate the necessary values when one of the fields is updated"""
expression = Expression()
def __init__(self, *args, **kwargs):
self.valueView = VariableDictionaryView(self)
self.dependencyGraph = DiGraph()
self.globaldict = dict()
super(VariableDictionary, self).__init__(*args, **kwargs)
def __getstate__(self):
return dict((key, value) for key, value in self.__dict__ if key not in ['globaldict'])
def __reduce__(self):
theclass, theitems, inst_dict = super(VariableDictionary, self).__reduce__()
inst_dict.pop('globaldict', None)
return theclass, theitems, inst_dict
def setGlobaldict(self, globaldict):
self.globaldict = globaldict
def calculateDependencies(self):
self.dependencyGraph = DiGraph() # clear the old dependency graph in case parameters got removed
for name, var in self.items():
if hasattr(var, 'strvalue'):
try:
var.value, dependencies = self.expression.evaluate(var.strvalue, self.valueView, listDependencies=True)
self.addDependencies(self.dependencyGraph, dependencies, name)
var.strerror = None
except (KeyError, ValueError, ZeroDivisionError) as e:
logging.getLogger(__name__).warning( str(e) )
var.strerror = str(e)
except Exception as e:
errstr = "Unable to evaluate the expression '{0}' for variable '{1}'.".format(var.strvalue,var.name)
logging.getLogger(__name__).warning( errstr )
var.strerror = errstr
else:
var.strerror = None
self.recalculateAll()
def merge(self, variabledict, globaldict=None, overwrite=False, linkNewToParent=False ):
if globaldict is not None:
self.globaldict = globaldict
for name in list(self.keys()):
if name not in variabledict:
self.pop(name)
for name, var in variabledict.items():
if var.type in ['parameter', 'address'] and (name not in self or overwrite):
self[name] = copy.deepcopy(var)
if linkNewToParent:
self[name].useParentValue = True
self.sortToMatch( list(variabledict.keys()) )
self.calculateDependencies()
def __setitem__(self, key, value):
super(VariableDictionary, self).__setitem__(key, value)
if hasattr(value, 'strvalue'):
self.setStrValue( key, value.strvalue )
def __deepcopy__(self, memo):
new = type(self)()
new.globaldict = self.globaldict
new.update( (name, copy.deepcopy(value)) for name, value in list(self.items()))
new.dependencyGraph = self.dependencyGraph
#calculateDependencies()
return new
def addDependencies(self, graph, dependencies, name):
"""add all the dependencies to name"""
for dependency in dependencies:
self.addEdgeNoCycle(graph, dependency, name)
def addEdgeNoCycle(self, graph, first, second ):
"""add the dependency to the graph, raise CyclicDependencyException in case of cyclic dependencies"""
graph.add_edge(first, second)
cycles = simple_cycles( graph )
for cycle in cycles:
raise CyclicDependencyException(cycle)
def setStrValueIndex(self, index, strvalue):
return self.setStrValue( self.keyAt(index), strvalue)
def setStrValue(self, name, strvalue):
"""update the variable value with strvalue and recalculate as necessary"""
var = self[name]
try:
result, dependencies = self.expression.evaluate(strvalue, self.valueView, listDependencies=True )
graph = self.dependencyGraph.copy() # make a copy of the graph. In case of cyclic dependencies we do not want o leave any changes
for edge in list(graph.in_edges([name])): # remove all the inedges, dependencies from other variables might be gone
graph.remove_edge(*edge)
self.addDependencies(graph, dependencies, name) # add all new dependencies
var.value = result
var.strvalue = strvalue
self.dependencyGraph = graph
var.strerror = None
except KeyError as e:
var.strerror = str(e)
except Exception as e:
errstr = "Unable to evaluate the expression '{0}' for variable '{1}'.".format(strvalue,name)
logging.getLogger(__name__).warning( errstr )
#.........这里部分代码省略.........