def test_multigraph(self): assert nx.bellman_ford_path(self.MXG, "s", "v") == ["s", "x", "u", "v"] assert nx.bellman_ford_path_length(self.MXG, "s", "v") == 9 assert nx.single_source_bellman_ford_path(self.MXG, "s")["v"] == [ "s", "x", "u", "v", ] assert nx.single_source_bellman_ford_path_length(self.MXG, "s")["v"] == 9 D, P = nx.single_source_bellman_ford(self.MXG, "s", target="v") assert D == 9 assert P == ["s", "x", "u", "v"] P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, "s") assert P["v"] == ["u"] assert D["v"] == 9 P, D = nx.goldberg_radzik(self.MXG, "s") assert P["v"] == "u" assert D["v"] == 9 assert nx.bellman_ford_path(self.MXG4, 0, 2) == [0, 1, 2] assert nx.bellman_ford_path_length(self.MXG4, 0, 2) == 4 assert nx.single_source_bellman_ford_path(self.MXG4, 0)[2] == [0, 1, 2] assert nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2] == 4 D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2) assert D == 4 assert P == [0, 1, 2] P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0) assert P[2] == [1] assert D[2] == 4 P, D = nx.goldberg_radzik(self.MXG4, 0) assert P[2] == 1 assert D[2] == 4
def test_multigraph(self): assert nx.bellman_ford_path(self.MXG, 's', 'v') == ['s', 'x', 'u', 'v'] assert nx.bellman_ford_path_length(self.MXG, 's', 'v') == 9 assert nx.single_source_bellman_ford_path( self.MXG, 's')['v'] == ['s', 'x', 'u', 'v'] assert nx.single_source_bellman_ford_path_length(self.MXG, 's')['v'] == 9 D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v') assert D == 9 assert P == ['s', 'x', 'u', 'v'] P, D = nx.bellman_ford_predecessor_and_distance(self.MXG, 's') assert P['v'] == ['u'] assert D['v'] == 9 P, D = nx.goldberg_radzik(self.MXG, 's') assert P['v'] == 'u' assert D['v'] == 9 assert nx.bellman_ford_path(self.MXG4, 0, 2) == [0, 1, 2] assert nx.bellman_ford_path_length(self.MXG4, 0, 2) == 4 assert nx.single_source_bellman_ford_path(self.MXG4, 0)[2] == [0, 1, 2] assert nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2] == 4 D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2) assert D == 4 assert P == [0, 1, 2] P, D = nx.bellman_ford_predecessor_and_distance(self.MXG4, 0) assert P[2] == [1] assert D[2] == 4 P, D = nx.goldberg_radzik(self.MXG4, 0) assert P[2] == 1 assert D[2] == 4
def test_multigraph(self): assert_equal(nx.bellman_ford_path(self.MXG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.MXG, 's', 'v'), 9) assert_equal(nx.single_source_bellman_ford_path(self.MXG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_bellman_ford_path_length(self.MXG, 's')['v'], 9) D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v') assert_equal(D, 9) assert_equal(P, ['s', 'x', 'u', 'v']) P, D = nx.bellman_ford_predecessor_and_distance(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) assert_equal(nx.bellman_ford_path(self.MXG4, 0, 2), [0, 1, 2]) assert_equal(nx.bellman_ford_path_length(self.MXG4, 0, 2), 4) assert_equal(nx.single_source_bellman_ford_path(self.MXG4, 0)[2], [0, 1, 2]) assert_equal(nx.single_source_bellman_ford_path_length(self.MXG4, 0)[2], 4) D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2) assert_equal(D, 4) assert_equal(P, [0, 1, 2]) P, D = nx.bellman_ford_predecessor_and_distance(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)
def test_multigraph(self): assert_equal(nx.bellman_ford_path(self.MXG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.MXG, 's', 'v'), 9) assert_equal( nx.single_source_bellman_ford_path(self.MXG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal( dict(nx.single_source_bellman_ford_path_length(self.MXG, 's'))['v'], 9) D, P = nx.single_source_bellman_ford(self.MXG, 's', target='v') assert_equal(D['v'], 9) assert_equal(P['v'], ['s', 'x', 'u', 'v']) P, D = nx.bellman_ford_predecessor_and_distance(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) assert_equal(nx.bellman_ford_path(self.MXG4, 0, 2), [0, 1, 2]) assert_equal(nx.bellman_ford_path_length(self.MXG4, 0, 2), 4) assert_equal( nx.single_source_bellman_ford_path(self.MXG4, 0)[2], [0, 1, 2]) assert_equal( dict(nx.single_source_bellman_ford_path_length(self.MXG4, 0))[2], 4) D, P = nx.single_source_bellman_ford(self.MXG4, 0, target=2) assert_equal(D[2], 4) assert_equal(P[2], [0, 1, 2]) P, D = nx.bellman_ford_predecessor_and_distance(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)
def test_others(self): assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9) assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal(dict(nx.single_source_bellman_ford_path_length(self.XG, 's'))['v'], 9) D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert_equal(D['v'], 9) assert_equal(P['v'], ['s', 'x', 'u', 'v']) (P, D) = nx.bellman_ford_predecessor_and_distance(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.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), {0: 0, 1: 1, 2: 2, 3: 3}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]})) assert_equal(nx.bellman_ford_predecessor_and_distance(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.single_source_bellman_ford_path(G, 3), {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)), {0: 3, 1: 2, 2: 1, 3: 0}) assert_equal(nx.single_source_bellman_ford(G, 3), ({0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]})) assert_equal(nx.bellman_ford_predecessor_and_distance(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) dist, path = nx.single_source_bellman_ford(G, (0, 0)) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) assert_equal(sorted(path.items()), [((0, 0), [(0, 0)]), ((0, 1), [(0, 0), (0, 1)]), ((1, 0), [(0, 0), (1, 0)]), ((1, 1), [(0, 0), (0, 1), (1, 1)])]) pred, dist = nx.bellman_ford_predecessor_and_distance(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), [None]), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]) 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)])
def test_path_graph(self): G = nx.path_graph(4) assert nx.single_source_bellman_ford_path(G, 0) == { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], } assert nx.single_source_bellman_ford_path_length(G, 0) == { 0: 0, 1: 1, 2: 2, 3: 3, } assert nx.single_source_bellman_ford(G, 0) == ( {0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}, ) assert nx.bellman_ford_predecessor_and_distance(G, 0) == ( {0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3}, ) assert nx.goldberg_radzik(G, 0) == ( {0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}, ) assert nx.single_source_bellman_ford_path(G, 3) == { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3], } assert nx.single_source_bellman_ford_path_length(G, 3) == { 0: 3, 1: 2, 2: 1, 3: 0, } assert nx.single_source_bellman_ford(G, 3) == ( {0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}, ) assert nx.bellman_ford_predecessor_and_distance(G, 3) == ( {0: [1], 1: [2], 2: [3], 3: []}, {0: 3, 1: 2, 2: 1, 3: 0}, ) assert nx.goldberg_radzik(G, 3) == ( {0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}, )
def getTree(self, node, upstream=False): """ Get :param node: A start node :param upstream: Should the graph be reversed (upstream search) :return: A list of edges """ if self.dirty: self.createGraph() # fix point pickle def pickle_point(p): return QgsPointXY, ( p.x(), p.y(), ) copyreg.pickle(QgsPointXY, pickle_point) if upstream: my_graph = self.graph.reverse() else: my_graph = self.graph # Returns pred, weight pred, _ = nx.bellman_ford_predecessor_and_distance(my_graph, node) edges = [(v[0], u, my_graph.edges[v[0], u]) for (u, v) in list(pred.items()) if v] nodes = [ my_graph.nodes[n] for n in set( list(pred.keys()) + [v[0] for v in list(pred.values()) if v]) if n is not None ] return nodes, edges
def ActionBellman_Ford(self): global graph try: pred, dist=nx.bellman_ford_predecessor_and_distance(graph,1) messagebox.showinfo("Bellman_Ford",'Predécédents : '+str(pred)+' Distances : '+str(dist)) except: messagebox.showinfo("Bellman_Ford", "Mauvaise source ou cycle poids négatif")
def test_bellman_ford(self): for _ in range(1000): nxg = nx.fast_gnp_random_graph(randint(1, 10), randint(1, 9) / 10, directed=True) for u, v in nxg.edges: nxg[u][v]['weight'] = randint(1, 12) print(sorted(nxg.nodes)) print(sorted(nxg.edges)) g = gx.Digraph() g.add_vertices_from(nxg.nodes) for u, v in nxg.edges: g.add_edge(u, v, nxg[u][v]['weight']) print(sorted(g.vertices)) print(sorted(g.edges)) pred1, dist1 = nx.bellman_ford_predecessor_and_distance(nxg, 0) print(pred1) print(dist1) pred2, dist2 = bellman_ford(g, 0) print(pred2) print(dist2) self.assertEqual( dist1, {k: v for k, v in dist2.items() if v != sys.maxsize})
def test_single_node_graph(self): G = nx.DiGraph() G.add_node(0) assert nx.single_source_bellman_ford_path(G, 0) == {0: [0]} assert nx.single_source_bellman_ford_path_length(G, 0) == {0: 0} assert nx.single_source_bellman_ford(G, 0) == ({0: 0}, {0: [0]}) assert nx.bellman_ford_predecessor_and_distance(G, 0) == ({0: []}, {0: 0}) assert nx.goldberg_radzik(G, 0) == ({0: None}, {0: 0})
def test_single_node_graph(self): G = nx.DiGraph() G.add_node(0) assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0}, {0: [0]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: []}, {0: 0})) assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0}))
def test_single_node_graph(self): G = nx.DiGraph() G.add_node(0) assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0}, {0: [0]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [None]}, {0: 0})) assert_equal(nx.goldberg_radzik(G, 0), ({0: None}, {0: 0})) assert_raises(nx.NodeNotFound, nx.bellman_ford_predecessor_and_distance, G, 1) assert_raises(nx.NodeNotFound, nx.goldberg_radzik, G, 1)
def test_path_graph(self): G = nx.path_graph(4) assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0, 1: 1, 2: 2, 3: 3}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: 2, 3: 3}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [], 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.single_source_bellman_ford_path(G, 3), {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 3), {0: 3, 1: 2, 2: 1, 3: 0}) assert_equal(nx.single_source_bellman_ford(G, 3), ({0: 3, 1: 2, 2: 1, 3: 0}, {0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 3), ({0: [1], 1: [2], 2: [3], 3: []}, {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}))
def nx_bellman_ford( graph: NetworkXGraph, source_node: NodeID) -> Tuple[PythonNodeMap, PythonNodeMap]: predecessors_map, distance_map = nx.bellman_ford_predecessor_and_distance( graph.value, source_node) single_parent_map = { child: parents[0] if len(parents) > 0 else source_node for child, parents in predecessors_map.items() } return ( PythonNodeMap(single_parent_map, ), PythonNodeMap(distance_map, ), )
def preprocess(self): ''' Preprocess the graph labeling every node with the shortest cost to the end node (target) ''' #nx.johnson(self.G,weight='Cost') #G_r=nx.DiGraph(self.G).reverse(copy=True) for i, r in enumerate(self.R): t = nx.shortest_path_length(self.G, weight=r, target=self.target) attrs = {i: {"s_" + r: t[i]} for i in t.keys()} attrs.update({ i: { "s_" + r: float("inf") } for i in self.G.nodes() if i not in t.keys() }) nx.set_node_attributes(self.G, attrs) #self.minimum_time=attrs[self.source]["s_time"] if self.R_max[i] == 0: try: self.R_max[i] = self.G[self.source]['s_' + r] * ( 1 + self.tightness) except: print("Infeasible") if self.n == None: #p=nx.shortest_path_length(self.G,weight="Cost",target=self.target) pred, p = nx.bellman_ford_predecessor_and_distance( nx.reverse(self.G, copy=True), weight="Cost", source=self.target) attrs = {i: {"labels": [], "s_cost": p[i]} for i in p.keys()} attrs.update({ i: { "labels": [], "s_cost": float("inf") } for i in self.G.nodes() if i not in p.keys() }) nx.set_node_attributes(self.G, attrs) else: self.bounding_scheme() for i in self.G.nodes: self.G.nodes[i]["labels"] = []
def test_others(self): assert nx.bellman_ford_path(self.XG, 's', 'v') == ['s', 'x', 'u', 'v'] assert nx.bellman_ford_path_length(self.XG, 's', 'v') == 9 assert nx.single_source_bellman_ford_path(self.XG, 's')['v'] == ['s', 'x', 'u', 'v'] assert nx.single_source_bellman_ford_path_length(self.XG, 's')['v'] == 9 D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert D == 9 assert P == ['s', 'x', 'u', 'v'] (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, 's') assert P['v'] == ['u'] assert D['v'] == 9 (P, D) = nx.goldberg_radzik(self.XG, 's') assert P['v'] == 'u' assert D['v'] == 9
def test_others(self): assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9) assert_equal(nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal(nx.single_source_bellman_ford_path_length(self.XG, 's')['v'], 9) D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert_equal(D, 9) assert_equal(P, ['s', 'x', 'u', 'v']) (P, D) = nx.bellman_ford_predecessor_and_distance(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)
def test_not_connected(self): G = nx.complete_graph(6) G.add_edge(10, 11) G.add_edge(10, 12) assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})) assert_equal(nx.bellman_ford_predecessor_and_distance(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.single_source_bellman_ford_path(G, 0, weight='load'), {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0, weight='load'), {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}) assert_equal(nx.single_source_bellman_ford(G, 0, weight='load'), ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})) assert_equal(nx.bellman_ford_predecessor_and_distance(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}))
def test_not_connected(self): G = nx.complete_graph(6) G.add_edge(10, 11) G.add_edge(10, 12) assert_equal(nx.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [], 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.single_source_bellman_ford_path(G, 0, weight='load'), {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0, weight='load'), {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}) assert_equal(nx.single_source_bellman_ford(G, 0, weight='load'), ({0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0, weight='load'), ({0: [], 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}))
def all_pairs_bellman_ford_path(g, weight='distance'): """ Compute the shorted paths between nodes of a graph using the Bellman-Ford algorithm. See Schmidt, M., Bakker, R., Hilgetag, C.C. et al. Brain Structure and Function (2018), 223:1409, for details. Parameters ---------- g : networkx.graph Graph object. weight : str Edge attributes used for path calculation. Defaults to 'weight'. Returns ------- paths : dict Dictionary of all shortest paths. path_lengths: dict Dictionary of all shortest path lengths. """ sources = g.nodes() predecessors = {} path_lengths = {} for node in sources: res = nx.bellman_ford_predecessor_and_distance(g, node, weight=weight) predecessors[node] = res[0] path_lengths[node] = res[1] paths = {} for source in sources: paths[source] = {} for target in predecessors[source]: if target != source: path = [] predec = target while predec != source: path.insert(0, predec) predec = predecessors[source][predec][0] path.insert(0, predec) else: path = [source] paths[source][target] = path return paths, path_lengths
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_predecessor_and_distance(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
def test_others(self): assert nx.bellman_ford_path(self.XG, "s", "v") == ["s", "x", "u", "v"] assert nx.bellman_ford_path_length(self.XG, "s", "v") == 9 assert nx.single_source_bellman_ford_path(self.XG, "s")["v"] == [ "s", "x", "u", "v", ] assert nx.single_source_bellman_ford_path_length(self.XG, "s")["v"] == 9 D, P = nx.single_source_bellman_ford(self.XG, "s", target="v") assert D == 9 assert P == ["s", "x", "u", "v"] (P, D) = nx.bellman_ford_predecessor_and_distance(self.XG, "s") assert P["v"] == ["u"] assert D["v"] == 9 (P, D) = nx.goldberg_radzik(self.XG, "s") assert P["v"] == "u" assert D["v"] == 9
def test_negative_weight_cycle(self): 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.single_source_bellman_ford_path, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i) assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i) assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, 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.single_source_bellman_ford_path, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i) assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i) assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i) G = nx.DiGraph([(1, 1, {'weight': -1})]) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1) assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1) assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1) # 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.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: -2, 3: -1, 4: 0}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [], 1: [0], 2: [1], 3: [2], 4: [3]}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0})) assert_equal(nx.goldberg_radzik(G, 0), ({0: None, 1: 0, 2: 1, 3: 2, 4: 3}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}))
def test_negative_weight_cycle(self): 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.single_source_bellman_ford_path, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i) assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i) assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, 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.single_source_bellman_ford_path, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, i) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, i) assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, i) assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i) G = nx.DiGraph([(1, 1, {'weight': -1})]) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path, G, 1) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path_length, G, 1) assert_raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G, 1) assert_raises(nx.NetworkXUnbounded, nx.bellman_ford_predecessor_and_distance, G, 1) assert_raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1) # 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.single_source_bellman_ford_path(G, 0), {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]}) assert_equal(nx.single_source_bellman_ford_path_length(G, 0), {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}) assert_equal(nx.single_source_bellman_ford(G, 0), ({0: 0, 1: 1, 2: -2, 3: -1, 4: 0}, {0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4]})) assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({0: [None], 1: [0], 2: [1], 3: [2], 4: [3]}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0})) assert_equal(nx.goldberg_radzik(G, 0), ({0: None, 1: 0, 2: 1, 3: 2, 4: 3}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}))
def test_4_cycle(self): # 4-cycle G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)]) dist, path = nx.single_source_bellman_ford(G, 0) assert dist == {0: 0, 1: 1, 2: 2, 3: 1} assert path[0] == [0] assert path[1] == [0, 1] assert path[2] in [[0, 1, 2], [0, 3, 2]] assert path[3] == [0, 3] pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0) assert pred[0] == [] assert pred[1] == [0] assert pred[2] in [[1, 3], [3, 1]] assert pred[3] == [0] assert dist == {0: 0, 1: 1, 2: 2, 3: 1} pred, dist = nx.goldberg_radzik(G, 0) assert pred[0] is None assert pred[1] == 0 assert pred[2] in [1, 3] assert pred[3] == 0 assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
def test_4_cycle(self): # 4-cycle G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)]) dist, path = nx.single_source_bellman_ford(G, 0) assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1}) assert_equal(path[0], [0]) assert_equal(path[1], [0, 1]) assert_true(path[2] in [[0, 1, 2], [0, 3, 2]]) assert_equal(path[3], [0, 3]) pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0) assert_equal(pred[0], []) assert_equal(pred[1], [0]) assert_true(pred[2] in [[1, 3], [3, 1]]) assert_equal(pred[3], [0]) assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1}) pred, dist = nx.goldberg_radzik(G, 0) assert_equal(pred[0], None) assert_equal(pred[1], 0) assert_true(pred[2] in [1, 3]) assert_equal(pred[3], 0) assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1})
def test_4_cycle(self): # 4-cycle G = nx.Graph([(0,1),(1,2),(2,3),(3,0)]) dist, path = nx.single_source_bellman_ford(G, 0) assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1}) assert_equal(path[0],[0]) assert_equal(path[1],[0,1]) assert_true(path[2] in [[0,1,2],[0,3,2]]) assert_equal(path[3],[0,3]) pred, dist = nx.bellman_ford_predecessor_and_distance(G, 0) assert_equal(pred[0],[None]) assert_equal(pred[1],[0]) assert_true(pred[2] in [[1,3],[3,1]]) assert_equal(pred[3],[0]) assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1}) pred, dist = nx.goldberg_radzik(G, 0) assert_equal(pred[0],None) assert_equal(pred[1],0) assert_true(pred[2] in [1,3]) assert_equal(pred[3],0) assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1})
def all_shortest_paths(G, source, target, weight=None, method='dijkstra'): """Compute all shortest paths in the graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. target : node Ending node for path. weight : None or string, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. method : string, optional (default = 'dijkstra') The algorithm to use to compute the path lengths. Supported options: 'dijkstra', 'bellman-ford'. Other inputs produce a ValueError. If `weight` is None, unweighted graph methods are used, and this suggestion is ignored. Returns ------- paths : generator of lists A generator of all paths between source and target. Raises ------ ValueError If `method` is not among the supported options. NetworkXNoPath If `target` cannot be reached from `source`. Examples -------- >>> G = nx.Graph() >>> nx.add_path(G, [0, 1, 2]) >>> nx.add_path(G, [0, 10, 2]) >>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)]) [[0, 1, 2], [0, 10, 2]] Notes ----- There may be many shortest paths between the source and target. See Also -------- shortest_path() single_source_shortest_path() all_pairs_shortest_path() """ method = 'unweighted' if weight is None else method if method == 'unweighted': pred = nx.predecessor(G, source) elif method == 'dijkstra': pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight) elif method == 'bellman-ford': pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight) else: raise ValueError('method not supported: {}'.format(method)) if target not in pred: raise nx.NetworkXNoPath('Target {} cannot be reached' 'from Source {}'.format(target, source)) stack = [[target, 0]] top = 0 while top >= 0: node, i = stack[top] if node == source: yield [p for p, n in reversed(stack[:top + 1])] if len(pred[node]) > i: top += 1 if top == len(stack): stack.append([pred[node][i], 0]) else: stack[top] = [pred[node][i], 0] else: stack[top - 1][1] += 1 top -= 1
def test_path_graph(self): G = nx.path_graph(4) assert_equal(nx.single_source_bellman_ford_path(G, 0), { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3] }) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), { 0: 0, 1: 1, 2: 2, 3: 3 }) assert_equal(nx.single_source_bellman_ford(G, 0), ({ 0: 0, 1: 1, 2: 2, 3: 3 }, { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3] })) assert_equal(nx.bellman_ford_predecessor_and_distance(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.single_source_bellman_ford_path(G, 3), { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3] }) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)), { 0: 3, 1: 2, 2: 1, 3: 0 }) assert_equal(nx.single_source_bellman_ford(G, 3), ({ 0: 3, 1: 2, 2: 1, 3: 0 }, { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3] })) assert_equal(nx.bellman_ford_predecessor_and_distance(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 }))
def test_not_connected(self): G = nx.complete_graph(6) G.add_edge(10, 11) G.add_edge(10, 12) assert nx.single_source_bellman_ford_path(G, 0) == { 0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5], } assert nx.single_source_bellman_ford_path_length(G, 0) == { 0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, } assert nx.single_source_bellman_ford(G, 0) == ( { 0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1 }, { 0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5] }, ) assert nx.bellman_ford_predecessor_and_distance(G, 0) == ( { 0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0] }, { 0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1 }, ) assert 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 nx.single_source_bellman_ford_path(G, 0, weight="load") == { 0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5], } assert nx.single_source_bellman_ford_path_length(G, 0, weight="load") == { 0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, } assert nx.single_source_bellman_ford(G, 0, weight="load") == ( { 0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1 }, { 0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4], 5: [0, 5] }, ) assert nx.bellman_ford_predecessor_and_distance(G, 0, weight="load") == ( { 0: [], 1: [0], 2: [0], 3: [0], 4: [0], 5: [0] }, { 0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1 }, ) assert 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 }, )
def all_shortest_paths(G, source, target, weight=None, method="dijkstra"): """Compute all shortest simple paths in the graph. Parameters ---------- G : NetworkX graph source : node Starting node for path. target : node Ending node for path. weight : None or string, optional (default = None) If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the edge weight. Any edge attribute not present defaults to 1. method : string, optional (default = 'dijkstra') The algorithm to use to compute the path lengths. Supported options: 'dijkstra', 'bellman-ford'. Other inputs produce a ValueError. If `weight` is None, unweighted graph methods are used, and this suggestion is ignored. Returns ------- paths : generator of lists A generator of all paths between source and target. Raises ------ ValueError If `method` is not among the supported options. NetworkXNoPath If `target` cannot be reached from `source`. Examples -------- >>> G = nx.Graph() >>> nx.add_path(G, [0, 1, 2]) >>> nx.add_path(G, [0, 10, 2]) >>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)]) [[0, 1, 2], [0, 10, 2]] Notes ----- There may be many shortest paths between the source and target. If G contains zero-weight cycles, this function will not produce all shortest paths because doing so would produce infinitely many paths of unbounded length -- instead, we only produce the shortest simple paths. See Also -------- shortest_path() single_source_shortest_path() all_pairs_shortest_path() """ method = "unweighted" if weight is None else method if method == "unweighted": pred = nx.predecessor(G, source) elif method == "dijkstra": pred, dist = nx.dijkstra_predecessor_and_distance(G, source, weight=weight) elif method == "bellman-ford": pred, dist = nx.bellman_ford_predecessor_and_distance(G, source, weight=weight) else: raise ValueError(f"method not supported: {method}") return _build_paths_from_predecessors({source}, target, pred)
def test_negative_weight(self): G = nx.cycle_graph(5, create_using=nx.DiGraph()) G.add_edge(1, 2, weight=-3) assert nx.single_source_bellman_ford_path(G, 0) == { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4], } assert nx.single_source_bellman_ford_path_length(G, 0) == { 0: 0, 1: 1, 2: -2, 3: -1, 4: 0, } assert nx.single_source_bellman_ford(G, 0) == ( { 0: 0, 1: 1, 2: -2, 3: -1, 4: 0 }, { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3], 4: [0, 1, 2, 3, 4] }, ) assert nx.bellman_ford_predecessor_and_distance(G, 0) == ( { 0: [], 1: [0], 2: [1], 3: [2], 4: [3] }, { 0: 0, 1: 1, 2: -2, 3: -1, 4: 0 }, ) assert nx.goldberg_radzik(G, 0) == ( { 0: None, 1: 0, 2: 1, 3: 2, 4: 3 }, { 0: 0, 1: 1, 2: -2, 3: -1, 4: 0 }, )
def test_others(self): assert_equal(nx.bellman_ford_path(self.XG, 's', 'v'), ['s', 'x', 'u', 'v']) assert_equal(nx.bellman_ford_path_length(self.XG, 's', 'v'), 9) assert_equal( nx.single_source_bellman_ford_path(self.XG, 's')['v'], ['s', 'x', 'u', 'v']) assert_equal( dict(nx.single_source_bellman_ford_path_length(self.XG, 's'))['v'], 9) D, P = nx.single_source_bellman_ford(self.XG, 's', target='v') assert_equal(D['v'], 9) assert_equal(P['v'], ['s', 'x', 'u', 'v']) (P, D) = nx.bellman_ford_predecessor_and_distance(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.single_source_bellman_ford_path(G, 0), { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3] }) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), { 0: 0, 1: 1, 2: 2, 3: 3 }) assert_equal(nx.single_source_bellman_ford(G, 0), ({ 0: 0, 1: 1, 2: 2, 3: 3 }, { 0: [0], 1: [0, 1], 2: [0, 1, 2], 3: [0, 1, 2, 3] })) assert_equal(nx.bellman_ford_predecessor_and_distance(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.single_source_bellman_ford_path(G, 3), { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3] }) assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 3)), { 0: 3, 1: 2, 2: 1, 3: 0 }) assert_equal(nx.single_source_bellman_ford(G, 3), ({ 0: 3, 1: 2, 2: 1, 3: 0 }, { 0: [3, 2, 1, 0], 1: [3, 2, 1], 2: [3, 2], 3: [3] })) assert_equal(nx.bellman_ford_predecessor_and_distance(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) dist, path = nx.single_source_bellman_ford(G, (0, 0)) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) assert_equal(sorted(path.items()), [((0, 0), [(0, 0)]), ((0, 1), [(0, 0), (0, 1)]), ((1, 0), [(0, 0), (1, 0)]), ((1, 1), [(0, 0), (0, 1), (1, 1)])]) pred, dist = nx.bellman_ford_predecessor_and_distance(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), [None]), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]) 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)])
# reference: https://networkx.github.io/documentation/stable/reference/algorithms/euler.html # Use-Case example: "The purpose of the proposed new roads is to make the town mailman-friendly. In graph theory terms, # we want to change the graph so it contains an Euler circuit. This is also referred to as Eulerizing a graph. The # most mailman-friendly graph is the one with an Euler circuit since it takes the mailman back to the starting point. # This means that the mailman can leave his car at one intersection, walk the route hitting all the streets just once, # and end up where he began. There is no backtracking or walking of streets twice. This saves him time." # reference: https://study.com/academy/lesson/eulerizing-graphs-in-math.html print(startBlue + '\nHas Eulerian path:\n' + endColor, nx.has_eulerian_path(G)) print(startBlue + '\nIs semi-Eulerian:\n' + endColor, nx.is_semieulerian(G)) # Shortest paths (Bellman Ford): # reference: https://networkx.github.io/documentation/stable/reference/algorithms/shortest_paths.html # defined: The Bellman-Ford algorithm is a graph search algorithm that finds the shortest path between a given source # vertex and all other vertices in the graph. This algorithm can be used on both weighted and unweighted graphs. # reference: https://brilliant.org/wiki/bellman-ford-algorithm/ print(startBlue + '\nBellman Ford path from Los Angeles:\n' + endColor, nx.bellman_ford_predecessor_and_distance(G, 'Los Angeles')) # Linear Algebra (Eigenvalues): # reference: https://networkx.github.io/documentation/stable/reference/linalg.html # defined: Using scaler multiplication (matrix multiplication = scaler multiplication) to create a new figure, # utilizing Eigenvalues and Eigenvectors # reference: https://www.youtube.com/watch?v=vs2sRvSzA3o # Real world use-case: To scale a model to a real-world dataset or graph # Reference: http://barabasi.com/f/94.pdf # Appears that utilizing the modularity spectrum, groups can be assigned into clusters/networks # reference: https://en.wikipedia.org/wiki/Modularity_(networks) print( startBlue + '\nThe Modularity Spectrum that returns eigenvalues of the modularity matrix of G:\n' + endColor, nx.modularity_spectrum(G)) print(