Advertisement
akariya

[ECE592] Project 2 Dijkstra search

Oct 15th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. import pandas as pd
  2. import numpy as np
  3. import time
  4. import matplotlib.pyplot as plt
  5.  
  6. # function to find city with smallest distance
  7. def minUnvisited(dist, done, number_of_cities):
  8.     minDistance = float('inf')
  9.     ans = -1
  10.     i = 0
  11.     while(i<number_of_cities):
  12.         if(dist[i] <= minDistance and i not in done):
  13.             minDistance = dist[i]
  14.             ans = i
  15.         i += 1;
  16.     return ans
  17.  
  18. # function to print path
  19. def printPath(dst, dist, parent, cities):
  20.     if(parent[dst] == -1):
  21.         print(cities[dst])
  22.         return
  23.     printPath(parent[dst], dist, parent, cities)
  24.     print(cities[dst])
  25.  
  26. # read excel to create matrix of distances
  27. NC = pd.read_excel('NC.xlsx', sheet_name='Miles', index_col=0, index_row=0)
  28. cities = NC.index.values
  29. NC = NC.to_numpy()
  30. number_of_cities = cities.shape[0]
  31.  
  32. # disallow direct routes for near by cities
  33. i = 0
  34. while(i<number_of_cities):
  35.     j = 0
  36.     while(j<number_of_cities):
  37.         if(i == j):
  38.             NC[i][j] = 0
  39.         if(NC[i][j] > 40):
  40.             NC[i][j] = float('inf')
  41.         j += 1
  42.     i += 1
  43.  
  44. # Dijkstra search algorithm
  45. dist = [float('inf')] * number_of_cities
  46. parent = [-1] * number_of_cities
  47. src_city = np.where(cities == 'Murphy')[0][0]
  48. dst_city = np.where(cities == 'Elizabeth City')[0][0]
  49. dist[src_city] = 0
  50. done = []
  51. start_time = time.time()
  52. node_traversed = [0]
  53. time_taken = [0]
  54. done_nodes_count = 0
  55. while(len(done) != number_of_cities):
  56.     current = minUnvisited(dist, done, number_of_cities)
  57.     done.insert(0, current)
  58.     if(current == dst_city):
  59.         break
  60.     j = 0
  61.     while(j < number_of_cities):
  62.         if(NC[current][j] != float('inf') and j not in done):
  63.             if(dist[current] + NC[current][j] < dist[j]):
  64.                 dist[j] = dist[current] + NC[current][j]
  65.                 parent[j] = current
  66.         j += 1;
  67.     done_nodes_count += 1
  68.     node_traversed.append(done_nodes_count)
  69.     time_taken.append(time.time() - start_time)
  70.  
  71. # print and display results
  72. printPath(dst_city, dist, parent, cities)
  73. print('Distance = ' + str(dist[dst_city]))
  74. print("Runtime = %s seconds" % (time.time() - start_time))
  75. plt.ylabel('Number of nodes traversed')
  76. plt.xlabel('Time in seconds')
  77. plt.plot(time_taken, node_traversed)
  78. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement