/
blossom_parallel.py
488 lines (435 loc) · 23.1 KB
/
blossom_parallel.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
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
import networkx as nx
import numpy as np
import copy
from multiprocessing import Pool
from functools import partial
import time
def find_maximum_matching(G,M):
P = finding_aug_path(G,M)
if P == []: #Base Case
return M
else: #Augment P to M
##Add the alternating edges of P to M
for i in xrange(0,len(P)-2,2): ######## could be parallelized
M.add_edge(P[i],P[i+1])
M.remove_edge(P[i+1],P[i+2])
M.add_edge(P[-2],P[-1])
return find_maximum_matching(G,M)
def dist_to_root(point,root,Graph):
path = nx.shortest_path(Graph, source = point, target = root)
return (len(path)-1)
def generate_random_graph(n,density=0.5):
## n - number of nodes
## d - "density" of the graph [0,1]
graph = nx.Graph()
for i in xrange(n):
for j in xrange(i+1,n):
if np.random.uniform() < density:
graph.add_edge(i,j)
return graph
def finding_aug_path(G,M,Blossom_stack=[]):
Forest = [] #Storing the Trees
Path = [] # The final path
unmarked_edges = list(set(G.edges()) - set(M.edges()))
unmarked_nodes = list(G.nodes())
Forest_nodes = []
## we need a map from v to the tree
tree_to_root = {} # key=idx of tree in forest, val=root
root_to_tree = {} # key=root, val=idx of tree in forest
##List of exposed vertices - ROOTS OF TREES
exp_vertex = list(set(G.nodes()) - set(M.nodes()))
counter = 0
#List of trees with the exposed vertices as the roots
for v in exp_vertex: ######## could be parallelized
temp = nx.Graph()
temp.add_node(v)
Forest.append(temp)
Forest_nodes.append(v)
#link each root to its tree
tree_to_root[counter] = v
root_to_tree[v] = counter
counter = counter + 1
for v in Forest_nodes:
root_of_v = None
tree_num_of_v = None
for tree_number in xrange(len(Forest)): ######## could be parallelized
# find tree of v
tree_in = Forest[tree_number]
if tree_in.has_node(v) == True:
root_of_v = tree_to_root[tree_number]
tree_num_of_v = tree_number
break #Break out of the for loop
edges_v = list(G.edges(v))
pool = Pool(processes = 4)
edge_data = edges_v
# Feed the function all global args
partial_edge = partial(edge_function,G,M,Forest,unmarked_edges,tree_to_root,tree_num_of_v,root_of_v,v,Blossom_stack)
#PARALLEL LOOP!
temp = pool.map(partial_edge, edge_data)
pool.terminate()
for i in xrange(len(temp)): ######## could be parallelized
if temp[i] != None and (temp[i][0] == 2 or temp[i][0] == 3):
return temp[i][1]
# Not CASE 2 or 3
## check for blossoms of 3-length
for i in xrange(len(temp)): ######## could be parallelized
if temp[i] != None and (temp[i][0] == 1 and G.has_edge(v,temp[i][1][1])):
#contract len 3 blossom
w = temp[i][1][0]
blossom = [v,w,temp[i][1][1],v]
contracted_G = copy.deepcopy(G)
contracted_M = copy.deepcopy(M)
for node in blossom[0:len(blossom)-1]:
if node != w:
contracted_G = nx.contracted_nodes(contracted_G, w, node, self_loops=False)
if node in contracted_M.nodes():
edge_rm = list(M.edges(node))[0] #this will be exactly one edge
contracted_M.remove_node(node)
contracted_M.remove_node(edge_rm[1])
# assert(len(list(contracted_M.nodes()))%2 == 0)
# add blossom to our stack
Blossom_stack.append(w)
# recurse
aug_path = finding_aug_path(contracted_G, contracted_M, Blossom_stack)
# check if blossom exists in aug_path
v_B = Blossom_stack.pop()
if (v_B in aug_path):
##Define the L_stem and R_stem
L_stem = aug_path[0:aug_path.index(v_B)]
R_stem = aug_path[aug_path.index(v_B)+1:]
lifted_blossom = [] #stores the path within the blossom to take
# Find base of blossom
i = 0
base = None
base_idx = -1
blossom_ext = blossom + [blossom[1]]
while base == None and i < len(blossom) - 1:
if not(M.has_edge(blossom[i],blossom[i+1])):
if not(M.has_edge(blossom[i+1],blossom_ext[i+2])):
base = blossom[i+1]
base_idx = i+1
else:
i += 2
else:
i += 1
# if needed, create list of blossom nodes starting at base
if blossom[0] != base:
based_blossom = []
base_idx = blossom.index(base)
for i in xrange(base_idx,len(blossom)-1):
based_blossom.append(blossom[i])
for i in xrange(0,base_idx):
based_blossom.append(blossom[i])
based_blossom.append(base)
else:
based_blossom = blossom
# CHECK IF BLOSSOM IS ENDPT
if L_stem == [] or R_stem == []:
if L_stem != []:
if G.has_edge(base, L_stem[-1]):
# CASE 1:
# Chuck the blossom
return L_stem + [base]
else:
# CASE 2:
# find where Lstem is connected
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],L_stem[-1]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = list(reversed(based_blossom))[-i-1:]
else: # opposite dir path
lifted_blossom = based_blossom[i:]
i += 1
return L_stem + lifted_blossom
else:
# R is not empty, L is empty
if G.has_edge(base, R_stem[0]):
# CASE 1:
# Chuck the blossom.
return [base] + R_stem
else:
# CASE 2:
# find where R_stem is connected
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],R_stem[0]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = based_blossom[:i+1]
# print lifted_blossom
else: # opposite dir path
lifted_blossom = list(reversed(based_blossom))[:-i]
i += 1
return lifted_blossom + R_stem
else: # blossom is in the middle
# LIFT the blossom
# check if L_stem attaches to base
if M.has_edge(base, L_stem[-1]):
# find where right stem attaches
if G.has_edge(base, R_stem[0]):
# blossom is useless
return L_stem + [base] + R_stem
else:
# blossom needs to be lifted
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],R_stem[0]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = based_blossom[:i+1]
print lifted_blossom
else: # opposite dir path
lifted_blossom = list(reversed(based_blossom))[:-i]
print lifted_blossom
i += 1
return L_stem + lifted_blossom + R_stem
else:
# R stem to base is in matching
assert(M.has_edge(base, R_stem[0]))
# check where left stem attaches
if G.has_edge(base, L_stem[-1]):
# blossom is useless
return L_stem + [base] + R_stem
else:
# blossom needs to be lifted
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],L_stem[-1]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = list(reversed(based_blossom))[-i-1:]
else: # opposite dir path
lifted_blossom = based_blossom[i:]
i += 1
return L_stem + list((lifted_blossom)) + R_stem
else: # blossom is not in aug_path
return aug_path
for i in xrange(len(temp)):
if temp[i] != None and temp[i][0] ==1:
Forest[tree_num_of_v].add_edge(v,temp[i][1][0])
Forest[tree_num_of_v].add_edge(temp[i][1][0],temp[i][1][1])
Forest_nodes.append(temp[i][1][1])
return [] #Empty Path
#######################################################################################################################################################
def edge_function(G,M,Forest,unmarked_edges,tree_to_root,tree_num_of_v,root_of_v,v,Blossom_stack,e):
e2 = (e[1],e[0]) #the edge in the other order
if ((e in unmarked_edges or e2 in unmarked_edges) and e!=[]):
w = e[1] # the other vertex of the unmarked edge
w_in_Forest = 0; ##Indicator for w in F or not
##Go through all the trees in the forest to check if w in F
tree_of_w = None
tree_num_of_w = None
for tree_number in xrange(len(Forest)):
tree = Forest[tree_number]
if tree.has_node(w) == True:
w_in_Forest = 1
root_of_w = tree_to_root[tree_number]
tree_num_of_w = tree_number
tree_of_w = Forest[tree_num_of_w]
break #Break the outer for loop
if w_in_Forest == 0:
## w is matched, so add e and w's matched edge to F
Forest[tree_num_of_v].add_edge(e[0],e[1]) # edge {v,w}
# print "edge added to forest: ", e
# Note: we don't add w to forest nodes b/c it's odd dist from root
# assert(M.has_node(w))
edge_w = list(M.edges(w))[0] # get edge {w,x}
return (1,edge_w) ## store to add to forest after parallel for
else: ## w is in Forest
# if odd, do nothing.
if dist_to_root(w,root_of_w,Forest[tree_num_of_w])%2 == 1: #CASE 4
return (4,0)
if dist_to_root(w,root_of_w,Forest[tree_num_of_w])%2 == 0:
if (tree_num_of_v != tree_num_of_w):
##Shortest path from root(v)--->v-->w---->root(w)
path_in_v = nx.shortest_path(Forest[tree_num_of_v], source = root_of_v, target = v)
path_in_w = nx.shortest_path(Forest[tree_num_of_w], source = w, target = root_of_w)
return (2,path_in_v + path_in_w)
else: ##Contract the blossom
# create blossom
blossom = nx.shortest_path(tree_of_w, source=v, target=w)
blossom.append(v)
# assert(len(blossom)%2 == 0)
# contract blossom into single node w
contracted_G = copy.deepcopy(G)
contracted_M = copy.deepcopy(M)
for node in blossom[0:len(blossom)-1]:
if node != w:
contracted_G = nx.contracted_nodes(contracted_G, w, node, self_loops=False)
if node in contracted_M.nodes():
edge_rm = list(M.edges(node))[0] #this will be exactly one edge
contracted_M.remove_node(node)
contracted_M.remove_node(edge_rm[1])
# assert(len(list(contracted_M.nodes()))%2 == 0)
# add blossom to our stack
Blossom_stack.append(w)
# recurse
aug_path = finding_aug_path(contracted_G, contracted_M, Blossom_stack)
# check if blossom exists in aug_path
v_B = Blossom_stack.pop()
if (v_B in aug_path):
##Define the L_stem and R_stem
L_stem = aug_path[0:aug_path.index(v_B)]
R_stem = aug_path[aug_path.index(v_B)+1:]
lifted_blossom = [] #stores the path within the blossom to take
# Find base of blossom
i = 0
base = None
base_idx = -1
blossom_ext = blossom + [blossom[1]]
while base == None and i < len(blossom) - 1:
if not(M.has_edge(blossom[i],blossom[i+1])):
if not(M.has_edge(blossom[i+1],blossom_ext[i+2])):
base = blossom[i+1]
base_idx = i+1
else:
i += 2
else:
i += 1
# if needed, create list of blossom nodes starting at base
if blossom[0] != base:
based_blossom = []
base_idx = blossom.index(base)
for i in xrange(base_idx,len(blossom)-1):
based_blossom.append(blossom[i])
for i in xrange(0,base_idx):
based_blossom.append(blossom[i])
based_blossom.append(base)
else:
based_blossom = blossom
# CHECK IF BLOSSOM IS ENDPT
if L_stem == [] or R_stem == []:
if L_stem != []:
if G.has_edge(base, L_stem[-1]):
# CASE 1:
# Chuck the blossom.
return L_stem + [base]
else:
# CASE 2:
# find where Lstem is connected
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],L_stem[-1]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = list(reversed(based_blossom))[-i-1:]
else: # opposite dir path
lifted_blossom = based_blossom[i:]
i += 1
return (3,L_stem + lifted_blossom)
else:
if G.has_edge(base, R_stem[0]):
# CASE 1:
# Chuck the blossom.
return (3,[base] + R_stem)
else:
# CASE 2:
# find where R_stem is connected
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],R_stem[0]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = based_blossom[:i+1]
print lifted_blossom
else: # opposite dir path
lifted_blossom = list(reversed(based_blossom))[:-i]
i += 1
return (3,lifted_blossom + R_stem)
else: # blossom is in the middle
# LIFT the blossom
# check if L_stem attaches to base
if M.has_edge(base, L_stem[-1]):
# find where right stem attaches
if G.has_edge(base, R_stem[0]):
# blossom is useless
return (3,L_stem + [base] + R_stem)
else:
# blossom needs to be lifted
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],R_stem[0]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = based_blossom[:i+1]
# print lifted_blossom
else: # opposite dir path
lifted_blossom = list(reversed(based_blossom))[:-i]
# print lifted_blossom
i += 1
return (3,L_stem + lifted_blossom + R_stem)
else:
# R stem to base is in matching
# assert(M.has_edge(base, R_stem[0]))
# check where left stem attaches
if G.has_edge(base, L_stem[-1]):
# blossom is useless
return (3,L_stem + [base] + R_stem)
else:
# blossom needs to be lifted
i = 1
while (lifted_blossom == []):
# assert(i < len(based_blossom)-1)
if G.has_edge(based_blossom[i],L_stem[-1]):
# make sure we're adding the even part to lifted path
if i%2 == 0: # same dir path
lifted_blossom = list(reversed(based_blossom))[-i-1:]
else: # opposite dir path
lifted_blossom = based_blossom[i:]
i += 1
return (3,L_stem + list((lifted_blossom)) + R_stem)
else: # blossom is not in aug_path
return (3,aug_path)
if __name__ == '__main__':
n_list = [20, 50, 100, 150, 200]
d_list = [0.3, 0.5, 0.7, 0.9]
niter = 5
results = np.ndarray((len(d_list),len(n_list)))
results.fill(0)
for i in range(niter):
iter_start = time.time()
print "starting round ", i
for n in n_list:
for d in d_list:
print "\t starting n=",n,"d=",d
G = generate_random_graph(n,d)
M = nx.Graph()
Blossom_stack = []
a = time.time()
MM = find_maximum_matching(G, M)
b = time.time()
results[d_list.index(d)][n_list.index(n)] += b - a
print "\t\tTook ", b-a
iter_end = time.time()
print "Iteration ", i, " took ", iter_end - iter_start
results /= float(niter)
print "final matrix: ",results
np.save("par_results", results)
sparse_results = np.ndarray((1,len(n_list)))
sparse_results.fill(0)
for i in range(niter):
print "starting iteration ", i
iter_start = time.time()
for n in n_list:
print "\t with n =",n
G = generate_random_graph(n,0.1)
M = nx.Graph()
a = time.time()
MM = find_maximum_matching(G, M)
b = time.time()
sparse_results[0][n_list.index(n)] += b - a
print "\t\ttook ", b-a
iter_end = time.time()
print "Iteration ", i, " took ", iter_end - iter_start
sparse_results /= float(niter)
print sparse_results
np.save("sparse_par_results", sparse_results)