本文整理汇总了Python中networkx.DiGraph.edges方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.edges方法的具体用法?Python DiGraph.edges怎么用?Python DiGraph.edges使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.edges方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: maximal_non_branching_paths
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def maximal_non_branching_paths(graph: nx.DiGraph) -> list:
paths = []
for node in graph:
if not is_in_1_out_1(graph, node) and graph.out_degree(node) > 0:
for v, w in graph.edges(node):
non_branching_path = [v, w]
while is_in_1_out_1(graph, w):
u = graph.edges(w)[0][1]
non_branching_path.append(u)
w = u
paths.append(non_branching_path)
return paths + isolated_cycles(graph)
示例2: mean_weight
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def mean_weight(self):
edges=DiGraph.edges(self,data='weight')
sum=0.0
for edge in edges:
sum=sum+edge[2]
mean_weight=sum/float(len(edges))
return mean_weight
示例3: build_dict_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def build_dict_graph(nodes: nx.DiGraph) -> dict:
graph = {}
for left, right in nodes.edges():
if left not in graph:
graph[left] = []
graph[left].append(right)
return graph
示例4: load_dependency_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [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
示例5: test_remove_node
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def test_remove_node():
mock_mapp = DiGraph()
mock_mapp.add_node('X')
mock_mapp.add_edges_from([('A', 'B', {'TP': ['X']}),
('B', 'C', {'TP': ['Y']})])
MapGraph.remove_node.im_func(mock_mapp, 'X')
nt.assert_equal(mock_mapp.edges(), [('B', 'C')])
示例6: common_edge_ratio
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def common_edge_ratio(ref_user_connections, eval_user_connections, is_directed=False):
""" caulcalate the fraction of common edges fraction out of union of two graphs
Parameters:
==========
ref_user_connections: a list of edges
eval_user_connections: a list of edges
is_directed: boolean,
False (default): edges forms an undirected graph
True: edges forms a directed graph
"""
ref_user_connections = _normalize_connections(ref_user_connections, is_directed)
eval_user_connections = _normalize_connections(eval_user_connections, is_directed)
if is_directed:
ref_graph, eval_graph = DiGraph(), DiGraph()
else:
ref_graph, eval_graph = Graph(), Graph()
ref_graph.add_edges_from(ref_user_connections)
eval_graph.add_edges_from(eval_user_connections)
ref_edges, eval_edges = ref_graph.edges(), eval_graph.edges()
tot_common = sum([1 if edge in ref_edges else 0 for edge in eval_edges])
union_size = len(ref_edges) + len(eval_edges) - tot_common
return tot_common / union_size
示例7: outcoming_edges
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def outcoming_edges(graph: nx.DiGraph, node: int or str) -> (int or str, int or str):
edges = []
for node_out, node_in in graph.edges():
if type(node) == str:
if node_out == str(node):
edges.append((str(node_out), str(node_in)))
else:
if node_out == node:
edges.append((node_out, node_in))
return edges
示例8: filter_edges
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [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])
示例9: incidence_matrix
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def incidence_matrix(graph: nx.DiGraph) -> scs.csc_matrix:
edges = graph.edges()
nodes = sorted(graph.nodes())
result = scs.lil_matrix((nodes.__len__(), edges.__len__()))
for i in range(nodes.__len__()):
for j in range(edges.__len__()):
u, v = edges[j]
if nodes[i] == u:
result[i, j] = 1
elif nodes[i] == v:
result[i, j] = -1
return result.tocsc()
示例10: median_weight
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def median_weight(self):
edges=DiGraph.edges(self,data='weight')
mlist=[]
for edge in edges:
mlist.append(edge[2])
n=len(mlist)
mlist=sorted(mlist)
if n%2==0:
x=mlist[round(n/2)]+mlist[round(n/2)+1]
median_weight=float(x)/float(2)
else:
median_weight=mlist[round(n/2)]
return median_weight
示例11: load_dependency_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [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
示例12: main
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def main(access_token, package_name, max_depth):
graph = DiGraph()
graphcommons = GraphCommons(access_token)
import_package_dependencies(graph, package_name, max_depth=max_depth)
signals = []
for (node, data) in graph.nodes(data=True):
if data['type'] == 'PACKAGE':
reference = "https://www.npmjs.com/package/%s" % node
else:
reference = 'https://www.npmjs.com/~%s' % node
signals.append(Signal(
action="node_create",
name=node,
type=data['type'],
reference=reference
))
for source, target, data in graph.edges(data=True):
signals.append(Signal(
action="edge_create",
from_name=source,
from_type=graph.node[source]['type'],
to_name=target,
to_type=graph.node[target]['type'],
name=data['type'],
weight=1
))
created_graph = graphcommons.new_graph(
name="Dependency Network of %s" % package_name,
description="Dependency Network of %s Package" % package_name,
signals=signals
)
print 'Created Graph URL:'
print 'https://graphcommons.com/graphs/%s' % created_graph.id
示例13: isolated_cycles
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def isolated_cycles(graph: nx.DiGraph) -> list:
cycles = []
cycled_nodes = set()
for node in graph:
w = node
cycle = [w]
is_isolated_cycle = True
while is_isolated_cycle:
if not is_in_1_out_1(graph, w) or w in cycled_nodes:
is_isolated_cycle = False
elif w == node:
break
else:
u = graph.edges(w)[0][1]
cycle.append(u)
w = u
if is_isolated_cycle:
cycles.append(cycle)
cycled_nodes.add(node)
return cycles
示例14: _update_one_step
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
def _update_one_step(self):
""" experiment advance by one iteration """
max_iter = self._set_info["max_iter"]
if self._is_directed:
old_graph, new_graph = DiGraph(), DiGraph()
else:
old_graph, new_graph = Graph(), Graph()
old_graph.add_edges_from(self._recommender._user_connections)
old_tot_conns = len(old_graph.edges())
new_connections = []
tot_suggestions = 0
tot_rejections = 0
if self._iteration < max_iter:
start_time = datetime.now()
uniq_user_ids = self._recommender._user_ids
for ii, user_id in enumerate(uniq_user_ids):
# retrieve recommended users
# if user_id in self._rejected_user_dict:
# block_list = self._rejected_user_dict[user_id]
# else:
# block_list = []
suggestions = self._recommender.gen_suggestion(user_id)
accepted, rejected = self._clicker.click(user_id, suggestions)
tot_suggestions += len(suggestions)
tot_rejections += len(rejected)
# append new connections
if len(accepted) > 0:
pairs = [[user_id, new_friend] for new_friend in accepted]
if len(new_connections) == 0:
new_connections = pairs
else:
new_connections.extend(pairs)
# track rejected users
# for some clicker simulator which, yeild rejected of empty
# all the time to allow re-suggestions on recommended users
if len(rejected) > 0:
if user_id in self._rejected_user_dict:
self._rejected_user_dict[user_id].extend(rejected)
else:
self._rejected_user_dict[user_id] = rejected
# consolidate new connections
new_connections = array(new_connections)
# tracking experiment progress
self._iteration += 1
if new_connections.shape[0] > 0:
# update simulator's connection data
# self.load_init_user_connections(updated_user_connections)
self._recommender.add_new_connections(new_connections)
self._recommender.update()
self._no_growth_counter = 0
new_graph.add_edges_from(self._recommender._user_connections)
new_tot_conns = len(new_graph.edges())
new_added_conns = new_tot_conns - old_tot_conns
duration = datetime.now() - start_time
total_cost = duration.total_seconds()
# collect evaluation scores
self._evaluator.load_eval_user_connections(self._recommender._user_connections)
eval_score = self._evaluator.get_score()
cand_size = 0
recommender_memory = copy.deepcopy(self._recommender._ordered_cand_dict)
for k in recommender_memory.keys():
cand_size += len(recommender_memory[k])
# measure the network
if self._is_directed:
now_graph = DiGraph()
else:
now_graph = Graph()
if self._total_edges_ref is None:
if self._is_directed:
ref_graph = DiGraph()
else:
ref_graph = Graph()
ref_graph.add_edges_from(self._evaluator._ref_user_connections)
self._total_edges_ref = len(ref_graph.edges())
now_graph.add_edges_from(self._recommender._user_connections)
now_num_edges = len(now_graph.edges())
ref_num_edges = self._total_edges_ref
# collect information
exp_record = {"iteration": self._iteration,
"start_time": start_time.strftime("%Y-%m-%d %H:%M:%S"),
#.........这里部分代码省略.........
示例15: MacroManager
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import edges [as 别名]
#.........这里部分代码省略.........
the value of m2 we use the value of m1.
Args:
m1 (string):
The name of the param used.
m2 (string):
The name of the param being specified.
Raises:
MacroException:
If the order of sections (test -> ds -> xp) is not respected.
"""
# Check if dependency is correct
if m1 in self.ds_params:
if m2 in self.test_macros:
logger.error("Not allowed dependency: ds -> test")
raise MacroException("Not allowed dependency: ds -> test")
elif m1 in self.xp_params:
if m2 in self.test_macros:
logger.error("Not allowed dependency: xp -> test")
raise MacroException("Not allowed dependency: xp -> test")
elif m2 in self.ds_params:
logger.error("Not allowed dependency: xp -> ds")
raise MacroException("Not allowed dependency: xp -> ds")
# Add dependency
self.dep_graph.add_edge(m1, m2)
def sort_macros(self):
"""Sort macros respecting dependencies.
Raises:
MacroException:
If there are cycles in dependencies between macros.
"""
# Filter out unused test variables
self.__filter_unused_test_macros()
# Sort ds and xp macros
try:
self.sorted_ds_macros = \
topological_sort(self.dep_graph.subgraph(self.ds_params))
self.sorted_xp_macros = \
topological_sort(self.dep_graph.subgraph(self.xp_params))
except NetworkXUnfeasible:
raise MacroException("Macros do not follow a DAG")
logger.info("Dependencies = " + str(self.dep_graph.edges()))
logger.info("Test macros = " + str(self.sorted_test_macros))
logger.info("Dataset macros = " + str(self.sorted_ds_macros))
logger.info("Experiment macros = " + str(self.sorted_xp_macros))
def _replace_macros_from_list(self, list_macros, value):
"""Replace the macros given in the list within the value if present.
Args:
list_macros (dict):
The list of macros to replace and their respective values.
value (string):
The value where to do the replacement.
"""
new_value = value
for m in list_macros:
new_value = new_value.replace("${" + m + "}", str(list_macros[m]))
return new_value
def replace_ds_macros(self, comb):
"""Replace macros in ds combination.
Args:
comb (dict):
The combination of parameters.
"""
list_macros = self.test_macros
for m in self.sorted_ds_macros:
comb[m] = self._replace_macros_from_list(list_macros, comb[m])
list_macros[m] = comb[m]
def replace_xp_macros(self, comb):
"""Replace macros in xp combination.
Args:
comb (dict):
The combination of parameters.
"""
list_macros = self.test_macros
for m in self.sorted_ds_macros:
comb[m] = self._replace_macros_from_list(list_macros, comb[m])
list_macros[m] = comb[m]
for m in self.sorted_xp_macros:
comb[m] = self._replace_macros_from_list(list_macros, comb[m])
list_macros[m] = comb[m]