-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprim.py
More file actions
348 lines (271 loc) · 9.22 KB
/
prim.py
File metadata and controls
348 lines (271 loc) · 9.22 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# prim's alg implemented in python
import numpy as np
import sys
import random
import time
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-s", action="store_true", dest="stock")
parser.add_option("-v", action="store_true", dest="verbose")
parser.add_option("-m", action="store_true", dest="matrix")
parser.add_option("-e", action="store_true", dest="edge_list")
parser.add_option("-d", action="store_true", dest="distance")
parser.add_option("-c", action="store_true", dest="clock")
parser.add_option("-f", action="store_true", dest="file")
parser.add_option("-r", "--random", action="store", type="int", dest="random", help="randomizes edge weights for the adjancency matrix")
parser.add_option("-l", "--limit", action="store", type="int", dest="random_limit", help="upper limit to the randomizer")
(options, args) = parser.parse_args()
def prim(n, W):
i = 0
vnear = 0
edge = (0,0)
min = -sys.maxint - 1
nearest = []
distance = []
F = []
for i in range (0,n):
# print "i = ",i
nearest.append(0)
distance.append(W[0][i])
# print "=========================================="
for x in range (0,n-1):
min = sys.maxsize
for i in range(1,n):
if ( distance[i] >= 0 and distance[i] < min):
min = distance[i]
vnear = i
e = ( vnear, nearest[vnear])
F.append(e)
distance[vnear] = -1
for i in range(1,n):
if ( W[i][vnear] < distance[i] ):
distance[i] = W[i][vnear]
nearest[i] = vnear
# print "=========================================="
# return the edge list
return F
def prim_get_matrix(n, W):
i = 0
vnear = 0
edge = (0,0)
min = -sys.maxint - 1
nearest = []
distance = []
F = []
for i in range (0,n):
# print "i = ",i
nearest.append(0)
distance.append(W[0][i])
# print "=========================================="
new_W = []
row = []
for i in range (0,n):
for j in range(0,n):
row.append(0)
new_W.append(row)
row = []
for x in range (0,n-1):
min = sys.maxsize
for i in range(1,n):
if ( distance[i] >= 0 and distance[i] < min):
min = distance[i]
vnear = i
e = ( vnear, nearest[vnear])
F.append(e)
new_W[vnear][nearest[vnear]] = W[vnear][nearest[vnear]]
distance[vnear] = -1
for i in range(1,n):
if ( W[i][vnear] < distance[i] ):
distance[i] = W[i][vnear]
nearest[i] = vnear
# print "=========================================="
# mirror the matrix
for i in range(0,n):
for j in range(0,n):
if new_W[i][j] == 0:
new_W[i][j] = new_W[j][i]
else:
new_W[j][i] = new_W[i][j]
return new_W, F
def get_dist_upper_triange(matrix):
total = 0
for i in range(0,n):
for j in range(i,n):
total = total + matrix[i][j]
return total
def get_dist_edge_list(edge_list, matrix):
total = 0
for i in range(0,len(edge_list)):
a = edge_list[i][0]
b = edge_list[i][1]
total = total + matrix[a][b]
return total
def uniqueify_dble_tup( items ):
print "================================="
print ""
new_items = []
for i in range(0,len(items)):
new_items.append(items[i])
for i in range(0, len(new_items) - 1):
item1 = int(new_items[i][0])
for j in range(i+1, len(new_items)):
item2 = int(new_items[j][0])
# print "item1[0] = ", item1
# print "item2[0] = ", item2
# print " item1[0] == item2[0] = ", item1 == item2
if item1 == item2:
# print "popped = ", new_items[i]
new_items[i] = (-(i+1),-(i+1))
# print "new_items = ", str(new_items)
# print "2 items = ", str(items)
new_new_items = []
for i in range (0, len(new_items)):
if new_items[i][0] > 0:
new_new_items.append(new_items[i])
print "leaving! ... new_new_items = ", str(new_new_items)
print ""
print "================================="
return new_new_items
def edge_list_to_mat(edge_list, matrix):
# build new matrix
W = []
row = []
for i in range(0,n):
for j in range(0,n):
row.append(0)
W.append(row)
row = []
# copy over
for i in range(0,len(edge_list)):
a = edge_list[i][0]
b = edge_list[i][1]
W[a][b] = matrix[a][b]
# mirror the matrix
for i in range(0,n):
for j in range(0,n):
if W[i][j] == 0:
W[i][j] = W[j][i]
else:
W[j][i] = W[i][j]
return W
# ==============================================================
# ============================ MAIN ============================
# ==============================================================
if __name__ == "__main__":
print ""
print "Start Prim's Algorithm in Python"
print ""
inf = sys.maxint
if options.file:
file_data = open("data.txt", 'r+')
# STOCK data from example Powerpointe
if options.stock:
n = 5
W = [
[0,3,inf,11,inf],
[3,0,12,6,9],
[inf,12,0,4,4],
[11,6,4,0,2],
[inf,9,4,2,0]
]
# Randomizer of edge weights
elif options.random:
n = options.random
random_limit = 10
if options.random_limit:
random_limit = options.random_limit
W = []
row = []
for i in range(0,n):
for j in range(0,n):
row.append(0)
W.append(row)
row = []
for i in range(0,n):
for j in range(i+1,n):
W [i][j] = random.randint(1,random_limit)
# print "np.squeeze(np.asarray(W)) = \n", np.squeeze(np.asarray(W))
# Manual entering of adjacency Matrix
else:
manual = True
n = 0
while n < 2:
n = int(raw_input("Enter 'n' where n >= 2: "))
print "n = ",n
W = []
row = []
for i in range(1,n):
for j in range(i,n):
row.append(0)
W.append(row)
row = []
print "Now start entering edge weights by a number"
print "Note: Let 'inf' = infinity (non-existent edge)"
print "Note: The diagonal will be set to all zeroes"
print ""
for i in range(1,n):
for j in range(i,n):
str_in = input("Enter number for matrix position " + str(i) + ", " + str(j) + ": ")
if str_in == "inf":
W[i][j] = inf
else:
num = int(str_in)
W[i][j] = num
for i in range(0,n):
W[i][i] = 0
# mirror
for i in range(0,n):
for j in range(i,n):
W[j][i] = W[i][j]
for i in range(0,n):
W[i][i] = 0
if options.verbose or options.stock or manual:
print "W = \n", np.squeeze(np.asarray(W))
# Get and print the MST
if options.clock:
clock_start = time.clock()
# ======================================================
F_list = prim(n,W)
# ======================================================
if options.clock:
clock_stop = time.clock()
F_mat = edge_list_to_mat(F_list, W)
if options.verbose or options.stock or manual:
print "W = \n", np.squeeze(np.asarray(F_mat))
print "Edge list = \n", F_list
# print the combined distane
d = get_dist_upper_triange(F_mat)
print "Distance = ",d
if options.clock:
total_clock = clock_stop - clock_start
print "total_time = ", total_clock, " seconds"
if options.file and options.clock:
# sort the file
file_list = list(file_data)
file_data.close()
file_data = open("data.txt", 'w')
file_n_val = []
file_time_val = []
split_line = []
file_tuples = []
print "file_list = ",file_list
for i in range (0, len(file_list)):
split_line = file_list[i].split(' ')
file_n_val.append(split_line[0])
file_time_val.append(split_line[1].split('\n')[0])
file_tuples.append( (split_line[0], split_line[1].split('\n')[0] ))
file_tuples.append( (str(n),total_clock))
file_tuples = uniqueify_dble_tup(file_tuples)
print "[unsort] file_tuples = ", file_tuples
file_tuples.sort(key=lambda tup: int(tup[0]))
print "[sort] file_tuples = ", file_tuples
# write out
for i in range (0, len(file_tuples)):
theLine = str(file_tuples[i][0]) + ' ' + str(file_tuples[i][1]) + '\n'
file_data.write(theLine)
print "file_n_val = ", file_n_val
print "file_time_val = ", file_time_val
print "file_tuples = ", file_tuples
file_data.close()
# theLine = str(n)+ " " + str(total_clock) + "\n"
# file_data.write( theLine )