def test_pathweight():
    valid_path = [1, 2, 3]
    invalid_path = [1, 3, 2]
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    edges = [
        (1, 2, dict(cost=5, dist=6)),
        (2, 3, dict(cost=3, dist=4)),
        (1, 2, dict(cost=1, dist=2)),
    ]
    for graph in graphs:
        graph.add_edges_from(edges)
        assert nx.path_weight(graph, valid_path, "cost") == 4
        assert nx.path_weight(graph, valid_path, "dist") == 6
        pytest.raises(nx.NetworkXNoPath, nx.path_weight, graph, invalid_path, "cost")
예제 #2
0
def approx_steiner(graph, terms):
    res = []
    Gt = nx.complete_graph(terms)

    #calcul de tout les plus court chemins
    path = dict(nx.all_pairs_shortest_path(graph))

    #pour chaque combinaison de 2 noeuds
    for (i, j) in it.combinations(terms, 2):
        #on met le poids au plus court chemin dans Gt
        Gt.add_edge(i,
                    j,
                    weight=nx.path_weight(graph, path[i][j], weight="weight"))

    #arbre couvrant minimum de Gt
    A = list(nx.minimum_spanning_tree(Gt).edges(data=True))

    for i in range(len(A)):
        pcc = path[A[i][0]][A[i][1]]
        for j in range(len(pcc) - 1):

            pair = (pcc[j], pcc[j + 1])
            res.append(pair)

    print_graph(Gt, terms)

    return res
def sum_costs(G, path, impedance):
    """
    This function calculates the sum of the costs
    of a path created according to the geographic
    scenario graph.

    :param G:       NetworkX graph.
                    Geographic scenario

    :param path:    list
                    The list must contains the id
                    of nodes of the path.

    :param weight:  String or function

    :return:        float
                    The sum of all cost (weight)
                    edges of the path.
    """
    sum_costs = nx.path_weight(G, path,
                               impedance)  # Graph._weight(G, impedance)
    #sum_costs = 0

    #for i in range(len(path)-1):
    #    e = G.adj[path[i]].get(path[i + 1])
    #    weight_edge = Graph.get_edge_weight(G, path[i], path[i + 1], e, impedance)
    #    sum_costs += weight_edge

    return sum_costs
def similar_length(
    M, G, R, S, T, cutoff
):  #cutoff=percentage of shortest path longer ie 110% would be cutoff=1.10
    tol = 1e-5
    (paths, lengths) = return_paths(M, G, R, S, T)

    G_adj = nx.Graph()
    norm = np.sqrt(sum(M.t[i].value * M.t[i].value for i in M.V))
    for (i, j) in G.edges:
        l = G[i][j]['length']
        r = G[i][j]['interdicted_length']
        if M.x[(i, j)].value >= 0.9:
            length = l + r
            if norm > tol:
                adjustment = (-1 / norm) * (sum(R[(i, j, k - 1)] * M.t[k].value
                                                for k in M.V))
                length = length + adjustment
        else:
            length = l
        if G_adj.has_edge(j, i):
            #Check which length to use
            if G_adj[j][i][
                    'adjusted_length'] <= length:  #Shorter Lengths indicate that the edge has been interdicted so we shoudl use that value for both directions
                G_adj[i][j]['adjusted_length'] = length
        else:
            G_adj.add_edge(i, j, adjusted_length=length)

    similar_paths = []
    all_paths = list(
        islice(nx.shortest_simple_paths(G_adj, S, T, weight='adjusted_length'),
               30))

    for path in all_paths:
        if nx.path_weight(G_adj, path,
                          weight='adjusted_length') <= cutoff * lengths:
            similar_paths.append(path)
        else:
            break
    no_of_similar_paths = len(similar_paths)
    return (similar_paths, no_of_similar_paths)
예제 #5
0
    def get_optimal_path(self,
                         start: Tuple,
                         goal: Tuple,
                         distance_tolerance=.05) -> List[Tuple]:
        """
        Provides the optimal path from start to goal. All inputs should be in the global coordinate frame. Output
        waypoints are in the global coordinate frame.
        :param start: tuple with x,y coordinates of starting location (in mm).
        :param goal: tuple with x,y coordinate of goal location (in mm).
        :param distance_tolerance: how close to the goal the path should be to.
        :return: List of waypoints representing the path.
        """
        if self.display:
            print('Initializing Display')
            self.__init_display(start, goal)

        self.__build_tree(start)
        graph = self.__build_graph(self.vertices, self.edges)
        potential_goals = []
        for vertex in self.vertices:  # find all vertices within 5m of goal
            if self.__euclidean_dist(vertex, goal) < distance_tolerance:
                potential_goals.append(vertex)

        path_queue = []
        for potential_goal in potential_goals:  # find shortest path among potential goals
            path = networkx.shortest_path(graph,
                                          start,
                                          potential_goal,
                                          weight='weight')
            cost = networkx.path_weight(graph, path, weight='weight')
            heapq.heappush(path_queue, (cost, path))
        if len(path_queue) == 0:
            return []

        best_path = heapq.heappop(path_queue)[1]
        best_path = self.__add_heading_to_waypoints(best_path, start[2],
                                                    goal[2])
        if self.display:
            self.__draw_optimal_path(best_path)
        return best_path
예제 #6
0
def parse_grid(grid, p2=False):
    R = len(grid)
    C = len(grid[0])

    G = nx.DiGraph()

    # Add the edges
    for r in range(R):
        for c in range(C):
            G.add_node((r, c), pos=[r, c])

            # Every point has an edge to another point up and down
            for dr, dc in [[1, 0], [0, 1], [-1, 0], [0, -1]]:
                rr = r + dr
                cc = c + dc
                if not (dr == 0
                        and dc == 0) and (0 <= rr < R) and (0 <= cc < C):
                    weight = grid[rr][cc]
                    G.add_edge((r, c), (rr, cc), weight=weight)

    path = nx.dijkstra_path(G, (0, 0), (R - 1, C - 1), weight="weight")
    return nx.path_weight(G, path, weight="weight")
     (47, 48, 20)]
G = nx.DiGraph()
for fr, to, cp in e:
    G.add_edge(fr, to, weight=cp)

plt.subplot(121)
nx.draw(G, with_labels=True)
plt.show()

##Минимальный путь с помошью ф-ции библиотеки networkx.algorithms.shortest_paths.generic.shortest_path
p = nx.shortest_path(G,
                     source=1,
                     target=48,
                     weight="weight",
                     method="dijkstra")
weight = nx.path_weight(G, p, "weight")

print("Путь ", end="")
for count, value in enumerate(p):
    if count < len(p) - 1:
        print(value, end=" -> ")
    else:
        print(value)
print("Вес пути", weight)

##инициализация графа
e = [(1, 2, 19), (2, 3, 15), (3, 4, 23), (4, 5, 22), (5, 6, 16), (6, 7, 16),
     (7, 8, 23), (1, 9, 23), (2, 10, 17), (3, 11, 23), (4, 12, 15),
     (5, 13, 15), (6, 14, 24), (7, 15, 15), (8, 16, 22), (9, 10, 15),
     (10, 11, 16), (11, 12, 15), (12, 13, 21), (13, 14, 20), (14, 15, 20),
     (15, 16, 18), (9, 17, 23), (10, 18, 19), (11, 19, 19), (12, 20, 24),
예제 #8
0
def calculate_stacking_velocity(semblance,
                                times,
                                velocities,
                                start_velocity_range,
                                end_velocity_range,
                                max_acceleration=None,
                                n_times=25,
                                n_velocities=25):
    """Calculate stacking velocity by given semblance.

    Stacking velocity is the value of the seismic velocity obtained from the best fit of the traveltime curve by a
    hyperbola for each timestamp. It is used to correct the arrival times of reflection events in the traces for their
    varying offsets prior to stacking.

    If calculated by semblance, stacking velocity must meet the following conditions:
    1. It should be monotonically increasing
    2. Its gradient should be bounded above to avoid gather stretching after NMO correction
    3. It should pass through local energy maxima on the semblance

    In order for these conditions to be satisfied, the following algorithm is proposed:
    1. Stacking velocity is being found inside a trapezoid whose vertices at first and last time are defined by
       `start_velocity_range` and `end_velocity_range` respectively.
    2. An auxiliary directed graph is constructed so that:
        1. `n_times` evenly spaced points are generated to cover the whole semblance time range. For each of these
           points `n_velocities` evenly spaced points are generated to cover the whole range of velocities inside the
           trapezoid from its left to right border. All these points form a set of vertices of the graph.
        2. An edge from a vertex A to a vertex B exists only if:
            1. Vertex B is located at the very next timestamp after vertex A,
            2. Velocity at vertex B is no less than at A,
            3. Velocity at vertex B does not exceed that of A by a value determined by `max_acceleration` provided.
        3. Edge weight is defined as sum of semblance values along its path.
    3. A path with maximal semblance sum along it between any of starting and ending nodes is found using Dijkstra
       algorithm and is considered to be the required stacking velocity.

    Parameters
    ----------
    semblance : 2d np.ndarray
        An array with calculated vertical velocity semblance values.
    times : 1d np.ndarray
        Recording time for each seismic trace value for which semblance was calculated. Measured in milliseconds.
    velocities : 1d np.ndarray
        Range of velocity values for which semblance was calculated. Measured in meters/seconds.
    start_velocity_range : tuple with 2 elements
        Valid range for stacking velocity for the first timestamp. Both velocities are measured in meters/seconds.
    end_velocity_range : tuple with 2 elements
        Valid range for stacking velocity for the last timestamp. Both velocities are measured in meters/seconds.
    max_acceleration : None or float, defaults to None
        Maximal acceleration allowed for the stacking velocity function. If `None`, equals to
        2 * (mean(end_velocity_range) - mean(start_velocity_range)) / total_time. Measured in meters/seconds^2.
    n_times : int, defaults to 25
        The number of evenly spaced points to split time range into to generate graph vertices.
    n_velocities : int, defaults to 25
        The number of evenly spaced points to split velocity range into for each time to generate graph vertices.

    Returns
    -------
    stacking_times : 1d np.ndarray
        Times for which stacking velocities were picked. Measured in milliseconds.
    stacking_velocities : 1d np.ndarray
        Picked stacking velocities. Matches the length of `stacking_times`. Measured in meters/seconds.
    metric : float
        Sum of semblance values along the stacking velocity path.

    Raises
    ------
    ValueError
        If no path was found for given parameters.
    """
    times = np.asarray(times, dtype=np.float32)
    velocities = np.asarray(velocities, dtype=np.float32)

    start_velocity_range = np.array(start_velocity_range, dtype=np.float32)
    end_velocity_range = np.array(end_velocity_range, dtype=np.float32)

    # Calculate maximal velocity growth (in samples) between two adjacent timestamps,
    # for which graph nodes are created
    total_time = (times[-1] - times[0]) / 1000  # from ms to s
    if max_acceleration is None:
        max_acceleration = 2 * (np.mean(end_velocity_range) -
                                np.mean(start_velocity_range)) / total_time
    max_vel_step = np.ceil((max_acceleration * total_time / n_times) /
                           np.mean(velocities[1:] - velocities[:-1]))
    max_vel_step = np.int32(max_vel_step)

    # Create a graph and find paths with maximal semblance sum along them to all reachable nodes
    edges, start_node, end_nodes = create_edges(semblance, times, velocities,
                                                start_velocity_range,
                                                end_velocity_range,
                                                max_vel_step, n_times,
                                                n_velocities)
    graph = nx.DiGraph()
    graph.add_weighted_edges_from(zip(*edges))
    paths = nx.shortest_path(graph, source=start_node, weight="weight")  # pylint: disable=unexpected-keyword-arg

    # Select only paths to the nodes at the last timestamp and choose the optimal one
    path_weights = [(paths[end_node],
                     nx.path_weight(graph, paths[end_node], weight="weight"))
                    for end_node in end_nodes if end_node in paths]
    if not path_weights:
        raise ValueError("No path was found for given parameters")
    path, metric = min(path_weights, key=lambda x: x[1])

    # Remove the first auxiliary node from the path and calculate mean semblance value along it
    path = np.array(path)[1:]
    metric = 1 - metric / len(times)
    return times[path[:, 0]], velocities[path[:, 1]], metric
예제 #9
0
 def finished_path_part_two(self, path):
     length = nx.path_weight(self.g, path, "weight")
     if length > self.longest_path_length:
         self.longest_path = path
         self.longest_path_length = length
예제 #10
0
 def finished_path(self, path):
     length = nx.path_weight(self.g, path, "weight")
     if length < self.shortest_path_length:
         self.shortest_path = path
         self.shortest_path_length = length
예제 #11
0
nx.algorithms.dijkstra_path(g, 1, 21)

list(itertools.combinations(g.nodes(),2))
nn = list(g.nodes())  # essentially a tuple
nn
# check out the iterable unpacking:
for pair in itertools.combinations(nn[:8], 2):
    print(nx.algorithms.shortest_path(g, *pair),
          nx.algorithms.dijkstra_path(g, *pair))

ee = list(g.edges())
## Add edge weights by appending a tuple of length 1 to each edge tuple
weighted_edges = [x + (random.choice(range(10)), ) for x in ee]
weighted_edges
g.clear()
g.add_weighted_edges_from(weighted_edges)
# Re-run the above, now with weight to take into account (paths may differ)
for pair in itertools.combinations(nn[:8], 2):
    print(pair,
          nx.algorithms.shortest_path(g, *pair),
          nx.algorithms.dijkstra_path(g, *pair),
          nx.path_weight(g, nx.algorithms.shortest_path(g, *pair), weight="weight"),
          nx.algorithms.dijkstra_path_length(g, *pair))







예제 #12
0
 def analyzePlacement(self, path):
     happiness = nx.path_weight(self.graph, path, "happiness")
     happiness = happiness + self.graph.get_edge_data(path[0], path[-1])["happiness"]
     if happiness > self.maxHappiness:
         self.maxHappiness = happiness
         self.optimumPlacement = path
예제 #13
0
def pathAnalysis(graph, \
                 valueFilter, distanceFilter,\
                 sourceResid, targetResid, \
                 selectedAtoms, num_paths):
    """
    This function calculates paths between a source and target residue.

    This function calculates a path between a source (beginning) and a 
    target (end) residue from the graph build out of your ccMatrix.
    Parameters
    ----------
    graph: object
        It is a Networkx Graph object.
    valueFilter: float
        The ccMatrix values lower than the valueFilter will be ignored.
    distanceFilter: float
        The distance values higher than the distanceFilter will be ignored
        and they will not be considered as edges in a network. 
        This kind of value pruning may work for low conformational change MD
        simulations or ENM based calculations. However, if there are large
        scale structural changes, it will be necessary to eliminate the edges 
        based on contacts and their preservation in during the entire simulation. 
    sourceResid: str
        Chain and residue ID of the source residue. For example, A41, B145 etc..
    targetResid: str
        Chain and residue ID of the target residue. For example, A145, B41 etc.. 
    selectedAtoms: object
        This is a prody.parsePDB object of typically CA atoms of a protein.
    num_paths: int
        Number of shortest paths to write to tcl or pml files. Minimum is 1.

    Returns
    -------
    Nothing

    """
    # # Build the graph
    # graph = buildDynamicsNetwork(ccMatrix, distanceMatrix, \
    #                    valueFilter, distanceFilter,\
    #                    selectedAtoms)

    suboptimalPaths = k_shortest_paths(graph,
                                       source=sourceResid,
                                       target=targetResid,
                                       k=num_paths,
                                       weight='weight')
    # #shortestPath = nx.shortest_path(graph, source=residue, target=targetResid, weight='weight', method='dijkstra')
    # shortestPathScoreList = []
    # for path in suboptimalPaths:
    #     shortestPathScore = 0.0
    #     for j in range(len(path)-1):
    #     #    print(path[j], end="\n")
    #     #    print(shortestPath[j+1], end="\n")
    #         shortestPathScore = shortestPathScore + ccMatrix[path[j]][path[j+1]]
    #     shortestPathScoreList.append(shortestPathScore)

    # spNP = np.array(shortestPath)
    # print(spNP)
    # print(shortestPathScoreList)
    # print("The shortest path score is: ", end='')
    # print(np.array(shortestPathScoreList).sum().round(3))
    k = 0
    for path in suboptimalPaths:
        k = k + 1
        path_length = nx.path_weight(graph, path, weight="weight")
        print("Path " + str(k) + " length: " + str(path_length))

    return suboptimalPaths
예제 #14
0
# Ingest and flatten
numbers = []
last_row = []
with open('big_triangle.txt') as f:
    for line in f:
        for number in line.split():
            numbers.append(int(number))
    last_row = line.split()

# Create graph
G = nx.DiGraph()
for i in range(1, len(numbers) + 1):
    G.add_node(i)

# Make connections (n -> n + r and n -> n + r + 1)
r = lambda n: math.ceil((math.sqrt(8 * n + 1) - 1) / 2)
for i in range(1, len(numbers) - len(last_row) + 1):
    # Don't attempt to connect the last row
    G.add_edge(i, i + r(i), weight=numbers[i - 1])
    G.add_edge(i, i + r(i) + 1, weight=numbers[i - 1])

# Connect the bottom row to a destination node
G.add_node(-1)
for i in range(len(numbers) - len(last_row) + 1, len(numbers) + 1):
    G.add_edge(i, -1, weight=numbers[i - 1])

# Find the longest path and its associated path weight
path = nx.dag_longest_path(G, weight='weight')
path_weight = nx.path_weight(G, path, weight='weight')
print(path)
print(path_weight)
예제 #15
0
 def path_weight(self, path, attribute):
     return nx.path_weight(self.graph, path=path, weight=attribute)
예제 #16
0
파일: d15a.py 프로젝트: apie/advent-of-code
def answer(lines):
    #find paths trough the maze, starting at 0,0 (dont count in total) and ending at maxx,maxy
    #you can not move diagonally
    #return the total risk of the path with the lowest total
    lines = list(lines)
    maxy = len(lines) - 1
    maxx = len(lines[-1].strip()) - 1
    print()
    G = nx.DiGraph()
    # input is a map of risk levels
    for y, line in enumerate(map(str.strip, lines)):
        for x in range(len(line)):
            weight = int(line[x])
            edges = []
            # add all inward edges
            if x > 0: edges.append(((x - 1, y), (x, y), weight))  #left ->
            if x < maxx: edges.append(((x + 1, y), (x, y), weight))  #right <-
            if y > 0: edges.append(((x, y - 1), (x, y), weight))  #top \/
            if y < maxy: edges.append(((x, y + 1), (x, y), weight))  #bottom /\
            G.add_weighted_edges_from(edges)

    def print_graph():
        for y in range(maxy + 1):
            for x in range(maxx + 1):
                n = (x, y)
                if n[0] % (maxx + 1) == 0:
                    print()
                try:
                    print(G[(n[0] - 1, n[1])][n]['weight'], end='')  #left
                except KeyError:
                    try:
                        print(G[(n[0], n[1] - 1)][n]['weight'], end='')  #top
                    except KeyError:
                        print('x', end='')
        print()

    def print_path(path):
        prevn = path[0]
        for y in range(maxy + 1):
            for x in range(maxx + 1):
                n = (x, y)
                if n[0] % (maxx + 1) == 0:
                    print()
                if n in path:
                    try:
                        w = int(G[prevn][n]['weight'])
                    except KeyError:
                        w = 'x'
                    print(w, end='')
                    prevn = n
                else:
                    print('.', end='')
        print()

    print_graph()
    startp = (0, 0)
    endp = (maxx, maxy)
    sp = nx.shortest_path(G, startp, endp, 'weight')
    #    return nx.shortest_path_length(G, startp, endp, 'weight')
    print_path(sp)
    return nx.path_weight(G, sp, 'weight')