fork(5) download
  1. # logicPlan.py
  2. # ------------
  3. # Licensing Information: You are free to use or extend these projects for
  4. # educational purposes provided that (1) you do not distribute or publish
  5. # solutions, (2) you retain this notice, and (3) you provide clear
  6. # attribution to UC Berkeley, including a link to http://a...content-available-to-author-only...y.edu.
  7. #
  8. # Attribution Information: The Pacman AI projects were developed at UC Berkeley.
  9. # The core projects and autograders were primarily created by John DeNero
  10. # (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
  11. # Student side autograding was added by Brad Miller, Nick Hay, and
  12. # Pieter Abbeel (pabbeel@cs.berkeley.edu).
  13.  
  14.  
  15. """
  16. In logicPlan.py, you will implement logic planning methods which are called by
  17. Pacman agents (in logicAgents.py).
  18. """
  19.  
  20. import util
  21. import sys
  22. import logic
  23. import game
  24.  
  25.  
  26. pacman_str = 'P'
  27. ghost_pos_str = 'G'
  28. ghost_east_str = 'GE'
  29. pacman_alive_str = 'PA'
  30.  
  31. class PlanningProblem:
  32. """
  33. This class outlines the structure of a planning problem, but doesn't implement
  34. any of the methods (in object-oriented terminology: an abstract class).
  35.  
  36. You do not need to change anything in this class, ever.
  37. """
  38.  
  39. def getStartState(self):
  40. """
  41. Returns the start state for the planning problem.
  42. """
  43. util.raiseNotDefined()
  44.  
  45. def getGhostStartStates(self):
  46. """
  47. Returns a list containing the start state for each ghost.
  48. Only used in problems that use ghosts (FoodGhostPlanningProblem)
  49. """
  50. util.raiseNotDefined()
  51.  
  52. def getGoalState(self):
  53. """
  54. Returns goal state for problem. Note only defined for problems that have
  55. a unique goal state such as PositionPlanningProblem
  56. """
  57. util.raiseNotDefined()
  58.  
  59. def tinyMazePlan(problem):
  60. """
  61. Returns a sequence of moves that solves tinyMaze. For any other maze, the
  62. sequence of moves will be incorrect, so only use this for tinyMaze.
  63. """
  64. from game import Directions
  65. s = Directions.SOUTH
  66. w = Directions.WEST
  67. return [s, s, w, s, w, w, s, w]
  68.  
  69. def sentence1():
  70. """Returns a logic.Expr instance that encodes that the following expressions are all true.
  71.  
  72. A or B
  73. (not A) if and only if ((not B) or C)
  74. (not A) or (not B) or C
  75. """
  76. "*** YOUR CODE HERE ***"
  77. A = logic.Expr('A')
  78. B = logic.Expr('B')
  79. C = logic.Expr('C')
  80. expr1 = A | B
  81. expr2 = (~A) % ((~B) | C)
  82. expr3 = logic.disjoin([~A, ~B, C])
  83. return logic.conjoin([expr1, expr2, expr3])
  84.  
  85. def sentence2():
  86. """Returns a logic.Expr instance that encodes that the following expressions are all true.
  87.  
  88. C if and only if (B or D)
  89. A implies ((not B) and (not D))
  90. (not (B and (not C))) implies A
  91. (not D) implies C
  92. """
  93. "*** YOUR CODE HERE ***"
  94. A = logic.Expr('A')
  95. B = logic.Expr('B')
  96. C = logic.Expr('C')
  97. D = logic.Expr('D')
  98. expr1 = C % (B | D)
  99. expr2 = A >> ((~B) & (~D))
  100. expr3 = (~(B & (~C))) >> A
  101. expr4 = (~D) >> C
  102. return logic.conjoin([expr1, expr2, expr3, expr4])
  103.  
  104.  
  105. def sentence3():
  106. """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0],
  107. created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr
  108. instance that encodes the following English sentences (in this order):
  109.  
  110. The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was
  111. not killed at time 0 or it was not alive and time 0 and it was born at time 0.
  112.  
  113. The Wumpus cannot both be alive at time 0 and be born at time 0.
  114.  
  115. The Wumpus is born at time 0.
  116. """
  117. "*** YOUR CODE HERE ***"
  118. WumpusAlive0 = logic.PropSymbolExpr("WumpusAlive", 0)
  119. WumpusAlive1 = logic.PropSymbolExpr("WumpusAlive", 1)
  120. WumpusBorn = logic.PropSymbolExpr("WumpusBorn", 0)
  121. WumpusKilled = logic.PropSymbolExpr("WumpusKilled", 0)
  122. expr1 = WumpusAlive1 % (WumpusAlive0 & ~WumpusKilled | ~WumpusAlive0 & WumpusBorn)
  123. expr2 = ~(WumpusAlive0 & WumpusBorn)
  124. expr3 = WumpusBorn
  125. return logic.conjoin([expr1, expr2, expr3])
  126.  
  127. def findModel(sentence):
  128. """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying
  129. model if one exists. Otherwise, returns False.
  130. """
  131. "*** YOUR CODE HERE ***"
  132. cnf = logic.to_cnf(sentence)
  133. return logic.pycoSAT(cnf)
  134.  
  135. def atLeastOne(literals) :
  136. """
  137. Given a list of logic.Expr literals (i.e. in the form A or ~A), return a single
  138. logic.Expr instance in CNF (conjunctive normal form) that represents the logic
  139. that at least one of the literals in the list is true.
  140. >>> A = logic.PropSymbolExpr('A');
  141. >>> B = logic.PropSymbolExpr('B');
  142. >>> symbols = [A, B]
  143. >>> atleast1 = atLeastOne(symbols)
  144. >>> model1 = {A:False, B:False}
  145. >>> print logic.pl_true(atleast1,model1)
  146. False
  147. >>> model2 = {A:False, B:True}
  148. >>> print logic.pl_true(atleast1,model2)
  149. True
  150. >>> model3 = {A:True, B:True}
  151. >>> print logic.pl_true(atleast1,model2)
  152. True
  153. """
  154. "*** YOUR CODE HERE ***"
  155. expr = -1
  156. for literal in literals:
  157. if(expr == -1):
  158. expr = literal
  159. else:
  160. expr = expr | literal
  161. return expr
  162.  
  163.  
  164. def atMostOne(literals) :
  165. """
  166. Given a list of logic.Expr literals, return a single logic.Expr instance in
  167. CNF (conjunctive normal form) that represents the logic that at most one of
  168. the expressions in the list is true.
  169. """
  170. "*** YOUR CODE HERE ***"
  171. expr = []
  172. for i in xrange(len(literals)):
  173. for j in xrange(len(literals)):
  174. if(i != j):
  175. expr += [~literals[i] | ~literals[j]]
  176. return logic.conjoin(expr)
  177.  
  178.  
  179. def exactlyOne(literals) :
  180. """
  181. Given a list of logic.Expr literals, return a single logic.Expr instance in
  182. CNF (conjunctive normal form)that represents the logic that exactly one of
  183. the expressions in the list is true.
  184. """
  185. "*** YOUR CODE HERE ***"
  186. expr = []
  187. for i in xrange(len(literals)):
  188. for j in xrange(len(literals)):
  189. if(i != j):
  190. expr += [~literals[i] | ~literals[j]]
  191. return logic.conjoin(expr+[logic.disjoin(literals)])
  192.  
  193.  
  194. def extractActionSequence(model, actions):
  195. """
  196. Convert a model in to an ordered list of actions.
  197. model: Propositional logic model stored as a dictionary with keys being
  198. the symbol strings and values being Boolean: True or False
  199. Example:
  200. >>> model = {"North[3]":True, "P[3,4,1]":True, "P[3,3,1]":False, "West[1]":True, "GhostScary":True, "West[3]":False, "South[2]":True, "East[1]":False}
  201. >>> actions = ['North', 'South', 'East', 'West']
  202. >>> plan = extractActionSequence(model, actions)
  203. >>> print plan
  204. ['West', 'South', 'North']
  205. """
  206. "*** YOUR CODE HERE ***"
  207. if not model:
  208. return []
  209. ret = []
  210. i = 0
  211. while True:
  212. flag = False
  213. for action in actions:
  214. symbol = logic.PropSymbolExpr(action, i)
  215. if symbol in model and model[symbol]:
  216. ret += [action]
  217. flag = True
  218. if not flag:
  219. break
  220. i+=1
  221. print ret
  222. return ret
  223.  
  224.  
  225. def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
  226. """
  227. Successor state axiom for state (x,y,t) (from t-1), given the board (as a
  228. grid representing the wall locations).
  229. Current <==> (previous position at time t-1) & (took action to move to x, y)
  230. """
  231. "*** YOUR CODE HERE ***"
  232. expr = []
  233. if(not walls_grid[x][y-1]):
  234. expr += [logic.PropSymbolExpr(pacman_str, x, y-1, t-1) & logic.PropSymbolExpr('North', t-1)]
  235. if(not walls_grid[x][y+1]):
  236. expr += [logic.PropSymbolExpr(pacman_str, x, y+1, t-1) & logic.PropSymbolExpr('South', t-1)]
  237. if(not walls_grid[x-1][y]):
  238. expr += [logic.PropSymbolExpr(pacman_str, x-1, y, t-1) & logic.PropSymbolExpr('East', t-1)]
  239. if(not walls_grid[x+1][y]):
  240. expr += [logic.PropSymbolExpr(pacman_str, x+1, y, t-1) & logic.PropSymbolExpr('West', t-1)]
  241. return logic.PropSymbolExpr(pacman_str, x, y, t) % logic.disjoin(expr) # Replace this with your expression
  242.  
  243.  
  244. def positionLogicPlan(problem):
  245. """
  246. Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
  247. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
  248. Note that STOP is not an available action.
  249. """
  250. walls = problem.walls
  251. width, height = problem.getWidth(), problem.getHeight()
  252. goalState = problem.getGoalState()
  253. startState = problem.getStartState()
  254. expr1 = [logic.PropSymbolExpr(pacman_str, startState[0], startState[1], 0)]
  255. expr2 = []
  256. finalState = [logic.PropSymbolExpr(pacman_str, goalState[0], goalState[1], 0)]
  257. for i in xrange(1, width+1):
  258. for j in xrange(1, height+1):
  259. if(i, j) != (startState):
  260. expr1 += [~logic.PropSymbolExpr(pacman_str, i, j, 0)]
  261. for m in xrange(0, 51):
  262. for i in xrange(1, width+1):
  263. for j in xrange(1, height+1):
  264. if m > 0:
  265. if not walls[i][j]:
  266. expr1 += [pacmanSuccessorStateAxioms(i, j, m, walls)]
  267. if m > 0:
  268. expr3 = []
  269. expr3 += [logic.PropSymbolExpr('North', m-1)]
  270. expr3 += [logic.PropSymbolExpr('South', m-1)]
  271. expr3 += [logic.PropSymbolExpr('West', m-1)]
  272. expr3 += [logic.PropSymbolExpr('East', m-1)]
  273. expr2 += [exactlyOne(expr3)]
  274. finalState += [logic.PropSymbolExpr(pacman_str, goalState[0], goalState[1], m)]
  275. aux = expr1 + expr2 + [logic.disjoin(finalState)]
  276. cnf = logic.to_cnf(logic.conjoin(aux))
  277. model = findModel(cnf)
  278. if(model != False):
  279. return extractActionSequence(model, ['West', 'South', 'North', 'East'])
  280. return False
  281.  
  282. def foodLogicPlan(problem):
  283. """
  284. Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman
  285. eat all of the food.
  286. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
  287. Note that STOP is not an available action.
  288. """
  289. walls = problem.walls
  290. width, height = problem.getWidth(), problem.getHeight()
  291. food = problem.startingGameState.getFood()
  292. startState = problem.getStartState()
  293. expr1 = [logic.PropSymbolExpr(pacman_str, startState[0][0], startState[0][1], 0)]
  294. expr2 = []
  295. for i in xrange(1, width+1):
  296. for j in xrange(1, height+1):
  297. if(i, j) != (startState[0]):
  298. expr1 += [~logic.PropSymbolExpr(pacman_str, i, j, 0)]
  299. for m in xrange(0, 51):
  300. for i in xrange(1, width+1):
  301. for j in xrange(1, height+1):
  302. if m > 0:
  303. if not walls[i][j]:
  304. expr1 += [pacmanSuccessorStateAxioms(i, j, m, walls)]
  305.  
  306. if m > 0:
  307. expr3 = []
  308. expr3 += [logic.PropSymbolExpr('North', m-1)]
  309. expr3 += [logic.PropSymbolExpr('South', m-1)]
  310. expr3 += [logic.PropSymbolExpr('West', m-1)]
  311. expr3 += [logic.PropSymbolExpr('East', m-1)]
  312. expr2 += [exactlyOne(expr3)]
  313.  
  314. finalState = []
  315. for i in xrange(1, width+1):
  316. for j in xrange(1, height+1):
  317. if food[i][j]:
  318. aux = []
  319. for k in xrange(0, m+1):
  320. aux += [logic.PropSymbolExpr(pacman_str, i, j, k)]
  321. finalState += [logic.disjoin(aux)]
  322. auxx = expr1 + expr2 + [logic.conjoin(finalState)]
  323. cnf = logic.to_cnf(logic.conjoin(auxx))
  324. model = findModel(cnf)
  325. if(model != False):
  326. return extractActionSequence(model, ['West', 'South', 'North', 'East'])
  327. return False
  328.  
  329. "*** YOUR CODE HERE ***"
  330. util.raiseNotDefined()
  331.  
  332. def ghostPositionSuccessorStateAxioms(x, y, t, ghost_num, walls_grid):
  333. """
  334. Successor state axiom for patrolling ghost state (x,y,t) (from t-1).
  335. Current <==> (causes to stay) | (causes of current)
  336. GE is going east, ~GE is going west
  337. """
  338. pos_str = ghost_pos_str+str(ghost_num)
  339. east_str = ghost_east_str+str(ghost_num)
  340. state = logic.PropSymbolExpr(pos_str, x, y, t)
  341. move = logic.PropSymbolExpr(east_str, t-1)
  342. condition = []
  343. if walls_grid[x-1][y] and walls_grid[x+1][y]:
  344. condition += [logic.PropSymbolExpr(pos_str, x, y, t-1)]
  345. else :
  346. if not walls_grid[x-1][y]:
  347. condition += [logic.PropSymbolExpr(pos_str, x-1, y, t-1) & move]
  348. if not walls_grid[x+1][y]:
  349. condition += [logic.PropSymbolExpr(pos_str, x+1, y, t-1) & ~move]
  350. axiom = state % logic.disjoin(condition)
  351. return axiom
  352.  
  353. def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions, blocked_east_positions):
  354. """
  355. Successor state axiom for patrolling ghost direction state (t) (from t-1).
  356. west or east walls.
  357. Current <==> (causes to stay) | (causes of current)
  358. """
  359. pos_str = ghost_pos_str+str(ghost_num)
  360. east_str = ghost_east_str+str(ghost_num)
  361. move = logic.PropSymbolExpr(east_str, t-1)
  362. moveT = logic.PropSymbolExpr(east_str, t)
  363. west_not_block = []
  364. condition = []
  365. for position in blocked_west_positions:
  366. west_not_block += [~logic.PropSymbolExpr(pos_str, position[0], position[1], t)]
  367. west_not_block = logic.conjoin(west_not_block)
  368. east_not_block = []
  369. for position in blocked_east_positions:
  370. east_not_block += [~logic.PropSymbolExpr(pos_str, position[0], position[1], t)]
  371. east_not_block = logic.conjoin(east_not_block)
  372. if t == 0:
  373. return east_not_block % moveT
  374. return moveT % ((move & east_not_block) | (~west_not_block & east_not_block) | (~west_not_block & ~east_not_block & ~move))
  375.  
  376.  
  377. def pacmanAliveSuccessorStateAxioms(x, y, t, num_ghosts):
  378. """
  379. Successor state axiom for patrolling ghost state (x,y,t) (from t-1).
  380. Current <==> (causes to stay) | (causes of current)
  381. """
  382.  
  383. aliveT = logic.PropSymbolExpr(pacman_alive_str, t)
  384. alive = logic.PropSymbolExpr(pacman_alive_str, t-1)
  385. ghost_strs = [ghost_pos_str+str(ghost_num) for ghost_num in xrange(num_ghosts)]
  386. cond = []
  387. for ghost in ghost_strs:
  388. cond += [logic.PropSymbolExpr(ghost, x, y, t)]
  389. cond += [logic.PropSymbolExpr(ghost, x, y, t-1)]
  390. cond = ~logic.disjoin(cond)
  391. cond = logic.PropSymbolExpr(pacman_str, x, y, t) >> cond
  392. if t == 0:
  393. return aliveT % cond
  394. return aliveT % (alive & cond)
  395.  
  396. def foodGhostLogicPlan(problem):
  397. """
  398. Given an instance of a FoodGhostPlanningProblem, return a list of actions that help Pacman
  399. eat all of the food and avoid patrolling ghosts.
  400. Ghosts only move east and west. They always start by moving East, unless they start next to
  401. and eastern wall.
  402. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
  403. Note that STOP is not an available action.
  404. """
  405. walls = problem.walls
  406. width, height = problem.getWidth(), problem.getHeight()
  407. food = problem.startingGameState.getFood()
  408. num_ghosts = len(problem.getGhostStartStates())
  409. blocked_west_positions = []
  410. blocked_east_positions = []
  411.  
  412. startState = problem.getStartState()
  413. expr1 = [logic.PropSymbolExpr(pacman_str, startState[0][0], startState[0][1], 0)]
  414. expr2 = []
  415. for state in xrange(len(problem.getGhostStartStates())):
  416. gs = ghost_pos_str+str(state)
  417. pos = problem.getGhostStartStates()[state].getPosition()
  418. expr1 += [logic.PropSymbolExpr(gs, pos[0], pos[1], 0)]
  419.  
  420. for i in xrange(1, width+1):
  421. for j in xrange(1, height+1):
  422. if walls[i-1][j]:
  423. blocked_west_positions += [(i, j)]
  424. if walls[i+1][j]:
  425. blocked_east_positions += [(i, j)]
  426.  
  427. for state in xrange(num_ghosts):
  428. if(i, j) != problem.getGhostStartStates()[state].getPosition():
  429. gs = ghost_pos_str+str(state)
  430. expr1 += [~logic.PropSymbolExpr(gs, i, j, 0)]
  431. if(i, j) != (startState[0]):
  432. expr1 += [~logic.PropSymbolExpr(pacman_str, i, j, 0)]
  433.  
  434. for m in xrange(0, 51):
  435. finalState = []
  436. for i in xrange(1, width+1):
  437. for j in xrange(1, height+1):
  438. if m > 0:
  439. if not walls[i][j]:
  440. for idx in xrange(0, num_ghosts):
  441. expr1 += [ghostPositionSuccessorStateAxioms(i, j, m, idx, walls)]
  442.  
  443. expr1 += [pacmanSuccessorStateAxioms(i, j, m, walls)]
  444. expr1 += [pacmanAliveSuccessorStateAxioms(i, j, m, num_ghosts)]
  445. if food[i][j]:
  446. aux = []
  447. for k in xrange(0, m+1):
  448. aux += [logic.PropSymbolExpr(pacman_str, i, j, k)]
  449. finalState += [logic.disjoin(aux)]
  450.  
  451. for idx in xrange(num_ghosts):
  452. expr1 += [ghostDirectionSuccessorStateAxioms(m, idx, blocked_west_positions, blocked_east_positions)]
  453.  
  454. expr1 += [logic.PropSymbolExpr(pacman_alive_str, m)]
  455.  
  456. if m > 0:
  457. expr3 = []
  458. expr3 += [logic.PropSymbolExpr('North', m-1)]
  459. expr3 += [logic.PropSymbolExpr('South', m-1)]
  460. expr3 += [logic.PropSymbolExpr('West', m-1)]
  461. expr3 += [logic.PropSymbolExpr('East', m-1)]
  462. expr2 += [exactlyOne(expr3)]
  463.  
  464. auxx = expr1 + expr2 + [logic.conjoin(finalState)]
  465. #cnf = logic.to_cnf(logic.conjoin(auxx))
  466. model = findModel(logic.conjoin(auxx))
  467. if(model != False):
  468. return extractActionSequence(model, ['West', 'South', 'North', 'East'])
  469. return False
  470.  
  471.  
  472. # Abbreviations
  473. plp = positionLogicPlan
  474. flp = foodLogicPlan
  475. fglp = foodGhostLogicPlan
  476.  
  477. # Some for the logic module uses pretty deep recursion on long expressions
  478. sys.setrecursionlimit(100000)
  479.  
Runtime error #stdin #stdout #stderr 0.04s 46240KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Traceback (most recent call last):
  File "<builtin>/app_main.py", line 75, in run_toplevel
  File "prog.py", line 20, in <module>
    import util
ImportError: No module named util