Beispiel #1
0
    def update_path(self):
        m = self.edge_number
        es = self.es
        et = self.et
        ds = self.ds
        dt = self.dt
        G = nx.DiGraph()
        E = [(int(es[k]), int(et[k]), self.time[k]) for k in range(m)]
        G.add_weighted_edges_from(E)
        shortest_path = dict(nx.all_pairs_bellman_ford_path(G))
        greedy_cost = 0
        n_path = len(self.f_vec)
        new_cost = list()
        l = 0
        for k in range(len(self.q)):
            path = shortest_path[int(ds[k])][int(dt[k])]
            edges = self.edge_serial[es[path[:-1]], et[path[1:]]]
            c_min = torch.sum(self.time[edges])
            greedy_cost += self.q[k] * c_min
            path_k = self.pool[k]
            if torch.min(torch.abs(self.cost_vec[path_k] - c_min)) < 1e-10:
                continue
            self.pool[k].append(n_path + l)
            new_cost.append(c_min)
            for a in edges:
                self.path_vec[0].append(int(a))
                self.path_vec[1].append(n_path + l)
            l += 1
        self.cost_vec = torch.cat((self.cost_vec, torch.tensor(new_cost)))
        zero_vector = torch.zeros(len(new_cost), dtype=torch.double)
        self.f_vec = torch.cat((self.f_vec, zero_vector))
        self.vectorization()

        return greedy_cost
Beispiel #2
0
def calc_shortest_path(Ga):
    G = Ga.copy()
    update_weight(G)

    f1 = open("../data/length.file", "wb")
    f2 = open("../data/path.file", "wb")

    def dict2df(data):
        return pd.DataFrame.from_dict(data, orient='index')

    length = dict(nx.all_pairs_bellman_ford_path_length(G))
    path = dict(nx.all_pairs_bellman_ford_path(G))

    pickle.dump(length, f1)
    pickle.dump(path, f2)
    def Update_shortest_dis(self):
        # change the dis matrix to avoid deleted edges in initial heuristic
        # This is needed for left nodes and the nodes under them
        # We use bellman ford algorithm to find al pair shorets beased on new Graph
        #Dis=nx.all_pairs_bellman_ford_path_length(self.G  ,  weight='Travel_time')

        paths = dict(nx.all_pairs_bellman_ford_path(self.G))
        for i, j in it.combinations(self.G.node, 2):
            path = paths[i][j]
            travel_dis = 0
            pernode = path.pop(0)
            while len(path):
                Cnode = path.pop(0)
                travel_dis += self.G.edges[pernode, Cnode]["Travel_distance"]
                pernode = Cnode
            self.Dis[i, j] = travel_dis
            self.Dis[j, i] = travel_dis
Beispiel #4
0
 def test_all_pairs_shortest_path(self):
     p = nx.shortest_path(self.cycle)
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_shortest_path(self.cycle)))
     p = nx.shortest_path(self.grid)
     validate_grid_path(4, 4, 1, 12, p[1][12])
     # now with weights
     p = nx.shortest_path(self.cycle, weight='weight')
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_dijkstra_path(self.cycle)))
     p = nx.shortest_path(self.grid, weight='weight')
     validate_grid_path(4, 4, 1, 12, p[1][12])
     # weights and method specified
     p = nx.shortest_path(self.cycle, weight='weight', method='dijkstra')
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_dijkstra_path(self.cycle)))
     p = nx.shortest_path(self.cycle, weight='weight',
                          method='bellman-ford')
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_bellman_ford_path(self.cycle)))
Beispiel #5
0
 def test_all_pairs_shortest_path(self):
     p = nx.shortest_path(self.cycle)
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_shortest_path(self.cycle)))
     p = nx.shortest_path(self.grid)
     validate_grid_path(4, 4, 1, 12, p[1][12])
     # now with weights
     p = nx.shortest_path(self.cycle, weight='weight')
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_dijkstra_path(self.cycle)))
     p = nx.shortest_path(self.grid, weight='weight')
     validate_grid_path(4, 4, 1, 12, p[1][12])
     # weights and method specified
     p = nx.shortest_path(self.cycle, weight='weight', method='dijkstra')
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_dijkstra_path(self.cycle)))
     p = nx.shortest_path(self.cycle, weight='weight',
                          method='bellman-ford')
     assert_equal(p[0][3], [0, 1, 2, 3])
     assert_equal(p, dict(nx.all_pairs_bellman_ford_path(self.cycle)))
Beispiel #6
0
 def test_all_pairs_shortest_path(self):
     p = nx.shortest_path(self.cycle)
     assert p[0][3] == [0, 1, 2, 3]
     assert p == dict(nx.all_pairs_shortest_path(self.cycle))
     p = nx.shortest_path(self.grid)
     validate_grid_path(4, 4, 1, 12, p[1][12])
     # now with weights
     p = nx.shortest_path(self.cycle, weight="weight")
     assert p[0][3] == [0, 1, 2, 3]
     assert p == dict(nx.all_pairs_dijkstra_path(self.cycle))
     p = nx.shortest_path(self.grid, weight="weight")
     validate_grid_path(4, 4, 1, 12, p[1][12])
     # weights and method specified
     p = nx.shortest_path(self.cycle, weight="weight", method="dijkstra")
     assert p[0][3] == [0, 1, 2, 3]
     assert p == dict(nx.all_pairs_dijkstra_path(self.cycle))
     p = nx.shortest_path(self.cycle,
                          weight="weight",
                          method="bellman-ford")
     assert p[0][3] == [0, 1, 2, 3]
     assert p == dict(nx.all_pairs_bellman_ford_path(self.cycle))
Beispiel #7
0
 def initialize_path(self):
     m = self.edge_number
     es = self.es
     et = self.et
     ds = self.ds
     dt = self.dt
     G = nx.DiGraph()
     E = [(int(es[k]), int(et[k]), self.time[k]) for k in range(m)]
     G.add_weighted_edges_from(E)
     shortest_path = dict(nx.all_pairs_bellman_ford_path(G))
     flow = torch.zeros(m, dtype=torch.double)
     self.f_vec = 1.0 * self.q
     self.cost_vec = torch.zeros_like(self.q)
     for k in range(len(self.q)):
         path = shortest_path[int(ds[k])][int(dt[k])]
         edges = self.edge_serial[es[path[:-1]], et[path[1:]]]
         self.cost_vec[k] = torch.sum(self.time[edges])
         self.pool[k] = [k]
         flow[edges] += self.q[k]
         for a in edges:
             self.path_vec[0].append(int(a))
             self.path_vec[1].append(k)
     self.x = flow
Beispiel #8
0
def shortest_path(G, source=None, target=None, weight=None, method='dijkstra'):
    """Compute shortest paths in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node, optional
        Starting node for path. If not specified, compute shortest
        paths for each possible starting node.

    target : node, optional
        Ending node for path. If not specified, compute shortest
        paths to all possible nodes.

    weight : None or string, optional (default = None)
        If None, every edge has weight/distance/cost 1.
        If a string, use this edge attribute as the edge weight.
        Any edge attribute not present defaults to 1.

    method : string, optional (default = 'dijkstra')
        The algorithm to use to compute the path.
        Supported options: 'dijkstra', 'bellman-ford'.
        Other inputs produce a ValueError.
        If `weight` is None, unweighted graph methods are used, and this
        suggestion is ignored.

    Returns
    -------
    path: list or dictionary
        All returned paths include both the source and target in the path.

        If the source and target are both specified, return a single list
        of nodes in a shortest path from the source to the target.

        If only the source is specified, return a dictionary keyed by
        targets with a list of nodes in a shortest path from the source
        to one of the targets.

        If only the target is specified, return a dictionary keyed by
        sources with a list of nodes in a shortest path from one of the
        sources to the target.

        If neither the source nor target are specified return a dictionary
        of dictionaries with path[source][target]=[list of nodes in path].

    Raises
    ------
    NodeNotFound
        If `source` is not in `G`.

    ValueError
        If `method` is not among the supported options.

    Examples
    --------
    >>> G = nx.path_graph(5)
    >>> print(nx.shortest_path(G, source=0, target=4))
    [0, 1, 2, 3, 4]
    >>> p = nx.shortest_path(G, source=0) # target not specified
    >>> p[4]
    [0, 1, 2, 3, 4]
    >>> p = nx.shortest_path(G, target=4) # source not specified
    >>> p[0]
    [0, 1, 2, 3, 4]
    >>> p = nx.shortest_path(G) # source, target not specified
    >>> p[0][4]
    [0, 1, 2, 3, 4]

    Notes
    -----
    There may be more than one shortest path between a source and target.
    This returns only one of them.

    See Also
    --------
    all_pairs_shortest_path()
    all_pairs_dijkstra_path()
    all_pairs_bellman_ford_path()
    single_source_shortest_path()
    single_source_dijkstra_path()
    single_source_bellman_ford_path()
    """
    if method not in ('dijkstra', 'bellman-ford'):
        # so we don't need to check in each branch later
        raise ValueError('method not supported: {}'.format(method))
    method = 'unweighted' if weight is None else method
    if source is None:
        if target is None:
            # Find paths between all pairs.
            if method == 'unweighted':
                paths = dict(nx.all_pairs_shortest_path(G))
            elif method == 'dijkstra':
                paths = dict(nx.all_pairs_dijkstra_path(G, weight=weight))
            else:  # method == 'bellman-ford':
                paths = dict(nx.all_pairs_bellman_ford_path(G, weight=weight))
        else:
            # Find paths from all nodes co-accessible to the target.
            with nx.utils.reversed(G):
                if method == 'unweighted':
                    paths = nx.single_source_shortest_path(G, target)
                elif method == 'dijkstra':
                    paths = nx.single_source_dijkstra_path(G,
                                                           target,
                                                           weight=weight)
                else:  # method == 'bellman-ford':
                    paths = nx.single_source_bellman_ford_path(G,
                                                               target,
                                                               weight=weight)
                # Now flip the paths so they go from a source to the target.
                for target in paths:
                    paths[target] = list(reversed(paths[target]))
    else:
        if target is None:
            # Find paths to all nodes accessible from the source.
            if method == 'unweighted':
                paths = nx.single_source_shortest_path(G, source)
            elif method == 'dijkstra':
                paths = nx.single_source_dijkstra_path(G,
                                                       source,
                                                       weight=weight)
            else:  # method == 'bellman-ford':
                paths = nx.single_source_bellman_ford_path(G,
                                                           source,
                                                           weight=weight)
        else:
            # Find shortest source-target path.
            if method == 'unweighted':
                paths = nx.bidirectional_shortest_path(G, source, target)
            elif method == 'dijkstra':
                paths = nx.dijkstra_path(G, source, target, weight)
            else:  # method == 'bellman-ford':
                paths = nx.bellman_ford_path(G, source, target, weight)
    return paths