本文整理汇总了Python中networkx.DiGraph.add_edge方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.add_edge方法的具体用法?Python DiGraph.add_edge怎么用?Python DiGraph.add_edge使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.DiGraph
的用法示例。
在下文中一共展示了DiGraph.add_edge方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_networkx
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def to_networkx(self):
"""Return a NetworkX DiGraph object representing the single linkage tree.
Edge weights in the graph are the distance values at which child nodes
merge to form the parent cluster.
Nodes have a `size` attribute attached giving the number of points
that are in the cluster.
"""
try:
from networkx import DiGraph, set_node_attributes
except ImportError:
raise ImportError('You must have networkx installed to export networkx graphs')
max_node = 2 * self._linkage.shape[0]
num_points = max_node - (self._linkage.shape[0] - 1)
result = DiGraph()
for parent, row in enumerate(self._linkage, num_points):
result.add_edge(parent, row[0], weight=row[2])
result.add_edge(parent, row[1], weight=row[2])
size_dict = {parent : row[3] for parent, row in enumerate(self._linkage, num_points)}
set_node_attributes(result, 'size', size_dict)
return result
示例2: filter_non_dependencies
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def filter_non_dependencies(nodes, get_deps_func):
node_set = set(nodes)
G = DiGraph()
G.add_nodes_from(nodes)
# process the edges based on the dependency function
for n in G:
deps = get_deps_func(n)
logging.info('%s depends on %s' % (n, deps))
for d in deps:
if d in G:
G.add_edge(n, d)
# now filter the nodes and return them
filtered_pkgs = {node for node, in_degree in G.in_degree_iter() if in_degree == 0}
# now find any strongly connected components with size greater than 1
# these will all have in degree > 0, but should still be included
glist = [g for g in strongly_connected_component_subgraphs(G, copy=False) if g.number_of_nodes() > 1]
for g in glist:
# only counts if it was the original list
nodes = [n for n in g.nodes() if n in node_set]
if len(nodes) > 0:
logging.debug('Strongly connected component: %s' % repr(nodes))
for n in nodes:
filtered_pkgs.add(n)
return filtered_pkgs
示例3: compute_dependent_cohorts
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def compute_dependent_cohorts(self, objects, deletion):
model_map = defaultdict(list)
n = len(objects)
r = range(n)
indexed_objects = zip(r, objects)
mG = self.model_dependency_graph[deletion]
oG = DiGraph()
for i in r:
oG.add_node(i)
for v0, v1 in mG.edges():
try:
for i0 in range(n):
for i1 in range(n):
if i0 != i1:
if not deletion and self.concrete_path_exists(
objects[i0], objects[i1]):
oG.add_edge(i0, i1)
elif deletion and self.concrete_path_exists(objects[i1], objects[i0]):
oG.add_edge(i0, i1)
except KeyError:
pass
components = weakly_connected_component_subgraphs(oG)
cohort_indexes = [reversed(topological_sort(g)) for g in components]
cohorts = [[objects[i] for i in cohort_index]
for cohort_index in cohort_indexes]
return cohorts
示例4: load_dependency_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [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: build_network_from_db
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def build_network_from_db():
"""
Creates a new graph with data inserted from the database,
overwrites the current graph. This function will extract all
producers from the database and iterate through their source_ratings
to build the global network. Therefore, the time to complete running this
function depends on the number of producers in the database
and the number of ratings they have set on each other.
Returns: the global network (type NetworkX DiGraph)
"""
global graph
# Users not included in graph.
producers = Producer.objects()
graph = DiGraph()
tmp = []
for p1 in producers:
try:
tmp.append(extractor.get_producer(p1.name))
except Exception:
pass
for p2 in tmp:
for k,v in p2.source_ratings.iteritems():
graph.add_edge(p2.name, k, v)
return graph
"""
示例6: sample
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def sample(n):
T = DiGraph()
alive = dict()
heights = list()
total = 0.0
for i in range(n):
alive[i] = 0.0
k = n
while k > 1:
event = exponential(1.0/binom(k, 2))
total += event
heights.append(total)
for c in alive.keys():
alive[c] += event
[a, b] = subset(alive.keys(), 2)
c = new_node(k)
alive[a]
alive[b]
T.add_edge(a, c, length = alive[a])
T.add_edge(b, c, length = alive[b])
del alive[a]
del alive[b]
alive[c] = 0.0
k -= 1
T.below = collapse(T)
T.heights = heights
return T
示例7: build_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def build_graph(alternatives, outranking, credibility=False):
"""There are some conventions to follow in this function:
1. labels (i.e. alternatives' ids) are kept in graph's dictionary (see:
graph.graph)
2. aggregated nodes (only numbers, as list) are kept under 'aggr' key in
node's dict (see: graph.nodes(data=True))
3. weights on the edges are kept under 'weight' key in edge's dict -
similarly as with nodes (see: graph.edges(data=True))
"""
graph = DiGraph() # we need directed graph for this
# creating nodes...
for i, alt in enumerate(alternatives):
graph.add_node(i)
graph.graph.update({i: alt})
# creating edges...
for i, alt in enumerate(alternatives):
relations = outranking.get(alt)
if not relations: # if graph is built from intersectionDistillation
continue
for relation in relations.items():
if relation[1] == 1.0:
weight = credibility[alt][relation[0]] if credibility else None
graph.add_edge(i, alternatives.index(relation[0]),
weight=weight)
return graph
示例8: lazy_load_trees
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def lazy_load_trees(skeleton_ids, node_properties):
""" Return a lazy collection of pairs of (long, DiGraph)
representing (skeleton_id, tree).
The node_properties is a list of strings, each being a name of a column
in the django model of the Treenode table that is not the treenode id, parent_id
or skeleton_id. """
values_list = ('id', 'parent_id', 'skeleton_id')
props = tuple(set(node_properties) - set(values_list))
values_list += props
ts = Treenode.objects.filter(skeleton__in=skeleton_ids) \
.order_by('skeleton') \
.values_list(*values_list)
skid = None
tree = None
for t in ts:
if t[2] != skid:
if tree:
yield (skid, tree)
# Prepare for the next one
skid = t[2]
tree = DiGraph()
fields = {k: v for k,v in izip(props, islice(t, 3, 3 + len(props)))}
tree.add_node(t[0], fields)
if t[1]:
# From child to parent
tree.add_edge(t[0], t[1])
if tree:
yield (skid, tree)
示例9: test_new_attributes_are_better
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def test_new_attributes_are_better():
mock_g = DiGraph()
mock_g.add_edge('A', 'B', PDC=5, TP=['C', 'D', 'E'])
method = MapGraph._new_attributes_are_better.im_func
nt.assert_true(method(mock_g, 'A', 'B', 18, []))
nt.assert_true(method(mock_g, 'A', 'B', 2, ['C', 'D', 'E']))
nt.assert_false(method(mock_g, 'A', 'B', 2, ['C', 'D', 'E', 'F']))
nt.assert_false(method(mock_g, 'A', 'B', 5, ['C', 'D', 'E']))
示例10: _graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def _graph(formula):
"""Build the implication graph"""
G = DiGraph()
for (a,b) in formula.iterclause():
G.add_edge(-a,b)
G.add_edge(-b,a)
return G
示例11: init_graph
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def init_graph(self):
#Represent the graph using adjacency lists
g = DiGraph()
g.add_nodes_from(self.vocabulary) #The keys (terms) become nodes in the graph
for x in self.vocabulary:
for y in self.vocabulary:
if self.conditional_probability(x,y) >= 0.8 and self.conditional_probability(y,x) < 0.8:
g.add_edge(x,y)
return g
示例12: add_edge
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def add_edge(self, u, v = None):
temp = self.copy()
DiGraph.add_edge(temp, u, v = v)
if not temp._is_directed_acyclic_graph():
raise ValueError("Edge (%s, %s) creates a cycle" %(u, v) )
elif not temp._is_connected():
raise ValueError("Edge (%s, %s) creates disconnected graph" %(u, v) )
else:
DiGraph.add_edge(self, u, v = v)
示例13: test_bidirectional_edges
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def test_bidirectional_edges(self):
"""A tournament must not have any pair of nodes with greater
than one edge joining the pair.
"""
G = DiGraph()
G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)])
G.add_edge(1, 0)
assert_false(is_tournament(G))
示例14: test_new_attributes_are_better
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def test_new_attributes_are_better():
mock_endg = DiGraph()
mock_endg.add_edge('A', 'B', {'PDC': 5, 'Connection': 'Unknown'})
method = EndGraph._new_attributes_are_better.im_func
nt.assert_false(method(mock_endg, 'A', 'B', {'Connection': 'Unknown'}))
nt.assert_true(method(mock_endg, 'A', 'B', {'Connection': 'Present',
'PDC': 2}))
nt.assert_false(method(mock_endg, 'A', 'B', {'EC_Source': 'U',
'EC_Target': 'X'}))
示例15: test_translate_attr_original
# 需要导入模块: from networkx import DiGraph [as 别名]
# 或者: from networkx.DiGraph import add_edge [as 别名]
def test_translate_attr_original():
mock_conn = DiGraph()
mock_conn.add_edge('B-1', 'B-2', {'EC_Source': 'N', 'EC_Target': 'Nc'})
translate = EndGraph._translate_attr_original.im_func
# PDCs that get averaged are 3 (RCs), 6 (existent conn edge), and
# 18 (non-existent conn edge).
nt.assert_equal(translate(EndGraph(), ('A-1', ['B-1', 'B-3']),
('A-2', ['B-2']), None, mock_conn),
{'EC_Source': 'N', 'EC_Target': 'Nc', 'PDC': 6.6})