Пример #1
0
 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
Пример #2
0
 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
Пример #3
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)
Пример #4
0
    def _check_resource(r):
        # check resource r's feasibility along a path

        def __get_weight(i, j, attr_dict):
            # returns number to use as weight for the algorithm
            return attr_dict['res_cost'][r]

        # Get paths from source to all other nodes
        length_s, path_s = single_source_bellman_ford(G,
                                                      'Source',
                                                      weight=__get_weight)
        length_t, path_t = single_source_bellman_ford(G.reverse(copy=True),
                                                      'Sink',
                                                      weight=__get_weight)

        try:
            # Collect nodes in paths that violate the resource bounds
            # see note above
            nodes_source.update({
                path_s[key][-1]: (val, r)
                for key, val in length_s.items()
                if (key != 'Source') and (val > max_res[r])
            })
            nodes_sink.update({
                path_t[key][-1]: (val, r)
                for key, val in length_t.items()
                if (key != 'Sink') and (val > max_res[r])
            })
        except IndexError:  # No nodes violate resource limits
            pass
Пример #5
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(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)
Пример #6
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)])
Пример #7
0
 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 optimal_path(g, s, t):
    """BEHAVIOUR: Given a graph g, a source date s and a target date t, find
    the path from any currency at s to any currency at t that maximises profit.
    
    PRECONDITIONS: Dates s and t are present in g with t after s. g only has
    four currencies USDEUR, USDJPY, USDGBP and USDAUD. g has nodes and edges in
    the form produced by make_graph.
    
    POSTCONDITION: Returns a float which represents the profit as a percentage
    and a list of nodes which represents the optimal path. If g has no path
    which increases value, returns 0 and an empty list."""

    currencies = ["USDEUR", "USDJPY", "USDGBP", "USDAUD"]
    length = 0
    path = []
    for c in currencies:
        for x in currencies:
            t_length, t_path = nx.single_source_bellman_ford(g,
                                                             source=s + c,
                                                             target=t + x,
                                                             weight="weight")
            # Our graphs can never have negative weight cycles so in theory
            # Dijsktra should work. However, nx.dijsktra is not guaranteed to
            # work for negative or float edge weights and we have both.
            if t_length < length:
                length = t_length
                path = t_path
                # Updates length and path if a more profitable path is found
                # with a different source or target.
    multiplier = math.exp(-length)
    profit = multiplier * 100 - 100
    return profit, path
Пример #9
0
 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})
Пример #10
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 cal_dist(Gn, q, p):
    for edge in G.edges:
        i, j = edge[0], edge[1]
        G[i][j]['length'] = max(G[i][j]['reduce_cost'], 0)
    length, path = nx.single_source_bellman_ford(G, q, weight='length')
    for i in length:
        G.node[i]['potential'] = G.node[i]['potential'] - length[i]

    return path[p]
Пример #12
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)
Пример #13
0
    def timeComparison(self, total_iterations):
        with open('Gnutella31.csv', mode='a+') as csv_file:
            fieldnames = ['Start', 'End', 'Algorithm', 'HopNumber', 'Time']
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

            i = 1
            while (i < total_iterations):
                node1 = RandomNodes(self.getMainGraph())
                node2 = RandomNodes(self.getMainGraph())
                print("From ", node1, " To ", node2, "İteration Number : ", i)

                if (self.checkPath(node1, node2) == True):

                    start = time.process_time()
                    self.astar = astarpath(self.getMainGraph(), node1, node2)
                    time1 = time.process_time() - start
                    writer.writerow({
                        'Start': node1,
                        'End': node2,
                        'Algorithm': 'Astar',
                        'HopNumber': len(self.astar),
                        'Time': time1
                    })

                    start = time.process_time()
                    self.dij = nx.single_source_dijkstra(
                        self.getMainGraph(), node1, node2)
                    time2 = time.process_time() - start
                    writer.writerow({
                        'Start': node1,
                        'End': node2,
                        'Algorithm': 'Dijkstra',
                        'HopNumber': len(self.dij[1]),
                        'Time': time2
                    })

                    start = time.process_time()
                    self.bellmanford = nx.single_source_bellman_ford(
                        self.getMainGraph(), node1, node2)
                    time3 = time.process_time() - start
                    writer.writerow({
                        'Start': node1,
                        'End': node2,
                        'Algorithm': 'Bellman-Ford',
                        'HopNumber': len(self.bellmanford[1]),
                        'Time': time3
                    })
                    i = i + 1
                else:
                    i = i + 1
                    continue
        subGraph = GraphCreator(self.astar)
        neighbor_list = AllNeighbors(self.getMainGraph(), self.astar)
        GraphWithNeighbors(subGraph, neighbor_list, self.astar)
Пример #14
0
 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}))
Пример #15
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
Пример #16
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)
Пример #17
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)
Пример #18
0
    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}))
Пример #19
0
    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}))
Пример #20
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
Пример #21
0
def filter_shortest_path(read_df, aligner="minimap2"):
    aligns = read_df[read_df.pass_filter]
    num_aligns = len(aligns)
    if num_aligns < 2:
        # can't build a graph, so nothing is filtered by this method
        return read_df

    if aligner == "minimap2":
        gap_fn = minimap_gapscore
    elif aligner == "bwa":
        gap_fn = bwa_gapscore
    else:
        raise ValueError(f"Unrecognised aligner: {aligner}")
    graph = create_align_graph(aligns, gap_fn)
    distance, shortest_path = nx.single_source_bellman_ford(graph, "ROOT", "SINK")
    for idx in aligns.index:
        if idx not in shortest_path:
            read_df.at[idx, "pass_filter"] = False
            read_df.at[idx, "filter_reason"] = "not_on_shortest_path"
    return read_df
Пример #22
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}))
Пример #23
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: [], 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}))
Пример #24
0
def skeleton_path(arr, base_id, dist, slice_interval):

    slice_ids = (dist / slice_interval).astype(int)

    G_skeleton = nx.Graph()

    uids = np.unique(slice_ids)
    pair = {}
    pair_dist = {}
    for u in range(len(uids[:-1])):
        mask_current = np.where(slice_ids == uids[u])[0]
        mask_next = np.where(slice_ids >= uids[u])[0]
        nbr_dist, nbr_ids = tls.utility.set_nbrs_knn(arr[mask_current],
                                                     arr[mask_next],
                                                     1,
                                                     return_dist=True)
        nbr_ids = nbr_ids.astype(int)
        for i, (ni, nd) in enumerate(zip(nbr_ids, nbr_dist)):
            if nd > 0:
                current_id = mask_next[i]
                back_id = mask_current[ni][0]
                if current_id in pair:
                    pair[current_id].append(back_id)
                    pair_dist[current_id].append(nd)
                else:
                    pair[current_id] = [back_id]
                    pair_dist[current_id] = [nd]

    # WOOD STRUCTURE UP UNTIL HERE
    for k, v in pair.iteritems():
        d = pair_dist[k]
        min_id = np.argmin(d)
        G_skeleton.add_weighted_edges_from([(k, v[min_id], d[min_id])])

    path_distance, path_ids = nx.single_source_bellman_ford(
        G_skeleton, base_id)

    return path_ids, path_distance
Пример #25
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_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})
Пример #26
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_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})
Пример #27
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}
Пример #28
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)])
Пример #29
0
def creategraph(algo, data):
    file = data
    a1 = []
    a2 = []
    a3 = []
    a4 = []
    a5 = []
    splat = file.split("\r\n\r\n")
    for number, section in enumerate(splat, 1):
        if number % 5 == 1:
            a1 += [section]
        elif number % 5 == 2:
            a2 += [section]
        elif number % 5 == 3:
            a3 += [section]
        elif number % 5 == 4:
            a4 += [section]
        elif number % 5 == 0:
            a5 += [section]

    a2 = int(a2[0])
    a5 = int(a5[0])
    Ad = adjency_matrix(a4, a2)
    G = nx.from_numpy_matrix(Ad)
    labels = []
    a3 = a3[0].split("\r\n")
    Xn = []
    Yn = []
    for i in range(0, a2):
        a3[i] = a3[i].split("\t")
        Xn.append(float(a3[i][1]))
        Yn.append(float(a3[i][2]))

    for i in range(0, a2):
        labels.append(i)

    if algo == "Prims":
        mst = tree.minimum_spanning_edges(G, algorithm='prim', data=False)
        path = list(mst)
        length = 0
        for i in range(0, len(path)):
            length = length + Ad[path[i][0]][path[i][1]]
        title = "Prims Cost : " + str(length)
        Xe = []
        Ye = []
        Xe2 = []
        Ye2 = []
        for e in G.edges():
            for i in range(0, len(path) - 1):
                if (e[0] == path[i][0] and e[1] == path[i + 1][1]):
                    Xe2.extend([Xn[e[0]], Xn[e[1]], None])
                    Ye2.extend([Yn[e[0]], Yn[e[1]], None])
            Xe.extend([Xn[e[0]], Xn[e[1]], None])
            Ye.extend([Yn[e[0]], Yn[e[1]], None])
    elif algo == "Kruskals":
        mst = tree.minimum_spanning_edges(G, algorithm='prim', data=False)
        path = list(mst)
        length = 0
        for i in range(0, len(path)):
            length = length + Ad[path[i][0]][path[i][1]]
        title = "Kruskal Cost : " + str(length)
        Xe = []
        Ye = []
        Xe2 = []
        Ye2 = []
        for e in G.edges():
            for i in range(0, len(path) - 1):
                if (e[0] == path[i][0] and e[1] == path[i + 1][1]):
                    Xe2.extend([Xn[e[0]], Xn[e[1]], None])
                    Ye2.extend([Yn[e[0]], Yn[e[1]], None])
            Xe.extend([Xn[e[0]], Xn[e[1]], None])
            Ye.extend([Yn[e[0]], Yn[e[1]], None])
    elif algo == "Dijkstra":
        length, path = nx.bidirectional_dijkstra(G, a5, a2 - 1)
        title = "Dijkstra Cost : " + str(length)
        Xe = []
        Ye = []
        Xe2 = []
        Ye2 = []
        for e in G.edges():
            for i in range(0, len(path) - 1):
                if (e[0] == path[i] and e[1] == path[i + 1]):
                    Xe2.extend([Xn[e[0]], Xn[e[1]], None])
                    Ye2.extend([Yn[e[0]], Yn[e[1]], None])
            Xe.extend([Xn[e[0]], Xn[e[1]], None])
            Ye.extend([Yn[e[0]], Yn[e[1]], None])
    elif algo == "Bellman Ford":
        length, path = nx.single_source_bellman_ford(G, 6, a2 - 1)
        title = "Bellman Ford Cost : " + str(length)
        Xe = []
        Ye = []
        Xe2 = []
        Ye2 = []
        for e in G.edges():
            for i in range(0, len(path) - 1):
                if (e[0] == path[i] and e[1] == path[i + 1]):
                    Xe2.extend([Xn[e[0]], Xn[e[1]], None])
                    Ye2.extend([Yn[e[0]], Yn[e[1]], None])
            Xe.extend([Xn[e[0]], Xn[e[1]], None])
            Ye.extend([Yn[e[0]], Yn[e[1]], None])
    elif algo == "Floyd Warshall":
        path = nx.floyd_warshall_numpy(G)
        np.fill_diagonal(path, path.max())
        title = "Floyd Warshall Cost : " + str(path.min())
        Xe = []
        Ye = []
        Xe2 = []
        Ye2 = []
        for e in G.edges():
            Xe.extend([Xn[e[0]], Xn[e[1]], None])
            Ye.extend([Yn[e[0]], Yn[e[1]], None])
    elif algo == "Clustering":
        c = nx.average_clustering(G)
        title = "Clustering Cost : " + str(c)
        Xe = []
        Ye = []
        Xe2 = []
        Ye2 = []
        for e in G.edges():
            Xe.extend([Xn[e[0]], Xn[e[1]], None])
            Ye.extend([Yn[e[0]], Yn[e[1]], None])

    trace_nodes = dict(type='scatter',
                       x=Xn,
                       y=Yn,
                       mode='markers',
                       marker=dict(size=28, color='peru'),
                       text=labels,
                       hoverinfo='text')

    trace_edges = dict(type='scatter',
                       mode='lines',
                       arrowstyle='->',
                       x=Xe,
                       y=Ye,
                       line=dict(width=1, color='royalblue'),
                       hoverinfo='none')

    trace_edges2 = dict(type='scatter',
                        mode='lines',
                        x=Xe2,
                        y=Ye2,
                        line=dict(width=4.1, color="firebrick"),
                        hoverinfo='none')
    axis = dict(
        showline=True,  # hide axis line, grid, ticklabels and  title
        zeroline=False,
        showgrid=True,
        showticklabels=True,
        title='')

    layout = dict(
        title=title,
        font=dict(family='Balto'),
        showlegend=True,
        xaxis=axis,
        yaxis=axis,
    )

    annotations = []
    for k in range(a2):
        annotations.append(
            dict(
                text=labels[k],
                x=Xn[k],
                y=Yn[k],  #this additional value is chosen by trial and error
                xref='x1',
                yref='y1',
                font=dict(color='rgb(10,10,10)', size=14),
                showarrow=False))
    data = dict(data=[trace_edges, trace_edges2, trace_nodes], layout=layout)
    data['layout'].update(annotations=annotations)
    return data
Пример #30
0
def skeleton_path(centres, max_dist=.1, verbose=False):
    """
    parameters
    ----------
    max_dist; float (default .1)
    maximum distance between nodes, designed to stop large gaps being spanned
    i.e. it is better to have a disconnection than an unrealistic conncetion
    """

    edges = pd.DataFrame(columns=['node1', 'node2', 'length'])

    if verbose: print('generating graph...')
    for i, row in tqdm(enumerate(centres.itertuples()),
                       total=len(centres),
                       disable=False if verbose else True):

        # first node
        if row.distance_from_base == centres.distance_from_base.min(): continue

        n, dist = 3, np.inf

        while n < 10 and dist > max_dist:

            # between required incase of small gap in pc
            nbrs = centres.loc[centres.slice_id.between(
                row.slice_id - n, row.slice_id - 1)]
            nbrs.loc[:, 'dist'] = np.linalg.norm(
                np.array([row.cx, row.cy, row.cz]) -
                nbrs[['cx', 'cy', 'cz']].values,
                axis=1)
            dist = nbrs.dist.min()
            n += 1

        if np.isnan(nbrs.dist.min()
                    ):  # prob an outlying cluster that can be removed
            continue

        edges = edges.append(
            {
                'node1':
                int(row.node_id),
                'node2':
                int(nbrs.loc[nbrs.dist == nbrs.dist.min()].node_id.values[0]),
                'length':
                nbrs.dist.min()
            },
            ignore_index=True)

    idx = centres.distance_from_base.idxmin()
    base_id = centres.loc[idx].node_id

    G_skeleton = nx.Graph()
    G_skeleton.add_weighted_edges_from([(int(row.node1), int(row.node2),
                                         row.length)
                                        for row in edges.itertuples()])

    path_distance, path_ids = nx.single_source_bellman_ford(
        G_skeleton, base_id)
    path_distance = {
        k: v if not isinstance(v, np.ndarray) else v[0]
        for k, v in path_distance.items()
    }

    centres.distance_from_base = centres.node_id.map(path_distance)
    # required as sometimes pc2graph produces strange results

    return path_distance, path_ids
Пример #31
0
                                       create_using=nx.DiGraph())
    fpath, fdist = fnx.single_source_shortest_path(frov_graph, src, \
                                                   return_distance=True)

    FrovedisServer.shut_down()
except Exception as e:
    sub_str = "sssp: negative cost cycle is detected!"
    if sub_str in str(e):
        exc1 = True
    else:
        print("status=Exception: " + str(e))
        sys.exit(1)

#NetworkX
try:
    nx_graph = nx.read_edgelist(DATASET, nodetype=np.int32, \
                                data=(("weight", float),), delimiter=' ', \
                                create_using=nx.DiGraph())
    npath = nx.single_source_bellman_ford(nx_graph, src)
except Exception as e:
    sub_str = "Negative cost cycle detected."
    if sub_str in str(e):
        exc2 = True
    else:
        print("status=Exception: " + str(e))
        sys.exit(1)
if exc1 and exc2:
    print("status=Passed")
else:
    print("status=Failed")
Пример #32
0
def cal_potential(G):
    length, path = nx.single_source_bellman_ford(G, 's', weight='c')

    for i in length:
        G.node[i]['potential'] = length[i]
Пример #33
0
def get_bellmanford(graph, src, dest):
    return nx.single_source_bellman_ford(graph, src, dest)
Пример #34
0
 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
     }))
Пример #35
0
def compute_all_pair_shortest_path(graphs_single_robot, trees_single_robot):
    all_pairs_shortest_paths_per_robot = []
    all_pairs_shortest_paths_per_robot_b = [
        dict() for i in range(len(graphs_single_robot))
    ]
    subgraph_nodes = [0] * len(graphs_single_robot)
    for i in range(len(graphs_single_robot)):
        all_pairs_shortest_paths_per_robot.append( \
            nx.johnson(graphs_single_robot[i], weight='weight'))
        subgraph_nodes[i] = random.sample(
            graphs_single_robot[i].nodes,
            math.ceil(len(graphs_single_robot[i].nodes) / 10))
        if len(
                subgraph_nodes[i]
        ) == 1:  # single_source_bellman_ford gets stuck on single node graph, so this is an edge case
            all_pairs_shortest_paths_per_robot_b[i][subgraph_nodes[i]
                                                    [0]] = dict()
            all_pairs_shortest_paths_per_robot_b[i][subgraph_nodes[i][0]][
                subgraph_nodes[i][0]] = [subgraph_nodes[i][0]]
        else:
            for j in range(len(subgraph_nodes[i])):
                all_pairs_shortest_paths_per_robot_b[i][
                    subgraph_nodes[i][j]] = nx.single_source_bellman_ford(
                        graphs_single_robot[i],
                        subgraph_nodes[i][j],
                        target=None,
                        weight='weight')[1]
        while len(all_pairs_shortest_paths_per_robot_b[i]) < len(
                graphs_single_robot[i].nodes):
            for node in list(all_pairs_shortest_paths_per_robot_b[i].keys()):
                N = drrt_ao.adj(graphs_single_robot[i], node)
                for neighbor in N:
                    if neighbor in all_pairs_shortest_paths_per_robot_b[i]:
                        continue
                    else:
                        all_pairs_shortest_paths_per_robot_b[i][
                            neighbor] = dict()
                        for key in all_pairs_shortest_paths_per_robot_b[i][
                                node].keys():
                            all_pairs_shortest_paths_per_robot_b[
                                i][neighbor][key] = list(
                                    all_pairs_shortest_paths_per_robot_b[i]
                                    [node][key]
                                )  # attaching copy of the list of the neighbor
                            all_pairs_shortest_paths_per_robot_b[i][neighbor][
                                key].insert(0, neighbor)
                            if key == neighbor:
                                all_pairs_shortest_paths_per_robot_b[i][neighbor][
                                    key] = all_pairs_shortest_paths_per_robot_b[
                                        i][neighbor][key][:1]
    for i in range(
            len(graphs_single_robot)
    ):  # A check to see the johnson and bellman ford dictionaries are equal
        for key in all_pairs_shortest_paths_per_robot[i].keys():
            if key not in all_pairs_shortest_paths_per_robot_b[i]:
                print("check out")
            else:
                for inkey in all_pairs_shortest_paths_per_robot[i][key].keys():
                    if inkey not in all_pairs_shortest_paths_per_robot_b[i][
                            key]:
                        print("check in")
    return all_pairs_shortest_paths_per_robot_b
Пример #36
0
def bellman_ford(G, initial_node, target_node, weight):
    weight = Graph._weight(G, weight)
    distance, route = nx.single_source_bellman_ford(G, initial_node,
                                                    target_node, weight)
    return distance, route
Пример #37
0
def bellman_ford_explored(G, source, destination):
    return " -> ".join(nx.single_source_bellman_ford(G, source)[1])
Пример #38
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
            },
        )