def pacmanAliveSuccessorStateAxioms(x, y, t, num_ghosts): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) """ ghost_strs = [ ghost_pos_str + str(ghost_num) for ghost_num in xrange(num_ghosts) ] "*** YOUR CODE HERE ***" no_ghost = [] for ghost in ghost_strs: ghost_position_before = ~logic.PropSymbolExpr(ghost, x, y, t - 1) no_ghost.append(ghost_position_before) ghost_position_now = ~logic.PropSymbolExpr(ghost, x, y, t) no_ghost.append(ghost_position_now) no_ghost_here = logic.conjoin(no_ghost) ghost_exists = ~(logic.conjoin(no_ghost)) pacman_alive_prev = logic.PropSymbolExpr(pacman_alive_str, t - 1) pacman_not_there = ~logic.PropSymbolExpr(pacman_str, x, y, t) return logic.PropSymbolExpr(pacman_alive_str, t) % (pacman_alive_prev & ( (no_ghost_here) | (ghost_exists & pacman_not_there)))
def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions, blocked_east_positions): """ Successor state axiom for patrolling ghost direction state (t) (from t-1). west or east walls. Current <==> (causes to stay) | (causes of current) """ pos_str = ghost_pos_str + str(ghost_num) east_str = ghost_east_str + str(ghost_num) "*** YOUR CODE HERE ***" west_action = ~(logic.PropSymbolExpr(east_str, t - 1)) east_action = logic.PropSymbolExpr(east_str, t - 1) west_list = [] east_list = [] for pos in blocked_east_positions: x, y = pos not_blocked_east = ~logic.PropSymbolExpr(pos_str, x, y, t) lst = logic.conjoin(east_action, not_blocked_east) east_list.append(lst) for pos in blocked_west_positions: x, y = pos blocked_west = logic.PropSymbolExpr(pos_str, x, y, t) lst = logic.conjoin(west_action, blocked_west) west_list.append(lst) east_list = logic.conjoin(east_list) west_list = logic.disjoin(west_list) return logic.PropSymbolExpr(east_str, t) % logic.disjoin( east_list, west_list)
def sentence2(): """Returns a logic.Expr instance that encodes that the following expressions are all true. C if and only if (B or D) A implies ((not B) and (not D)) (not (B and (not C))) implies A (not D) implies C """ "*** YOUR CODE HERE ***" A = logic.Expr('A') B = logic.Expr('B') C = logic.Expr('C') D = logic.Expr('D') notB = ~B notD = ~D notC = ~C B_or_D = logic.disjoin((B), (D)) notB_and_notD = logic.conjoin((notB), (notD)) C_iff_B_or_D = C % B_or_D A_implies_notB_and_notD = A >> notB_and_notD B_and_notC = logic.conjoin((B), (notC)) not_B_and_notC_implies_A = ~B_and_notC >> A notD_implies_C = notD >> C return logic.conjoin((C_iff_B_or_D), (A_implies_notB_and_notD), (not_B_and_notC_implies_A), (notD_implies_C))
def SLAMSensorAxioms(t, non_outer_wall_coords): all_percept_exprs = [] combo_var_def_exprs = [] for direction in DIRECTIONS: percept_exprs = [] dx, dy = DIR_TO_DXDY_MAP[direction] for x, y in non_outer_wall_coords: combo_var = PropSymbolExpr(pacman_wall_str, x, y, t, x + dx, y + dy) percept_exprs.append(combo_var) combo_var_def_exprs.append( combo_var % (PropSymbolExpr(pacman_str, x, y, t) & PropSymbolExpr(wall_str, x + dx, y + dy))) blocked_dir_clause = PropSymbolExpr(blocked_str_map[direction], t) all_percept_exprs.append(blocked_dir_clause % disjoin(percept_exprs)) percept_to_blocked_sent = [] for n in range(1, 4): wall_combos_size_n = itertools.combinations(blocked_str_map.values(), n) n_walls_blocked_sent = disjoin([ conjoin( [PropSymbolExpr(blocked_str, t) for blocked_str in wall_combo]) for wall_combo in wall_combos_size_n ]) # n_walls_blocked_sent is of form: (N & S) | (N & E) | ... percept_to_blocked_sent.append( PropSymbolExpr(geq_num_adj_wall_str_map[n], t) % n_walls_blocked_sent) return conjoin(all_percept_exprs + combo_var_def_exprs + percept_to_blocked_sent)
def mapping(problem, agent): ''' problem: a MappingProblem instance agent: a MappingLogicAgent instance ''' debug = False pac_x_0, pac_y_0 = problem.startState KB = [] all_coords = list( itertools.product(range(problem.getWidth() + 2), range(problem.getHeight() + 2))) non_outer_wall_coords = list( itertools.product(range(1, problem.getWidth() + 1), range(1, problem.getHeight() + 1))) # map describes what we know, for GUI rendering purposes. -1 is unknown, 0 is open, 1 is wall known_map = [[-1 for y in range(problem.getHeight() + 2)] for x in range(problem.getWidth() + 2)] known_map_by_timestep = [] # Pacman knows that the outer border of squares are all walls outer_wall_sent = [] for x, y in all_coords: if ((x == 0 or x == problem.getWidth() + 1) or (y == 0 or y == problem.getHeight() + 1)): known_map[x][y] = 1 outer_wall_sent.append(PropSymbolExpr(wall_str, x, y)) KB.append(conjoin(outer_wall_sent)) KB.append(PropSymbolExpr(pacman_str, pac_x_0, pac_y_0, 0)) for t in range(agent.num_timesteps): KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords)) KB.append(PropSymbolExpr(agent.actions[t], t)) KB.append(sensorAxioms(t, non_outer_wall_coords)) percept_rules = four_bit_percept_rules(t, agent.getPercepts()) KB.append(percept_rules) for xy in non_outer_wall_coords: wall_present = PropSymbolExpr(wall_str, xy[0], xy[1]) model1 = findModel(conjoin(conjoin(KB), wall_present)) model2 = findModel(conjoin(conjoin(KB), ~wall_present)) if model2 is False: known_map[xy[0]][xy[1]] = 1 KB.append(wall_present) if model1 is False: known_map[xy[0]][xy[1]] = 0 KB.append(~wall_present) if model1 and model2: known_map[xy[0]][xy[1]] = -1 known_map_by_timestep.append(copy.deepcopy(known_map)) agent.moveToNextState(agent.actions[t]) KB.append( allLegalSuccessorAxioms(t + 1, known_map_by_timestep[t], non_outer_wall_coords)) return known_map_by_timestep
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are ['North', 'East', 'South', 'West'] Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() walls_list = walls.asList() x0, y0 = problem.startState xg, yg = problem.goal # Get lists of possible locations (i.e. without walls) and possible actions all_coords = list(itertools.product(range(width + 2), range(height + 2))) non_wall_coords = [loc for loc in all_coords if loc not in walls_list] actions = ['North', 'South', 'East', 'West'] KB = [] "*** BEGIN YOUR CODE HERE ***" KB.append(PropSymbolExpr(pacman_str, x0, y0, 0)) for t in range(50): KB.append( exactlyOne([ PropSymbolExpr(pacman_str, x, y, t) for x, y in non_wall_coords ])) model = findModel( conjoin(conjoin(KB), PropSymbolExpr(pacman_str, xg, yg, t))) if (model != False): return extractActionSequence(model, actions) KB.append(exactlyOne([PropSymbolExpr(action, t) for action in actions])) KB.append(allLegalSuccessorAxioms(t + 1, walls, non_wall_coords)) "*** END YOUR CODE HERE ***"
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are ['North', 'East', 'South', 'West'] Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() walls_list = walls.asList() x0, y0 = problem.startState xg, yg = problem.goal # Get lists of possible locations (i.e. without walls) and possible actions all_coords = list(itertools.product(range(width + 2), range(height + 2))) non_wall_coords = [loc for loc in all_coords if loc not in walls_list] actions = ['North', 'South', 'East', 'West'] KB = [] pos_t0 = PropSymbolExpr(pacman_str, x0, y0, 0) KB.append(pos_t0) for t in range(50): nonwallpos = [ PropSymbolExpr(pacman_str, xy[0], xy[1], t) for xy in non_wall_coords ] KB.append(exactlyOne(nonwallpos)) goal_assertion = PropSymbolExpr(pacman_str, xg, yg, t) model = findModel(conjoin(conjoin(KB), goal_assertion)) if model: return extractActionSequence(model, actions) action_list = [PropSymbolExpr(action, t) for action in actions] KB.append(exactlyOne(action_list)) for xy in non_wall_coords: KB.append(pacmanSuccessorStateAxioms(xy[0], xy[1], t + 1, walls))
def pacmanSuccessorStateAxioms(x, y, t, walls_grid): """ Successor state axiom for state (x,y,t) (from t-1), given the board (as a grid representing the wall locations). Current <==> (previous position at time t-1) & (took action to move to x, y) """ curPosition = logic.PropSymbolExpr(pacman_str, x, y, t) neighbors = [] if not walls_grid[x + 1][y]: prevPosition = logic.PropSymbolExpr(pacman_str, x + 1, y, t - 1) action = logic.PropSymbolExpr('West', t - 1) neighbors.append(logic.conjoin(prevPosition, action)) if not walls_grid[x - 1][y]: prevPosition = logic.PropSymbolExpr(pacman_str, x - 1, y, t - 1) action = logic.PropSymbolExpr('East', t - 1) neighbors.append(logic.conjoin(prevPosition, action)) if not walls_grid[x][y + 1]: prevPosition = logic.PropSymbolExpr(pacman_str, x, y + 1, t - 1) action = logic.PropSymbolExpr('South', t - 1) neighbors.append(logic.conjoin(prevPosition, action)) if not walls_grid[x][y - 1]: prevPosition = logic.PropSymbolExpr(pacman_str, x, y - 1, t - 1) action = logic.PropSymbolExpr('North', t - 1) neighbors.append(logic.conjoin(prevPosition, action)) return curPosition % logic.disjoin(neighbors)
def pacphysics_axioms(t, all_coords, non_outer_wall_coords): """ Given: t: timestep all_coords: list of (x, y) coordinates of the entire problem non_outer_wall_coords: list of (x, y) coordinates of the entire problem, excluding the outer border (these are the actual squares pacman can possibly be in) Return a logic sentence containing all of the following: - for all (x, y) in all_coords: If a wall is at (x, y) --> Pacman is not at (x, y) - Pacman is at one of the non_outer_wall_coords. - Pacman is at exactly one of the squares at timestep t. - Pacman takes one of the four actions in DIRECTIONS - Pacman takes exactly one action at timestep t. """ pacphysics_sentences = [] "*** BEGIN YOUR CODE HERE ***" all_coords_elements = [] for i in all_coords: x = i[0] y = i[1] all_coords_elements.append(PropSymbolExpr(wall_str, x, y) >> ~PropSymbolExpr(pacman_str, x, y ,t)) first = conjoin(all_coords_elements) second = exactlyOne([PropSymbolExpr(pacman_str, i[0], i[1], t) for i in non_outer_wall_coords]) third = exactlyOne([PropSymbolExpr(action, t) for action in DIRECTIONS]) pacphysics_sentences.append(first) pacphysics_sentences.append(second) pacphysics_sentences.append(third) "*** END YOUR CODE HERE ***" return conjoin(pacphysics_sentences)
def pacphysics_axioms(t, all_coords, non_outer_wall_coords): """ Given: t: timestep all_coords: list of (x, y) coordinates of the entire problem non_outer_wall_coords: list of (x, y) coordinates of the entire problem, excluding the outer border (these are the actual squares pacman can possibly be in) Return a logic sentence containing all of the following: - for all (x, y) in all_coords: If a wall is at (x, y) --> Pacman is not at (x, y) - Pacman is at exactly one of the squares at timestep t. - Pacman takes exactly one action at timestep t. """ pacphysics_sentences = [] "*** BEGIN YOUR CODE HERE ***" for x, y in all_coords: s = PropSymbolExpr(wall_str, x, y) >> ~PropSymbolExpr(pacman_str, x, y, t) pacphysics_sentences.append(s) inp_wall = [] for x, y in non_outer_wall_coords: inp_wall.append(PropSymbolExpr(pacman_str, x, y, t)) pacphysics_sentences.append(exactlyOne(inp_wall)) inp_dir = [] for dir in DIRECTIONS: inp_dir.append(PropSymbolExpr(dir, t)) pacphysics_sentences.append(exactlyOne(inp_dir)) return conjoin(pacphysics_sentences) "*** END YOUR CODE HERE ***" return conjoin(pacphysics_sentences)
def ghostPositionSuccessorStateAxioms(x, y, t, ghost_num, walls_grid): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) GE is going east, ~GE is going west """ pos_str = ghost_pos_str + str(ghost_num) east_str = ghost_east_str + str(ghost_num) current = logic.PropSymbolExpr(pos_str, x, y, t) neighbors = [] if walls_grid[x - 1][y] == False: prev_position = logic.PropSymbolExpr(pos_str, x - 1, y, t - 1) action = logic.PropSymbolExpr(east_str, t - 1) state = logic.conjoin(prev_position, action) neighbors.append(state) if walls_grid[x + 1][y] == False: prev_position = logic.PropSymbolExpr(pos_str, x + 1, y, t - 1) action = ~logic.PropSymbolExpr(east_str, t - 1) state = logic.conjoin(prev_position, action) neighbors.append(state) prev_states = atLeastOne(neighbors) if str(prev_states) == "FALSE": final_axiom = current % logic.PropSymbolExpr(pos_str, x, y, t - 1) else: final_axiom = current % prev_states return final_axiom
def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions, blocked_east_positions): """ Successor state axiom for patrolling ghost direction state (t) (from t-1). west or east walls. Current <==> (causes to stay) | (causes of current) """ pos_str = ghost_pos_str + str(ghost_num) east_str = ghost_east_str + str(ghost_num) move = logic.PropSymbolExpr(east_str, t - 1) moveT = logic.PropSymbolExpr(east_str, t) west_not_block = [] condition = [] for position in blocked_west_positions: west_not_block += [ ~logic.PropSymbolExpr(pos_str, position[0], position[1], t) ] west_not_block = logic.conjoin(west_not_block) east_not_block = [] for position in blocked_east_positions: east_not_block += [ ~logic.PropSymbolExpr(pos_str, position[0], position[1], t) ] east_not_block = logic.conjoin(east_not_block) if t == 0: return east_not_block % moveT return moveT % ((move & east_not_block) | (~west_not_block & east_not_block) | (~west_not_block & ~east_not_block & ~move))
def sentence3(): """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0], created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr instance that encodes the following English sentences (in this order): The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was not killed at time 0 or it was not alive and time 0 and it was born at time 0. The Wumpus cannot both be alive at time 0 and be born at time 0. The Wumpus is born at time 0. """ "*** YOUR CODE HERE ***" #know the use of the PropSymbolExpr from logic.py Alive_1 = logic.PropSymbolExpr("WumpusAlive", 1) #print (Alive_1) Alive_0 = logic.PropSymbolExpr("WumpusAlive", 0) Born_0 = logic.PropSymbolExpr("WumpusBorn", 0) Killed_0 = logic.PropSymbolExpr("WumpusKilled", 0) One = Alive_1 % logic.disjoin(logic.conjoin(Alive_0, ~Killed_0), logic.conjoin(~Alive_0, Born_0)) Two = ~logic.conjoin(Alive_0, Born_0) Three = Born_0 return logic.conjoin(One, Two, Three) util.raiseNotDefined()
def ghostPositionSuccessorStateAxioms(x, y, t, ghost_num, walls_grid): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) GE is going east, ~GE is going west """ pos_str = ghost_pos_str + str(ghost_num) east_str = ghost_east_str + str(ghost_num) "*** YOUR CODE HERE ***" left = walls_grid[x - 1][y] right = walls_grid[x + 1][y] possible_locations = [] left_prev = logic.PropSymbolExpr(pos_str, x - 1, y, t - 1) right_prev = logic.PropSymbolExpr(pos_str, x + 1, y, t - 1) west_action = ~(logic.PropSymbolExpr(east_str, t - 1)) east_action = logic.PropSymbolExpr(east_str, t - 1) if left and right: return logic.PropSymbolExpr(pos_str, x, y, t) % logic.PropSymbolExpr( pos_str, x, y, t - 1) if not left: possible_locations.append(logic.conjoin(left_prev, east_action)) if not right: possible_locations.append(logic.conjoin(right_prev, west_action)) return logic.PropSymbolExpr(pos_str, x, y, t) % logic.disjoin(possible_locations)
def ghostPositionSuccessorStateAxioms(x, y, t, ghost_num, walls_grid): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) GE is going east, ~GE is going west """ pos_str = ghost_pos_str+str(ghost_num) east_str = ghost_east_str+str(ghost_num) pos = logic.PropSymbolExpr(pos_str, x, y, t) listAdj = [(x-1, y), (x+1, y)] lst = [] for l in listAdj: if not walls_grid[l[0]][l[1]]: if l == (x-1, y): e = logic.conjoin([logic.PropSymbolExpr(pos_str, x-1, y, t-1), logic.PropSymbolExpr(east_str, t-1)]) else: e = logic.conjoin([logic.PropSymbolExpr(pos_str, x+1, y, t-1), ~(logic.PropSymbolExpr(east_str, t-1))]) lst.append(e) if walls_grid[x-1][y] & walls_grid[x+1][y]: #if there are walls on both sides and ghost cannot move lst.append(logic.PropSymbolExpr(pos_str, x, y, t-1)) if (len(lst) == 0): return pos % pos r = logic.disjoin(lst) return pos % r
def ghostPositionSuccessorStateAxioms(x, y, t, ghost_num, walls_grid): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) GE is going east, ~GE is going west """ pos_str = ghost_pos_str+str(ghost_num) east_str = ghost_east_str+str(ghost_num) pos = logic.PropSymbolExpr(pos_str, x, y, t) listAdj = [(x-1, y), (x+1, y)] lst = [] for l in listAdj: if not walls_grid[l[0]][l[1]]: if l == (x-1, y): e = logic.conjoin([logic.PropSymbolExpr(pacman_str, x-1, y, t-1), logic.PropSymbolExpr(east_str, t-1)]) else: e = logic.conjoin([logic.PropSymbolExpr(pacman_str, x+1, y, t-1), ~(logic.PropSymbolExpr(east_str, t-1))]) lst.append(e) if (len(lst) == 0): return pos % pos r = logic.disjoin(lst) return pos % r "*** YOUR CODE HERE ***" return logic.Expr('A') # Replace this with your expression
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() MAX_TIME = 50 start_pos = problem.getStartState() goal_pos = problem.getGoalState() actions = ['North', 'South', 'East', 'West'] # pacman can only start at one position (with this and other constarin, there is no need to generate knowledge that pacman can not in two place at one time) start_one_list = [] for x in range(1, width + 1): for y in range(1, height + 1): if (x, y) != start_pos: start_one_list.append( ~logic.PropSymbolExpr(pacman_str, x, y, 0)) start_one = logic.conjoin(start_one_list) #pacman start state start_state = logic.PropSymbolExpr(pacman_str, start_pos[0], start_pos[1], 0) #pacman is in start_pos and not in any other position start = logic.conjoin(start_state, start_one) one_action_list = [] transition_list = [] #update knowledge base through time for t in range(1, MAX_TIME + 1): goal = logic.PropSymbolExpr(pacman_str, goal_pos[0], goal_pos[1], t) #can only take one action to get to current state temp = [] for action in actions: one = logic.PropSymbolExpr(action, t - 1) temp.append(one) step_one_action = exactlyOne(temp) one_action_list.append(step_one_action) for x in range(1, width + 1): for y in range(1, height + 1): if not walls[x][y]: transition_list.append( pacmanSuccessorStateAxioms(x, y, t, walls)) one_action = logic.conjoin(one_action_list) one_action_list = [one_action] transition = logic.conjoin(transition_list) transition_list = [transition] result = findModel(logic.conjoin(start, one_action, transition, goal)) if result is not False: return extractActionSequence(result, actions)
def mapping(problem, agent): ''' problem: a MappingProblem instance agent: a MappingLogicAgent instance ''' debug = False pac_x_0, pac_y_0 = problem.startState KB = [] all_coords = list(itertools.product(range(problem.getWidth()+2), range(problem.getHeight()+2))) non_outer_wall_coords = list(itertools.product(range(1, problem.getWidth()+1), range(1, problem.getHeight()+1))) #map describes what we know, for GUI rendering purposes. -1 is unknown, 0 is open, 1 is wall known_map = [[-1 for y in range(problem.getHeight()+2)] for x in range(problem.getWidth()+2)] known_map_by_timestep = [] # Pacman knows that the outer border of squares are all walls outer_wall_sent = [] for x, y in all_coords: if ((x == 0 or x == problem.getWidth() + 1) or (y == 0 or y == problem.getHeight() + 1)): known_map[x][y] = 1 outer_wall_sent.append(PropSymbolExpr(wall_str, x, y)) KB.append(conjoin(outer_wall_sent)) "*** BEGIN YOUR CODE HERE ***" KB.append(PropSymbolExpr(pacman_str, pac_x_0, pac_y_0, 0)) for t in range(agent.num_timesteps): # Add pacphysics, action, sensor, and percept information to KB KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords)) KB.append(PropSymbolExpr(agent.actions[t], t)) KB.append(sensorAxioms(t, non_outer_wall_coords)) KB.append(four_bit_percept_rules(t, agent.getPercepts())) # Find provable wall locations with updated KB for i in non_outer_wall_coords: x, y = i # find a model such that (x,y) is wall model1 = findModel(conjoin(KB) & PropSymbolExpr(wall_str, x, y)) # find a model such that (x,y) is not wall model2 = findModel(conjoin(KB) & ~PropSymbolExpr(wall_str, x, y)) if not model2: KB.append(PropSymbolExpr(wall_str, x, y)) known_map[x][y] = 1 elif not model1: KB.append(~PropSymbolExpr(wall_str, x, y)) known_map[x][y] = 0 map_copy = copy.deepcopy(known_map) known_map_by_timestep.append(map_copy) agent.moveToNextState(agent.actions[t]) KB.append(allLegalSuccessorAxioms(t + 1, known_map, non_outer_wall_coords)) "*** END YOUR CODE HERE ***" return known_map_by_timestep
def foodLogicPlan(problem): """ Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman eat all of the food. Available actions are ['North', 'East', 'South', 'West'] Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() walls_list = walls.asList() (x0, y0), food = problem.start food = food.asList() # Get lists of possible locations (i.e. without walls) and possible actions all_coords = list(itertools.product(range(width + 2), range(height + 2))) #locations = list(filter(lambda loc : loc not in walls_list, all_coords)) non_wall_coords = [loc for loc in all_coords if loc not in walls_list] actions = ['North', 'South', 'East', 'West'] KB = [] "*** BEGIN YOUR CODE HERE ***" for x, y in food: KB.append(PropSymbolExpr(food_str, x, y, 0)) KB.append(PropSymbolExpr(pacman_str, x0, y0, 0)) for t in range(50): inp_wall = [] for x, y in non_wall_coords: inp_wall.append(PropSymbolExpr(pacman_str, x, y, t)) KB.append(exactlyOne(inp_wall)) inp_food = [] for x, y in food: inp_food.append(~PropSymbolExpr(food_str, x, y, t)) food_goal = conjoin(inp_food) model = findModel(conjoin(KB) & food_goal) if model: return extractActionSequence(model, actions) inp_dir = [] for dir in actions: inp_dir.append(PropSymbolExpr(dir, t)) KB.append(exactlyOne(inp_dir)) for x, y in non_wall_coords: KB.append(pacmanSuccessorStateAxioms(x, y, t + 1, walls)) for x, y in food: expr = (PropSymbolExpr(pacman_str, x, y, t) & PropSymbolExpr(food_str, x, y, t)) expr2 = ~PropSymbolExpr(food_str, x, y, t + 1) KB.append(expr2 % expr | ~PropSymbolExpr(food_str, x, y, t)) "*** END YOUR CODE HERE ***"
def foodLogicPlan(problem): """ Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman eat all of the food. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" initialState = problem.getStartState() foodGrid = initialState[1] (x, y) = initialState[0] initial = [] initial.append(logic.PropSymbolExpr(pacman_str, x, y, 0)) foodLoc = [] foodLoac = [] for r in xrange(1,width+1): for c in xrange(1, height+1): if not walls[r][c] and ((r,c) != (x,y)): initial.append(~(logic.PropSymbolExpr(pacman_str, r,c,0))) if foodGrid[r][c]: foodLoc.append(logic.PropSymbolExpr(pacman_str,r,c,0)) foodLoac.append((r,c)) init = logic.conjoin(initial) lst = [] for t in range(1,51): for r in xrange(1,width+1): for c in xrange(1, height+1): if not walls[r][c]: lst.append(pacmanSuccessorStateAxioms(r, c, t, walls)) d = [] d.append(logic.PropSymbolExpr(game.Directions.NORTH,t-1)) d.append(logic.PropSymbolExpr(game.Directions.SOUTH,t-1)) d.append(logic.PropSymbolExpr(game.Directions.EAST,t-1)) d.append(logic.PropSymbolExpr(game.Directions.WEST,t-1)) for food in foodLoac: foodLoc[foodLoac.index(food)] = foodLoc[foodLoac.index(food)] | logic.PropSymbolExpr(pacman_str,food[0],food[1],t) goalState = logic.conjoin(foodLoc) lst.append(exactlyOne(d)) lisst = logic.conjoin(lst) result = lisst & init & goalState model = findModel(result) if model != False: seq = extractActionSequence(model, [game.Directions.NORTH, game.Directions.SOUTH,game.Directions.EAST, game.Directions.WEST]) return seq util.raiseNotDefined()
def localization(problem, agent): ''' problem: a LocalizationProblem instance agent: a LocalizationLogicAgent instance ''' debug = False walls_grid = problem.walls walls_list = walls_grid.asList() all_coords = list( itertools.product(range(problem.getWidth() + 2), range(problem.getHeight() + 2))) non_outer_wall_coords = list( itertools.product(range(1, problem.getWidth() + 1), range(1, problem.getHeight() + 1))) possible_locs_by_timestep = [] KB = [] "*** BEGIN YOUR CODE HERE ***" for x, y in all_coords: if (x, y) in walls_list: KB.append(PropSymbolExpr(wall_str, x, y)) else: KB.append(~PropSymbolExpr(wall_str, x, y)) for t in range(agent.num_timesteps): KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords)) KB.append(PropSymbolExpr(agent.actions[t], t)) KB.append(sensorAxioms(t, non_outer_wall_coords)) percepts = agent.getPercepts() KB.append(four_bit_percept_rules(t, percepts)) possible_locations_t = [] for x, y in non_outer_wall_coords: res1 = findModel( conjoin(KB) & ~PropSymbolExpr(pacman_str, x, y, t)) res2 = findModel(conjoin(KB) & PropSymbolExpr(pacman_str, x, y, t)) if not res1: KB.append(PropSymbolExpr(pacman_str, x, y, t)) elif not res2: KB.append(~PropSymbolExpr(pacman_str, x, y, t)) if res2: possible_locations_t.append((x, y)) possible_locs_by_timestep.append(possible_locations_t) agent.moveToNextState(agent.actions[t]) KB.append( allLegalSuccessorAxioms(t + 1, walls_grid, non_outer_wall_coords)) "*** END YOUR CODE HERE ***" print(possible_locs_by_timestep) return possible_locs_by_timestep
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() available_action = ['North', 'East', 'South', 'West'] # evacuate STOP "*** YOUR CODE HERE ***" # get start/goal loaction start = problem.getStartState() goal = problem.getGoalState() start_state = logic.PropSymbolExpr("P", start[0], start[1], 0) start_logic = [] for i in range(1, width+1): for j in range(1, height+1): start_logic.append(logic.PropSymbolExpr("P", i, j, 0)) start_logic = exactlyOne(start_logic) start_logic = logic.conjoin(start_logic, start_state) # note that we must assert any other position is not allowed, otherwise it will cause weird error t = 1 # initial time # note that time start from 1 but not 0 path = False while not path: # goal state goal_state = logic.PropSymbolExpr("P", goal[0], goal[1], t+1) # build succession logic successor = [] for k in range(1, t+2): # note here must be t+2 for i in range(1, width + 1): # skip the most-outside wall for j in range(1, height + 1): if not walls[i][j]: # if (x, y) is not a wall successor.append(pacmanSuccessorStateAxioms(i, j, k, walls)) successor = logic.conjoin(successor) action_taken = [] for i in range(0, t + 1):# last one is t all_action = [] for action in available_action: all_action += [logic.PropSymbolExpr(action, i)] # one step must take exactly one action action_taken.append(exactlyOne(all_action)) # each step must take action each_step_action = logic.conjoin(action_taken) # assemble model model = logic.conjoin(start_logic, goal_state, each_step_action, successor) path = findModel(model) # complicated init state & goal state & way to achieve goal & all possible action can be taken & all possible successors to any point t += 1 return extractActionSequence(path, available_action)
def pacphysics_axioms(t, all_coords, non_outer_wall_coords): """ Given: t: timestep all_coords: list of (x, y) coordinates of the entire problem non_outer_wall_coords: list of (x, y) coordinates of the entire problem, excluding the outer border (these are the actual squares pacman can possibly be in) Return a logic sentence containing all of the following: - for all (x, y) in all_coords: If a wall is at (x, y) --> Pacman is not at (x, y) - Pacman is at one of the non_outer_wall_coords. - Pacman is at exactly one of the squares at timestep t. - Pacman takes one of the four actions in DIRECTIONS - Pacman takes exactly one action at timestep t. """ pacphysics_sentences = [] "*** BEGIN YOUR CODE HERE ***" #Pacman at x,y at time t: #PropSymbolExpr(pacman_str, x, y, t) #Whether or not a wall is at x,y #PropSymbolExpr(wall_str, x, y) #Whether or not pacman takes action a at time t #PropSymbolExpr(action, t) #if a wall at x,y >> pacman not at x,y implications = [] for (x, y) in all_coords: implications.append( PropSymbolExpr(wall_str, x, y) >> ~PropSymbolExpr(pacman_str, x, y, t)) pacphysics_sentences.append(conjoin(implications)) #pacman is at exactly one of the non_outer_wall_coords props = [] for (x, y) in non_outer_wall_coords: props.append(PropSymbolExpr(pacman_str, x, y, t)) is_somewhere = exactlyOne(props) pacphysics_sentences.append(is_somewhere) #Pacman takes exactly one of four directions one_direction = exactlyOne([ PropSymbolExpr('North', t), PropSymbolExpr('South', t), PropSymbolExpr('East', t), PropSymbolExpr('West', t) ]) pacphysics_sentences.append(one_direction) "*** END YOUR CODE HERE ***" return conjoin(pacphysics_sentences)
def foodLogicPlan(problem): """ Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman eat all of the food. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() food = problem.startingGameState.getFood() startState = problem.getStartState() expr1 = [ logic.PropSymbolExpr(pacman_str, startState[0][0], startState[0][1], 0) ] expr2 = [] for i in xrange(1, width + 1): for j in xrange(1, height + 1): if (i, j) != (startState[0]): expr1 += [~logic.PropSymbolExpr(pacman_str, i, j, 0)] for m in xrange(0, 51): for i in xrange(1, width + 1): for j in xrange(1, height + 1): if m > 0: if not walls[i][j]: expr1 += [pacmanSuccessorStateAxioms(i, j, m, walls)] if m > 0: expr3 = [] expr3 += [logic.PropSymbolExpr('North', m - 1)] expr3 += [logic.PropSymbolExpr('South', m - 1)] expr3 += [logic.PropSymbolExpr('West', m - 1)] expr3 += [logic.PropSymbolExpr('East', m - 1)] expr2 += [exactlyOne(expr3)] finalState = [] for i in xrange(1, width + 1): for j in xrange(1, height + 1): if food[i][j]: aux = [] for k in xrange(0, m + 1): aux += [logic.PropSymbolExpr(pacman_str, i, j, k)] finalState += [logic.disjoin(aux)] auxx = expr1 + expr2 + [logic.conjoin(finalState)] cnf = logic.to_cnf(logic.conjoin(auxx)) model = findModel(cnf) if (model != False): return extractActionSequence(model, ['West', 'South', 'North', 'East']) return False "*** YOUR CODE HERE ***" util.raiseNotDefined()
def pacmanSLAMSuccessorStateAxioms(x, y, t, walls_grid, var_str=pacman_str): """ Similar to `pacmanSuccessorStateAxioms` but accounts for illegal actions where the pacman might not move timestep to timestep. Available actions are ['North', 'East', 'South', 'West'] """ moved_tm1_possibilities = [] if not walls_grid[x][y + 1]: moved_tm1_possibilities.append( PropSymbolExpr(var_str, x, y + 1, t - 1) & PropSymbolExpr('South', t - 1)) if not walls_grid[x][y - 1]: moved_tm1_possibilities.append( PropSymbolExpr(var_str, x, y - 1, t - 1) & PropSymbolExpr('North', t - 1)) if not walls_grid[x + 1][y]: moved_tm1_possibilities.append( PropSymbolExpr(var_str, x + 1, y, t - 1) & PropSymbolExpr('West', t - 1)) if not walls_grid[x - 1][y]: moved_tm1_possibilities.append( PropSymbolExpr(var_str, x - 1, y, t - 1) & PropSymbolExpr('East', t - 1)) if not moved_tm1_possibilities: return None moved_tm1_sent = conjoin([ ~PropSymbolExpr(var_str, x, y, t - 1), ~PropSymbolExpr(wall_str, x, y), disjoin(moved_tm1_possibilities) ]) unmoved_tm1_possibilities_aux_exprs = [] # merged variables aux_expr_defs = [] for direction in DIRECTIONS: dx, dy = DIR_TO_DXDY_MAP[direction] wall_dir_clause = PropSymbolExpr( wall_str, x + dx, y + dy) & PropSymbolExpr(direction, t - 1) wall_dir_combined_literal = PropSymbolExpr(wall_str + direction, x + dx, y + dy, t - 1) unmoved_tm1_possibilities_aux_exprs.append(wall_dir_combined_literal) aux_expr_defs.append(wall_dir_combined_literal % wall_dir_clause) unmoved_tm1_sent = conjoin([ PropSymbolExpr(var_str, x, y, t - 1), disjoin(unmoved_tm1_possibilities_aux_exprs) ]) return conjoin([ PropSymbolExpr(var_str, x, y, t) % disjoin([moved_tm1_sent, unmoved_tm1_sent]) ] + aux_expr_defs)
def sentence2(): """Returns a Expr instance that encodes that the following expressions are all true. C if and only if (B or D) A implies ((not B) and (not D)) (not (B and (not C))) implies A (not D) implies C """ s1 = C % disjoin(B, D) s2 = A >> conjoin(~B, ~D) s3 = ~conjoin(B, ~C) >> A s4 = ~D >> C return conjoin(s1, s2, s3, s4)
def localization(problem, agent): ''' problem: a LocalizationProblem instance agent: a LocalizationLogicAgent instance ''' debug = False walls_grid = problem.walls walls_list = walls_grid.asList() all_coords = list( itertools.product(range(problem.getWidth() + 2), range(problem.getHeight() + 2))) non_outer_wall_coords = list( itertools.product(range(1, problem.getWidth() + 1), range(1, problem.getHeight() + 1))) possible_locs_by_timestep = [] KB = [] for xy in all_coords: if xy in walls_list: KB.append(PropSymbolExpr(wall_str, xy[0], xy[1])) else: KB.append(~PropSymbolExpr(wall_str, xy[0], xy[1])) for t in range(agent.num_timesteps): KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords)) KB.append(PropSymbolExpr(agent.actions[t], t)) KB.append(sensorAxioms(t, non_outer_wall_coords)) percept_rules = four_bit_percept_rules(t, agent.getPercepts()) KB.append(percept_rules) possible_locations_t = [] for xy in non_outer_wall_coords: pacman_present = PropSymbolExpr(pacman_str, xy[0], xy[1], t) model1 = findModel(conjoin(conjoin(KB), pacman_present)) model2 = findModel(conjoin(conjoin(KB), ~pacman_present)) if model2 is False: possible_locations_t.append(xy) KB.append(pacman_present) if model1 is False: KB.append(~pacman_present) if model1 and model2: possible_locations_t.append(xy) possible_locs_by_timestep.append(possible_locations_t) agent.moveToNextState(agent.actions[t]) KB.append( allLegalSuccessorAxioms(t + 1, walls_grid, non_outer_wall_coords)) return possible_locs_by_timestep
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" actions = ['North', 'South', 'East', 'West'] startState = [] initialX, initialY = problem.getStartState() initial = logic.PropSymbolExpr(pacman_str, initialX, initialY, 0) goalX, goalY = problem.getGoalState() goalSuccessors = [] goalActions = [] steps = 50 for x in range(1, width + 1): for y in range(1, height + 1): if not (x, y) in walls.asList(): startState.append(logic.PropSymbolExpr(pacman_str, x, y, 0)) for i in range(1, steps): successors = [] start = exactlyOne(startState) # needed for goal goal = logic.PropSymbolExpr(pacman_str, goalX, goalY, i) for x in range(1, width + 1): for y in range(1, height + 1): if (x, y) not in walls.asList(): successors.append( pacmanSuccessorStateAxioms(x, y, i, walls)) successor = logic.conjoin(successors) action = [] for a in actions: action.append(logic.PropSymbolExpr(a, i - 1)) goalActions.append(exactlyOne(action)) goalSuccessors.append(successor) # print("start: ", start) # print("initial: ", initial) # print("goal: ", goal) # print("goalActions: ", goalActions) # print("goalSuccessors: ", goalSuccessors) isGoal = findModel( logic.conjoin([ start, initial, goal, logic.conjoin(goalSuccessors), logic.conjoin(goalActions) ])) if isGoal: return extractActionSequence(isGoal, actions)
def check_location_satisfiability(x1_y1, x0_y0, action0, action1, problem): """ Given: - x1_y1 = (x1, y1), a potential location at time t = 1 - x0_y0 = (x0, y0), Pacman's location at time t = 0 - action0 = one of the four items in DIRECTIONS, Pacman's action at time t = 0 - problem = An instance of logicAgents.LocMapProblem Return: - a model proving whether Pacman is at (x1, y1) at time t = 1 - a model proving whether Pacman is not at (x1, y1) at time t = 1 """ walls_grid = problem.walls walls_list = walls_grid.asList() all_coords = list( itertools.product(range(problem.getWidth() + 2), range(problem.getHeight() + 2))) non_outer_wall_coords = list( itertools.product(range(1, problem.getWidth() + 1), range(1, problem.getHeight() + 1))) KB = [] x0, y0 = x0_y0 x1, y1 = x1_y1 # We know which coords are walls: map_sent = [PropSymbolExpr(wall_str, x, y) for x, y in walls_list] KB.append(conjoin(map_sent)) pos_t0 = PropSymbolExpr(pacman_str, x0, y0, 0) axioms_t0 = pacphysics_axioms(0, all_coords, non_outer_wall_coords) action_t0 = PropSymbolExpr(action0, 0) legal_axioms_t0 = allLegalSuccessorAxioms(1, walls_grid, non_outer_wall_coords) axioms_t1 = pacphysics_axioms(1, all_coords, non_outer_wall_coords) action_t1 = PropSymbolExpr(action1, 1) KB.append(pos_t0) KB.append(axioms_t0) KB.append(action_t0) KB.append(legal_axioms_t0) KB.append(axioms_t1) KB.append(action_t1) model1 = findModel( conjoin(conjoin(KB), PropSymbolExpr(pacman_str, x1, y1, 1))) model2 = findModel( conjoin(conjoin(KB), ~PropSymbolExpr(pacman_str, x1, y1, 1))) return model2, model1
def localization(problem, agent): ''' problem: a LocalizationProblem instance agent: a LocalizationLogicAgent instance ''' debug = False walls_grid = problem.walls walls_list = walls_grid.asList() all_coords = list(itertools.product(range(problem.getWidth()+2), range(problem.getHeight()+2))) non_outer_wall_coords = list(itertools.product(range(1, problem.getWidth()+1), range(1, problem.getHeight()+1))) possible_locs_by_timestep = [] KB = [] "*** BEGIN YOUR CODE HERE ***" for i in all_coords: if i in walls_list: KB.append(PropSymbolExpr(wall_str, i[0], i[1])) else: KB.append(~PropSymbolExpr(wall_str, i[0], i[1])) for t in range(agent.num_timesteps): # Add pacphysics, action, sensor, and percept information to KB KB.append(pacphysics_axioms(t, all_coords, non_outer_wall_coords)) KB.append(PropSymbolExpr(agent.actions[t], t)) KB.append(sensorAxioms(t, non_outer_wall_coords)) KB.append(four_bit_percept_rules(t, agent.getPercepts())) #Find possible pacman locations with updated KB possible_locations_t = [] for i in non_outer_wall_coords: model1 = findModel(conjoin(KB) & PropSymbolExpr(pacman_str, i[0], i[1], t)) model2 = findModel(conjoin(KB) & ~PropSymbolExpr(pacman_str, i[0], i[1], t)) if model1: possible_locations_t.append(i) elif not model2: KB.append(~PropSymbolExpr(pacman_str, i[0], i[1], t)) elif not model1: KB.append(~PropSymbolExpr(pacman_str, i[0], i[1], t)) possible_locs_by_timestep.append(possible_locations_t) agent.moveToNextState(agent.actions[t]) KB.append(allLegalSuccessorAxioms(t + 1, walls_grid, non_outer_wall_coords)) return possible_locs_by_timestep #print(KB) "*** END YOUR CODE HERE ***" return possible_locs_by_timestep
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls actions = ['North', 'South', 'East', 'West'] x, y = problem.startState t = 0 final_expression = p_0 = logic.PropSymbolExpr(pacman_str, problem.startState[0], problem.startState[1], 0) initial_state = ([], [p_0], x, y, t) states = [initial_state] visited = [] while len(states) > 0: state = states.pop(0) sentence, path, x, y, t = state[0], state[1], state[2], state[3], state[4] if not findModel(logic.conjoin(sentence + path)): continue if state != initial_state and (x, y) == problem.goal and findModel(logic.conjoin(sentence + path)): final_expression = logic.conjoin(sentence + path) break else: if (x, y) not in visited and not walls[x][y]: visited.append((x, y)) if (x - 1, y) not in visited and not walls[x - 1][y]: tmp = logic.PropSymbolExpr(pacman_str, x - 1, y, t + 1) % ( logic.PropSymbolExpr('West', t) & logic.PropSymbolExpr(pacman_str, x, y, t)) states.append( ([tmp] + sentence, [logic.PropSymbolExpr(pacman_str, x - 1, y, t + 1)] + path, x - 1, y, t + 1)) if (x + 1, y) not in visited and not walls[x + 1][y]: tmp = logic.PropSymbolExpr(pacman_str, x + 1, y, t + 1) % ( logic.PropSymbolExpr('East', t) & logic.PropSymbolExpr(pacman_str, x, y, t)) states.append( ([tmp] + sentence, [logic.PropSymbolExpr(pacman_str, x + 1, y, t + 1)] + path, x + 1, y, t + 1)) if (x, y - 1) not in visited and not walls[x][y - 1]: tmp = logic.PropSymbolExpr(pacman_str, x, y - 1, t + 1) % ( logic.PropSymbolExpr('South', t) & logic.PropSymbolExpr(pacman_str, x, y, t)) states.append( ([tmp] + sentence, [logic.PropSymbolExpr(pacman_str, x, y - 1, t + 1)] + path, x, y - 1, t + 1)) if (x, y + 1) not in visited and not walls[x][y + 1]: tmp = logic.PropSymbolExpr(pacman_str, x, y + 1, t + 1) % ( logic.PropSymbolExpr('North', t) & logic.PropSymbolExpr(pacman_str, x, y, t)) states.append( ([tmp] + sentence, [logic.PropSymbolExpr(pacman_str, x, y + 1, t + 1)] + path, x, y + 1, t + 1)) return extractActionSequence(findModel(final_expression), actions)
def foodLogicPlan(problem): """ Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman eat all of the food. Available actions are ['North', 'East', 'South', 'West'] Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() walls_list = walls.asList() (x0, y0), food = problem.start food = food.asList() # Get lists of possible locations (i.e. without walls) and possible actions all_coords = list(itertools.product(range(width + 2), range(height + 2))) #locations = list(filter(lambda loc : loc not in walls_list, all_coords)) non_wall_coords = [loc for loc in all_coords if loc not in walls_list] actions = [ 'North', 'South', 'East', 'West' ] KB = [] "*** BEGIN YOUR CODE HERE ***" KB.append(PropSymbolExpr(pacman_str, x0, y0, 0)) for i in food: expression = PropSymbolExpr(food_str, i[0], i[1], 0) KB.append(expression) for t in range(50): goal_check = conjoin([~PropSymbolExpr(food_str, f[0], f[1], t) for f in food]) KB.append(exactlyOne([PropSymbolExpr(pacman_str, i[0], i[1], t) for i in non_wall_coords])) model = findModel(conjoin(KB) & goal_check) if model is not False: return extractActionSequence(model, actions) KB.append(exactlyOne([PropSymbolExpr(action, t) for action in actions])) for i in non_wall_coords: KB.append(pacmanSuccessorStateAxioms(i[0], i[1], t + 1, walls)) for f in food: KB.append(PropSymbolExpr(food_str, f[0], f[1], t + 1) % (~PropSymbolExpr(pacman_str, f[0], f[1], t) & PropSymbolExpr(food_str, f[0], f[1], t))) return None "*** END YOUR CODE HERE ***"
def pacmanAliveSuccessorStateAxioms(x, y, t, num_ghosts): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) """ ghost_strs = [ ghost_pos_str + str(ghost_num) for ghost_num in xrange(num_ghosts) ] current = logic.PropSymbolExpr(pacman_str, x, y, t) ghosts = ghost_strs[:] neighbors = [] k = [] l = [] while num_ghosts != 0: k += [ logic.PropSymbolExpr(ghost_strs[num_ghosts - 1], x, y, t - 1) | logic.PropSymbolExpr(ghost_strs[num_ghosts - 1], x, y, t) ] num_ghosts -= 1 m = ~logic.PropSymbolExpr(pacman_alive_str, t - 1) prev_states = logic.disjoin(k) prev_states = logic.conjoin(logic.PropSymbolExpr(pacman_str, x, y, t), prev_states) | m final_axiom = ~logic.PropSymbolExpr(pacman_alive_str, t) % prev_states return final_axiom
def exactlyOne(literals) : """ Given a list of logic.Expr literals, return a single logic.Expr instance in CNF (conjunctive normal form)that represents the logic that exactly one of the expressions in the list is true. """ "*** YOUR CODE HERE ***" return logic.conjoin(atLeastOne(literals), atMostOne(literals))
def sentence2(): """Returns a logic.Expr instance that encodes that the following expressions are all true. C if and only if (B or D) A implies ((not B) and (not D)) (not (B and (not C))) implies A (not D) implies C """ "*** YOUR CODE HERE ***" A, B, C, D = logic.Expr('A'), logic.Expr('B'), logic.Expr('C'), logic.Expr('D') C_iff = C % logic.disjoin([B,D]) A_imp = A >> logic.conjoin([~B, ~D]) nots = ~(logic.conjoin([B, ~C])) >> A notD = ~D >> C return logic.conjoin([C_iff, A_imp, nots, notD]) util.raiseNotDefined()
def exactlyOne(literals) : """ Given a list of logic.Expr literals, return a single logic.Expr instance in CNF (conjunctive normal form)that represents the logic that exactly one of the expressions in the list is true. """ if len(literals) == 1: return literals[0] return logic.conjoin([logic.disjoin(literals),atMostOne(literals)])
def pacmanAliveSuccessorStateAxioms(x, y, t, num_ghosts): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) """ ghost_strs = [ghost_pos_str+str(ghost_num) for ghost_num in xrange(num_ghosts)] alive = logic.PropSymbolExpr(pacman_alive_str, t) lst = [] e = [] for g in ghost_strs: e.append(~logic.PropSymbolExpr(g, x, y, t-1)) e.append(~logic.PropSymbolExpr(g, x, y, t)) q = logic.conjoin(e) lst.append(q) lst.append(~logic.PropSymbolExpr(pacman_str, x, y, t)) res = logic.disjoin(lst) if len(lst) == 0: return alive % alive return alive % (logic.conjoin([logic.PropSymbolExpr(pacman_alive_str, t-1), res]))
def sentence1(): """Returns a logic.Expr instance that encodes that the following expressions are all true. A or B (not A) if and only if ((not B) or C) (not A) or (not B) or C """ "*** YOUR CODE HERE ***" A, B, C = logic.Expr('A'), logic.Expr('B'), logic.Expr('C') line1, line2, line3 = A | B, ~A % (~B | C), logic.disjoin(~A, ~B, C) return logic.conjoin(line1, line2, line3)
def sentence2(): """Returns a logic.Expr instance that encodes that the following expressions are all true. C if and only if (B or D) A implies ((not B) and (not D)) (not (B and (not C))) implies A (not D) implies C """ "*** YOUR CODE HERE ***" A, B, C, D = logic.Expr('A'), logic.Expr('B'), logic.Expr('C'), logic.Expr('D') line1, line2, line3, line4 = C % (B | D), A >> (~B & ~D), ~(B & ~C) >> A, ~D >> C return logic.conjoin(line1, line2, line3, line4)
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" (x, y) = problem.getStartState(); (v, w) = problem.getGoalState(); initial = [] initial.append(logic.PropSymbolExpr(pacman_str, x, y, 0)) for r in xrange(1,width+1): for c in xrange(1, height+1): if not walls[r][c] and ((r,c) != (x,y)): initial.append(~(logic.PropSymbolExpr(pacman_str, r,c,0))) init = logic.conjoin(initial) lst = [] for t in range(1,51): for r in xrange(1,width+1): for c in xrange(1, height+1): if not walls[r][c]: lst.append(pacmanSuccessorStateAxioms(r, c, t, walls)) d = [] d.append(logic.PropSymbolExpr(game.Directions.NORTH,t-1)) d.append(logic.PropSymbolExpr(game.Directions.SOUTH,t-1)) d.append(logic.PropSymbolExpr(game.Directions.EAST,t-1)) d.append(logic.PropSymbolExpr(game.Directions.WEST,t-1)) lst.append(exactlyOne(d)) lisst = logic.conjoin(lst) result = lisst & logic.PropSymbolExpr(pacman_str, v, w, t) & init model = findModel(result) if model != False: seq = extractActionSequence(model, [game.Directions.NORTH, game.Directions.SOUTH,game.Directions.EAST, game.Directions.WEST]) return seq
def atMostOne(literals) : """ Given a list of logic.Expr literals, return a single logic.Expr instance in CNF (conjunctive normal form) that represents the logic that at most one of the expressions in the list is true. """ notliterals = [~literal for literal in literals] clauses = [] for i in range(0,len(literals)-1): for j in range(i+1, len(literals)): clause = [notliterals[i]] + [notliterals[j]] clauses.append(logic.disjoin(clause)) return logic.conjoin(clauses)
def sentence1(): """Returns a logic.Expr instance that encodes that the following expressions are all true. A or B (not A) if and only if ((not B) or C) (not A) or (not B) or C """ A = logic.Expr('A') B = logic.Expr('B') C = logic.Expr('C') expr1 = A | B expr2 = (~A) % ((~B)|C) expr3 = logic.disjoin([~A,~B,C]) return logic.conjoin([expr1,expr2,expr3])
def foodLogicPlan(problem): """ Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman eat all of the food. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" kb = [] actions = ['North', 'South', 'East', 'West'] start = problem.getStartState()[0] food = problem.getStartState()[1] for x in range(1, width + 1): for y in range(1, height + 1): if (x, y) == start: kb.append(logic.PropSymbolExpr(pacman_str, x, y, 0)) else: kb.append(~logic.PropSymbolExpr(pacman_str, x, y, 0)) for t in range(50): lst = [] for a in actions: lst.append(logic.PropSymbolExpr(a, t)) kb.append(exactlyOne(lst)) #print(kb) for x in range(1, width + 1): for y in range(1, height + 1): kb.append(pacmanSuccessorStateAxioms(x, y, t + 1, walls)) for x in range(1, width + 1): for y in range(1, height + 1): if food[x][y]: lst = [] for t in range(t + 1): lst.append(logic.PropSymbolExpr(pacman_str, x, y, t)) kb.append(atLeastOne(lst)) model = findModel(logic.conjoin(kb)) if model: return extractActionSequence(model, actions) for x in range(1, width + 1): for y in range(1, height + 1): if food[x][y]: kb.pop()
def foodLogicPlan(problem): """ Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman eat all of the food. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() start, foodGrid = problem.getStartState()[0],problem.getStartState()[1] start_axiom = [logic.PropSymbolExpr(pacman_str,start[0],start[1],0)] for x in range(1,width+1): for y in range(1,height+1): if not walls[x][y] and (x != start[0] or y != start[1]): start_axiom.append(~logic.PropSymbolExpr(pacman_str,x,y,0)) start_axiom.append(exactlyOne([logic.PropSymbolExpr('East',0), logic.PropSymbolExpr('West',0), logic.PropSymbolExpr('South',0), logic.PropSymbolExpr('North',0)])) for t in range(1,51): start_axiom.append(exactlyOne([logic.PropSymbolExpr('East',t), logic.PropSymbolExpr('West',t), logic.PropSymbolExpr('South',t), logic.PropSymbolExpr('North',t)])) position_t = [] move_t = [] for x in range(1,width+1): for y in range(1,height+1): if not walls[x][y]: move_t.append(pacmanSuccessorStateAxioms(x,y,t,walls)) start_axiom += move_t pops = 0 for x in range(1,width+1): for y in range(1,height+1): visit = [] if foodGrid[x][y]: for i in range(1,t+1): visit.append(logic.PropSymbolExpr(pacman_str,x,y,i)) start_axiom.append(atLeastOne(visit)) pops += 1 model = logic.pycoSAT(logic.conjoin(start_axiom)) if model: directions = [game.Directions.NORTH,game.Directions.SOUTH,game.Directions.EAST,game.Directions.WEST] actions = extractActionSequence(model, directions) return actions for i in range(0,pops): start_axiom.pop()
def atMostOne(literals) : """ Given a list of logic.Expr literals, return a single logic.Expr instance in CNF (conjunctive normal form) that represents the logic that at most one of the expressions in the list is true. """ "*** YOUR CODE HERE ***" lst = [] for i in range(len(literals)): for j in range(len(literals)): if i != j: l1, l2 = ~literals[i] | ~literals[j], ~literals[j] | ~literals[i] if l1 not in lst and l2 not in lst: lst.append(l1) return logic.conjoin(lst)
def atMostOne(literals) : """ Given a list of logic.Expr literals, return a single logic.Expr instance in CNF (conjunctive normal form) that represents the logic that at most one of the expressions in the list is true. """ "*** YOUR CODE HERE ***" allComp = [] for l in literals: for i in literals[literals.index(l)+1:]: allComp.append(~l | ~i) return logic.conjoin(allComp) util.raiseNotDefined()
def sentence3(): """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0], created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr instance that encodes the following English sentences (in this order): The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was not killed at time 0 or it was not alive and time 0 and it was born at time 0. The Wumpus cannot both be alive at time 0 and be born at time 0. The Wumpus is born at time 0. """ "*** YOUR CODE HERE ***" line1 = logic.PropSymbolExpr("WumpusAlive", 1) % ((logic.PropSymbolExpr("WumpusAlive", 0) & ~logic.PropSymbolExpr("WumpusKilled", 0)) | (~logic.PropSymbolExpr("WumpusAlive", 0) & logic.PropSymbolExpr("WumpusBorn", 0))) line2 = ~(logic.PropSymbolExpr("WumpusAlive", 0) & logic.PropSymbolExpr("WumpusBorn", 0)) line3 = logic.PropSymbolExpr("WumpusBorn", 0) return logic.conjoin(line1, line2, line3)
def sentence2(): """Returns a logic.Expr instance that encodes that the following expressions are all true. C if and only if (B or D) A implies ((not B) and (not D)) (not (B and (not C))) implies A (not D) implies C """ A = logic.Expr('A') B = logic.Expr('B') C = logic.Expr('C') D = logic.Expr('D') expr1 = C % (B | D) expr2 = A >> ((~B)&(~D)) expr3 = (~(B&(~C))) >> A expr4 = (~D) >> C return logic.conjoin([expr1,expr2,expr3,expr4])
def sentence1(): """Returns a logic.Expr instance that encodes that the following expressions are all true. A or B (not A) if and only if ((not B) or C) (not A) or (not B) or C """ "*** YOUR CODE HERE ***" A = logic.Expr('A') B = logic.Expr('B') C = logic.Expr('C') a_or_b = A | B notA, notB = ~A, ~B notB_or_C = notB | C notA_iff = notA % notB_or_C notA_or_else = logic.disjoin([notA,notB,C]) return logic.conjoin([(a_or_b),(notA_iff),(notA_or_else)]) util.raiseNotDefined()
def pacmanAliveSuccessorStateAxioms(x, y, t, num_ghosts): """ Successor state axiom for patrolling ghost state (x,y,t) (from t-1). Current <==> (causes to stay) | (causes of current) """ ghost_strs = [ghost_pos_str+str(ghost_num) for ghost_num in xrange(num_ghosts)] "*** YOUR CODE HERE ***" lst1, lst2 = [], [] for g in ghost_strs: lst1.append(logic.PropSymbolExpr(g, x, y, t)) lst2.append(logic.PropSymbolExpr(g, x, y, t - 1)) if len(ghost_strs): causes = (logic.PropSymbolExpr(pacman_str, x, y, t) & logic.disjoin(lst2)) | logic.conjoin((logic.PropSymbolExpr(pacman_str, x, y, t), ~logic.disjoin(lst2), logic.disjoin(lst1))) else: return ~logic.PropSymbolExpr(pacman_alive_str, t) % ~logic.PropSymbolExpr(pacman_alive_str, t - 1) #print logic.PropSymbolExpr(pacman_alive_str, t) % logic.conjoin(logic.PropSymbolExpr(pacman_alive_str, t - 1), cause) return ~logic.PropSymbolExpr(pacman_alive_str, t) % ((logic.PropSymbolExpr(pacman_alive_str, t - 1) & causes) | ~logic.PropSymbolExpr(pacman_alive_str, t - 1))
def sentence3(): """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0], created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr instance that encodes the following English sentences (in this order): The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was not killed at time 0 or it was not alive and time 0 and it was born at time 0. The Wumpus cannot both be alive at time 0 and be born at time 0. The Wumpus is born at time 0. """ WumpusAlive0 = logic.PropSymbolExpr('WumpusAlive',0) WumpusAlive1 = logic.PropSymbolExpr('WumpusAlive',1) WumpusBorn0 = logic.PropSymbolExpr('WumpusBorn',0) WumpusKilled0 = logic.PropSymbolExpr('WumpusKilled',0) expr1 = WumpusAlive1 % ((WumpusAlive0 & ~WumpusKilled0) | (~WumpusAlive0 & WumpusBorn0)) expr2 = ~(WumpusAlive0 & WumpusBorn0) expr3 = WumpusBorn0 return logic.conjoin([expr1,expr2,expr3])
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" kb = [] actions = ['North', 'South', 'East', 'West'] start = problem.getStartState() goal = problem.getGoalState() for x in range(1, width + 1): for y in range(1, height + 1): if (x, y) == start: kb.append(logic.PropSymbolExpr(pacman_str, x, y, 0)) else: kb.append(~logic.PropSymbolExpr(pacman_str, x, y, 0)) for t in range(50): action = [] for a in actions: action.append(logic.PropSymbolExpr(a, t)) kb.append(exactlyOne(action)) #print(kb) for x in range(1, width + 1): for y in range(1, height + 1): kb.append(pacmanSuccessorStateAxioms(x, y, t + 1, walls)) kb.append(logic.PropSymbolExpr(pacman_str, goal[0], goal[1], t)) model = findModel(logic.conjoin(kb)) if model: return extractActionSequence(model, actions) kb.pop()
def positionLogicPlan(problem): """ Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() start = problem.getStartState() goal = problem.getGoalState() start_axiom = [logic.PropSymbolExpr(pacman_str,start[0],start[1],0)] for x in range(1,width+1): for y in range(1,height+1): if not walls[x][y] and (x != start[0] or y != start[1]): start_axiom.append(~logic.PropSymbolExpr(pacman_str,x,y,0)) start_axiom.append(exactlyOne([logic.PropSymbolExpr('East',0), logic.PropSymbolExpr('West',0), logic.PropSymbolExpr('South',0), logic.PropSymbolExpr('North',0)])) for t in range(1,51): start_axiom.append(exactlyOne([logic.PropSymbolExpr('East',t), logic.PropSymbolExpr('West',t), logic.PropSymbolExpr('South',t), logic.PropSymbolExpr('North',t)])) for x in range(1,width+1): for y in range(1,height+1): if not walls[x][y]: start_axiom.append(pacmanSuccessorStateAxioms(x,y,t,walls)) start_axiom.append(pacmanSuccessorStateAxioms(goal[0],goal[1],t+1,walls)) start_axiom.append(logic.PropSymbolExpr(pacman_str,goal[0],goal[1],t+1)) model = logic.pycoSAT(logic.conjoin(start_axiom)) if model: directions = [game.Directions.NORTH, game.Directions.SOUTH,game.Directions.EAST,game.Directions.WEST] actions = extractActionSequence(model, directions) return actions start_axiom.pop() start_axiom.pop()
def sentence3(): """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0], created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr instance that encodes the following English sentences (in this order): The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was not killed at time 0 or it was not alive and time 0 and it was born at time 0. The Wumpus cannot both be alive at time 0 and be born at time 0. The Wumpus is born at time 0. """ "*** YOUR CODE HERE ***" time_1_alive = logic.PropSymbolExpr('WumpusAlive', 1) time_0_alive = logic.PropSymbolExpr("WumpusAlive", 0) time_0_born = logic.PropSymbolExpr("WumpusBorn", 0) time_0_killed = logic.PropSymbolExpr("WumpusKilled", 0) alive_and_notkilled = time_0_alive & ~time_0_killed notalive_and_born = ~time_0_alive & time_0_born first_exp = time_1_alive % (alive_and_notkilled | notalive_and_born) second_exp = ~(time_0_alive & time_0_born) return logic.conjoin([first_exp, second_exp, time_0_born]) util.raiseNotDefined()
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostPlanningProblem, return a list of actions that help Pacman eat all of the food and avoid patrolling ghosts. Ghosts only move east and west. They always start by moving East, unless they start next to and eastern wall. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" kb = [] actions = ['North', 'South', 'East', 'West'] start = problem.getStartState()[0] food = problem.getStartState()[1] ghosts = problem.getGhostStartStates() num_ghosts = len(ghosts) blocked_west_positions, blocked_east_positions = [], [] ghosts_pos = [] # init KB for i in range(len(ghosts)): ghosts_pos.append(ghosts[i].getPosition()) for x in range(1, width + 1): for y in range(1, height + 1): if (x, y) == start: kb.append(logic.PropSymbolExpr(pacman_str, x, y, 0)) else: kb.append(~logic.PropSymbolExpr(pacman_str, x, y, 0)) for i in range(len(ghosts)): pos_str = ghost_pos_str + str(i) if (x, y) == ghosts_pos[i]: kb.append(logic.PropSymbolExpr(pos_str, x, y, 0)) else: kb.append(~logic.PropSymbolExpr(pos_str, x, y, 0)) if walls[x + 1][y]: blocked_east_positions.append((x, y)) if walls[x - 1][y]: blocked_west_positions.append((x, y)) for i in range(len(ghosts)): east_str = ghost_east_str + str(i) if ghosts_pos[i] not in blocked_east_positions: kb.append(logic.PropSymbolExpr(east_str, 0)) else: kb.append(~logic.PropSymbolExpr(east_str, 0)) kb.append(logic.PropSymbolExpr(pacman_alive_str, 0)) #print(kb) # loop each time for t in range(50): #print(t) #exactly one action each time lst = [] for a in actions: lst.append(logic.PropSymbolExpr(a, t)) kb.append(exactlyOne(lst)) # SSAs for x in range(1, width + 1): for y in range(1, height + 1): kb.append(logic.to_cnf(pacmanSuccessorStateAxioms(x, y, t + 1, walls))) kb.append(logic.to_cnf(pacmanAliveSuccessorStateAxioms(x, y, t + 1, num_ghosts))) for i in range(len(ghosts)): kb.append(logic.to_cnf(ghostPositionSuccessorStateAxioms(x, y, t + 1, i, walls))) for i in range(len(ghosts)): kb.append(logic.to_cnf(ghostDirectionSuccessorStateAxioms(t + 1, i, blocked_west_positions, blocked_east_positions))) # goal KB for x in range(1, width + 1): for y in range(1, height + 1): if food[x][y]: lst = [] for t in range(t + 1): lst.append(logic.PropSymbolExpr(pacman_str, x, y, t)) kb.append(atLeastOne(lst)) # whether satisfy the model model = logic.pycoSAT(logic.conjoin(kb)) if model: return extractActionSequence(model, actions) # pop goal KB for x in range(1, width + 1): for y in range(1, height + 1): if food[x][y]: kb.pop()
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostPlanningProblem, return a list of actions that help Pacman eat all of the food and avoid patrolling ghosts. Ghosts only move east and west. They always start by moving East, unless they start next to and eastern wall. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() not_walls = [] for x in range(1,width+1): for y in range(1,height+1): if not walls[x][y]: not_walls += [(x,y)] ghosts = problem.getGhostStartStates() start, foodGrid = problem.getStartState()[0],problem.getStartState()[1] start_axiom = [logic.PropSymbolExpr(pacman_str,start[0],start[1],0)] start_axiom.append(logic.PropSymbolExpr(pacman_alive_str,0)) blocked_west_positions = [] blocked_east_positions = [] ghost_num = 0 num_ghosts = len(ghosts) reachable = {} all_reachable = [] ghost_y = [] for ghost in ghosts: ghost_start = ghost.getPosition() x = ghost_start[0] + 1 y = ghost_start[0] - 1 ghost_y.append(ghost_start[1]) start_axiom.append(logic.PropSymbolExpr(ghost_pos_str+str(ghost_num),ghost_start[0],ghost_start[1],0)) if not walls[ghost_start[0]+1][ghost_start[1]]: start_axiom.append(logic.PropSymbolExpr(ghost_pos_str+str(ghost_num),ghost_start[0]+1,ghost_start[1],1)) start_axiom.append(logic.PropSymbolExpr(ghost_east_str+str(ghost_num),0)) elif not walls[ghost_start[0]-1][ghost_start[1]]: start_axiom.append(logic.PropSymbolExpr(ghost_pos_str+str(ghost_num),ghost_start[0]-1,ghost_start[1],1)) start_axiom.append(~logic.PropSymbolExpr(ghost_east_str+str(ghost_num),0)) else: start_axiom.append(logic.PropSymbolExpr(ghost_pos_str+str(ghost_num),ghost_start[0],ghost_start[1],1)) start_axiom.append(logic.PropSymbolExpr(ghost_east_str+str(ghost_num),0)) for space in not_walls: if (space[0] != ghost_start[0] or space[1] != ghost_start[1]): start_axiom.append(~logic.PropSymbolExpr(ghost_pos_str+str(ghost_num),space[0],space[1],0)) reachable[ghost_num] = [(ghost_start[0],ghost_start[1])] all_reachable.append((ghost_start[0],ghost_start[1])) while not walls[x][ghost_start[1]]: reachable[ghost_num].append((x,ghost_start[1])) all_reachable.append((x,ghost_start[1])) x += 1 while not walls[y][ghost_start[1]]: reachable[ghost_num].append((y,ghost_start[1])) all_reachable.append((y,ghost_start[1])) y -= 1 ghost_num += 1 for space in not_walls: if walls[space[0]-1][space[1]]: blocked_west_positions.append((space[0],space[1])) if walls[space[0]+1][space[1]]: blocked_east_positions.append((space[0],space[1])) if (space[0] != start[0] or space[1] != start[1]): start_axiom.append(~logic.PropSymbolExpr(pacman_str,space[0],space[1],0)) start_axiom.append(exactlyOne([logic.PropSymbolExpr('East',0), logic.PropSymbolExpr('West',0), logic.PropSymbolExpr('South',0), logic.PropSymbolExpr('North',0)])) for t in range(1,51): pops = 0 start_axiom.append(exactlyOne([logic.PropSymbolExpr('East',t), logic.PropSymbolExpr('West',t), logic.PropSymbolExpr('South',t), logic.PropSymbolExpr('North',t)])) position_t = [] for space in not_walls: start_axiom.append(pacmanSuccessorStateAxioms(space[0],space[1],t,walls)) if space in all_reachable: start_axiom.append(pacmanAliveSuccessorStateAxioms(space[0], space[1], t, num_ghosts)) for ghost_num in xrange(num_ghosts): if space in reachable[ghost_num]: start_axiom.append(ghostPositionSuccessorStateAxioms(space[0], space[1], t, ghost_num, walls)) start_axiom.append(ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions, blocked_east_positions)) else: start_axiom.append(~logic.PropSymbolExpr(ghost_pos_str+str(ghost_num),space[0],space[1],t)) for x in range(1,width+1): for y in range(1,height+1): visit = [] if foodGrid[x][y]: for i in range(1,t+1): visit.append(logic.PropSymbolExpr(pacman_str,x,y,i)) start_axiom.append(atLeastOne(visit)) pops += 1 model = logic.pycoSAT(logic.conjoin(start_axiom)) if model: directions = [game.Directions.NORTH,game.Directions.SOUTH,game.Directions.EAST,game.Directions.WEST] actions = extractActionSequence(model, directions) return actions for i in range(0,pops): start_axiom.pop()
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostPlanningProblem, return a list of actions that help Pacman eat all of the food and avoid patrolling ghosts. Ghosts only move east and west. They always start by moving East, unless they start next to and eastern wall. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ walls = problem.walls width, height = problem.getWidth(), problem.getHeight() "*** YOUR CODE HERE ***" initialState = problem.getStartState(); (x, y) = initialState[0] foodGrid = initialState[1] initial = [] num_ghosts = len(problem.getGhostStartStates()) initial.append(logic.PropSymbolExpr(pacman_str, x, y, 0) & logic.PropSymbolExpr(pacman_alive_str, 0)) gStart = [] for ghost_num in range(0, num_ghosts): gStart.append(logic.PropSymbolExpr(ghost_pos_str+str(ghost_num), problem.getGhostStartStates()[ghost_num].getPosition()[0], problem.getGhostStartStates()[ghost_num].getPosition()[1], 0)) foodLoc = [] foodLoac = [] blockedWest = [] blockedEast = [] for r in xrange(1, width+1): for c in xrange(1, height+1): if not walls[r][c]: if ((r,c) != (x,y)): initial.append(~(logic.PropSymbolExpr(pacman_str, r, c, 0))) for ghost_num in range(0, num_ghosts): if ((r, c) != (problem.getGhostStartStates()[ghost_num].getPosition()[0], problem.getGhostStartStates()[ghost_num].getPosition()[1])): a = ~(logic.PropSymbolExpr(ghost_pos_str+str(ghost_num), r, c, 0)) gStart.append(a) if not walls[r][c] and walls[r+1][c]: blockedEast.append((r, c)) if not walls[r][c] and walls[r-1][c]: blockedWest.append((r, c)) if foodGrid[r][c]: foodLoc.append(logic.PropSymbolExpr(pacman_str,r,c,0)) foodLoac.append((r,c)) for ghost_num in range(0, num_ghosts): startPos = (problem.getGhostStartStates()[ghost_num].getPosition()[0], problem.getGhostStartStates()[ghost_num].getPosition()[1]) if startPos in blockedEast: gStart.append(~logic.PropSymbolExpr(ghost_east_str+str(ghost_num), 0)) else: gStart.append(logic.PropSymbolExpr(ghost_east_str+str(ghost_num), 0)) init = logic.to_cnf(logic.conjoin(initial + gStart)) pacmanAliveList = [] ghostDirList = [] pacmanPositionList = [] ghostPositionList = [] lst = [] for t in range(1, 51): for ghost_num in range(0, num_ghosts): ghostDirList.append(ghostDirectionSuccessorStateAxioms(t, ghost_num, blockedWest, blockedEast)) for r in xrange(1, width+1): for c in xrange(1, height+1): if not walls[r][c]: pacmanPositionList.append(pacmanSuccessorStateAxioms(r, c, t, walls)) pacmanAliveList.append(pacmanAliveSuccessorStateAxioms(r, c, t, num_ghosts)) for ghost_num in range(0, num_ghosts): ghostPositionList.append(ghostPositionSuccessorStateAxioms(r, c, t, ghost_num, walls)) d = [] d.append(logic.PropSymbolExpr(game.Directions.NORTH, t-1)) d.append(logic.PropSymbolExpr(game.Directions.SOUTH, t-1)) d.append(logic.PropSymbolExpr(game.Directions.EAST, t-1)) d.append(logic.PropSymbolExpr(game.Directions.WEST, t-1)) lst.append(exactlyOne(d)) for food in foodLoac: foodLoc[foodLoac.index(food)] = foodLoc[foodLoac.index(food)] | logic.PropSymbolExpr(pacman_str,food[0],food[1],t) goalState = logic.to_cnf(logic.conjoin(foodLoc) & logic.PropSymbolExpr(pacman_alive_str, t)) lisst = logic.to_cnf(logic.conjoin(list(set(pacmanPositionList)) + list(set(pacmanAliveList)) + list(set(ghostPositionList)) + list(set(ghostDirList)) + list(set(lst)))) result = lisst & init & goalState model = logic.pycoSAT(result) if model != False: seq = extractActionSequence(model, [game.Directions.NORTH, game.Directions.SOUTH,game.Directions.EAST, game.Directions.WEST]) return seq util.raiseNotDefined()
def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions, blocked_east_positions): """ Successor state axiom for patrolling ghost direction state (t) (from t-1). west or east walls. Current <==> (causes to stay) | (causes of current) """ pos_str = ghost_pos_str+str(ghost_num) east_str = ghost_east_str+str(ghost_num) "*** YOUR CODE HERE ***" wlst, elst = [], [] for (x, y) in blocked_east_positions: elst.append(~logic.PropSymbolExpr(pos_str, x, y, t)) for (x, y) in blocked_west_positions: wlst.append(logic.PropSymbolExpr(pos_str, x, y, t)) if not elst and wlst: return logic.PropSymbolExpr(east_str, t) % (logic.PropSymbolExpr(east_str, t - 1) | (~logic.PropSymbolExpr(east_str, t - 1) & logic.disjoin(wlst))) elif elst and not wlst: return logic.PropSymbolExpr(east_str, t) % (logic.PropSymbolExpr(east_str, t - 1) & logic.conjoin(elst)) elif not elst and not wlst: return logic.PropSymbolExpr(east_str, t) % logic.PropSymbolExpr(east_str, t - 1) else: return logic.PropSymbolExpr(east_str, t) % ((logic.PropSymbolExpr(east_str, t - 1) & logic.conjoin(elst)) | (~logic.PropSymbolExpr(east_str, t - 1) & logic.disjoin(wlst)))