本文整理汇总了Python中networkx.DiGraph.reverse方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.reverse方法的具体用法?Python DiGraph.reverse怎么用?Python DiGraph.reverse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.reverse方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_dependency_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
def load_dependency_graph(self):
dep_path = Config.get("dependency_graph")
self.log.info('Loading model dependency graph', path = dep_path)
try:
dep_graph_str = open(dep_path).read()
# joint_dependencies is of the form { Model1 -> [(Model2, src_port, dst_port), ...] }
# src_port is the field that accesses Model2 from Model1
# dst_port is the field that accesses Model1 from Model2
joint_dependencies = json.loads(dep_graph_str)
model_dependency_graph = DiGraph()
for src_model, deps in joint_dependencies.items():
for dep in deps:
dst_model, src_accessor, dst_accessor = dep
if src_model != dst_model:
edge_label = {'src_accessor': src_accessor,
'dst_accessor': dst_accessor}
model_dependency_graph.add_edge(
src_model, dst_model, edge_label)
model_dependency_graph_rev = model_dependency_graph.reverse(
copy=True)
self.model_dependency_graph = {
# deletion
True: model_dependency_graph_rev,
False: model_dependency_graph
}
self.log.info("Loaded dependencies", edges = model_dependency_graph.edges())
except Exception as e:
self.log.exception("Error loading dependency graph", e = e)
raise e
示例2: update_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
def update_from_db(self, session):
# Only allow one thread at a time to construct a fresh graph.
with self.update_lock:
checkpoint, checkpoint_time = self._get_checkpoint(session)
if checkpoint == self.checkpoint:
self.logger.debug("Checkpoint hasn't changed. Not Updating.")
return
self.logger.debug("Checkpoint changed; updating!")
new_graph = DiGraph()
new_graph.add_nodes_from(self._get_nodes_from_db(session))
new_graph.add_edges_from(self._get_edges_from_db(session))
rgraph = new_graph.reverse()
users = set()
groups = set()
for (node_type, node_name) in new_graph.nodes():
if node_type == "User":
users.add(node_name)
elif node_type == "Group":
groups.add(node_name)
user_metadata = self._get_user_metadata(session)
permission_metadata = self._get_permission_metadata(session)
service_account_permissions = all_service_account_permissions(session)
group_metadata = self._get_group_metadata(session, permission_metadata)
group_service_accounts = self._get_group_service_accounts(session)
permission_tuples = self._get_permission_tuples(session)
group_tuples = self._get_group_tuples(session)
disabled_group_tuples = self._get_group_tuples(session, enabled=False)
with self.lock:
self._graph = new_graph
self._rgraph = rgraph
self.checkpoint = checkpoint
self.checkpoint_time = checkpoint_time
self.users = users
self.groups = groups
self.permissions = {perm.permission
for perm_list in permission_metadata.values()
for perm in perm_list}
self.user_metadata = user_metadata
self.group_metadata = group_metadata
self.group_service_accounts = group_service_accounts
self.permission_metadata = permission_metadata
self.service_account_permissions = service_account_permissions
self.permission_tuples = permission_tuples
self.group_tuples = group_tuples
self.disabled_group_tuples = disabled_group_tuples
示例3: load_dependency_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
def load_dependency_graph(self):
try:
if Config.get("dependency_graph"):
self.log.debug(
"Loading model dependency graph",
path=Config.get("dependency_graph"),
)
dep_graph_str = open(Config.get("dependency_graph")).read()
else:
self.log.debug("Using default model dependency graph", graph={})
dep_graph_str = "{}"
# joint_dependencies is of the form { Model1 -> [(Model2, src_port, dst_port), ...] }
# src_port is the field that accesses Model2 from Model1
# dst_port is the field that accesses Model1 from Model2
static_dependencies = json.loads(dep_graph_str)
dynamic_dependencies = (
[]
) # Dropped Service and ServiceInstance dynamic dependencies
joint_dependencies = dict(
list(static_dependencies.items()) + dynamic_dependencies
)
model_dependency_graph = DiGraph()
for src_model, deps in joint_dependencies.items():
for dep in deps:
dst_model, src_accessor, dst_accessor = dep
if src_model != dst_model:
edge_label = {
"src_accessor": src_accessor,
"dst_accessor": dst_accessor,
}
model_dependency_graph.add_edge(
src_model, dst_model, **edge_label
)
model_dependency_graph_rev = model_dependency_graph.reverse(copy=True)
self.model_dependency_graph = {
# deletion
True: model_dependency_graph_rev,
False: model_dependency_graph,
}
self.log.debug("Loaded dependencies", edges=model_dependency_graph.edges())
except Exception as e:
self.log.exception("Error loading dependency graph", e=e)
raise e
示例4: update_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
def update_from_db(self, session):
# type: (Session) -> None
# Only allow one thread at a time to construct a fresh graph.
with self._update_lock:
checkpoint, checkpoint_time = self._get_checkpoint(session)
if checkpoint == self.checkpoint:
self._logger.debug("Checkpoint hasn't changed. Not Updating.")
return
self._logger.debug("Checkpoint changed; updating!")
start_time = datetime.utcnow()
user_metadata = self._get_user_metadata(session)
groups, disabled_groups = self._get_groups(session, user_metadata)
permissions = self._get_permissions(session)
group_grants = self._get_group_grants(session)
group_service_accounts = self._get_group_service_accounts(session)
service_account_grants = all_service_account_permissions(session)
graph = DiGraph()
graph.add_nodes_from(self._get_nodes(groups, user_metadata))
graph.add_edges_from(self._get_edges(session))
rgraph = graph.reverse()
grants_by_permission = self._get_grants_by_permission(
graph, group_grants, service_account_grants
)
with self.lock:
self._graph = graph
self._rgraph = rgraph
self.checkpoint = checkpoint
self.checkpoint_time = checkpoint_time
self.user_metadata = user_metadata
self._groups = groups
self._disabled_groups = disabled_groups
self._permissions = permissions
self._group_grants = group_grants
self._group_service_accounts = group_service_accounts
self._service_account_grants = service_account_grants
self._grants_by_permission = grants_by_permission
duration = datetime.utcnow() - start_time
stats.log_rate("graph_update_ms", int(duration.total_seconds() * 1000))
示例5: __init__
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [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()
示例6: update_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
def update_from_db(self, session):
checkpoint, checkpoint_time = self._get_checkpoint(session)
if checkpoint == self.checkpoint:
logging.debug("Checkpoint hasn't changed. Not Updating.")
return
logging.debug("Checkpoint changed; updating!")
new_graph = DiGraph()
new_graph.add_nodes_from(self._get_nodes_from_db(session))
new_graph.add_edges_from(self._get_edges_from_db(session))
rgraph = new_graph.reverse()
users = set()
groups = set()
for (node_type, node_name) in new_graph.nodes():
if node_type == "User":
users.add(node_name)
elif node_type == "Group":
groups.add(node_name)
user_metadata = self._get_user_metadata(session)
permission_metadata = self._get_permission_metadata(session)
group_metadata = self._get_group_metadata(session, permission_metadata)
with self.lock:
self._graph = new_graph
self._rgraph = rgraph
self.checkpoint = checkpoint
self.checkpoint_time = checkpoint_time
self.users = users
self.groups = groups
self.permissions = {perm.permission
for perm_list in permission_metadata.values()
for perm in perm_list}
self.user_metadata = user_metadata
self.group_metadata = group_metadata
self.permission_metadata = permission_metadata
示例7: VariableDictionary
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
#.........这里部分代码省略.........
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 )
var.strerror = errstr
return self.recalculateDependent(name)
def setParentStrValue(self, name, strvalue):
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.parentValue = result
var.parentStrvalue = 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 )
var.strerror = errstr
return self.recalculateDependent(name)
def setValue(self, name, value):
"""update the variable value with value and recalculate as necessary.
This is done using existing dependencies."""
var = self[name]
try:
var.value = value
var.strvalue = ""
var.strerror = None
except KeyError as e:
var.strerror = str(e)
return self.recalculateDependent(name, returnResult=True)
def setParentValue(self, name, value):
"""update the variable value with value and recalculate as necessary.
This is done using existing dependencies."""
var = self[name]
try:
var.parentValue = value
var.parentStrvalue = ""
var.strerror = None
except KeyError as e:
var.strerror = str(e)
return self.recalculateDependent(name, returnResult=True)
def setEncodingIndex(self, index, encoding):
self.at(index).encoding = None if encoding == 'None' else str(encoding)
def setEnabledIndex(self, index, enabled):
self.at(index).enabled = enabled
def recalculateDependent(self, node, returnResult=False):
if self.dependencyGraph.has_node(node):
generator = dfs_preorder_nodes(self.dependencyGraph, node)
next(generator ) # skip the first, that is us
nodelist = list(generator) # make a list, we need it twice
result = [ self.recalculateNode(node) for node in nodelist ]
return (nodelist, result) if returnResult else nodelist # return which ones were re-calculated, so gui can be updated
return (list(), list()) if returnResult else list()
def recalculateNode(self, node):
if node in self:
var = self[node]
if hasattr(var, 'strvalue'):
try:
var.value = self.expression.evaluate(var.strvalue, self.valueView)
var.strerror = None
except (KeyError, ValueError) as e:
var.strerror = str(e)
except Exception as e:
errstr = 'Unable to evaluate the expression \'{0}\'.'.format(var.strvalue)
logging.getLogger(__name__).warning( errstr )
var.strerror = errstr
else:
logging.getLogger(__name__).warning("variable {0} does not have strvalue. Value is {1}".format(var, var.value))
return var.value
return None
def recalculateAll(self):
g = self.dependencyGraph.reverse()
for node, indegree in g.in_degree_iter():
if indegree==0:
for calcnode in dfs_postorder_nodes(g, node):
self.recalculateNode(calcnode)
def bareDictionaryCopy(self):
return SequenceDict( self )
示例8: reverse_weights
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import reverse [as 别名]
def reverse_weights(g:nx.DiGraph, weight='weight'):
g = g.reverse()
for s, t in g.edges_iter():
e = g[s][t]
e[weight] = -e[weight]
return g