def checker(path_to_input, path_to_output): true_output = {} user_output = {} with open(path_to_input, 'r') as f: start, finish = map(int, f.readline().split()) start -= 1 finish -= 1 n, m, t = map(int, f.readline().split()) input_path = [[0 for _ in range(n)] for _ in range(n)] for _ in range(m): i, j, k = map(int, f.readline().split()) i -= 1 j -= 1 input_path[i][j] = k with open(path_to_output, 'r') as f: output_dist = int(f.readline()) if output_dist == 100000: output_dist = 0 user_output['n'] = output_dist matrix = csr_matrix(input_path) try: dist, aa = bellman_ford(matrix, return_predecessors=True) except: input_dist = -1 else: input_dist = 0 if dist[start, finish] == float('inf') else dist[start, finish] true_output['n'] = input_dist return user_output, true_output, output_dist == input_dist
def sp_bellman_ford(graph, src_vertex): """ From a given start vertex, finds the shortest paths to every other (reachable) vertex in the graph. graph: weighted graph src_vertex: source vertex return: Vector of computed distances """ return csgraph.bellman_ford(graph, indices=src_vertex, return_predecessors=False)
def find_persons_less_than_x_meioses_from_poi(trio_dict, gedcom_dict, x, poi): gedcom_ids = trio_dict.keys() poi_index = gedcom_ids.index(poi) ''' Build a sparse adjacency matrix ''' n = len(gedcom_ids) rows =[] cols = [] for i, child in enumerate(gedcom_ids): mother, father = trio_dict[child] if mother is None: continue mother = gedcom_ids.index(mother) father = gedcom_ids.index(father) rows.extend([i, i, mother, father]) cols.extend([mother, father, i, i]) adj_matrix = sps.coo_matrix(([1] * len(rows), (rows, cols)), shape=(n,n)) ''' Use Bellman-Ford to calculate distance from P.O.I. to others ''' meioses = bellman_ford(adj_matrix, unweighted=True, indices=[poi_index])[0].tolist() ''' Remove individuals who are too distant to consider. ''' gedcom_ids_to_keep = [] for i, gedcom_id in enumerate(gedcom_ids): if meioses[i] < x: gedcom_ids_to_keep.append(gedcom_id) new_gedcom_dict = {} new_trio_dict = {} for gedcom_id in gedcom_ids_to_keep: new_gedcom_dict[gedcom_id] = gedcom_dict[gedcom_id] mother, father = trio_dict[gedcom_id] ''' Make sure that both parents of a child are included in the pedigree either parent would be included in the pedigree. ''' if mother in gedcom_ids_to_keep: if father not in gedcom_ids_to_keep: new_gedcom_dict[father] = gedcom_dict[father] new_trio_dict[father] = (None, None) new_trio_dict[gedcom_id] = trio_dict[gedcom_id] elif father in gedcom_ids_to_keep: new_gedcom_dict[mother] = gedcom_dict[mother] new_trio_dict[mother] = (None, None) new_trio_dict[gedcom_id] = trio_dict[gedcom_id] else: new_trio_dict[gedcom_id] = (None, None) return new_trio_dict, new_gedcom_dict
def find_persons_less_than_x_meioses_from_poi(trio_dict, gedcom_dict, x, poi): gedcom_ids = trio_dict.keys() poi_index = gedcom_ids.index(poi) ''' Build a sparse adjacency matrix ''' n = len(gedcom_ids) rows = [] cols = [] for i, child in enumerate(gedcom_ids): mother, father = trio_dict[child] if mother is None: continue mother = gedcom_ids.index(mother) father = gedcom_ids.index(father) rows.extend([i, i, mother, father]) cols.extend([mother, father, i, i]) adj_matrix = sps.coo_matrix(([1] * len(rows), (rows, cols)), shape=(n, n)) ''' Use Bellman-Ford to calculate distance from P.O.I. to others ''' meioses = bellman_ford(adj_matrix, unweighted=True, indices=[poi_index])[0].tolist() ''' Remove individuals who are too distant to consider. ''' gedcom_ids_to_keep = [] for i, gedcom_id in enumerate(gedcom_ids): if meioses[i] < x: gedcom_ids_to_keep.append(gedcom_id) new_gedcom_dict = {} new_trio_dict = {} for gedcom_id in gedcom_ids_to_keep: new_gedcom_dict[gedcom_id] = gedcom_dict[gedcom_id] mother, father = trio_dict[gedcom_id] ''' Make sure that both parents of a child are included in the pedigree either parent would be included in the pedigree. ''' if mother in gedcom_ids_to_keep: if father not in gedcom_ids_to_keep: new_gedcom_dict[father] = gedcom_dict[father] new_trio_dict[father] = (None, None) new_trio_dict[gedcom_id] = trio_dict[gedcom_id] elif father in gedcom_ids_to_keep: new_gedcom_dict[mother] = gedcom_dict[mother] new_trio_dict[mother] = (None, None) new_trio_dict[gedcom_id] = trio_dict[gedcom_id] else: new_trio_dict[gedcom_id] = (None, None) return new_trio_dict, new_gedcom_dict
def test_bf(): aj, start, end = read_matrix("mat/300.mat") print(aj) # indices = np.zeros([aj.shape[0]]) # indices[0] = 1 # indices[1] = 1 # print(indices) dist, predecessors = bellman_ford(aj, return_predecessors=True, indices=start) print(dist) print(predecessors) k = end while k != start: print(k, "<-", end="") if k == NO_PATH: print("NO PATH") break k = predecessors[k] print(k)
def test_bellman(): """ 最大ノード数 M, 最大エッジ数 M**2 の負のサイクルを含まない重み付き有向グラフをランダム生成することを Iteration 回行う。 それぞれについて単一始点最短距離を求め、 scipy.sparce.csgraph.bellman_ford の結果と照合するストレステストを行う。 """ Iteration = 50 M = 30 inf = float('inf') for _ in range(Iteration): v = randint(2, M) e = randint(v, v**2) # ---- ndarray, csr_matrix, エッジリスト生成 ---- mat = np.full((v, v), inf) for i in range(e): # 最大で v**2 個辺を張ろうとする a, b = randint(0, v - 1), randint(0, v - 1) if a == b: # 自己ループはだめ continue w = randint(-M, M) # - M mat[a, b] = w # 上書きすることも多々あるだろう。 csr = cs.csgraph_from_dense(mat, null_value=inf) edges = [] for i in range(v): for j in range(v): if mat[i, j] != inf: edges.append(Edge(i, j, mat[i, j])) # ---- 結果の比較 ---- try: dist_mat = cs.bellman_ford(csr, return_predecessors=False).tolist() for i in range(v): # print(dist_mat) assert bellman(edges, v, i) == approx(dist_mat[i]) # 負サイクルができてしまった場合に検出できるか except cs._shortest_path.NegativeCycleError: with pytest.raises(NegativeCycleError): for i in range(v): bellman(edges, v, i)
floyd_warshall(csr) # 1.61 ms ± 17 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit dijkstra(a, indices=0) # 762 µs ± 29.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit dijkstra(csr, indices=0) # 164 µs ± 4.85 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) a_n = a.copy() a_n[0, 1] = -10 csr_n = csr_matrix(a_n) %%timeit johnson(csr_n) # 6.53 ms ± 72.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %%timeit bellman_ford(csr_n) # 79.8 ms ± 354 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) %%timeit floyd_warshall(csr_n) # 1.57 ms ± 15.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %%timeit johnson(csr_n, indices=0) # 952 µs ± 11.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
import sys from scipy.sparse.csgraph import bellman_ford input = sys.stdin.readline n, m, p = map(int, input().split()) dist = [[0 for _ in range(n)] for _ in range(n)] for _ in range(m): a, b, c = map(int, input().split()) c -= p if a != b: dist[a - 1][b - 1] = -c try: dist = bellman_ford(csgraph=dist) res = int(-dist[0][n - 1]) print(res if res > 0 else 0) except: print(-1)
import sys input = lambda: sys.stdin.readline() import numpy as np from scipy.sparse.csgraph import shortest_path, bellman_ford from scipy.sparse import csr_matrix n, m = map(int, input().split()) cost = np.zeros((n, n), dtype='i8') for i in range(m): a, b, t = map(int, input().split()) a, b = a - 1, b - 1 cost[a][b] = -t try: tmp = bellman_ford(csr_matrix(cost), indices=0) ans = -tmp[-1] ans_i = ans.astype('i8') print(ans_i) except Exception: # Note that any error could be captured print("inf")
[0, 0, 0, 0, np.inf]]) # Las siguientes 2 funciones, simplemente transforman la matriz cargada anteriormente para que se representen adecuadamente aquellos pesos de # valores cero (0) y transiciones infinitas. G_masked = np.ma.masked_invalid(G_data) print 'Matriz de Pesos: \n\n', G_masked, '\n' G_sparse = csgraph_from_dense(G_data, null_value=np.inf) print 'Nodos y pesos: (U--w-->V):\n' print ' (U, V) -----> weight' print G_sparse # El valor del Indice es el orden de la matriz menos uno: M-1 # La funcion regresa la distancia mas corta desde un punto i a un punto j sobre el grafo #dist_matrix, predecessors = floyd_warshall(csgraph=G_sparse, directed=True, return_predecessors=True), directed=True, return_predecessors=True) dist_matrix, predecessors = bellman_ford(csgraph=G_sparse, directed=True, indices=len(G_data)-1, return_predecessors=True) print '\nThe Shortest Path Lengths: \n', dist_matrix, '\n' #print predecessors # Matrices de prueba, tomadas del libro; Unidad 4, unidad 6, Apendice A #G_data = np.array([[np.inf, np.inf, 5, 4, np.inf], # [0 , np.inf, 2, np.inf, np.inf], # [np.inf, np.inf, np.inf, -1, np.inf], # [np.inf, np.inf, np.inf, np.inf, np.inf], # [0 , 0, 0, 0, np.inf]]) # # #G_data = np.array([[np.inf, -3, np.inf, np.inf], # [np.inf, np.inf, 1, 2 ], # [np.inf, np.inf, np.inf, 2 ],
for i in range(n): val = graph[vertex][i] if val != float("inf") and dist + val < distance[i]: precursor[i] = vertex distance[i] = dist + val queue.append((dist + val, i)) return distance, precursor if __name__ == '__main__': graphData = [[0, 2, float("inf"), float("inf"), 10], [float("inf"), 0, -3, float("inf"), 7], [4, float("inf"), 0, 4, float("inf")], [float("inf"), float("inf"), float("inf"), 0, 5], [float("inf"), float("inf"), 3, float("inf"), 0]] shortest, path = spfa(graphData, 0) print(shortest, path) print('-' * 75) graphData = csr_matrix(graphData) distMatrix = bellman_ford(csgraph=graphData, directed=True, indices=0, return_predecessors=True) print(distMatrix)
from scipy.sparse.csgraph import bellman_ford N, M = map(int, input().split()) edge = [[0 for i in range(N)] for _ in range(N)] for i in range(M): a, b, c = map(int, input().split()) edge[a - 1][b - 1] = -c try: dist = bellman_ford(edge) print(int(-dist[0][-1])) except: print("inf")
import numpy as np import scipy.sparse.csgraph as cs inf = float('inf') mat = np.full((10, 10), inf) mat[0, 1] = 5 mat[1, 4] = -2 mat[2, 0] = 6 mat[2, 3] = 2 mat[3, 6] = 1 mat[4, 5] = -3 mat[4, 7] = 7 mat[5, 2] = 4 mat[5, 8] = 1 mat[8, 9] = -1 G = cs.csgraph_from_dense(mat, null_value=inf) dist, path = cs.bellman_ford(G, return_predecessors=True) print("SciPy Power!") print(dist) print(path) """ [[ 0. 5. 4. 6. 3. 0. 7. 10. 1. 0.] [ 5. 0. -1. 1. -2. -5. 2. 5. -4. -5.] [ 6. 11. 0. 2. 9. 6. 3. 16. 7. 6.] [inf inf inf 0. inf inf 1. inf inf inf] [ 7. 12. 1. 3. 0. -3. 4. 7. -2. -3.] [10. 15. 4. 6. 13. 0. 7. 20. 1. 0.] [inf inf inf inf inf inf 0. inf inf inf] [inf inf inf inf inf inf inf 0. inf inf] [inf inf inf inf inf inf inf inf 0. -1.] [inf inf inf inf inf inf inf inf inf 0.]]
if __name__ == '__main__': Edges = np.array([[1, 4], [3, 1], [1, 3], [0, 1], [0, 2], [3, 2], [1, 2], [4, 3]]) w = np.array([2, 1, 2, 1, 4, 5, 3, 1], dtype=float) A = sparse.coo_matrix((w, (Edges[:, 0], Edges[:, 1]))) c = np.array([0,1,2,3,4]) print('\nreference--') for cc in c: d, m = bellman_ford_reference(A, [cc]) print(d, m) print('\npyamg--') from pyamg.graph import bellman_ford for cc in c: d, m = bellman_ford(A, [cc]) print(d, m) print('\ncsgraph.bellman_ford') from scipy.sparse import csgraph for cc in c: d, p = csgraph.bellman_ford(A, directed=True, indices=[cc], return_predecessors=True) print(d.ravel(), p.ravel())
from scipy.sparse import csr_matrix arr = np.array([[0, 1, 2], [1, 0, 0], [2, 0, 0]]) newarr = csr_matrix(arr) print(connected_components(newarr)) print() # Dijkstra print(dijkstra(newarr, return_predecessors=True, indices=0)) print() # Floyd Warshall print(floyd_warshall(newarr, return_predecessors=True)) print() # Bellman Ford print(bellman_ford(newarr, return_predecessors=True, indices=0)) print() # Depth First Order arr = np.array([[0, 1, 0, 1], [1, 1, 1, 1], [2, 1, 1, 0], [0, 1, 0, 1]]) newarr = csr_matrix(arr) print(depth_first_order(newarr, 1)) print() # Breadth First Order newarr = csr_matrix(arr) print(breadth_first_order(newarr, 1)) print() # SciPy Spatial Data from scipy.spatial import Delaunay, ConvexHull, KDTree
def q2(): N, s = 4, 0 edges = [[0, 1, 2], [0, 2, 3], [1, 2, -5], [1, 3, 1], [2, 3, 2], [3, 1, 0]] ok, dist = bellmanFord(N, edges, s) print(ok, *dist) if __name__ == "__main__": questions = [[ 4, 0, [[0, 1, 2], [0, 2, 3], [1, 2, -5], [1, 3, 1], [2, 3, 2]] ], [ 4, 0, [[0, 1, 2], [0, 2, 3], [1, 2, -6], [1, 3, 1], [2, 3, 2], [3, 1, 1]] ]] for q in questions: n, s, e = q ok, dist = bellmanFord(n, e, s) print(ok, *dist) g = [[0] * n for _ in range(n)] for u, v, w in e: g[u][v] = w try: print(bellman_ford(csr_matrix(g), directed=True, indices=s)) except NegativeCycleError: print(False)
from scipy.sparse import csr_matrix from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, NegativeCycleError, maximum_bipartite_matching, maximum_flow, minimum_spanning_tree import numpy as np n, m = map(int, input().split()) edges = [list(map(int, input().split())) for i in range(m)] def graph_csr(edges, n, directed=True, indexed_1=True): # 隣接リストから粗行列を作成 arr = np.array(edges, dtype=np.int64).T arr = arr.astype(np.int64) index = int(indexed_1) if not directed: return csr_matrix((np.concatenate([arr[2], arr[2]]), (np.concatenate([arr[0]-index, arr[1]-index]), np.concatenate([arr[1]-index, arr[0]-index]))), shape=(n, n)) else: return csr_matrix((arr[2], (arr[0]-index, arr[1]-index)), shape=(n, n)) csr = graph_csr(edges, n) try: print(floyd_warshall(csr)) except NegativeCycleError: print('-1') dijkstra(csr, indices=0) bellman_ford(csr, indices=0) maximum_bipartite_matching(csr, perm_type='column') maximum_flow(csr, source=0, sink=1).flow_value maximum_flow(csr, source=0, sink=1).residual int(sum(minimum_spanning_tree(csr).data))