コード例 #1
0
    def test_zero_cycle_smoke(self):
        D = nx.DiGraph()
        D.add_weighted_edges_from([(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 1, -2)])

        nx.bellman_ford_path(D, 1, 3)
        nx.dijkstra_path(D, 1, 3)
        nx.bidirectional_dijkstra(D, 1, 3)
コード例 #2
0
 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)
コード例 #3
0
ファイル: test_weighted.py プロジェクト: networkx/networkx
 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)
コード例 #4
0
ファイル: test_weighted.py プロジェクト: ynux/networkx
 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
コード例 #5
0
ファイル: test_weighted.py プロジェクト: Rigosebuta/biathlon
 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
コード例 #6
0
def __nx_bellman_ford(graph, src_entry_nodes, dst_entry_nodes):
    """
    Find shortest path between src and dst using Bellman-Ford's algorithm
    :param graph: NetworkX graph
        graph used for path finding
    :param src_entry_nodes: list of NetworkX nodes
        source nodes from graph
    :param dst_entry_nodes: list of NetworkX nodes
        destination nodes from graph
    :return: list of NetworkX nodes describing the shortest path between src and dst
    """
    path = None
    path_length = None

    for src_entrance in src_entry_nodes:
        for dst_entrance in dst_entry_nodes:
            if path is None and path_length is None:

                path = nx.bellman_ford_path(graph,
                                            source=src_entrance,
                                            target=dst_entrance)
                path_length = nx.bellman_ford_path_length(graph,
                                                          source=src_entrance,
                                                          target=dst_entrance)
            else:
                temp_length = nx.bellman_ford_path_length(graph,
                                                          source=src_entrance,
                                                          target=dst_entrance)
                if temp_length < path_length:
                    path = nx.bellman_ford_path(graph,
                                                source=src_entrance,
                                                target=dst_entrance)
                    path_length = temp_length

    return path
コード例 #7
0
def lab_3():
    np.random.seed(int(time()))
    G = nx.Graph(ox.load_graphml('data/Beijing.graphml'))
    print(len(G.nodes))  # 61525
    print(len(G.edges))  # 90657

    iterations = 100
    result = np.zeros((iterations, 3))

    def heuristic(u, v):
        x1, y1 = G.nodes[u]['x'], G.nodes[u]['y']
        x2, y2 = G.nodes[v]['x'], G.nodes[v]['y']
        return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)

    for i in trange(iterations):
        src = np.random.choice(G.nodes)
        dst = np.random.choice(G.nodes)

        t = time()
        nx.dijkstra_path(G, src, dst, weight='length')
        result[i][0] = time() - t

        t = time()
        nx.bellman_ford_path(G, src, dst, weight='length')
        result[i][1] = time() - t

        t = time()
        nx.astar_path(G, src, dst, heuristic, weight='length')
        result[i][2] = time() - t

    np.save('out/lab3.npy', result)

    result = np.load('out/lab3.npy')
    x = np.arange(result.shape[0])

    matplotlib.rc('font', **{'size': 24})

    plt.figure(figsize=(12, 9))
    plt.title('Time')
    plt.scatter(x, result[:, 0], color='#5FACFC', label='Dijkstra')
    plt.scatter(x, result[:, 1], color='#D5EB59', label='Bellman-Ford')
    plt.scatter(x, result[:, 2], color='#FA816D', label='A-Star')
    plt.legend(loc='upper right')
    plt.ylabel('Seconds')
    plt.show()

    x = np.arange(result.shape[1])
    y = np.zeros(result.shape[1])
    for i in x:
        y[i] = np.average(result[:, i])

    plt.figure(figsize=(12, 9))
    plt.title('Average Time')
    plt.bar(x[0], y[0], color='#5FACFC')
    plt.bar(x[1], y[1], color='#D5EB59')
    plt.bar(x[2], y[2], color='#FA816D')
    plt.xticks(x, ['Dijktra', 'Bellman-Ford', 'A-Star'])
    plt.ylabel('Seconds')
    plt.show()
コード例 #8
0
def bellman_ford(start, end):
    time_start = pygame.time.get_ticks()
    p = networkx.bellman_ford_path(Board_Graph, start, end)
    time_end = pygame.time.get_ticks()
    time = time_end - time_start
    return p, time, True, []
    distancias = dict()
    anterior = dict()
    for V in list(Board_Graph):
        distancias[V] = float('Inf')
        anterior[V] = None
    distancias[start] = 0
    for V in list(Board_Graph):
        for u, v in Board_Graph.edges():
            distancia = distancias[u] + 1
            if distancia < distancias[v]:
                distancias[v] = distancia
                anterior[v] = u
    antes = anterior[end]
    path = [end]
    while antes != start and antes is not None:
        path.insert(0, antes)
        antes = anterior[antes]
    if antes == start:
        path.insert(0, start)
        return path
    return []
コード例 #9
0
def findPath(graph, src, dest):
    # finds node predecessors using a function imported from networkx
    predecessors, _ = nx.floyd_warshall_predecessor_and_distance(graph)

    try:
        # finds the shortest path through the Floyd-Warshall algorithm by using a function imported from networkx
        path = nx.reconstruct_path(src, dest, predecessors)
        dpath = nx.dijkstra_path(graph, src, dest)
        bfpath = nx.bellman_ford_path(graph, src, dest)

        # prints the shortest path
        print("Path:", path)
        # print("Dijkstra's Path:", dpath)
        # print("Bellman-Ford Path:", bfpath)

        # prints the number of hops from source to destination
        print("Number of Hops:", len(path) - 1)
        # print("Dijkstra's Number of Hops:", len(dpath)-1)
        # print("Bellman-Ford Number of Hops:", len(bfpath)-1)

        # gets the total cost
        edge = 0
        for i in range(1, len(path)):
            edge += graph.edges[path[i - 1], path[i]]['weight']
        dpathcost = nx.dijkstra_path_length(graph, src, dest)
        bfpathcost = nx.bellman_ford_path_length(graph, src, dest)
        print("Total Cost:", edge)
        # print("Dijkstra's Total Cost:", dpathcost)
        # print("Bellman-Ford Total Cost:", bfpathcost)
        print()

    except:
        # Print to the terminal if no path exists.
        print("ERROR: No available path from source: node", src,
              "to destination: node", dest)
コード例 #10
0
    def set_package(self, data):
        from networkx import bellman_ford_path, NetworkXNoPath, NodeNotFound
        self.data = data
        origin, destination, _ = data
        try:
            bellman_ford_path(self.network.topology, origin, destination)
        except NetworkXNoPath:
            self.__error_message('No route between node {o} and node {d}'.format(o=origin, d=destination))
            return
        except NodeNotFound:
            self.__error_message('Origin can\'t be the same as destination.')
            return
        except KeyError:
            self.__error_message('Node not in graph')

        self.verticalGroupBox.findChild(QPushButton, 'start_simulation').setEnabled(True)
        self.paint_nodes()
コード例 #11
0
ファイル: feasibleRegions.py プロジェクト: pokutta/lacg
 def LPOracleBellmanFord(self, weight):
     self.weight = weight.copy()
     pathAlg = nx.bellman_ford_path(self.graph, self.topologicalSort[0],
                                    self.topologicalSort[-1], self.func)
     #Reconstruct the vertex.
     outputVect = np.zeros(nx.number_of_edges(self.graph))
     for i in range(len(pathAlg) - 1):
         outputVect[self.dictIndices[(pathAlg[i], pathAlg[i + 1])]] = 1.0
     return outputVect
コード例 #12
0
ファイル: test_weighted.py プロジェクト: AllenDowney/networkx
    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)])
コード例 #13
0
ファイル: test_weighted.py プロジェクト: Rigosebuta/biathlon
    def test_negative_weight(self):
        G = nx.DiGraph()
        G.add_nodes_from("abcd")
        G.add_edge("a", "d", weight=0)
        G.add_edge("a", "b", weight=1)
        G.add_edge("b", "c", weight=-3)
        G.add_edge("c", "d", weight=1)

        assert nx.bellman_ford_path(G, "a", "d") == ["a", "b", "c", "d"]
        assert nx.bellman_ford_path_length(G, "a", "d") == -1
コード例 #14
0
ファイル: test_weighted.py プロジェクト: networkx/networkx
    def test_negative_weight(self):
        G = nx.DiGraph()
        G.add_nodes_from('abcd')
        G.add_edge('a','d', weight = 0)
        G.add_edge('a','b', weight = 1)
        G.add_edge('b','c', weight = -3)
        G.add_edge('c','d', weight = 1)

        assert_equal(nx.bellman_ford_path(G, 'a', 'd'), ['a', 'b', 'c', 'd'])
        assert_equal(nx.bellman_ford_path_length(G, 'a', 'd'), -1)
コード例 #15
0
ファイル: test_weighted.py プロジェクト: ynux/networkx
    def test_negative_weight(self):
        G = nx.DiGraph()
        G.add_nodes_from('abcd')
        G.add_edge('a', 'd', weight=0)
        G.add_edge('a', 'b', weight=1)
        G.add_edge('b', 'c', weight=-3)
        G.add_edge('c', 'd', weight=1)

        assert nx.bellman_ford_path(G, 'a', 'd') == ['a', 'b', 'c', 'd']
        assert nx.bellman_ford_path_length(G, 'a', 'd') == -1
コード例 #16
0
def solve_problem(nodes_cnt, start_node, end_node):
    graph = create_graph(nodes_cnt)

    try:
        path = nx.bellman_ford_path(graph, start_node, end_node)
        length = nx.bellman_ford_path_length(graph, start_node, end_node)
        print('Path: ' + str(path))
        print('Length: ' + str(length))
        draw_graph(graph, path)
    except nx.exception.NetworkXNoPath:
        print('Node {0} is not reachable from {1}'.format(
            str(end_node), str(start_node)))
コード例 #17
0
def shortest_path(V_pred, height=3, width=3):
    import networkx as nx
    V_pred = np.where(V_pred < 0, 0, V_pred)

    def create_graph(height, width):
        #G = nx.Graph()
        G = nx.DiGraph()
        G.add_nodes_from([
            str(i) + "," + str(j) for i in range(height + 1)
            for j in range(width + 1)
        ])
        return G

    def add_weight(G, L, height, width):
        # G is the directed graph L is the the list of weights
        t = 0
        d = {}
        for i in range(height + 1):
            for j in range(width + 1):
                if i < width:
                    #G.add_weighted_edges_from([( str(i)+","+str(j),str(i+1)+","+str(j) ,L[t])])
                    G.add_edge(str(i) + "," + str(j),
                               str(i + 1) + "," + str(j),
                               weight=L[t])
                    d[str(i) + "," + str(j), str(i + 1) + "," + str(j)] = t
                    #d[str(i+1)+","+str(j),str(i)+","+str(j)]= t
                    t += 1
                if j < height:
                    #G.add_weighted_edges_from([( str(i)+","+str(j),str(i)+","+str(j+1) ,L[t])])
                    G.add_edge(str(i) + "," + str(j),
                               str(i) + "," + str(j + 1),
                               weight=L[t])
                    d[str(i) + "," + str(j), str(i) + "," + str(j + 1)] = t
                    #d[str(i)+","+str(j+1), str(i)+","+str(j)]= t
                    t += 1
        return G, d

    def path_distance(G, path):
        labels = nx.get_edge_attributes(G, 'weight')
        dist = 0
        for l in range(len(path) - 1):
            dist += labels[(path[l], path[l + 1])]
        return dist

    H = create_graph(height, width)
    H, dt = add_weight(H, V_pred, height, width)
    sp = nx.bellman_ford_path(H, "0,0", str(height) + "," + str(width))
    #sp =  nx.dijkstra_path (H,"0,0",str(height)+","+str(width) )
    ret = np.zeros(V_pred.shape[0])
    for i in range(len(sp) - 1):
        ret[dt[sp[i], sp[i + 1]]] = 1
    return ret
コード例 #18
0
def get_heaviest_path_faster(graph,start_node,target_node):
  
  #A graph with the weights inverted. We use this to calculate the longest path.
  #inverse_graph = deepcopy(graph)
  graph = invert_weights(graph)
  
  heaviest_path = nx.bellman_ford_path(graph,start_node,target_node,weight='weight')
  #Returning the weights to normal.
  graph = invert_weights(graph)
  #Getting the path length of the heaviest path.  
  heaviest_path_weight = sum_weights_of_path(graph,heaviest_path)
  
  return heaviest_path_weight
コード例 #19
0
 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
コード例 #20
0
ファイル: test_weighted.py プロジェクト: networkx/networkx
 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)
コード例 #21
0
    def use_bell(self, s, t):

        path = nx.bellman_ford_path(self.G, source=s, target=t)

        # path1 = nx.single_source_bellman_ford_path(self.G, 0)
        # length1 = dict(nx.single_source_bellman_ford_path_length(self.G, 0))
        #
        # path2 = dict(nx.all_pairs_bellman_ford_path(self.G))
        # length2 = dict(nx.all_pairs_bellman_ford_path_length(self.G))
        #
        # length, path = nx.single_source_bellman_ford(self.G, 0)
        # pred, dist = nx.bellman_ford_predecessor_and_distance(self.G, 0)
        # print('\n加权图最短路径长度和前驱: ', pred, dist)
        return path
コード例 #22
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(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)
コード例 #23
0
ファイル: AlgorithmMain.py プロジェクト: AiProgram/essay_code
def mwld_get_aux_graph_edge(graph, point_s, point_t):
    """Get the edges between two points in the auxiliary graph for mwld alogrithm"""
    try:
        path_p = nx.bellman_ford_path(graph, point_s, point_t, "weight")
    except:
        return 0, None, None
    if path_p is None:
        return 0, None, None

    reverse_graph = get_SP_reverse_graph(graph, path_p)
    try:
        path_q = nx.bellman_ford_path(reverse_graph, point_s, point_t,
                                      "weight")
    except:
        return 0, None, None
    if path_q is None:
        return 0, None, None
    del reverse_graph

    tmp = []  #因为reverse_graph有拆点,这里处理拆过的点
    for node in path_q:
        if node >= 2 * graph.number_of_nodes():
            tmp.append(node - 2 * graph.number_of_nodes())
        elif node >= graph.number_of_nodes():
            tmp.append(node - graph.number_of_nodes())
        else:
            tmp.append(node)
    path_q = tmp

    path_p1, path_p2 = mwld_path_xor(path_p, path_q)
    #print("P: "+str(path_p)+"  Q: "+str(path_q))
    #print("p1: "+str(path_p1)+"  p2: "+str(path_p2))
    w_p1 = util.get_SP_weight(graph, path_p1)
    w_p2 = util.get_SP_weight(graph, path_p2)
    w_sum = w_p1 + w_p2
    return w_sum, path_p1, path_p2
コード例 #24
0
    def find_path(self, graph, src, dest):
        # finds node predecessors using a function imported from networkx
        predecessors, _ = nx.floyd_warshall_predecessor_and_distance(graph)

        try:
            # finds the shortest path through the Floyd-Warshall algorithm by using a function imported from networkx
            self.path = nx.reconstruct_path(src, dest, predecessors)
            self.dpath = nx.dijkstra_path(graph, src, dest)
            self.bfpath = nx.bellman_ford_path(graph, src, dest)

        except:
            # Print to the terminal if no path exists.
            self.path = []
            self.dpath = []
            self.bfpath = []
コード例 #25
0
def get_ksp_with_delay(graph,start_point,des_point,sp_num):
    """获得k条最短路径,但是只考虑delay,不考虑cost"""
    aux_graph=copy.deepcopy(graph)
    all_sp=[]
    cur_sp_num=0
    while(cur_sp_num<sp_num):
        try:
            sp=nx.bellman_ford_path(aux_graph,start_point,des_point,weight="delay")
        except:
            return None
        if sp is None:
            return None
        else:
            all_sp=paths_xor(all_sp,sp)
            cur_sp_num+=1
        aux_graph=get_delay_reverse_graph(graph,all_sp)
    return all_sp
コード例 #26
0
    def max(self, v):
        '''
        Given the set of weights -v, returns the shortest path between source and target
        '''
        self.max_calls += 1
        self._weightG(
            -v)  #CRITICAL: flips the weights so you can use the shortest-path
        path = nx.bellman_ford_path(self.G,
                                    source=self.source,
                                    target=self.target,
                                    weight='weight')
        #         paths = nx.johnson(self.G,weight='weight')
        #         path = paths[self.source][self.target]
        z = np.array(self._path_to_z(path))
        logging.debug('max shortest path: {}'.format(z))

        return np.inner(v, z), z
コード例 #27
0
def bf_time(graph):
    data = []
    for i, start_v in enumerate(
            tqdm.tqdm(list(graph.nodes)[:-1], desc="Generating Bellman-Ford")):
        for end_v in list(graph.nodes)[i + 1:]:
            t = timeit.timeit(
                stmt=f"nx.bellman_ford_path(graph, {start_v}, {end_v})",
                globals=globals(),
                number=10)
            path = nx.bellman_ford_path(graph, start_v, end_v)
            data.append({
                "vertices": [start_v, end_v],
                "path": path,
                "path_len": len(path),
                "time": t
            })
    return data
コード例 #28
0
def test_shortest_path_bellman_ford():
    graph = nx.DiGraph()
    e = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2),
         ('c', 'e', 1.6), ('b', 'e', 0.7), ('d', 'e', 1.3)]
    graph.add_weighted_edges_from(e)

    path = nx.shortest_path(graph, 'a', 'e', method='bellman-ford')
    assert nx.shortest_path_length(graph, 'a', 'e',
                                   method='bellman-ford') == len(path) - 1
    assert nx.has_path(graph, 'a', 'e') == True

    allPaths = nx.all_shortest_paths(graph, 'a', 'e', method='bellman-ford')
    assert path in allPaths

    graph2 = nx.DiGraph()
    e2 = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2),
          ('c', 'e', 1.6), ('b', 'e', 0.7), ('d', 'e', 1.3), ('a', 'e', 0.4)]
    graph2.add_weighted_edges_from(e2)
    path2 = nx.shortest_path(graph2, 'a', 'e', method='bellman-ford')
    assert nx.shortest_path_length(graph2, 'a', 'e',
                                   method='bellman-ford') == len(path2) - 1
    assert nx.has_path(graph2, 'a', 'e') == True
    allPaths2 = nx.all_shortest_paths(graph2, 'a', 'e', method='bellman-ford')
    assert path2 in allPaths2

    #graph1 shortest path should be diffrent from graph2 shortest path
    assert nx.shortest_path_length(
        graph, 'a', 'e', method='bellman-ford') != nx.shortest_path_length(
            graph2, 'a', 'e', method='bellman-ford')
    #graph1 paths should not contain graph2 shortest path
    assert nx.shortest_path(
        graph2, 'a', 'e', method='bellman-ford') not in nx.all_shortest_paths(
            graph, 'a', 'e', method='bellman-ford')
    #When removed edge, they should equal again
    graph2.remove_edge('a', 'e')
    assert nx.shortest_path_length(
        graph, 'a', 'e', method='bellman-ford') == nx.shortest_path_length(
            graph2, 'a', 'e', method='bellman-ford')
    assert nx.shortest_path(graph2, 'a', 'e',
                            method='bellman-ford') in nx.all_shortest_paths(
                                graph, 'a', 'e', method='bellman-ford')

    #Outputs the same path as bellman_ford_path
    assert nx.shortest_path(graph, 'a', 'e',
                            method='bellman-ford') == nx.bellman_ford_path(
                                graph, 'a', 'e')
コード例 #29
0
    def algorithm_selector(g, pos, winning_nodes, n, identifier, paths):

        if identifier == 'up':
            for i in range(n):
                paths.append(nx.dijkstra_path(g, pos, winning_nodes[i]))

        elif identifier == 'down':
            for i in range(n):
                paths.append(nx.astar_path(g, pos, winning_nodes[i]))

        elif identifier == 'left':
            for i in range(n):
                paths.append(nx.bellman_ford_path(g, pos, winning_nodes[i]))

        elif identifier == 'right':
            for i in range(n):
                paths.append(nx.shortest_path(g, pos, winning_nodes[i]))
コード例 #30
0
ファイル: ShortestPath.py プロジェクト: nariaki3551/csp
def shortest_path_bf(MultiGraph, source, target, weight):
    if all(weights[weight] >= 0
           for _, _, weights in MultiGraph.edges(data=True)):
        path_nodes = nx.shortest_path(MultiGraph,
                                      source=source,
                                      target=target,
                                      weight=weight)
    else:
        path_nodes = nx.bellman_ford_path(MultiGraph, source, target, weight)

    path_edges = []
    for tail, head in zip(path_nodes, path_nodes[1:]):
        min_key = min(
            MultiGraph[tail][head],
            key=lambda edge_key: MultiGraph[tail][head][edge_key][weight])
        path_edges.append((tail, head, min_key))

    return path_nodes, path_edges
コード例 #31
0
 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
コード例 #32
0
    def _find_optimal_query_set(self, W0):
        def get_extreme(which):
            if which not in ['top', 'bottom']:
                raise ValueError()

            sign = 1 if which == 'top' else -1
            t_W0 = (sign * W0 <= sign).sum(axis=1)
            t_max = t_W0.max()

            ext = t_W0.index[t_W0 == t_max]
            if len(ext) > 1:
                ext = [W0[ext].max(axis=0).idxmax()]
            return ext[0]

        top = get_extreme('top')
        bot = get_extreme('bottom')
        D = nx.from_pandas_adjacency(np.abs(np.log(W0) + 1),
                                     create_using=nx.DiGraph)
        path = nx.bellman_ford_path(D, source=top, target=bot, weight='weight')

        return path
コード例 #33
0
def get_bicameral_cycle(reversed_graph,ksp,cost_bound,start_point,des_point,sp_num):
    aux_graph=get_cycle_aux_graph(reversed_graph,cost_bound,des_point)
    node_num=reversed_graph.number_of_nodes()
    #发现负环时直接使用负环,目前等待处理
    for upper_num in range(cost_bound+1):
        cycle=find_negative_cycle(aux_graph,get_split_node(start_point,upper_num,node_num))
        if cycle is not None:
            cycle=get_ori_path(cycle,node_num)
            cycle=get_best_cycle(reversed_graph,cycle)
            return cycle
            """
            if cycle_path_xor(cycle,ksp,sp_num) is not None:#负圈可能会无效,待解决
                print("负圈")
                return  cycle
            else:
                return None
            """
    #没有负环
    for node in reversed_graph.nodes():
        for upper_num_s in range(0,cost_bound):
            for upper_num_t in range(upper_num_s+1,cost_bound+1):
                s=get_split_node(node,upper_num_s,node_num)
                t=get_split_node(node,upper_num_t,node_num)
                try:#可能存在不可达的出错情况
                    path_delay=nx.bellman_ford_path_length(aux_graph,s,t,weight="delay")
                except:
                    continue
                if path_delay>=0:#当找到的路径没有改善时放弃
                    continue
                else:
                    #获得的是辅助图中的路径,需要转成普通路径
                    cycle_path=nx.bellman_ford_path(aux_graph,s,t,weight="delay")
                    ori_cycle=get_ori_path(cycle_path,node_num)
                    return get_best_cycle(reversed_graph,ori_cycle)
                    """
                    if cycle_path_xor(ori_cycle,ksp,sp_num) is  not None:
                        return ori_cycle#这里返回的时环的简单点路径,且首尾点重复
                    """
    return None
コード例 #34
0
def Bellman_Ford(G, start, end):
    return nx.bellman_ford_path(G, start, end)
    distancias = dict()
    anterior = dict()
    for V in list(G):
        distancias[V] = float('Inf')
        anterior[V] = None
    distancias[start] = 0
    for V in list(G):
        for u, v in G.edges():
            distancia = distancias[u] + 1
            if distancia < distancias[v]:
                distancias[v] = distancia
                anterior[v] = u
    antes = anterior[end]
    path = [end]
    while antes != start and antes is not None:
        path.insert(0, antes)
        antes = anterior[antes]
    if antes == start:
        path.insert(0, start)
        return path
    return []
コード例 #35
0
def get(G):
    #使用迪杰斯特拉算法获得从源结点(source)到目的结点的最短路径长度
    length1 = nx.dijkstra_path_length(G, 0, 4)
    #使用迪杰斯特拉算法获取从源结点(source)到目的结点的最短路径
    path1 = nx.dijkstra_path(G, 0, 4)
    #使用贝尔曼-福特算法获得从源结点(source)到目的结点的最短路径长度
    length2 = nx.bellman_ford_path_length(G, 0, 4)
    #使用贝尔曼-福特算法获取从源结点(source)到目的结点的最短路径
    path2 = nx.bellman_ford_path(G, 0, 4)
    #使用迪杰斯特拉算法获得每两个节点之间的最短路径长度
    length3 = dict(nx.all_pairs_dijkstra_path_length(G))
    #使用迪杰斯特拉算法获得每两个节点之间的最短路径
    path3 = dict(nx.all_pairs_dijkstra_path(G))

    #实现最短路径的高亮
    answer = []
    for i in range(0, len(path1) - 1):
        answer.append((path1[i], path1[i + 1]))
    nx.draw_networkx_edges(G,
                           pos,
                           edgelist=answer,
                           width=3.0,
                           alpha=0.5,
                           edge_color='y')