本文整理汇总了Python中networkx.bellman_ford函数的典型用法代码示例。如果您正苦于以下问题:Python bellman_ford函数的具体用法?Python bellman_ford怎么用?Python bellman_ford使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bellman_ford函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_others
def test_others(self):
(P, D) = nx.bellman_ford(self.XG, 's')
assert_equal(P['v'], 'u')
assert_equal(D['v'], 9)
(P, D) = nx.goldberg_radzik(self.XG, 's')
assert_equal(P['v'], 'u')
assert_equal(D['v'], 9)
G = nx.path_graph(4)
assert_equal(nx.bellman_ford(G, 0),
({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
assert_equal(nx.goldberg_radzik(G, 0),
({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
assert_equal(nx.bellman_ford(G, 3),
({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}))
assert_equal(nx.goldberg_radzik(G, 3),
({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}))
G = nx.grid_2d_graph(2, 2)
pred, dist = nx.bellman_ford(G, (0, 0))
assert_equal(sorted(pred.items()),
[((0, 0), None), ((0, 1), (0, 0)),
((1, 0), (0, 0)), ((1, 1), (0, 1))])
assert_equal(sorted(dist.items()),
[((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
pred, dist = nx.goldberg_radzik(G, (0, 0))
assert_equal(sorted(pred.items()),
[((0, 0), None), ((0, 1), (0, 0)),
((1, 0), (0, 0)), ((1, 1), (0, 1))])
assert_equal(sorted(dist.items()),
[((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
示例2: test_bellman_ford
def test_bellman_ford(self):
# single node graph
G = nx.DiGraph()
G.add_node(0)
assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0}))
assert_raises(KeyError, nx.bellman_ford, G, 1)
# negative weight cycle
G = nx.cycle_graph(5, create_using=nx.DiGraph())
G.add_edge(1, 2, weight=-7)
for i in range(5):
assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, i)
G = nx.cycle_graph(5) # undirected Graph
G.add_edge(1, 2, weight=-3)
for i in range(5):
assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, i)
# no negative cycle but negative weight
G = nx.cycle_graph(5, create_using=nx.DiGraph())
G.add_edge(1, 2, weight=-3)
assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2, 4: 3}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}))
# not connected
G = nx.complete_graph(6)
G.add_edge(10, 11)
G.add_edge(10, 12)
assert_equal(
nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
)
# not connected, with a component not containing the source that
# contains a negative cost cycle.
G = nx.complete_graph(6)
G.add_edges_from([("A", "B", {"load": 3}), ("B", "C", {"load": -10}), ("C", "A", {"load": 2})])
assert_equal(
nx.bellman_ford(G, 0, weight="load"),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}),
)
# multigraph
P, D = nx.bellman_ford(self.MXG, "s")
assert_equal(P["v"], "u")
assert_equal(D["v"], 9)
P, D = nx.bellman_ford(self.MXG4, 0)
assert_equal(P[2], 1)
assert_equal(D[2], 4)
# other tests
(P, D) = nx.bellman_ford(self.XG, "s")
assert_equal(P["v"], "u")
assert_equal(D["v"], 9)
G = nx.path_graph(4)
assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
assert_equal(nx.bellman_ford(G, 3), ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}))
G = nx.grid_2d_graph(2, 2)
pred, dist = nx.bellman_ford(G, (0, 0))
assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))])
assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
示例3: test_multigraph
def test_multigraph(self):
P, D = nx.bellman_ford(self.MXG, 's')
assert_equal(P['v'], 'u')
assert_equal(D['v'], 9)
P, D = nx.goldberg_radzik(self.MXG, 's')
assert_equal(P['v'], 'u')
assert_equal(D['v'], 9)
P, D = nx.bellman_ford(self.MXG4, 0)
assert_equal(P[2], 1)
assert_equal(D[2], 4)
P, D = nx.goldberg_radzik(self.MXG4, 0)
assert_equal(P[2], 1)
assert_equal(D[2], 4)
示例4: peptideSequencing
def peptideSequencing(spectralVector, proteins=None):
if proteins is None:
proteins = proteinMass
graph = nx.DiGraph()
maxIndex = len(spectralVector)
graph.add_nodes_from(xrange(maxIndex))
for idx in xrange(maxIndex):
# Ignore nodes with no incoming edges except the 1st one.
if idx > 0 and len(graph.in_edges(idx)) == 0:
continue
for p, mass in proteins.iteritems():
if idx + mass < len(spectralVector):
try:
graph.add_edge(idx, idx+mass,{'amino': p,
'weight': -1 * spectralVector[idx+mass]})
except IndexError as e:
pass
pred, dist = nx.bellman_ford(graph, 0)
proteinLookup = {v:k for k,v in proteins.iteritems()}
idx = len(spectralVector)-1
path = []
while idx > 0:
path.append(proteinLookup[idx-pred[idx]])
idx = pred[idx]
return ''.join(path[::-1])
示例5: SubSolve
def SubSolve(G,pi):
#print "pi=",pi
G.edge[1][2]["cost"]-=pi[1]
G.edge[1][3]["cost"]-=pi[1]
G.edge[1]['t']["cost"]-=pi[1]
G.edge[2][3]["cost"]-=pi[2]
G.edge[2]['t']["cost"]-=pi[2]
G.edge[3]['t']["cost"]-=pi[3]
#print G.edges(data=True)
pred, dist = nx.bellman_ford(G,'s',weight="cost")
new_chemin=[]
chemin=['t']
predecesseur = pred['t']
chemin.append(predecesseur)
k=predecesseur
while predecesseur != 's':
predecesseur = pred[k]
chemin.append(predecesseur)
k=predecesseur
chemin.reverse()
G.edge[1][2]["cost"]+=pi[1]
G.edge[1][3]["cost"]+=pi[1]
G.edge[1]['t']["cost"]+=pi[1]
G.edge[2][3]["cost"]+=pi[2]
G.edge[2]['t']["cost"]+=pi[2]
G.edge[3]['t']["cost"]+=pi[3]
L=2*dist['t']+sum(pi[i] for i in [1,2,3])
#print "chemin optimal=",chemin,"de cout",dist['t']
print "L=",L
return L,chemin
示例6: test_single_node_graph
def test_single_node_graph(self):
G = nx.DiGraph()
G.add_node(0)
assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0}))
assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0}))
assert_raises(KeyError, nx.bellman_ford, G, 1)
assert_raises(KeyError, nx.goldberg_radzik, G, 1)
示例7: test_bellman_ford
def test_bellman_ford(self):
# single node graph
G = nx.DiGraph()
G.add_node(0)
assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0}))
# negative weight cycle
G = nx.cycle_graph(5, create_using = nx.DiGraph())
G.add_edge(1, 2, weight = -7)
assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, 0)
G = nx.cycle_graph(5)
G.add_edge(1, 2, weight = -7)
assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, 0)
# not connected
G = nx.complete_graph(6)
G.add_edge(10, 11)
G.add_edge(10, 12)
assert_equal(nx.bellman_ford(G, 0),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
# not connected, with a component not containing the source that
# contains a negative cost cycle.
G = nx.complete_graph(6)
G.add_edges_from([('A', 'B', {'load': 3}),
('B', 'C', {'load': -10}),
('C', 'A', {'load': 2})])
assert_equal(nx.bellman_ford(G, 0, weight = 'load'),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
# multigraph
P, D = nx.bellman_ford(self.MXG,'s')
assert_equal(P['v'], 'u')
assert_equal(D['v'], 9)
P, D = nx.bellman_ford(self.MXG4, 0)
assert_equal(P[2], 1)
assert_equal(D[2], 4)
# other tests
(P,D)= nx.bellman_ford(self.XG,'s')
assert_equal(P['v'], 'u')
assert_equal(D['v'], 9)
G=nx.path_graph(4)
assert_equal(nx.bellman_ford(G,0),
({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
G=nx.grid_2d_graph(2,2)
pred,dist=nx.bellman_ford(G,(0,0))
assert_equal(sorted(pred.items()),
[((0, 0), None), ((0, 1), (0, 0)),
((1, 0), (0, 0)), ((1, 1), (0, 1))])
assert_equal(sorted(dist.items()),
[((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
示例8: compute_paths
def compute_paths(self):
self.shortest_paths = list()
for src in xrange(self.parameters.nodes_in):
try:
(pred, dist) = nx.bellman_ford(self, src)
except:
continue
for tar in xrange(self.parameters.nodes_end_middle,\
self.parameters.nodes_total):
if dist.has_key(tar):
self.shortest_paths.append(dist[tar])
示例9: prog_20
def prog_20(fname):
graph = nx.DiGraph()
f = open(fname)
value, num = map(int, f.readline().strip().split())
for line in f:
e1,e2,weight = map(int, line.strip().split())
graph.add_weighted_edges_from([(e1,e2,weight)])
graph.add_nodes_from(xrange(1,value+1))
f.close()
pred, dist = nx.bellman_ford(graph,1)
for i in xrange(1,value+1):
print dist.get(i, 'x'),
示例10: getTree
def getTree(self,node,reverse=False):
if self.dirty:
self.createGraph()
if reverse:
myGraph = self.graph.reverse()
else:
myGraph = self.graph
# Returns pred, weight
pred, _ = nx.bellman_ford(myGraph, node)
edges = [(v,u,myGraph[v][u]) for (u,v) in pred.items() if v is not None]
return edges
示例11: test_not_connected
def test_not_connected(self):
G = nx.complete_graph(6)
G.add_edge(10, 11)
G.add_edge(10, 12)
assert_equal(nx.bellman_ford(G, 0),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
assert_equal(nx.goldberg_radzik(G, 0),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
# not connected, with a component not containing the source that
# contains a negative cost cycle.
G = nx.complete_graph(6)
G.add_edges_from([('A', 'B', {'load': 3}),
('B', 'C', {'load': -10}),
('C', 'A', {'load': 2})])
assert_equal(nx.bellman_ford(G, 0, weight='load'),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
assert_equal(nx.goldberg_radzik(G, 0, weight='load'),
({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
{0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))
示例12: _bellman_ford_path
def _bellman_ford_path(G, source, target, weight):
"Returns shortest path using bellman_ford algorithm."
pred, dist = nx.bellman_ford(G, source, weight)
if target not in pred:
raise nx.NetworkXNoPath(
"Node %s not reachable from %s." % (source, target))
# Since predecessors are given, build path backwards, then reverse.
path = []
curr = target
while curr != source:
path.append(curr)
curr = pred[curr]
path.append(source)
path.reverse()
return path
示例13: objective
def objective(graph, centers):
"""Calculates the distance between nodes and centers.
:param graph: Graph
:param centers: list
:return: float
"""
if centers:
# For big k networkx.floyd_warshall_numpy can be faster:
# distance = networkx.floyd_warshall_numpy(graph)
# return distance[numpy.ix_([graph.nodes().index(c) for c in centers])].min(axis=0).max(axis=1)[0,0]
distance = {c: networkx.bellman_ford(graph, c)[1] for c in centers}
return max([min([distance[c].get(n, float('inf')) for c in centers]) for n in graph.nodes_iter()])
else:
return float("inf")
示例14: _get_longest_paths
def _get_longest_paths(g, source_nodes):
''' Get the longest path for nodes in 'source_nodes'
Find with bellman_ford() by setting weight = -1
'''
ng = copy.deepcopy(g)
for u, v in ng.edges():
ng[u][v]["weight"] = -1
ret = {}
for cn in source_nodes:
pred, dist = nx.bellman_ford(ng, cn, weight="weight")
path = _get_path(pred, dist)
assert path[0] == cn
assert len(path) - 1 == -dist[path[-1]]
ret[cn] = path
return ret
示例15: plot_big_graph
def plot_big_graph(task):
args = resolve_args(task._algorithm, *task._args)
data = args[1]
fig = pylab.figure(figsize=(5, 5))
pylab.axis('off')
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(pylab.NullLocator())
ax.yaxis.set_major_locator(pylab.NullLocator())
ax.set_aspect('equal')
pos = networkx.get_node_attributes(data, 'pos')
nodes = data.nodes().copy()
for c in task._result:
nodes.remove(c)
distance = {c: networkx.bellman_ford(data, c)[1] for c in task._result}
node_colors = [
COLORS[min(range(len(task._result)), key=lambda i: distance[task._result[i]].get(n, float('inf')))]
for n in nodes
]
networkx.draw_networkx(data, pos, with_labels=False, node_size=5, nodelist=nodes, node_color=node_colors,
linewidths=0)
networkx.draw_networkx_nodes(data, pos, with_labels=False, node_size=100, node_color=COLORS,
nodelist=task._result, node_shape='p')
x = [p[0] for p in pos.values()]
y = [p[1] for p in pos.values()]
minx = min(x)
maxx = max(x)
extrax = 0.1 * (maxx - minx)
miny = min(y)
maxy = max(y)
extray = 0.1 * (maxy - miny)
ax.set_ylim([miny - extray, maxy + extray])
ax.set_xlim([minx - extrax, maxx + extrax])
stream = io.BytesIO()
fig.savefig(stream, format='png', bbox_inches='tight', pad_inches=0)
return stream.getvalue()