-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchTestClasses.py
823 lines (679 loc) · 31.5 KB
/
searchTestClasses.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
# searchTestClasses.py
# --------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# ([email protected]) and Dan Klein ([email protected]).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel ([email protected]).
import sys
import re
import testClasses
import textwrap
# import project specific code
import layout
import pacman
from search import SearchProblem
# helper function for printing solutions in solution files
def wrap_solution(solution):
if type(solution) == type([]):
return '\n'.join(textwrap.wrap(' '.join(solution)))
else:
return str(solution)
def followAction(state, action, problem):
for successor1, action1, cost1 in problem.getSuccessors(state):
if action == action1: return successor1
return None
def followPath(path, problem):
state = problem.getStartState()
states = [state]
for action in path:
state = followAction(state, action, problem)
states.append(state)
return states
def checkSolution(problem, path):
state = problem.getStartState()
for action in path:
state = followAction(state, action, problem)
return problem.isGoalState(state)
# Search problem on a plain graph
class GraphSearch(SearchProblem):
# Read in the state graph; define start/end states, edges and costs
def __init__(self, graph_text):
self.expanded_states = []
lines = graph_text.split('\n')
r = re.match('start_state:(.*)', lines[0])
if r == None:
print("Broken graph:")
print('"""%s"""' % graph_text)
raise Exception("GraphSearch graph specification start_state not found or incorrect on line 0")
self.start_state = r.group(1).strip()
r = re.match('goal_states:(.*)', lines[1])
if r == None:
print("Broken graph:")
print('"""%s"""' % graph_text)
raise Exception("GraphSearch graph specification goal_states not found or incorrect on line 1")
goals = r.group(1).split()
self.goals = [str.strip(g) for g in goals]
self.successors = {}
all_states = set()
self.orderedSuccessorTuples = []
for l in lines[2:]:
if len(l.split()) == 3:
start, action, next_state = l.split()
cost = 1
elif len(l.split()) == 4:
start, action, next_state, cost = l.split()
else:
print("Broken graph:")
print('"""%s"""' % graph_text)
raise Exception("Invalid line in GraphSearch graph specification on line:" + l)
cost = float(cost)
self.orderedSuccessorTuples.append((start, action, next_state, cost))
all_states.add(start)
all_states.add(next_state)
if start not in self.successors:
self.successors[start] = []
self.successors[start].append((next_state, action, cost))
for s in all_states:
if s not in self.successors:
self.successors[s] = []
# Get start state
def getStartState(self):
return self.start_state
# Check if a state is a goal state
def isGoalState(self, state):
return state in self.goals
# Get all successors of a state
def getSuccessors(self, state):
self.expanded_states.append(state)
return list(self.successors[state])
# Calculate total cost of a sequence of actions
def getCostOfActions(self, actions):
total_cost = 0
state = self.start_state
for a in actions:
successors = self.successors[state]
match = False
for (next_state, action, cost) in successors:
if a == action:
state = next_state
total_cost += cost
match = True
if not match:
print('invalid action sequence')
sys.exit(1)
return total_cost
# Return a list of all states on which 'getSuccessors' was called
def getExpandedStates(self):
return self.expanded_states
def __str__(self):
print(self.successors)
edges = ["%s %s %s %s" % t for t in self.orderedSuccessorTuples]
return \
"""start_state: %s
goal_states: %s
%s""" % (self.start_state, " ".join(self.goals), "\n".join(edges))
def parseHeuristic(heuristicText):
heuristic = {}
for line in heuristicText.split('\n'):
tokens = line.split()
if len(tokens) != 2:
print("Broken heuristic:")
print('"""%s"""' % heuristicText)
raise Exception("GraphSearch heuristic specification broken at tokens:" + str(tokens))
state, h = tokens
heuristic[state] = float(h)
def graphHeuristic(state, problem=None):
if state in heuristic:
return heuristic[state]
else:
import pprint
pp = pprint.PrettyPrinter(indent=4)
print("Heuristic:")
pp.pprint(heuristic)
raise Exception("Graph heuristic called with invalid state: " + str(state))
return graphHeuristic
class GraphSearchTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(GraphSearchTest, self).__init__(question, testDict)
self.graph_text = testDict['graph']
self.alg = testDict['algorithm']
self.diagram = testDict['diagram']
self.exactExpansionOrder = testDict.get('exactExpansionOrder', 'True').lower() == "true"
if 'heuristic' in testDict:
self.heuristic = parseHeuristic(testDict['heuristic'])
else:
self.heuristic = None
# Note that the return type of this function is a tripple:
# (solution, expanded states, error message)
def getSolInfo(self, search):
alg = getattr(search, self.alg)
problem = GraphSearch(self.graph_text)
if self.heuristic != None:
solution = alg(problem, self.heuristic)
else:
solution = alg(problem)
if type(solution) != type([]):
return None, None, 'The result of %s must be a list. (Instead, it is %s)' % (self.alg, type(solution))
return solution, problem.getExpandedStates(), None
# Run student code. If an error message is returned, print error and return false.
# If a good solution is returned, printn the solution and return true; otherwise,
# print both the correct and student's solution and return false.
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
gold_solution = [str.split(solutionDict['solution']), str.split(solutionDict['rev_solution'])]
gold_expanded_states = [str.split(solutionDict['expanded_states']), str.split(solutionDict['rev_expanded_states'])]
solution, expanded_states, error = self.getSolInfo(search)
if error != None:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\t%s' % error)
return False
if solution in gold_solution and (not self.exactExpansionOrder or expanded_states in gold_expanded_states):
grades.addMessage('PASS: %s' % self.path)
grades.addMessage('\tsolution:\t\t%s' % solution)
grades.addMessage('\texpanded_states:\t%s' % expanded_states)
return True
else:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\tgraph:')
for line in self.diagram.split('\n'):
grades.addMessage('\t %s' % (line,))
grades.addMessage('\tstudent solution:\t\t%s' % solution)
grades.addMessage('\tstudent expanded_states:\t%s' % expanded_states)
grades.addMessage('')
grades.addMessage('\tcorrect solution:\t\t%s' % gold_solution[0])
grades.addMessage('\tcorrect expanded_states:\t%s' % gold_expanded_states[0])
grades.addMessage('\tcorrect rev_solution:\t\t%s' % gold_solution[1])
grades.addMessage('\tcorrect rev_expanded_states:\t%s' % gold_expanded_states[1])
return False
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# open file and write comments
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
handle.write('# This solution is designed to support both right-to-left\n')
handle.write('# and left-to-right implementations.\n')
# write forward solution
solution, expanded_states, error = self.getSolInfo(search)
if error != None: raise Exception("Error in solution code: %s" % error)
handle.write('solution: "%s"\n' % ' '.join(solution))
handle.write('expanded_states: "%s"\n' % ' '.join(expanded_states))
# reverse and write backwards solution
search.REVERSE_PUSH = not search.REVERSE_PUSH
solution, expanded_states, error = self.getSolInfo(search)
if error != None: raise Exception("Error in solution code: %s" % error)
handle.write('rev_solution: "%s"\n' % ' '.join(solution))
handle.write('rev_expanded_states: "%s"\n' % ' '.join(expanded_states))
# clean up
search.REVERSE_PUSH = not search.REVERSE_PUSH
handle.close()
return True
class PacmanSearchTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(PacmanSearchTest, self).__init__(question, testDict)
self.layout_text = testDict['layout']
self.alg = testDict['algorithm']
self.layoutName = testDict['layoutName']
# TODO: sensible to have defaults like this?
self.leewayFactor = float(testDict.get('leewayFactor', '1'))
self.costFn = eval(testDict.get('costFn', 'None'))
self.searchProblemClassName = testDict.get('searchProblemClass', 'PositionSearchProblem')
self.heuristicName = testDict.get('heuristic', None)
def getSolInfo(self, search, searchAgents):
alg = getattr(search, self.alg)
lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
start_state = pacman.GameState()
start_state.initialize(lay, 0)
problemClass = getattr(searchAgents, self.searchProblemClassName)
problemOptions = {}
if self.costFn != None:
problemOptions['costFn'] = self.costFn
problem = problemClass(start_state, **problemOptions)
heuristic = getattr(searchAgents, self.heuristicName) if self.heuristicName != None else None
if heuristic != None:
solution = alg(problem, heuristic)
else:
solution = alg(problem)
if type(solution) != type([]):
return None, None, 'The result of %s must be a list. (Instead, it is %s)' % (self.alg, type(solution))
from game import Directions
dirs = Directions.LEFT.keys()
if [el in dirs for el in solution].count(False) != 0:
return None, None, 'Output of %s must be a list of actions from game.Directions' % self.alg
expanded = problem._expanded
return solution, expanded, None
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
gold_solution = [str.split(solutionDict['solution']), str.split(solutionDict['rev_solution'])]
gold_expanded = max(int(solutionDict['expanded_nodes']), int(solutionDict['rev_expanded_nodes']))
solution, expanded, error = self.getSolInfo(search, searchAgents)
if error != None:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('%s' % error)
return False
# FIXME: do we want to standardize test output format?
if solution not in gold_solution:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('Solution not correct.')
grades.addMessage('\tstudent solution length: %s' % len(solution))
grades.addMessage('\tstudent solution:\n%s' % wrap_solution(solution))
grades.addMessage('')
grades.addMessage('\tcorrect solution length: %s' % len(gold_solution[0]))
grades.addMessage('\tcorrect (reversed) solution length: %s' % len(gold_solution[1]))
grades.addMessage('\tcorrect solution:\n%s' % wrap_solution(gold_solution[0]))
grades.addMessage('\tcorrect (reversed) solution:\n%s' % wrap_solution(gold_solution[1]))
return False
if expanded > self.leewayFactor * gold_expanded and expanded > gold_expanded + 1:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('Too many node expanded; are you expanding nodes twice?')
grades.addMessage('\tstudent nodes expanded: %s' % expanded)
grades.addMessage('')
grades.addMessage('\tcorrect nodes expanded: %s (leewayFactor %s)' % (gold_expanded, self.leewayFactor))
return False
grades.addMessage('PASS: %s' % self.path)
grades.addMessage('\tpacman layout:\t\t%s' % self.layoutName)
grades.addMessage('\tsolution length: %s' % len(solution))
grades.addMessage('\tnodes expanded:\t\t%s' % expanded)
return True
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# open file and write comments
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
handle.write('# This solution is designed to support both right-to-left\n')
handle.write('# and left-to-right implementations.\n')
handle.write('# Number of nodes expanded must be with a factor of %s of the numbers below.\n' % self.leewayFactor)
# write forward solution
solution, expanded, error = self.getSolInfo(search, searchAgents)
if error != None: raise Exception("Error in solution code: %s" % error)
handle.write('solution: """\n%s\n"""\n' % wrap_solution(solution))
handle.write('expanded_nodes: "%s"\n' % expanded)
# write backward solution
search.REVERSE_PUSH = not search.REVERSE_PUSH
solution, expanded, error = self.getSolInfo(search, searchAgents)
if error != None: raise Exception("Error in solution code: %s" % error)
handle.write('rev_solution: """\n%s\n"""\n' % wrap_solution(solution))
handle.write('rev_expanded_nodes: "%s"\n' % expanded)
# clean up
search.REVERSE_PUSH = not search.REVERSE_PUSH
handle.close()
return True
from game import Actions
def getStatesFromPath(start, path):
"Returns the list of states visited along the path"
vis = [start]
curr = start
for a in path:
x,y = curr
dx, dy = Actions.directionToVector(a)
curr = (int(x + dx), int(y + dy))
vis.append(curr)
return vis
class CornerProblemTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(CornerProblemTest, self).__init__(question, testDict)
self.layoutText = testDict['layout']
self.layoutName = testDict['layoutName']
def solution(self, search, searchAgents):
lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')])
gameState = pacman.GameState()
gameState.initialize(lay, 0)
problem = searchAgents.CornersProblem(gameState)
path = search.bfs(problem)
gameState = pacman.GameState()
gameState.initialize(lay, 0)
visited = getStatesFromPath(gameState.getPacmanPosition(), path)
top, right = gameState.getWalls().height-2, gameState.getWalls().width-2
missedCorners = [p for p in ((1,1), (1,top), (right, 1), (right, top)) if p not in visited]
return path, missedCorners
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
gold_length = int(solutionDict['solution_length'])
solution, missedCorners = self.solution(search, searchAgents)
if type(solution) != type([]):
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('The result must be a list. (Instead, it is %s)' % type(solution))
return False
if len(missedCorners) != 0:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('Corners missed: %s' % missedCorners)
return False
if len(solution) != gold_length:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('Optimal solution not found.')
grades.addMessage('\tstudent solution length:\n%s' % len(solution))
grades.addMessage('')
grades.addMessage('\tcorrect solution length:\n%s' % gold_length)
return False
grades.addMessage('PASS: %s' % self.path)
grades.addMessage('\tpacman layout:\t\t%s' % self.layoutName)
grades.addMessage('\tsolution length:\t\t%s' % len(solution))
return True
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# open file and write comments
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
print("Solving problem", self.layoutName)
print(self.layoutText)
path, _ = self.solution(search, searchAgents)
length = len(path)
print("Problem solved")
handle.write('solution_length: "%s"\n' % length)
handle.close()
# template = """class: "HeuristicTest"
#
# heuristic: "foodHeuristic"
# searchProblemClass: "FoodSearchProblem"
# layoutName: "Test %s"
# layout: \"\"\"
# %s
# \"\"\"
# """
#
# for i, (_, _, l) in enumerate(doneTests + foodTests):
# f = open("food_heuristic_%s.test" % (i+1), "w")
# f.write(template % (i+1, "\n".join(l)))
# f.close()
class HeuristicTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(HeuristicTest, self).__init__(question, testDict)
self.layoutText = testDict['layout']
self.layoutName = testDict['layoutName']
self.searchProblemClassName = testDict['searchProblemClass']
self.heuristicName = testDict['heuristic']
def setupProblem(self, searchAgents):
lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')])
gameState = pacman.GameState()
gameState.initialize(lay, 0)
problemClass = getattr(searchAgents, self.searchProblemClassName)
problem = problemClass(gameState)
state = problem.getStartState()
heuristic = getattr(searchAgents, self.heuristicName)
return problem, state, heuristic
def checkHeuristic(self, heuristic, problem, state, solutionCost):
h0 = heuristic(state, problem)
if solutionCost == 0:
if h0 == 0:
return True, ''
else:
return False, 'Heuristic failed H(goal) == 0 test'
if h0 < 0:
return False, 'Heuristic failed H >= 0 test'
if not h0 > 0:
return False, 'Heuristic failed non-triviality test'
if not h0 <= solutionCost:
return False, 'Heuristic failed admissibility test'
for succ, action, stepCost in problem.getSuccessors(state):
h1 = heuristic(succ, problem)
if h1 < 0: return False, 'Heuristic failed H >= 0 test'
if h0 - h1 > stepCost: return False, 'Heuristic failed consistency test'
return True, ''
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
solutionCost = int(solutionDict['solution_cost'])
problem, state, heuristic = self.setupProblem(searchAgents)
passed, message = self.checkHeuristic(heuristic, problem, state, solutionCost)
if not passed:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('%s' % message)
return False
else:
grades.addMessage('PASS: %s' % self.path)
return True
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# open file and write comments
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
print("Solving problem", self.layoutName, self.heuristicName)
print(self.layoutText)
problem, _, heuristic = self.setupProblem(searchAgents)
path = search.astar(problem, heuristic)
cost = problem.getCostOfActions(path)
print("Problem solved")
handle.write('solution_cost: "%s"\n' % cost)
handle.close()
return True
class HeuristicGrade(testClasses.TestCase):
def __init__(self, question, testDict):
super(HeuristicGrade, self).__init__(question, testDict)
self.layoutText = testDict['layout']
self.layoutName = testDict['layoutName']
self.searchProblemClassName = testDict['searchProblemClass']
self.heuristicName = testDict['heuristic']
self.basePoints = int(testDict['basePoints'])
self.thresholds = [int(t) for t in testDict['gradingThresholds'].split()]
def setupProblem(self, searchAgents):
lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')])
gameState = pacman.GameState()
gameState.initialize(lay, 0)
problemClass = getattr(searchAgents, self.searchProblemClassName)
problem = problemClass(gameState)
state = problem.getStartState()
heuristic = getattr(searchAgents, self.heuristicName)
return problem, state, heuristic
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
problem, _, heuristic = self.setupProblem(searchAgents)
path = search.astar(problem, heuristic)
expanded = problem._expanded
if not checkSolution(problem, path):
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\tReturned path is not a solution.')
grades.addMessage('\tpath returned by astar: %s' % expanded)
return False
grades.addPoints(self.basePoints)
points = 0
for threshold in self.thresholds:
if expanded <= threshold:
points += 1
grades.addPoints(points)
if points >= len(self.thresholds):
grades.addMessage('PASS: %s' % self.path)
else:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\texpanded nodes: %s' % expanded)
grades.addMessage('\tthresholds: %s' % self.thresholds)
return True
def writeSolution(self, moduleDict, filePath):
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
handle.write('# File intentionally blank.\n')
handle.close()
return True
# template = """class: "ClosestDotTest"
#
# layoutName: "Test %s"
# layout: \"\"\"
# %s
# \"\"\"
# """
#
# for i, (_, _, l) in enumerate(foodTests):
# f = open("closest_dot_%s.test" % (i+1), "w")
# f.write(template % (i+1, "\n".join(l)))
# f.close()
class ClosestDotTest(testClasses.TestCase):
def __init__(self, question, testDict):
super(ClosestDotTest, self).__init__(question, testDict)
self.layoutText = testDict['layout']
self.layoutName = testDict['layoutName']
def solution(self, searchAgents):
lay = layout.Layout([l.strip() for l in self.layoutText.split('\n')])
gameState = pacman.GameState()
gameState.initialize(lay, 0)
path = searchAgents.ClosestDotSearchAgent().findPathToClosestDot(gameState)
return path
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
gold_length = int(solutionDict['solution_length'])
solution = self.solution(searchAgents)
if type(solution) != type([]):
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('\tThe result must be a list. (Instead, it is %s)' % type(solution))
return False
if len(solution) != gold_length:
grades.addMessage('FAIL: %s' % self.path)
grades.addMessage('Closest dot not found.')
grades.addMessage('\tstudent solution length:\n%s' % len(solution))
grades.addMessage('')
grades.addMessage('\tcorrect solution length:\n%s' % gold_length)
return False
grades.addMessage('PASS: %s' % self.path)
grades.addMessage('\tpacman layout:\t\t%s' % self.layoutName)
grades.addMessage('\tsolution length:\t\t%s' % len(solution))
return True
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# open file and write comments
handle = open(filePath, 'w')
handle.write('# This is the solution file for %s.\n' % self.path)
print("Solving problem", self.layoutName)
print(self.layoutText)
length = len(self.solution(searchAgents))
print("Problem solved")
handle.write('solution_length: "%s"\n' % length)
handle.close()
return True
class CornerHeuristicSanity(testClasses.TestCase):
def __init__(self, question, testDict):
super(CornerHeuristicSanity, self).__init__(question, testDict)
self.layout_text = testDict['layout']
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
game_state = pacman.GameState()
lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
game_state.initialize(lay, 0)
problem = searchAgents.CornersProblem(game_state)
start_state = problem.getStartState()
h0 = searchAgents.cornersHeuristic(start_state, problem)
succs = problem.getSuccessors(start_state)
# cornerConsistencyA
for succ in succs:
h1 = searchAgents.cornersHeuristic(succ[0], problem)
if h0 - h1 > 1:
grades.addMessage('FAIL: inconsistent heuristic')
return False
heuristic_cost = searchAgents.cornersHeuristic(start_state, problem)
true_cost = float(solutionDict['cost'])
# cornerNontrivial
if heuristic_cost == 0:
grades.addMessage('FAIL: must use non-trivial heuristic')
return False
# cornerAdmissible
if heuristic_cost > true_cost:
grades.addMessage('FAIL: Inadmissible heuristic')
return False
path = solutionDict['path'].split()
states = followPath(path, problem)
heuristics = []
for state in states:
heuristics.append(searchAgents.cornersHeuristic(state, problem))
for i in range(0, len(heuristics) - 1):
h0 = heuristics[i]
h1 = heuristics[i+1]
# cornerConsistencyB
if h0 - h1 > 1:
grades.addMessage('FAIL: inconsistent heuristic')
return False
# cornerPosH
if h0 < 0 or h1 <0:
grades.addMessage('FAIL: non-positive heuristic')
return False
# cornerGoalH
if heuristics[len(heuristics) - 1] != 0:
grades.addMessage('FAIL: heuristic non-zero at goal')
return False
grades.addMessage('PASS: heuristic value less than true cost at start state')
return True
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# write comment
handle = open(filePath, 'w')
handle.write('# In order for a heuristic to be admissible, the value\n')
handle.write('# of the heuristic must be less at each state than the\n')
handle.write('# true cost of the optimal path from that state to a goal.\n')
# solve problem and write solution
lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
start_state = pacman.GameState()
start_state.initialize(lay, 0)
problem = searchAgents.CornersProblem(start_state)
solution = search.astar(problem, searchAgents.cornersHeuristic)
handle.write('cost: "%d"\n' % len(solution))
handle.write('path: """\n%s\n"""\n' % wrap_solution(solution))
handle.close()
return True
class CornerHeuristicPacman(testClasses.TestCase):
def __init__(self, question, testDict):
super(CornerHeuristicPacman, self).__init__(question, testDict)
self.layout_text = testDict['layout']
def execute(self, grades, moduleDict, solutionDict):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
total = 0
true_cost = float(solutionDict['cost'])
thresholds = [int(x) for x in solutionDict['thresholds'].split()]
game_state = pacman.GameState()
lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
game_state.initialize(lay, 0)
problem = searchAgents.CornersProblem(game_state)
start_state = problem.getStartState()
if searchAgents.cornersHeuristic(start_state, problem) > true_cost:
grades.addMessage('FAIL: Inadmissible heuristic')
return False
path = search.astar(problem, searchAgents.cornersHeuristic)
print("path:", path)
print("path length:", len(path))
cost = problem.getCostOfActions(path)
if cost > true_cost:
grades.addMessage('FAIL: Inconsistent heuristic')
return False
expanded = problem._expanded
points = 0
for threshold in thresholds:
if expanded <= threshold:
points += 1
grades.addPoints(points)
if points >= len(thresholds):
grades.addMessage('PASS: Heuristic resulted in expansion of %d nodes' % expanded)
else:
grades.addMessage('FAIL: Heuristic resulted in expansion of %d nodes' % expanded)
return True
def writeSolution(self, moduleDict, filePath):
search = moduleDict['search']
searchAgents = moduleDict['searchAgents']
# write comment
handle = open(filePath, 'w')
handle.write('# This solution file specifies the length of the optimal path\n')
handle.write('# as well as the thresholds on number of nodes expanded to be\n')
handle.write('# used in scoring.\n')
# solve problem and write solution
lay = layout.Layout([l.strip() for l in self.layout_text.split('\n')])
start_state = pacman.GameState()
start_state.initialize(lay, 0)
problem = searchAgents.CornersProblem(start_state)
solution = search.astar(problem, searchAgents.cornersHeuristic)
handle.write('cost: "%d"\n' % len(solution))
handle.write('path: """\n%s\n"""\n' % wrap_solution(solution))
handle.write('thresholds: "2000 1600 1200"\n')
handle.close()
return True