-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijkstra.py
180 lines (153 loc) · 5.22 KB
/
Dijkstra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import numpy as np
import scipy as sp
import math as ma
import sys
import time
def BellmanFord(ist,isp,wei):
#----------------------------------
# ist: index of starting node
# isp: index of stopping node
# wei: adjacency matrix (V x V)
#
# shpath: shortest path
#----------------------------------
V = wei.shape[1]
# step 1: initialization
Inf = sys.maxint
d = np.ones((V),float)*np.inf
p = np.zeros((V),int)*Inf
d[ist] = 0
# step 2: iterative relaxation
for i in range(0,V-1):
for u in range(0,V):
for v in range(0,V):
w = wei[u,v]
if (w != 0):
if (d[u]+w < d[v]):
d[v] = d[u] + w
p[v] = u
# step 3: check for negative-weight cycles
for u in range(0,V):
for v in range(0,V):
w = wei[u,v]
if (w != 0):
if (d[u]+w < d[v]):
print('graph contains a negative-weight cycle')
# step 4: determine the shortest path
shpath = [isp]
while p[isp] != ist:
shpath.append(p[isp])
isp = p[isp]
shpath.append(ist)
return shpath[::-1]
def Dijkst(ist,isp,wei):
# Dijkstra algorithm for shortest path in a graph
# ist: index of starting node
# isp: index of stopping node
# wei: weight matrix
# exception handling (start = stop)
if (ist == isp):
shpath = [ist]
return shpath
# initialization
N = len(wei)
Inf = sys.maxint
UnVisited = np.ones(N,int)
cost = np.ones(N)*1.e6
par = -np.ones(N,int)*Inf
# set the source point and get its (unvisited) neighbors
jj = ist
cost[jj] = 0
UnVisited[jj] = 0
tmp = UnVisited*wei[jj,:]
ineigh = np.array(tmp.nonzero()).flatten()
L = np.array(UnVisited.nonzero()).flatten().size
# start Dijkstra algorithm
while (L != 0):
# step 1: update cost of unvisited neighbors,
# compare and (maybe) update
for k in ineigh:
newcost = cost[jj] + wei[jj,k]
if ( newcost < cost[k] ):
cost[k] = newcost
par[k] = jj
# step 2: determine minimum-cost point among UnVisited
# vertices and make this point the new point
icnsdr = np.array(UnVisited.nonzero()).flatten()
cmin,icmin = cost[icnsdr].min(0),cost[icnsdr].argmin(0)
jj = icnsdr[icmin]
# step 3: update "visited"-status and determine neighbors of new point
UnVisited[jj] = 0
tmp = UnVisited*wei[jj,:]
ineigh = np.array(tmp.nonzero()).flatten()
L = np.array(UnVisited.nonzero()).flatten().size
# determine the shortest path
shpath = [isp]
while par[isp] != ist:
shpath.append(par[isp])
isp = par[isp]
shpath.append(ist)
return shpath[::-1]
def calcWei(RX,RY,RA,RB,RV):
# calculate the weight matrix between the points
n = len(RX)
wei = np.zeros((n,n),dtype=float)
m = len(RA)
for i in range(m):
xa = RX[RA[i]-1]
ya = RY[RA[i]-1]
xb = RX[RB[i]-1]
yb = RY[RB[i]-1]
dd = ma.sqrt((xb-xa)**2 + (yb-ya)**2)
tt = dd/RV[i]
wei[RA[i]-1,RB[i]-1] = tt
return wei
if __name__ == '__main__':
import csv
# EXAMPLE 1
# starting and stopping node
#ist = 4
#isp = 3
# adjacency matrix
#wei = np.array([[ 0, 20, 0, 80, 0, 0, 90, 0],
# [ 0, 0, 0, 0, 0, 10, 0, 0],
# [ 0, 0, 0, 10, 0, 50, 0, 20],
# [ 0, 0, 10, 0, 0, 0, 20, 0],
# [ 0, 50, 0, 0, 0, 0, 30, 0],
# [ 0, 0, 10, 40, 0, 0, 0, 0],
# [20, 0, 0, 0, 0, 0, 0, 0],
# [ 0, 0, 0, 0, 0, 0, 0, 0]])
#shpath = Dijkst(ist,isp,wei)
#print ist,' -> ',isp,' is ',shpath
# EXAMPLE 2 (path through Rome)
RomeX = np.empty(0,dtype=float)
RomeY = np.empty(0,dtype=float)
with open('RomeVertices','r') as file:
AAA = csv.reader(file)
for row in AAA:
RomeX = np.concatenate((RomeX,[float(row[1])]))
RomeY = np.concatenate((RomeY,[float(row[2])]))
file.close()
RomeA = np.empty(0,dtype=int)
RomeB = np.empty(0,dtype=int)
RomeV = np.empty(0,dtype=float)
with open('RomeEdges','r') as file:
AAA = csv.reader(file)
for row in AAA:
RomeA = np.concatenate((RomeA,[int(row[0])]))
RomeB = np.concatenate((RomeB,[int(row[1])]))
RomeV = np.concatenate((RomeV,[float(row[2])]))
file.close()
wei = calcWei(RomeX,RomeY,RomeA,RomeB,RomeV)
ist = 12 # St. Peter's Square
isp = 51 # Coliseum
# use the Bellman-Ford algorithm
t0 = time.time()
shpath = BellmanFord(12,51,wei)
t1 = time.time()
print 'Bellman-Ford: ',ist+1,' -> ',isp+1,' is ',np.array(shpath)+1,t1-t0
# use the Dijkstra algorithm
t0 = time.time()
shpath = Dijkst(12,51,wei)
t1 = time.time()
print 'Dijkstra: ',ist+1,' -> ',isp+1,' is ',np.array(shpath)+1,t1-t0