本文整理汇总了Python中networkx.classes.digraph.DiGraph.add_edges_from方法的典型用法代码示例。如果您正苦于以下问题:Python DiGraph.add_edges_from方法的具体用法?Python DiGraph.add_edges_from怎么用?Python DiGraph.add_edges_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx.classes.digraph.DiGraph
的用法示例。
在下文中一共展示了DiGraph.add_edges_from方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_example_1
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_example_1():
# input
g = DiGraph()
g.add_edges_from([[1, 2], [1, 3], [2, 4], [3, 4]])
g.node[1]['r'] = 1
g.node[2]['r'] = 1
g.node[3]['r'] = 1.5
g.node[4]['r'] = 1
g[1][2]['c'] = 2
g[1][3]['c'] = 1
g[2][4]['c'] = 1
g[3][4]['c'] = 3
U = range(6) # 0...5
expected_edge_list = [
[],
[(1, 3)],
[(1, 3)], # DiGraph([(1, 2)])
[(1, 2), (1, 3)],
[(1, 2), (1, 3), (2, 4)],
[(1, 2), (1, 3), (2, 4)]
]
return g, U, expected_edge_list
示例2: get_example_2
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_example_2():
# input
g = DiGraph()
g.add_edges_from([[1, 2], [1, 3], [2, 4], [3, 4]])
g.node[1]['r'] = 1
g.node[2]['r'] = 1
g.node[3]['r'] = 1.5
g.node[4]['r'] = 1
g[1][2]['c'] = 0.021
g[1][3]['c'] = 0.011
g[2][4]['c'] = 0.009
g[3][4]['c'] = 0.03
U = [float(i) / 100 for i in xrange(6)] # 0...5
# expected value
expected_edge_list = [
[],
[(1, 3)],
[(1, 3)],
[(1, 2), (1, 3)],
[(1, 2), (1, 3), (2, 4)],
[(1, 2), (1, 3), (2, 4)]
]
return (g, U, expected_edge_list)
示例3: create_fair_graph
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def create_fair_graph(self,system):
G = DiGraph()
G.add_edges_from(self.edges(data=True))
controls = nx.get_edge_attributes(self,'control')
unfair_cycles = []
for cycle in nx.simple_cycles(G):
edges = [(cycle[i],cycle[(i+1)%len(cycle)]) for i in range(len(cycle))]
trace = [(c[0],controls[c].values()) for c in edges]
nbre_controls = [range(len(t[1])) for t in trace]
control_configuration = itertools.product(*nbre_controls)
for conf in control_configuration:
current_trace = [(t[0],t[1][conf[i]]) for i,t in enumerate(trace)]
if not self.is_cycle_fair(system,current_trace):
unfair_cycles.append(current_trace)
print "Unfair cycles ",unfair_cycles
示例4: make_test_graph
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def make_test_graph():
''' (4) 6
^ ^
| X |
(3) 5
^ ^
\ /
[2]
^
|
(1)
'''
web = DiGraph()
web.add_edges_from([(1,2), (2,3), (3,4), (2,5), (3,6), (5,6), (5,4)])
return web
示例5: get_example_5
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_example_5():
g = DiGraph()
g.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4),
(2, 4), (2, 5), (2, 6)])
for s, t in g.edges():
g[s][t]['c'] = 1
g[1][4]['c'] = 0
g[2][4]['c'] = 0
g[2][6]['c'] = 3
for n in g.nodes():
g.node[n]['r'] = 1
g.node[3]['r'] = 10
g.node[4]['r'] = 100
g.node[5]['r'] = 11
U = [10]
# sub-optimal answer actually
expected_edge_set = [[(0, 2), (2, 4), (2, 5), (2, 6)]]
return (g, U, expected_edge_set)
示例6: get_example_4
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_example_4():
g = DiGraph()
g.add_edges_from([(0, 1), (1, 2), (2, 3), (2, 14), # tree 1
(2, 15), (3, 16), (3, 17),
(0, 4), (4, 5), (4, 6), # tree 2
(5, 11), (6, 11), (6, 12), (6, 13),
(0, 7), (7, 8), (7, 9), # tree 3
(8, 10), (8, 11), (9, 12), (9, 13)])
for s, t in g.edges():
g[s][t]['c'] = 1
for n in g.nodes():
g.node[n]['r'] = 1
g.node[10]['r'] = 2
U = [7]
expected_edge_set = [
[(0, 7), (7, 8), (7, 9), # tree 3
(8, 10), (8, 11), (9, 12), (9, 13)]
]
return (g, U, expected_edge_set)
示例7: get_example_6
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_example_6():
# IN-OPTIMAL CASE
g = DiGraph()
g.add_edges_from([(0, 1), (0, 2), (1, 3),
(1, 4), (2, 4), (2, 5)])
for s, t in g.edges():
g[s][t]['c'] = 0
g[1][3]['c'] = 4
g[1][4]['c'] = 4
g[2][4]['c'] = 2
g[2][5]['c'] = 1
for n in g.nodes():
g.node[n]['r'] = 0
g.node[3]['r'] = 1
g.node[4]['r'] = 100
g.node[5]['r'] = 1
U = [7]
# sub-optimal answer actually
expected_edge_set = [[(0, 2), (2, 4), (2, 5)]]
return (g, U, expected_edge_set)
示例8: test_variance_based_cost
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def test_variance_based_cost():
D = {'u': {}, 'v': {10: {'x', 'dum'}}, 'w': {12: {'y'}}}
G = DiGraph()
G.add_edges_from([('u', 'v'),
('u', 'w'),
('v', 'dum'),
('dum', 'x'),
('w', 'y')])
G.node['dum']['dummy'] = True
reprs = np.array([[0, 1],
[1, 0],
[0, 1],
[1, 1],
[0, 0]])
real_nodes = ['u', 'v', 'w', 'x', 'y']
for r, n in zip(reprs, real_nodes):
G.node[n]['r'] = r
n = 'u'
children = [(10, 'v'),
(12, 'w')]
actual = get_all_nodes(G, n, D, children, ignore_dummy=True)
expected = real_nodes
assert_equal(sorted(expected), sorted(actual))
cost_func = make_variance_cost_func(euclidean, 'r')
actual = cost_func(n, D, G,
children)
mean_vec = np.mean(reprs, axis=0)
expected = np.sum([euclidean(mean_vec, v)
for v in reprs])
np.testing.assert_almost_equal(expected, actual)
# with fixed_point
cost_func_fp = make_variance_cost_func(euclidean, 'r', fixed_point=2)
actual = cost_func_fp(n, D, G,
children)
assert_equal(int(expected*100), actual)
示例9: test_find_connecting_nodes_good_sourceDep
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def test_find_connecting_nodes_good_sourceDep(self):
''' (4) 6
^ ^
| X |
(3) 5
^ ^
\ /
[2]
^
|
(1)
'''
web = DiGraph()
web.add_edges_from([(1,2), (2,3), (3,4), (2,5), (3,6), (5,6), (5,4)])
inp = (1, 3, 4)
out = (2,)
(_, _, cn_nodes, _) = _research_calculation_routes(web, inp, out)
all_out = {1,4,3}
all_in = {2,5,6}
self.assertTrue(cn_nodes - all_out == cn_nodes, cn_nodes)
self.assertTrue(all_in & cn_nodes == all_in, cn_nodes)
示例10: get_example_3
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_example_3():
"""get a binarized example, whose original graph is
more complicated than the above example
"""
g = DiGraph()
g.add_nodes_from(range(1, 10))
g.add_edges_from([(1, 2), (1, 3), (1, 7),
(2, 4), (2, 5), (2, 6),
(2, 7), (3, 8), (3, 9)])
rewards = range(1, 10)
for r, n in zip(rewards, g.nodes()):
g.node[n]['r'] = r
# all edges have cost 2 except 1 -> 2 and 1 -> 3(cost 1)
for s, t in g.edges():
g[s][t]['c'] = 2
g[1][2]['c'] = 1
g[1][3]['c'] = 1
g = binarize_dag(g,
vertex_weight_key='r',
edge_weight_key='c',
dummy_node_name_prefix='d_')
# parameters and expected output
U = [0, 2, 3, 4, 100]
expected_edges_set = [
[],
[(1, 7)],
[(1, 'd_1'), ('d_1', 3), (3, 9)],
[(1, 'd_1'), ('d_1', 3), (3, 9), ('d_1', 2)],
# (1, 7) removed to make it a tree
list(set(g.edges()) - set([(1, 7)]))
]
return (g, U, expected_edges_set)
示例11: get_variance_example_1
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def get_variance_example_1():
g = DiGraph()
g.add_edges_from([
(0, 1), (0, 2),
(2, 3), (3, 4),
(2, 'dummy'),
('dummy', 5)
])
g.node['dummy']['dummy'] = True
for n in (0, 1, 2, 5): # topic 1
g.node[n]['repr'] = np.array([0, 0])
for n in (3, 4): # topic 2
g.node[n]['repr'] = np.array([1, 1])
for n in g.nodes_iter():
g.node[n]['r'] = 1
# correct is (0, 1, 2, 5) for cost 0
U = [0, 42]
expected_edge_set = [
set(g.edges()) - {(2, 3), (3, 4)},
set(g.edges())
]
return (g, U, expected_edge_set)
示例12: syn_plan_comb
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def syn_plan_comb(prod_mdp, S_fi, gamma, alpha):
#----Synthesize combined optimal plan prefix and suffix
#----with bounded risk and minimal mean total cost----
print "===========[plan prefix synthesis starts]==========="
Sf = set()
for mec in S_fi:
Sf.update(mec[0]) # mec = (sf, ip, act)
delta = 1.0
for init_node in prod_mdp.graph['initial']:
path_init = single_source_shortest_path(prod_mdp, init_node)
print 'Reachable from init size: %s' %len(path_init.keys())
if not set(path_init.keys()).intersection(Sf):
print "Initial node can not reach Sf"
return None, None, None, None, None, None, None, None
Sn = set(path_init.keys()).difference(Sf)
#----find bad states that can not reach MEC
simple_digraph = DiGraph()
simple_digraph.add_edges_from(((v,u) for u,v in prod_mdp.edges()))
reachable_set = set()
ip_set = set()
for mec in S_fi:
ip = mec[1]
path = single_source_shortest_path(simple_digraph, random.sample(ip,1)[0])
reachable_set.update(set(path.keys()))
ip_set.update(ip)
print 'States that can reach Sf, size: %s' %str(len(reachable_set))
Sd = Sn.difference(reachable_set)
Sr = Sn.intersection(reachable_set)
# #--------------
print 'Sn size: %s; Sd inside size: %s; Sr inside size: %s' %(len(Sn),len(Sd), len(Sr))
# ---------solve lp------------
print '-----'
print 'Gurobi starts now'
print '-----'
try:
#if True:
model = Model('plan_comb')
#--------------------
#prefix variable
Y = defaultdict(float)
# create variables
for s in Sr:
for u in prod_mdp.node[s]['act'].copy():
Y[(s,u)] = model.addVar(vtype=GRB.CONTINUOUS,lb=0, name='y[(%s, %s)]' %(s, u))
print 'Prefix Y variables added'
#--------------------
#suffix variables
Z = defaultdict(float)
for mec in S_fi:
sf = mec[0]
ip = mec[1]
act = mec[2].copy()
for s in sf:
for u in act[s]:
Z[(s,u)] = model.addVar(vtype=GRB.CONTINUOUS,lb=0, name='z[(%s, %s)]' %(s, u))
print 'Suffix Z variables added'
model.update()
# set objective
obj = 0
for s in Sr:
for t in prod_mdp.successors_iter(s):
prop = prod_mdp.edge[s][t]['prop'].copy()
for u in prop.iterkeys():
pe = prop[u][0]
ce = prop[u][1]
obj += alpha*Y[(s,u)]*pe*ce
for mec in S_fi:
sf = mec[0]
ip = mec[1]
act = mec[2].copy()
for s in sf:
for u in act[s]:
for t in prod_mdp.successors_iter(s):
prop = prod_mdp.edge[s][t]['prop'].copy()
if u in prop.keys():
pe = prop[u][0]
ce = prop[u][1]
obj += (1.0-alpha)*Z[(s,u)]*pe*ce
model.setObjective(obj, GRB.MINIMIZE)
print 'alpha*Prefix + (1.0-alpha)*Suffix cost Objective function set'
# add constraints
#------------------------------
y_to_sd = 0.0
y_to_sf = 0.0
for s in Sr:
for t in prod_mdp.successors_iter(s):
if t in Sd:
prop = prod_mdp.edge[s][t]['prop'].copy()
for u in prop.iterkeys():
pe = prop[u][0]
y_to_sd += Y[(s,u)]*pe
elif t in sf:
prop = prod_mdp.edge[s][t]['prop'].copy()
for u in prop.iterkeys():
pe = prop[u][0]
y_to_sf += Y[(s,u)]*pe
model.addConstr(y_to_sf+y_to_sd >= delta, 'sum_out')
model.addConstr(y_to_sf >= (1.0-gamma)*(y_to_sf+y_to_sd), 'risk')
print 'Prefix risk constraint added'
#--------------------
#.........这里部分代码省略.........
示例13: syn_plan_prefix
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def syn_plan_prefix(prod_mdp, MEC, gamma):
#----Synthesize optimal plan prefix to reach accepting MEC or SCC----
#----with bounded risk and minimal expected total cost----
print "===========[plan prefix synthesis starts]==========="
sf = MEC[0]
ip = MEC[1] #force convergence to ip
delta = 1.0
for init_node in prod_mdp.graph['initial']:
path_init = single_source_shortest_path(prod_mdp, init_node)
print 'Reachable from init size: %s' %len(path_init.keys())
if not set(path_init.keys()).intersection(sf):
print "Initial node can not reach sf"
return None, None, None, None, None, None
Sn = set(path_init.keys()).difference(sf)
#----find bad states that can not reach MEC
simple_digraph = DiGraph()
simple_digraph.add_edges_from(((v,u) for u,v in prod_mdp.edges()))
path = single_source_shortest_path(simple_digraph, random.sample(ip,1)[0])
reachable_set = set(path.keys())
print 'States that can reach sf, size: %s' %str(len(reachable_set))
Sd = Sn.difference(reachable_set)
Sr = Sn.intersection(reachable_set)
# #--------------
print 'Sn size: %s; Sd inside size: %s; Sr inside size: %s' %(len(Sn),len(Sd), len(Sr))
# ---------solve lp------------
print '-----'
print 'Gurobi starts now'
print '-----'
try:
#if True:
Y = defaultdict(float)
model = Model('plan_prefix')
# create variables
for s in Sr:
for u in prod_mdp.node[s]['act'].copy():
Y[(s,u)] = model.addVar(vtype=GRB.CONTINUOUS,lb=0, name='y[(%s, %s)]' %(s, u))
model.update()
print 'Variables added'
# set objective
obj = 0
for s in Sr:
for t in prod_mdp.successors_iter(s):
prop = prod_mdp.edge[s][t]['prop'].copy()
for u in prop.iterkeys():
pe = prop[u][0]
ce = prop[u][1]
obj += Y[(s,u)]*pe*ce
model.setObjective(obj, GRB.MINIMIZE)
print 'Objective function set'
# add constraints
#------------------------------
y_to_sd = 0.0
y_to_sf = 0.0
for s in Sr:
for t in prod_mdp.successors_iter(s):
if t in Sd:
prop = prod_mdp.edge[s][t]['prop'].copy()
for u in prop.iterkeys():
pe = prop[u][0]
y_to_sd += Y[(s,u)]*pe
elif t in sf:
prop = prod_mdp.edge[s][t]['prop'].copy()
for u in prop.iterkeys():
pe = prop[u][0]
y_to_sf += Y[(s,u)]*pe
model.addConstr(y_to_sf+y_to_sd >= delta, 'sum_out')
model.addConstr(y_to_sf >= (1.0-gamma)*(y_to_sf+y_to_sd), 'risk')
print 'Risk constraint added'
#--------------------
for t in Sr:
node_y_in = 0.0
node_y_out = 0.0
for u in prod_mdp.node[t]['act']:
node_y_out += Y[(t,u)]
for f in prod_mdp.predecessors_iter(t):
if f in Sr:
prop = prod_mdp.edge[f][t]['prop'].copy()
for uf in prop.iterkeys():
node_y_in += Y[(f,uf)]*prop[uf][0]
if t == init_node:
model.addConstr(node_y_out == 1.0 + node_y_in, 'init_node_flow_balance')
else:
model.addConstr(node_y_out == node_y_in, 'middle_node_flow_balance')
print 'Initial node flow balanced'
print 'Middle node flow balanced'
#----------------------
# solve
print '--optimization starts--'
model.optimize()
# print '--variables value--'
# for v in model.getVars():
# print v.varName, v.x
# print 'obj:', model.objVal
#------------------------------
# compute plan prefix given the LP solution
plan_prefix = dict()
for s in Sr:
norm = 0
U = []
#.........这里部分代码省略.........
示例14: subgraph
# 需要导入模块: from networkx.classes.digraph import DiGraph [as 别名]
# 或者: from networkx.classes.digraph.DiGraph import add_edges_from [as 别名]
def subgraph(graph:DiGraph, nodes, include_outgoing=True):
sg = DiGraph()
for src, dst_seq in graph.adjacency():
sg.add_edges_from((src, dst) for dst in dst_seq if src in nodes and include_outgoing or dst in nodes)
return sg