test_shortest_path.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from collections import defaultdict
  2. import numpy as np
  3. from numpy.testing import assert_array_almost_equal
  4. from sklearn.utils.graph import single_source_shortest_path_length
  5. def floyd_warshall_slow(graph, directed=False):
  6. N = graph.shape[0]
  7. # set nonzero entries to infinity
  8. graph[np.where(graph == 0)] = np.inf
  9. # set diagonal to zero
  10. graph.flat[:: N + 1] = 0
  11. if not directed:
  12. graph = np.minimum(graph, graph.T)
  13. for k in range(N):
  14. for i in range(N):
  15. for j in range(N):
  16. graph[i, j] = min(graph[i, j], graph[i, k] + graph[k, j])
  17. graph[np.where(np.isinf(graph))] = 0
  18. return graph
  19. def generate_graph(N=20):
  20. # sparse grid of distances
  21. rng = np.random.RandomState(0)
  22. dist_matrix = rng.random_sample((N, N))
  23. # make symmetric: distances are not direction-dependent
  24. dist_matrix = dist_matrix + dist_matrix.T
  25. # make graph sparse
  26. i = (rng.randint(N, size=N * N // 2), rng.randint(N, size=N * N // 2))
  27. dist_matrix[i] = 0
  28. # set diagonal to zero
  29. dist_matrix.flat[:: N + 1] = 0
  30. return dist_matrix
  31. def test_shortest_path():
  32. dist_matrix = generate_graph(20)
  33. # We compare path length and not costs (-> set distances to 0 or 1)
  34. dist_matrix[dist_matrix != 0] = 1
  35. for directed in (True, False):
  36. if not directed:
  37. dist_matrix = np.minimum(dist_matrix, dist_matrix.T)
  38. graph_py = floyd_warshall_slow(dist_matrix.copy(), directed)
  39. for i in range(dist_matrix.shape[0]):
  40. # Non-reachable nodes have distance 0 in graph_py
  41. dist_dict = defaultdict(int)
  42. dist_dict.update(single_source_shortest_path_length(dist_matrix, i))
  43. for j in range(graph_py[i].shape[0]):
  44. assert_array_almost_equal(dist_dict[j], graph_py[i, j])