/
pdb_alpha.py
694 lines (648 loc) · 24.3 KB
/
pdb_alpha.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import os
import sys
import json
import copy
import threading
from multiprocessing import Process
from Queue import PriorityQueue, Queue
from math import sqrt
from collections import OrderedDict
moveList = ["UP", "DOWN", "LEFT", "RIGHT"]
mMap = [1, 0, 3, 2]
finalGoal = []
PDB4_3 = 3360
PDB4_5 = 524160
PDB5_6 = 127512000
START = -2
FINISHED = -1
#3-6-6 partition
pdb33a = {0:0, 2:0, 3:0, 4:0}
pdb33b = {2:0, 3:0, 4:0}
pdb361a = {0:0, 1:0, 5:0, 6:0, 9:0, 10:0, 13:0}
pdb361b = {1:0, 5:0, 6:0, 9:0, 10:0, 13:0}
pdb362a = {0:0, 7:0, 8:0, 11:0, 12:0, 14:0, 15:0}
pdb362b = {7:0, 8:0, 11:0, 12:0, 14:0, 15:0}
#5-5-5 partition
pdb351a = {0:0, 1:0, 2:0, 3:0, 4:0, 5:0}
pdb351b = {1:0, 2:0, 3:0, 4:0, 5:0}
pdb352a = {0:0, 6:0, 7:0, 8:0, 9:0, 10:0}
pdb352b = {6:0, 7:0, 8:0, 9:0, 10:0}
pdb353a = {0:0, 11:0, 12:0, 13:0, 14:0, 15:0}
pdb353b = {11:0, 12:0, 13:0, 14:0, 15:0}
#6-6-6-6 partition
pdb561a = {0:0, 1:0, 2:0, 3:0, 6:0, 7:0, 8:0}
pdb561b = {1:0, 2:0, 3:0, 6:0, 7:0, 8:0}
pdb562a = {0:0, 4:0, 5:0, 9:0, 10:0, 14:0, 15:0}
pdb562b = {4:0, 5:0, 9:0, 10:0, 14:0, 15:0}
pdb563a = {0:0, 13:0, 18:0, 19:0, 20:0, 23:0, 24:0}
pdb563b = {13:0, 18:0, 19:0, 20:0, 23:0, 24:0}
pdb564a = {0:0, 11:0, 12:0, 16:0, 17:0, 21:0, 22:0}
pdb564b = {11:0, 12:0, 16:0, 17:0, 21:0, 22:0}
lock = threading.Lock()
procDic = {}
def getP3(puzzle, pattern):
output = ''
tempMap = {}
pq = PriorityQueue()
for key in pattern:
tempMap[key] = 0
pq.put((key, key))
#print 'keyA', key
for i in range(len(puzzle)):
for j in range(len(puzzle)):
if puzzle[i][j] in pattern:
temp = ''
temp += str(i+1)
temp += str(j+1)
tempMap[puzzle[i][j]] = temp
#print 'num',puzzle[i][j],i,j
while not pq.empty():
key = pq.get()[1]
output += str(tempMap[key])
#print 'keyB', key, 'value', tempMap[key]
return output
def setFormattedPuzzle(puzzle, pattern):
for i in range(len(puzzle)):
for j in range(len(puzzle)):
if puzzle[i][j] not in pattern:
puzzle[i][j] = -1
def locPrint(*arg):
lock.acquire()
try:
for i in arg:
print i
finally:
lock.release()
def getStr(puzzle):
output = ''
for i in range(len(puzzle)):
for j in range(len(puzzle)):
output += str(puzzle[i][j])
if j != len(puzzle) - 1:
output += ' '
output += '\n'
return output
###
class Node:
#PDB node contains
#state, parent, moves
#cost
def __init__(self, puzzle, parent=None, action=None):
self.state = puzzle
self.parent = parent
self.g = 0
#self.h = self.getHvalue()
self.movelist = []
self.cost = 0
#if parent exists, increment distance/step from parent's
if parent is not None:
self.g = parent.g + 1
self.cost = parent.cost
if self.parent.movelist is None:
self.movelist = [moveList[action]]
else:
self.movelist = copy.deepcopy(self.parent.movelist)
self.movelist.append(moveList[action])
else:
self.g = 0
self.movelist = None
self.moves = action
self.key = str(self.getNodeKey(self.state.puzzle))
def getHvalue(self):
return self.getManhattanValue()
def getManhattanValue(self):
h = 0
size = len(self.state.puzzle)
for i in range(0, size):
for j in range(0, size):
num = self.state.puzzle[i][j]
if num != 0:
rowGoal = (num - 1) // size
colGoal = (num - 1) % size
diffRow = abs(rowGoal - i)
diffCol = abs(colGoal - j)
dist = diffRow + diffCol
h += dist
linearCon = 0
linearCon = self.getLinearConflict()
manTotal = h + linearCon*2
return manTotal
def getLinearConflict(self):
size = len(self.state.puzzle)
inCol = [0]*(size**2)
inRow = [0]*(size**2)
conflicts = 0
#Precompute coordinates for all the numbers
for y in range(size):
for x in range(size):
num = self.state.puzzle[y][x]
rowGoal = (num - 1) // size
colGoal = (num - 1) % size
inRow[num] = rowGoal
inCol[num] = colGoal
#Check row conflicts
for r in range(size):
for cI in range(size):
for cN in range(cI+1, size):
if self.state.puzzle[r][cI] and self.state.puzzle[r][cN] and\
r == inRow[self.state.puzzle[r][cI]] and\
inRow[self.state.puzzle[r][cI]] == inRow[self.state.puzzle[r][cN]] and\
inCol[self.state.puzzle[r][cI]] > inCol[self.state.puzzle[r][cN]]:
#Conflict exists!
conflicts += 1
#Check col conflicts
for c in range(size):
for rI in range(size):
for rN in range(rI+1, size):
if self.state.puzzle[rI][c] and self.state.puzzle[rN][c] and\
c == inCol[self.state.puzzle[rI][c]] and\
inCol[self.state.puzzle[rI][c]] == inCol[self.state.puzzle[rN][c]] and\
inRow[self.state.puzzle[rI][c]] > inRow[self.state.puzzle[rN][c]]:
#Conflict exists!
conflicts += 1
return conflicts
def isGoalState(self):
return self.state.checkPuzzle()
def swap(self, puzzle, p1, p2):
(y1, x1) = p1
(y2, x2) = p2
temp = puzzle[y1][x1]
puzzle[y1][x1] = puzzle[y2][x2]
puzzle[y2][x2] = temp
def getNodeKey(self, puzzle):
output = ''
for i in puzzle:
for j in i:
output += str(j)
return output
def copy(self, puzzle):
copy = []
for i in range(0, len(puzzle)):
temp = []
for j in range(0, len(puzzle)):
temp.append(puzzle[i][j])
copy.append(temp)
return copy
def findZero(self, puzzle):
(y, x) = (0, 0)
for i in range(0, len(puzzle)):
for j in range(0, len(puzzle)):
if puzzle[i][j] == 0:
(y, x) = (i, j)
return (y, x)
def getChildren(self):
#children(list) contains a child(tuple)
#child contains: (puzzle, action(str), nodekey)
children = []
(y, x) = self.findZero(self.state.puzzle)
moves = [(y-1, x), (y+1, x), (y, x-1), (y, x+1)]
iniPuzzle = self.state.puzzle
for action in range(0, len(moves)):
(y1, x1) = moves[action]
flag = False
if action == 0 and y > 0:
#move up
flag = True
elif action == 1 and y < (self.state.size - 1):
#move down
flag = True
elif action == 2 and x > 0:
#move left
flag = True
elif action == 3 and x < (self.state.size - 1):
#move right
flag = True
if flag == True:
tempPuzzle = self.copy(iniPuzzle)
self.swap(tempPuzzle, (y1, x1), (y, x))
children.append( (tempPuzzle,\
action, \
str(tempPuzzle)) )
return children
def getNeighbour(self, pattern, pattern0):
children = []
(y, x) = self.findZero(self.state.puzzle)
moves = [(y-1, x), (y+1, x), (y, x-1), (y, x+1)]
iniPuzzle = self.state.puzzle
for action in range(len(moves)):
(y1, x1) = moves[action]
flag = False
if action == 0 and y > 0:
#move up
flag = True
elif action == 1 and y < (self.state.size - 1):
#move down
flag = True
elif action == 2 and x > 0:
#move left
flag = True
elif action == 3 and x < (self.state.size - 1):
#move right
flag = True
if flag == True:
tempPuzzle = self.copy(iniPuzzle)
cost = 0
#if neighbour is inside pattern, add to the cost
#pdb33a = {2:0, 3:0, 4:0, 0:0}
#pdb33b = {2:0, 3:0, 4:0}
if tempPuzzle[y1][x1] in pattern:
#print tempPuzzle[y1][x1], 'in', y1, x1
#print 'swapping', y1, x1, 'with', y, x
cost += 1
self.swap(tempPuzzle, (y1, x1), (y, x))
newKey = getP3(tempPuzzle, pattern0)
#print 'zero @', self.findZero(tempPuzzle), newKey
#print 'newKey', newKey
children.append( (tempPuzzle,\
action, \
newKey, \
cost, \
str(self.getNodeKey(tempPuzzle))) )
return children
### Class 'Puzzle' to store initial state
class Puzzle:
def __init__(self, initState):
#todo
self.size = len(initState)
self.puzzle = initState
#self.end = goalState
#prints out puzzle for debugging
def printP(self):
for i in range(0, self.size):
for j in range(0, self.size):
print self.puzzle[i][j],
print ""
#check if Goal is reached
def checkPuzzle(self):
if self.puzzle == finalGoal:
return True
### Class 'Search' to run path-finding algorithm
class Search:
def __init__(self, puzzle):
self.startNode = Node(puzzle)
def generatePDB(self):
temp = START
qu = Queue()
#qu.put(temp)
## threadA = Process(target=self.generate4x4,\
## name="T1",\
## args=[pdb351a,pdb351b,PDB4_5,qu,'A']\
## )
## threadB = Process(target=self.generate4x4,\
## name="T2",\
## args=[pdb352a,pdb352b,PDB4_5,qu,'B']\
## )
## threadC = Process(target=self.generate4x4,\
## name="T3",\
## args=[pdb353a,pdb353b,PDB4_5,qu,'C']\
## )
proc56a = Process(target=self.generate4x4,\
name="P1",\
args=[pdb561a,pdb561b,PDB5_6,qu,'6A']\
)
proc56a.start()
proc56a.join()
## threadA.start()
## threadB.start()
## threadC.start()
#output = qu.get()
#print output
## threadA.join()
## threadB.join()
## threadC.join()
## threadA = threading.Thread(target=self.generate4x4,\
## name="T1",\
## args=[pdb33a,pdb33b,PDB4_3,qu,'3']\
## )
## threadA.start()
## threadA.join()
return FINISHED
### 3-6-6
#For 3 partition
#return self.generate4x4(pdb33a,pdb33b,PDB4_3,qu,'3')
#For 6a partition
#return self.generate4x4(pdb361a,pdb361b,PDB4_6)
#For 6b partition
#return self.generate4x4(pdb362a,pdb362b,PDB4_6)
### 5-5-5
#For 5a partition
#return self.generate4x4(pdb351a,pdb351b,PDB4_5)
#For 5b partition
#return self.generate4x4(pdb352a,pdb352b,PDB4_5,qu,'B')
#For 5c partition
#return self.generate4x4(pdb353a,pdb353b,PDB4_5)
#print 'test'
def generate4x4(self, patternZero, patternHash, LIMIT, qu, filename):
currNode = copy.deepcopy(self.startNode)
#Replace 'useless' tiles with '-1'
setFormattedPuzzle(currNode.state.puzzle, patternZero)
currNode.key = currNode.getNodeKey(currNode.state.puzzle)
#currNode.state.printP()
#locPrint(getStr(currNode.state.puzzle))
## 4 Data structures
# 1) openList - PQ to store next nodes to pop
# 2) openMap - Dict to prune off scrub nodes
# 3) closedList - Dict to track pattern config with 0
# 4) p3 - Dict to track pattern config without 0
#Frontier to pop off more nodes
openList = Queue()
#Start from goal state
openList.put(currNode)
#To prune stuff on the Q
openMap = {currNode.key:currNode.g}
#Visited list: key(patternZero), value(cost)
closedList = {getP3(currNode.state.puzzle, patternZero):0}
#Visited list wo blank: key(patternHash), value(cost)
p3 = {getP3(currNode.state.puzzle, patternHash):0}
#print getP3(currNode.state.puzzle, patternHash)
#pdb33a: 0, pdb33b: no 0
stepCount = 0
sA=0; sB=0; sC=0; sD=0
flag = True
while True:
stepCount += 1
if stepCount % 10000 == 0:
#print("step:", stepCount)
#print "step:", stepCount, 'thread', filename
s = 'step ' + str(stepCount) + ' thread ' + filename
s += ' size ' + str(len(p3))
#sys.stdout.write(s + '\n')
locPrint(s)
## print 'hashTable size',len(p3),'openList size',openList.qsize()
## print 'c1',sA,'c2',sB,'c3',sC,'c4',sD
if openList.empty():
print "EMPTY FRONTIER, help"
return None
currNode = openList.get()
## if flag:
## print patKey
## flag = False
if len(p3) >= 50000:
#if len(p3) >= 2000:
print 'FINISHED', filename
self.storeHash(p3, filename)
procDic[FINISHED] = FINISHED
#qu.put(FINISHED)
return FINISHED
#child: puzzle, action(int), patternkey0, cost, nodekey
for child in currNode.getNeighbour(patternHash, patternZero):
# Perform 4 checks
# 1) Minimise previous movements back to parent
# 2) Check openMap, prune g <= existing key's g
# 3) Check closedlist, prune greater costs
# 4) Check p3, update p3 if cost is lower
### CHECK ONE
if currNode.moves is not None and child[1] == mMap[currNode.moves]:
#print 'b: prevMove'
sA += 1
continue
### CHECK TWO
if child[4] in openMap:
if openMap[child[4]] <= currNode.g + 1:
sB += 1
continue
### CHECK THREE
if child[2] in closedList:
if currNode.cost + child[3] < closedList[child[2]]:
sC += 1
#Update region cost to lower one
closedList[child[2]] = currNode.cost + child[3]
else:
#We don't want similar nodes inside openList
continue
hashKey = getP3(child[0], patternHash)
### CHECK FOUR
if hashKey in p3:
if currNode.cost + child[3] < p3[hashKey]:
sD += 1
#Update hashTable to lower one
p3[hashKey] = currNode.cost + child[3]
else:
p3[hashKey] = currNode.cost + child[3]
#Finally, copy previous node
newPuz = copy.deepcopy(currNode.state)
newPuz.puzzle = child[0]
newNode = Node(newPuz, currNode, child[1])
newNode.cost += child[3]
openList.put(newNode)
openMap[newNode.key] = newNode.g
closedList[child[2]] = currNode.cost + child[3]
print 'GG end of while loop'
return None
def storeHash(self, hashTable, filename):
with open('pdbTest' + filename +'.json', 'w') as f:
json.dump(hashTable, f, indent=4, sort_keys=True)
## def aStarOne(self):
## currNode = self.startNode
## if self.checkSolvable(currNode.state.puzzle) == False:
## return None
## openList = PriorityQueue()
## openList.put((currNode.h, (currNode.key, currNode)))
## closedList = {}
## openMap = {}
## openMap[currNode.key] = currNode
## stepCount = 0
## while True:
## stepCount += 1
## if stepCount % 10000 == 0:
## print "step:", stepCount
## #Check frontier if empty
## if openList.empty():
## #print("Unsolvable")
## print "Unsolvable"
## return None
## currNode = openList.get()[1][1]
## nodeKey = currNode.key
## #Set state to visited
## closedList[nodeKey] = 1
## #Current node is the GOAL!!!
## if currNode.isGoalState():
## #print(stepCount)
## print 'Total steps:', stepCount
## return currNode
## #child contains: (puzzle, action(int), nodekey)
## #child IS NOT A NODE!!! its a tuple...
## for child in currNode.getChildren():
## #If previously visited child, skip child
## if child[2] in closedList:
## continue
## #If parent is not first node popped AND
## #If child's move does not lead back to parent
## #THEN skip child
## if currNode.moves is not None and child[1] == mMap[currNode.moves]:
## continue
## #Copies parent' puzzle, changing only initial state
## newPuz = copy.deepcopy(currNode.state)
## newPuz.puzzle = child[0]
##
## newNode = Node(newPuz, currNode, child[1])
## #Checks if child state in openMap
## #If in openMap and more moves needed, skip child
## if newNode.key in openMap:
## if openMap[newNode.key].g < newNode.g:
## continue
## #newNode.state.printP()
## newH = newNode.h
## newG = newNode.g
## newF = newG + newH
## openList.put( (newF,\
## (newNode.key, newNode)) )
## openMap[newNode.key] = newNode
## return None
##
## #Function to check for solvable state
## def checkSolvable(self, puzzle):
## inversions = 0
## lineList = []
## (y, x) = (0, 0)
## for i in range(0, len(puzzle)):
## for j in range(0, len(puzzle)):
## lineList.append(puzzle[i][j])
## if puzzle[i][j] == 0:
## (y, x) = (i, j)
## print 'Y', 'X', i, j
##
## for i in range(0, len(lineList)-1):
## for j in range(i+1, len(lineList)):
## if lineList[j] and lineList[i] and lineList[i] > lineList[j]:
## inversions += 1
##
## del lineList
## #print("INV:", inversions)
## print 'INV:', inversions
## if len(puzzle) % 2 == 1:
## #ODD, must have even inversions
## if (inversions % 2) == 0:
## print 'ODD length Solvable'
## return True
## else:
## print 'ODD length Unsolvable'
## return False
## else:
## #EVEN, must have:
## #1) blank on EVEN row & ODD inversions
## #2) blank on ODD row & EVEN inversions
## if (y % 2 == 0 and inversions % 2 == 1) or \
## (y % 2 == 1 and inversions % 2 == 0):
## print 'EVEN length Solvable'
## return True
## else:
## print 'EVEN length Unsolvable'
## return False
##
### Convenient function to retrace path
def reconstruct(currentNode):
path = []
current = currentNode
while current is not None:
if current.moves is None:
break
path.append(moveList[current.moves])
current = current.parent
return path[::-1]
if __name__ == "__main__":
## data = {}
## data[112122313242] = 1
## data[112122313241] = 0
## field = {}
## try:
## #check if pdb exist
## f = open('pdbTest.json', 'r')
## #read from json file into dict
## field = json.load(f)
## except IOError:
## #print("No File detected")
## #print("Writing new data")
## #populate json file with dict
## with open('pdbTest.json', 'w') as f:
## json.dump(data, f)
## finally:
## f.close()
n = 5
max_num = n ** 2 - 1
goal_state = [[0 for i in range(n)] for j in range(n)]
#Set goal state
for i in range(1, max_num + 1):
goal_state[(i-1)//n][(i-1)%n] = i
goal_state[n - 1][n - 1] = 0
#Global reference to goal state
finalGoal = goal_state
puzzle = Puzzle(goal_state)
#Prints initial state
puzzle.printP()
#Solve the puzzle
search = Search(puzzle)
result = search.generatePDB()
if result is None:
print 'GG END'
elif result == FINISHED:
print 'DONE GENERATING PDB'
## # do NOT modify below
##
## # argv[0] represents the name of the file that is being executed
## # argv[1] represents name of input file
## # argv[2] represents name of destination output file
##
## #PROPER USE[1]
## if len(sys.argv) != 3:
## raise ValueError("Wrong number of arguments!")
##
## try:
## #f = open("n_equals_3/input_2.txt", 'r')
## #PROPER USE[2]
## f = open(sys.argv[1], 'r')
## except IOError:
## raise IOError("Input file not found!")
##
## lines = f.readlines()
##
## # n = num rows in input file
## n = len(lines)
## # max_num = n to the power of 2 - 1
## max_num = n ** 2 - 1
##
## # Instantiate a 2D list of size n x n
## init_state = [[0 for i in range(n)] for j in range(n)]
## goal_state = [[0 for i in range(n)] for j in range(n)]
##
## #Parse file into 2d list
## i,j = 0, 0
## for line in lines:
## lll = line.split()
## ll = [int(x) for x in lll]
## for number in ll:
## if 0 <= number <= max_num:
## init_state[i][j] = int(number)
## j += 1
## if j == n:
## i += 1
## j = 0
## #Set goal state
## for i in range(1, max_num + 1):
## goal_state[(i-1)//n][(i-1)%n] = i
## goal_state[n - 1][n - 1] = 0
## #Global reference to goal state
## finalGoal = goal_state
## puzzle = Puzzle(init_state)
## #Prints initial state
## puzzle.printP()
## #Solve the puzzle
## search = Search(puzzle)
## result = search.aStarOne()
##
## #PROPER USE[3]
## with open(sys.argv[2], 'w') as out:
## if result is None:
## #print("UNSOLVABLE")
## print "UNSOLVABLE"
## out.write('UNSOLVABLE')
## else:
## path = reconstruct(result)
## output = ''
## for action in path:
## #print(action)
## output = output + str(action) + '\n'
## print output
## out.write(output)
## #print("TOTAL:", len(path))
## print "TOTAL", len(path)