def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** YOUR CODE HERE ***" if logic.is_valid_cnf(sentence): return logic.pycoSAT(sentence) cnf = logic.to_cnf(sentence) return logic.pycoSAT(cnf)
def isSafe(position, pkeReadings, knownSafePositions, walls): exprList = [] ghostStr = "G" pkeStr = "PKE" positionSymbol = logic.PropSymbolExpr(ghostStr,position[0],position[1]) for (x,y) in knownSafePositions: exprList += [~logic.PropSymbolExpr(ghostStr,x,y)] for ((x,y), pkeReading) in pkeReadings.items(): pkeSymbol = logic.PropSymbolExpr(pkeStr,x,y) if pkeReading: exprList += [pkeSymbol] else: exprList += [~pkeSymbol] allNeighbors = [(x-1,y), (x+1,y), (x,y-1), (x,y+1)] neighborSymbols = [] for (nx,ny) in allNeighbors: if not walls[nx][ny]: neighborSymbols += [logic.PropSymbolExpr(ghostStr,nx,ny)] pkeExpr = pkeSymbol % reduce((lambda a,b: a|b), neighborSymbols) exprList += [logic.to_cnf(pkeExpr)] # # A pke reading in any square means that there is a ghost in at least one adjacent square # for x in xrange(1,walls.width-1): # for y in xrange(1,walls.height-1): # if walls[x][y]: # continue # # allNeighbors = [(x-1,y), (x+1,y), (x,y-1), (x,y+1)] # neighborSymbols = [] # for (nx,ny) in allNeighbors: # if not walls[nx][ny]: # neighborSymbols += [logic.PropSymbolExpr(ghostStr,nx,ny)] # # pkeSymbol = logic.PropSymbolExpr(pkeStr,x,y) # pkeExpr = pkeSymbol % reduce((lambda a,b: a|b), neighborSymbols) # exprList += [logic.to_cnf(pkeExpr)] ghostModel = logic.pycoSAT(exprList + [positionSymbol]) # print "ghostModel={}".format(ghostModel) if not ghostModel: # print "exprList={}".format(exprList + [positionSymbol]) return True; else: noGhostModel = logic.pycoSAT(exprList + [~positionSymbol]) # print "noGhostModel={}".format(noGhostModel) if not noGhostModel: return False; else: return None
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" MAX_TIME_STEPS = 50 actions = [ Directions.NORTH, Directions.EAST, Directions.SOUTH, Directions.WEST ] initial_models = get_initial_models(problem) successor_state_axioms = [] action_exclusion_axioms = [] legal_actions = set() for x in xrange(1, problem.getWidth() + 1): for y in xrange(1, problem.getHeight() + 1): if not problem.isWall((x, y)): for action in problem.actions((x, y)): legal_actions.add((x, y, action)) for t in xrange(MAX_TIME_STEPS): goal_assertion = goal_sentence(problem, t) if t > 0: successor_state_axioms += transition_models( problem, t, actions, legal_actions) action_exclusion_axioms += create_action_exclusion_axioms( actions, t - 1) solution_model = logic.pycoSAT(initial_models + successor_state_axioms + goal_assertion + action_exclusion_axioms) if solution_model is not False: return extractActionSequence(solution_model, actions) return None
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ "*** YOUR CODE HERE ***" MAX_TIME_STEPS = 50 actions = [Directions.NORTH, Directions.EAST, Directions.SOUTH, Directions.WEST] initial_models = get_food_initial_models(problem) successor_state_axioms = [] action_exclusion_axioms = [] legal_actions = set() for x in xrange(1, problem.getWidth()+1): for y in xrange(1, problem.getHeight()+1): if not problem.isWall((x, y)): for action in problem.actions(((x, y), problem.getStartState()[1])): legal_actions.add((x, y, action)) for t in xrange(MAX_TIME_STEPS): food_axioms = get_food_axioms(problem, t) goal_assertion = food_goal_sentence(problem, t) if t > 0: successor_state_axioms += transition_models(problem, t, actions, legal_actions) action_exclusion_axioms += create_action_exclusion_axioms(actions, t-1) sentence = initial_models + successor_state_axioms + goal_assertion + action_exclusion_axioms + food_axioms solution_model = logic.pycoSAT(sentence) if solution_model is not False: actions = extractActionSequence(solution_model, actions) return actions return None
def findModel(sentence): """Given a propositional logic sentence (i.e. a Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** BEGIN YOUR CODE HERE ***" return pycoSAT(to_cnf(sentence)) "*** END YOUR CODE HERE ***"
def solve(sudoku_str): sudoku_str = sudoku_str.translate(None, "\n") assert len(sudoku_str) == 81, "Invalid problem" t_0 = time.clock() s = rules() problem_dict = dict() row = 0 col = 0 for c in sudoku_str: if c in string.digits[1:]: problem_dict[symbols[row][col][int(c) - 1]] = True s.add(symbols[row][col][int(c) - 1]) col += 1 if col == 9: col = 0 row += 1 print "Problem:" print_sudoku(problem_dict) for e in s: assert logic_extra.is_valid_cnf(e) t_prep_done = time.clock() solution_dict = logic.pycoSAT(s) t_solve_done = time.clock() assert solution_dict, "No valid solution" print "Solution:" print_sudoku(solution_dict) print "Expression Build + Sanity Check: {0:.2f}s\nSolving: {1:.2f}s\n{2}\nTotal: {3:.2f}s".format(t_prep_done - t_0, t_solve_done - t_prep_done, "-" * 15, t_solve_done - t_0)
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ actions = [ game.Directions.EAST, game.Directions.SOUTH, game.Directions.WEST, game.Directions.NORTH ] init_t = util.manhattanDistance(problem.getStartState(), problem.getGoalState()) goal_s = problem.getGoalState() preds = getPredecessors(problem) start_pos = problem.getStartState() init_state = [logic.Expr("&", logic.PropSymbolExpr("P", start_pos[0],start_pos[1],0),\ *[logic.Expr("~", logic.PropSymbolExpr("P", s[0],s[1],0)) for s in preds.keys() if s != start_pos])] for t in xrange(init_t, 51): goal = [logic.PropSymbolExpr("P", goal_s[0], goal_s[1]), \ logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P", goal_s[0], goal_s[1]),\ logic.Expr("|", *[logic.PropSymbolExpr("P", goal_s[0], goal_s[1], time) for time in xrange(1,t+1)])))] successors = generateSuccessorState(preds, t) exps = goal + successors + init_state model = logic.pycoSAT(exps) if model: return extractActionSequence(model, actions) return []
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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 an eastern wall. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ actions = [ game.Directions.EAST, game.Directions.SOUTH, game.Directions.WEST, game.Directions.NORTH ] # this is my food grid as a list [(x,y), (x,y) ...] food_list = problem.getStartState()[1].asList() # this is a list of the distances from my start state to each food on the grid manhattan_food_distances = [ util.manhattanDistance(problem.getStartState()[0], food) for food in food_list ] # for the predecessors function extractState = lambda x: x[0][0] generateState = lambda x: (x, problem.getStartState()[1]) # return the food that is furthest away init_t = max(manhattan_food_distances) preds = getPredecessors(problem, extractState, generateState) start_pos = problem.getStartState()[0] init_state = [logic.Expr("&", logic.PropSymbolExpr("P", start_pos[0],start_pos[1],0),\ *[logic.Expr("~", logic.PropSymbolExpr("P", s[0],s[1],0)) for s in preds.keys() if s != start_pos])] ghost_pos_arrays = [ getGhostPositionArray(problem, ghost.getPosition()) for ghost in problem.getGhostStartStates() ] for t in xrange(init_t, 51): ghosts = reduce(lambda x,y: x + y, [[[~logic.PropSymbolExpr("P", g[i%len(g)][0],g[i%len(g)][1],i+1),\ ~logic.PropSymbolExpr("P", g[i%len(g)][0],g[i%len(g)][1],i)]\ for i in xrange(t+1)] for g in ghost_pos_arrays]) ghosts = reduce(lambda x, y: x + y, ghosts) goal_list = [] for food in food_list: # food is an (x, y) coordinate goal_list.append([logic.PropSymbolExpr("P", food[0], food[1]), \ logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P", food[0], food[1]),\ logic.Expr("|", *[logic.PropSymbolExpr("P", food[0], food[1], time) for time in xrange(t+1)])))]) successors = generateSuccessorState(preds, t) # makes goal_list a list, previously was a list of lists goal_list = reduce(lambda x, y: x + y, goal_list) exps = goal_list + successors + init_state + ghosts model = logic.pycoSAT(exps) if model: return extractActionSequence(model, actions) return []
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** YOUR CODE HERE ***" cnf = logic.to_cnf(sentence) solution = logic.pycoSAT(cnf) # note: if no possible solution, return false return solution
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ cnf = logic.to_cnf(sentence) model = logic.pycoSAT(cnf) if str(model) == "False": return False return model
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** YOUR CODE HERE ***" cnf = logic.to_cnf(sentence) return logic.pycoSAT(cnf) util.raiseNotDefined()
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** YOUR CODE HERE ***" cnf_s = logic.to_cnf(sentence) sat_s = logic.pycoSAT(cnf_s) # print(sat_s) return sat_s util.raiseNotDefined()
def positionLogicPlan(problem): manhattanDistance = util.manhattanDistance(problem.getStartState(), problem.getGoalState()) for time in range(manhattanDistance, 3000): exprs = [] start=problem.getStartState() goal=problem.getGoalState() exprs.append(logic.PropSymbolExpr("P",start[0],start[1],0)) exprs.append(logic.PropSymbolExpr("P",goal[0],goal[1],time)) positions = [] for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if not problem.isWall((x,y)) and (x,y)!=problem.getStartState(): positionSymbol = logic.Expr('~',logic.PropSymbolExpr("P",x,y,0)) exprs.append(positionSymbol) for t in range(0,time): northSymbol = logic.PropSymbolExpr("North", t) southSymbol = logic.PropSymbolExpr("South", t) westSymbol = logic.PropSymbolExpr("West", t) eastSymbol = logic.PropSymbolExpr("East", t) exactlyOneAction = exactlyOne([northSymbol, southSymbol, westSymbol, eastSymbol]) appendToExprs(exprs, exactlyOneAction) for t in range(1, time+1): for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if not problem.isWall((x,y)): actions = problem.actions((x,y)) prevExprs = [] for action in actions: currentStatePropSymbolExpr = logic.PropSymbolExpr("P", x, y, t) prevState = () if action == 'North': action = 'South' prevState = (x,y+1) elif action == 'South': action = 'North' prevState = (x,y-1) elif action == 'West': action = 'East' prevState = (x-1,y) elif action == 'East': action = 'West' prevState = (x+1,y) actionPropSymbolExpr = logic.PropSymbolExpr(action, t-1) prevStatePropSymbolExpr = logic.PropSymbolExpr("P", prevState[0], prevState[1], t-1) prevExprs.append(logic.Expr("&", actionPropSymbolExpr, prevStatePropSymbolExpr)) prevExprsOrred = logic.Expr("|", *prevExprs) iff = logic.Expr("<=>", prevExprsOrred, currentStatePropSymbolExpr) appendToExprs(exprs, iff) result = logic.pycoSAT(exprs) if result: return extractActionSequence(result, ["North", "South", "East", "West"])
def findModel(sentence): """Given a propositional logic sentence (i.e. a Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** BEGIN YOUR CODE HERE ***" sentence_in_cnf = to_cnf(sentence) satisfying_model = pycoSAT(sentence_in_cnf) if not satisfying_model: return False return satisfying_model "*** END YOUR CODE HERE ***"
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** YOUR CODE HERE ***" #print sentence cnf_form = logic.to_cnf(sentence) #convert the input to cnf form if_have_model = logic.pycoSAT( cnf_form) #return a model, if not have a model ,return false return if_have_model util.raiseNotDefined()
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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. """ "*** YOUR CODE HERE ***" MAX_TIME_STEPS = 50 actions = [ Directions.NORTH, Directions.EAST, Directions.SOUTH, Directions.WEST ] initial_models = get_food_initial_models(problem) successor_state_axioms = [] action_exclusion_axioms = [] ghost_axioms = [] legal_actions = set() for x in xrange(1, problem.getWidth() + 1): for y in xrange(1, problem.getHeight() + 1): if not problem.isWall((x, y)): for action in problem.actions( ((x, y), problem.getStartState()[1])): legal_actions.add((x, y, action)) ghost_states = [] for agentstate in problem.getGhostStartStates(): ghost_states.append([agentstate.getPosition(), True]) #(position, goingEast?) ghost_axioms += get_ghost_axioms(map(lambda x: x[0], ghost_states), 0) for t in xrange(MAX_TIME_STEPS): for i in xrange(len(ghost_states)): ghost_state = ghost_states[i] new_ghost_state = update_ghost_state(problem, ghost_state[0], ghost_state[1]) ghost_states[i] = new_ghost_state ghost_axioms += get_ghost_axioms(map(lambda x: x[0], ghost_states), t + 1) food_axioms = get_food_axioms(problem, t) goal_assertion = food_goal_sentence(problem, t) if t > 0: successor_state_axioms += transition_models( problem, t, actions, legal_actions) action_exclusion_axioms += create_action_exclusion_axioms( actions, t - 1) sentence = initial_models + successor_state_axioms + goal_assertion + action_exclusion_axioms + food_axioms + ghost_axioms solution_model = logic.pycoSAT(sentence) if solution_model is not False: actions = extractActionSequence(solution_model, actions) return actions return None
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ "*** YOUR CODE HERE ***" #A = logic.Expr("A") #sentence = A & ~A cnf = logic.to_cnf(sentence) result = logic.pycoSAT(cnf) #print(result) #if(str(result) == "False"): #return False return result
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ # need a list where all the food is # go through with the logic phrase, for each food make sure at some time step t I will be there actions = [ game.Directions.EAST, game.Directions.SOUTH, game.Directions.WEST, game.Directions.NORTH ] # this is my food grid as a list [(x,y), (x,y) ...] food_list = problem.getStartState()[1].asList() # this is a list of the distances from my start state to each food on the grid manhattan_food_distances = [ util.manhattanDistance(problem.getStartState()[0], food) for food in food_list ] # for the predecessors function extractState = lambda x: x[0][0] generateState = lambda x: (x, problem.getStartState()[1]) # return the food that is furthest away init_t = max(manhattan_food_distances) preds = getPredecessors(problem, extractState, generateState) start_pos = problem.getStartState()[0] init_state = [logic.Expr("&", logic.PropSymbolExpr("P", start_pos[0],start_pos[1],0),\ *[logic.Expr("~", logic.PropSymbolExpr("P", s[0],s[1],0)) for s in preds.keys() if s != start_pos])] for t in xrange(init_t, 51): goal_list = [] for food in food_list: # food is an (x, y) coordinate goal_list.append([logic.PropSymbolExpr("P", food[0], food[1]), \ logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P", food[0], food[1]),\ logic.Expr("|", *[logic.PropSymbolExpr("P", food[0], food[1], time) for time in xrange(1,t+1)])))]) successors = generateSuccessorState(preds, t) # makes goal_list a list, previously was a list of lists goal_list = reduce(lambda x, y: x + y, goal_list) exps = goal_list + successors + init_state model = logic.pycoSAT(exps) if model: return extractActionSequence(model, actions) return []
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" Directions = ['North', 'South', 'East', 'West'] start = problem.getStartState() goal = problem.getGoalState() states = [] for x in range(0, problem.getWidth()+1): for y in range(0, problem.getHeight()+1): if not problem.isWall((x,y)): states.append((x,y)) for step in range(util.manhattanDistance(start, goal), 51): cnf = [] cnf.append(logic.PropSymbolExpr('P',start[0],start[1], 0)) cnf.append(logic.PropSymbolExpr('P',goal[0],goal[1], step)) for timeStep in range(0, step + 1): cnf.append(exactlyOne([logic.PropSymbolExpr(action,timeStep) for action in Directions])) cnf.append(exactlyOne([logic.PropSymbolExpr('P',state[0],state[1], timeStep) for state in states])) for state in states: actions = problem.actions(state) for action in actions: nextState = problem.result(state, action)[0] expr0 = logic.PropSymbolExpr('P',state[0],state[1], timeStep) expr1 = logic.PropSymbolExpr(action,timeStep) expr2 = logic.PropSymbolExpr('P',nextState[0],nextState[1], timeStep+1) cnf.append(logic.to_cnf((expr0 & expr1) >> expr2)) for state in states: lst = [] exp = None for timeStep in range(step + 1): lst.append(logic.PropSymbolExpr('P',state[0],state[1],timeStep)) exp = atMostOne(lst) cnf.append(exp) newlist = [x for x in list(Directions) if x not in list(problem.actions(state))] for action in newlist: for timeStep in range(step+1): expr0 = logic.PropSymbolExpr('P',state[0],state[1], timeStep) expr1 = ~logic.PropSymbolExpr(action,timeStep) cnf.append(logic.to_cnf( expr0 >> expr1)) success = logic.pycoSAT(cnf) if success: return extractActionSequence(success, Directions)
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 foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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 an eastern wall. Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ actions = [game.Directions.EAST,game.Directions.SOUTH,game.Directions.WEST,game.Directions.NORTH] # this is my food grid as a list [(x,y), (x,y) ...] food_list = problem.getStartState()[1].asList() # this is a list of the distances from my start state to each food on the grid manhattan_food_distances = [util.manhattanDistance(problem.getStartState()[0], food) for food in food_list] # for the predecessors function extractState = lambda x: x[0][0] generateState = lambda x: (x, problem.getStartState()[1]) # return the food that is furthest away init_t = max(manhattan_food_distances) preds = getPredecessors(problem, extractState, generateState) start_pos = problem.getStartState()[0] init_state = [logic.Expr("&", logic.PropSymbolExpr("P", start_pos[0],start_pos[1],0),\ *[logic.Expr("~", logic.PropSymbolExpr("P", s[0],s[1],0)) for s in preds.keys() if s != start_pos])] ghost_pos_arrays = [getGhostPositionArray(problem, ghost.getPosition()) for ghost in problem.getGhostStartStates()] for t in xrange(init_t, 51): ghosts = reduce(lambda x,y: x + y, [[[~logic.PropSymbolExpr("P", g[i%len(g)][0],g[i%len(g)][1],i+1),\ ~logic.PropSymbolExpr("P", g[i%len(g)][0],g[i%len(g)][1],i)]\ for i in xrange(t+1)] for g in ghost_pos_arrays]) ghosts = reduce(lambda x,y: x + y,ghosts) goal_list = [] for food in food_list: # food is an (x, y) coordinate goal_list.append([logic.PropSymbolExpr("P", food[0], food[1]), \ logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P", food[0], food[1]),\ logic.Expr("|", *[logic.PropSymbolExpr("P", food[0], food[1], time) for time in xrange(t+1)])))]) successors = generateSuccessorState(preds, t) # makes goal_list a list, previously was a list of lists goal_list = reduce(lambda x,y: x+y, goal_list) exps = goal_list + successors + init_state + ghosts model = logic.pycoSAT(exps) if model: return extractActionSequence(model, actions) return []
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ # print sentence # print "his" a = logic.to_cnf(sentence) # print "pis" b = logic.pycoSAT(a) # print "dis" if str(b) == "FALSE": # print "wis" return False # print "jis" return b
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, return a list of actions that help Pacman eat all of the food. Available actions are gameDirections.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ "*** YOUR CODE HERE ***" states = [] food = [] gameDirections = ['North', 'South', 'East', 'West'] fGrid = problem.getStartState()[1] for i in range(0,problem.getWidth()+1): for j in range(0, problem.getHeight()+1): if not problem.isWall((i,j)): states.append((i,j)) if fGrid[i][j]: food.append((i,j)) for tLimit in xrange(len(food), 51): cnf = [] for state in states: actions = problem.actions((state, fGrid)) for action in actions: for time in xrange(tLimit): nextState = problem.result((state, fGrid), action)[0] expression = (logic.PropSymbolExpr('P', state[0], state[1], time) & logic.PropSymbolExpr(action, time)) >> logic.PropSymbolExpr('P', nextState[0][0], nextState[0][1], time+1) cnf.append(logic.to_cnf(expression)) for action in list(set(gameDirections)-set(actions)): for time in xrange(tLimit): expression = logic.PropSymbolExpr('P', state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time) cnf.append(logic.to_cnf(expression)) cnf.append(logic.PropSymbolExpr('P', problem.getStartState()[0][0], problem.getStartState()[0][1], 0)) for time in range(0, tLimit): cnf.append(exactlyOne([logic.PropSymbolExpr(action,time) for action in gameDirections])) cnf.append(exactlyOne([logic.PropSymbolExpr('P', state[0], state[1], time) for state in states])) for f in food: cnf.append(atLeastOne([logic.PropSymbolExpr('P', f[0], f[1], time) for time in range(0, tLimit)])) model = logic.pycoSAT(cnf) if model: return extractActionSequence(model, gameDirections)
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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. """ "*** YOUR CODE HERE ***" MAX_TIME_STEPS = 50 actions = [Directions.NORTH, Directions.EAST, Directions.SOUTH, Directions.WEST] initial_models = get_food_initial_models(problem) successor_state_axioms = [] action_exclusion_axioms = [] ghost_axioms = [] legal_actions = set() for x in xrange(1, problem.getWidth()+1): for y in xrange(1, problem.getHeight()+1): if not problem.isWall((x, y)): for action in problem.actions(((x, y), problem.getStartState()[1])): legal_actions.add((x, y, action)) ghost_states = [] for agentstate in problem.getGhostStartStates(): ghost_states.append([agentstate.getPosition(), True]) #(position, goingEast?) ghost_axioms += get_ghost_axioms(map(lambda x: x[0], ghost_states), 0) for t in xrange(MAX_TIME_STEPS): for i in xrange(len(ghost_states)): ghost_state = ghost_states[i] new_ghost_state = update_ghost_state(problem, ghost_state[0], ghost_state[1]) ghost_states[i] = new_ghost_state ghost_axioms += get_ghost_axioms(map(lambda x: x[0], ghost_states), t+1) food_axioms = get_food_axioms(problem, t) goal_assertion = food_goal_sentence(problem, t) if t > 0: successor_state_axioms += transition_models(problem, t, actions, legal_actions) action_exclusion_axioms += create_action_exclusion_axioms(actions, t-1) sentence = initial_models + successor_state_axioms + goal_assertion + action_exclusion_axioms + food_axioms + ghost_axioms solution_model = logic.pycoSAT(sentence) if solution_model is not False: actions = extractActionSequence(solution_model, actions) return actions return None
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ # need a list where all the food is # go through with the logic phrase, for each food make sure at some time step t I will be there actions = [game.Directions.EAST,game.Directions.SOUTH,game.Directions.WEST,game.Directions.NORTH] # this is my food grid as a list [(x,y), (x,y) ...] food_list = problem.getStartState()[1].asList() # this is a list of the distances from my start state to each food on the grid manhattan_food_distances = [util.manhattanDistance(problem.getStartState()[0], food) for food in food_list] # for the predecessors function extractState = lambda x: x[0][0] generateState = lambda x: (x, problem.getStartState()[1]) # return the food that is furthest away init_t = max(manhattan_food_distances) preds = getPredecessors(problem, extractState, generateState) start_pos = problem.getStartState()[0] init_state = [logic.Expr("&", logic.PropSymbolExpr("P", start_pos[0],start_pos[1],0),\ *[logic.Expr("~", logic.PropSymbolExpr("P", s[0],s[1],0)) for s in preds.keys() if s != start_pos])] for t in xrange(init_t, 51): goal_list = [] for food in food_list: # food is an (x, y) coordinate goal_list.append([logic.PropSymbolExpr("P", food[0], food[1]), \ logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P", food[0], food[1]),\ logic.Expr("|", *[logic.PropSymbolExpr("P", food[0], food[1], time) for time in xrange(1,t+1)])))]) successors = generateSuccessorState(preds, t) # makes goal_list a list, previously was a list of lists goal_list = reduce(lambda x,y: x+y, goal_list) exps = goal_list + successors + init_state model = logic.pycoSAT(exps) if model: return extractActionSequence(model, actions) return []
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] time = 0 start = problem.getStartState() cnf.append(generate_initial_statements(problem)) current = start goal = problem.getGoalState() frontier = Queue() queue.push(((start[0],start[1]), (start[0],start[1]), time)) """ ((current_position), (previous_position), time) """ while !queue.isEmpty(): current = queue.pop() actions = problem.actions(current[0]) for elem in actions: sucessor = generateFromDirections(current, elem) if problem.terminalTest(successor[0]): cnf.append(goal_expression(problem, current, successor)) break cnf.append(transition_expression(problem, current, successor)) queue.push(elem, current[0], current[2]+1) """ solve cnf shit """ from game import Directions n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST return extractActionSequence(logic.pycoSAT(cnf), [n,s,e,w]) util.raiseNotDefined()
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 positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ actions = [game.Directions.EAST,game.Directions.SOUTH,game.Directions.WEST,game.Directions.NORTH] init_t = util.manhattanDistance(problem.getStartState(), problem.getGoalState()) goal_s = problem.getGoalState() preds = getPredecessors(problem) start_pos = problem.getStartState() init_state = [logic.Expr("&", logic.PropSymbolExpr("P", start_pos[0],start_pos[1],0),\ *[logic.Expr("~", logic.PropSymbolExpr("P", s[0],s[1],0)) for s in preds.keys() if s != start_pos])] for t in xrange(init_t, 51): goal = [logic.PropSymbolExpr("P", goal_s[0], goal_s[1]), \ logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P", goal_s[0], goal_s[1]),\ logic.Expr("|", *[logic.PropSymbolExpr("P", goal_s[0], goal_s[1], time) for time in xrange(1,t+1)])))] successors = generateSuccessorState(preds, t) exps = goal + successors + init_state model = logic.pycoSAT(exps) if model: return extractActionSequence(model, actions) return []
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. destination_time1 <=> (src1_time0 & action1_time0) | src2_time0 & action2_0) |(src3_time0 & action3_time0) and your goal state can just be like: goal_timeT then you plug it in for each value of time (0-50) """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e , w] width = problem.getWidth()+1 height = problem.getHeight()+1 for time in range(0, maxTime): stateLogicList = [] if time == 0: #Only need Start/Goal # Start State startState = problem.getStartState() pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x,y) == (startState[0], startState[1]): continue else nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) else: for x in range(1,width): for y in range(1, height): currentState = (x,y) currentLogic = logic.PropSymbolExpr("P", currentState[0], currentState[1], time) for action in problem.actions(currentState): if action == n: nextstate = problem.result(currentState, action)[0] logic.PropSymbolExpr("P", x, y+1, time-1) nextaction = logic.PropSymbolExpr(s, time-1) elif action == s: nextstate = logic.PropSymbolExpr("P", x, y-1, time-1) nextaction = logic.PropSymbolExpr(n, time-1) elif action == e: nextstate = logic.PropSymbolExpr("P", x+1, y, time-1) nextaction = logic.PropSymbolExpr(w, time-1) elif action == w: nextstate = logic.PropSymbolExpr("P", x-1, y, time-1) nextaction = logic.PropSymbolExpr(e, time-1) stateLogicList.append((currentLogic, (nextstate & nextaction))) dictionary = {} for elem in stateLogicList: if elem[0] not in dictionary.keys(): dictionary[elem[0]] = [elem[1]] if elem[0] in dictionary.keys(): dictionary[elem[0]].append(elem[1]) for key in dictionary.keys(): val = dictionary[key] parents = logic.associate('|', val) cnf.append(logic.to_cnf(key % parents)) # exactly one action is taken at one time Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) OneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(OneMove)) #Goal State goalState = problem.getGoalState() cnf.append(logic.to_cnf(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))) model = logic.pycoSAT(cnf) if model: return extractActionSequence(model, DirectionsList) #remove goal if the model is false cnf.remove(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))
def findModel(sentence): """Given a propositional logic sentence (i.e. a logic.Expr instance), returns a satisfying model if one exists. Otherwise, returns False. """ return logic.pycoSAT(logic.to_cnf(sentence))
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" start = problem.getStartState() goal = problem.getGoalState() allActions = ['North', 'South', 'East', 'West'] expr = [] states = [] for i in range(1, problem.getWidth() + 1): for j in range(1, problem.getHeight() + 1): if not problem.isWall((i,j)): states.append((i,j)) startingConstraint = logic.PropSymbolExpr("P", start[0], start[1], 0) for state in states: if state != start: startingConstraint = startingConstraint & ~logic.PropSymbolExpr("P", state[0], state[1], 0) expr.append(startingConstraint) for t in range(1, 50): allStateSymbols = [] sentences = [] allActionSymbols = [] goalConstraint = logic.PropSymbolExpr("P", goal[0], goal[1], t) for action in allActions: actionSymbol = logic.PropSymbolExpr(action, t) allStateSymbols.append(actionSymbol) oneAction = exactlyOne(allStateSymbols) sentences.append(logic.to_cnf(oneAction)) for state in states: stateSymbol = logic.PropSymbolExpr("P", state[0], state[1], t) allStateSymbols.append(stateSymbol) actions = problem.actions(state) for action in allActions: if action in actions: actionSymbol = logic.PropSymbolExpr(action, t) result = problem.result(state, action) resultSymbol = logic.PropSymbolExpr("P", result[0][0], result[0][1], t + 1) constraint = (stateSymbol & actionSymbol) >> resultSymbol sentences.append(logic.to_cnf(constraint)) else: actionSymbol = logic.PropSymbolExpr(action, t) constraint = stateSymbol >> ~actionSymbol sentences.append(logic.to_cnf(constraint)) if state != goal: goalConstraint = goalConstraint & ~stateSymbol oneState = exactlyOne(allStateSymbols) sentences.append(logic.to_cnf(oneState)) sentences.append(logic.to_cnf(goalConstraint)) expr += sentences model = logic.pycoSAT(expr) if model != False: print model return extractActionSequence(model, allActions) else: expr.remove(logic.to_cnf(goalConstraint))
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 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. """ actions = ['North', 'South', 'East', 'West'] walls = problem.walls width, height = problem.getWidth(), problem.getHeight() loc_list = [] list_walls = walls.asList() for w in range(width + 1): for h in range(height + 1): if (w, h) not in list_walls: loc_list.append((w, h)) # loc_list=[(w,h) for h in range(height+1) if ((w, h) not in list_walls)] else: pass # loc_list=[(w,h) for w in range(width+1) for h in range(height+1) if ((w, h) not in list_walls)] final_list = [] final_cnf = [] for i in range(50): ac_list = [ logic.PropSymbolExpr(actions[k], i) for k in range(len(actions)) ] final_list.append(exactlyOne(ac_list)) pac_pos_list = [ logic.PropSymbolExpr(pacman_str, j[0], j[1], i) for j in loc_list ] final_list.append(exactlyOne(pac_pos_list)) if (i != 0): for k in loc_list: final_list.append( pacmanSuccessorStateAxioms(k[0], k[1], i, walls)) # tem_axiom=[pacmanSuccessorStateAxioms (k[0], k[1], i, walls) for k in loc_list] # final_list.extend(tem_axiom) else: pass # print(final_list) # x=findModel(logic.conjoin(final_list)) final_list.append( logic.PropSymbolExpr(pacman_str, problem.getStartState()[0], problem.getStartState()[1], 0)) cnf_s = logic.to_cnf(logic.conjoin(final_list)) final_cnf.append(cnf_s) End_pos_con = logic.PropSymbolExpr(pacman_str, problem.getGoalState()[0], problem.getGoalState()[1], i) # print(cnf_s) # sat_s = logic.pycoSAT (cnf_s) #print (logic.pycoSAT (logic.conjoin (final_cnf))) #print(findModel(logic.conjoin (final_cnf))) if (logic.pycoSAT((logic.conjoin(final_cnf)) & End_pos_con) == False): # print("pass") print(i) final_list = [] else: # print("break") break return extractActionSequence( logic.pycoSAT(logic.conjoin(final_cnf) & End_pos_con), actions) "*** YOUR CODE HERE ***" util.raiseNotDefined()
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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 gameDirections.{NORTH,SOUTH,EAST,WEST} Note that STOP is not an available action. """ "*** YOUR CODE HERE ***" states = [] food = [] gameDirections = ['North', 'South', 'East', 'West'] fGrid = problem.getStartState()[1] for i in range(0,problem.getWidth()+1): for j in range(0, problem.getHeight()+1): if not problem.isWall((i,j)): states.append((i,j)) if fGrid[i][j]: food.append((i,j)) for tLimit in range(len(food), 51): cnf = [] for state in states: actions = problem.actions((state, fGrid)) for action in actions: for time in range(0, tLimit): nextState = problem.result((state, fGrid), action)[0] expression = (logic.PropSymbolExpr('P', state[0], state[1], time) & logic.PropSymbolExpr(action, time)) >> logic.PropSymbolExpr('P', nextState[0][0], nextState[0][1], time+1) cnf.append(logic.to_cnf(expression)) for action in list(set(gameDirections)-set(actions)): for time in range(0, tLimit): expression = logic.PropSymbolExpr('P', state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time) cnf.append(logic.to_cnf(expression)) cnf.append(logic.PropSymbolExpr('P', problem.getStartState()[0][0], problem.getStartState()[0][1], 0)) for time in range(0, tLimit): cnf.append(exactlyOne([logic.PropSymbolExpr(action,time) for action in gameDirections])) cnf.append(exactlyOne([logic.PropSymbolExpr('P', state[0], state[1], time) for state in states])) for f in food: cnf.append(atLeastOne([logic.PropSymbolExpr('P', f[0], f[1], time) for time in range(0, tLimit)])) for x in range(0, len(problem.getGhostStartStates())): ghostState = problem.getGhostStartStates()[x] ghostPos = ghostState.getPosition() cnf.append(logic.PropSymbolExpr('G' + str(x), ghostPos[0], ghostPos[1], 0)) if not problem.isWall((ghostPos[0]+1, ghostPos[1])): cnf.append(logic.PropSymbolExpr('G' + str(x), ghostPos[0]+1, ghostPos[1], 1)) else: cnf.append(logic.PropSymbolExpr('G' + str(x), ghostPos[0]-1, ghostPos[1], 1)) ghosts = [] trav = ghostPos[0] ghostY = ghostPos[1] while(not problem.isWall((trav, ghostY))): ghosts.append((trav, ghostY)) trav -= 1 trav = ghostPos[0] + 1 while(not problem.isWall((trav, ghostY))): ghosts.append((trav, ghostY)) trav += 1 for time in range(0, tLimit + 2): for pos in ghosts: east = (pos[0]+1, pos[1]) west = (pos[0]-1, pos[1]) if problem.isWall(west): expression = logic.PropSymbolExpr('G' + str(x), pos[0], pos[1], time) >> logic.PropSymbolExpr('G' + str(x), pos[0]+1, pos[1], time+1) cnf.append(logic.to_cnf(expression)) elif problem.isWall(east): expression = logic.PropSymbolExpr('G' + str(x), pos[0], pos[1], time) >> logic.PropSymbolExpr('G' + str(x), pos[0]-1, pos[1], time+1) cnf.append(logic.to_cnf(expression)) elif time != 0: expression = (logic.PropSymbolExpr('G' + str(x), pos[0]-1, pos[1], time -1) & logic.PropSymbolExpr('G' + str(x), pos[0], pos[1], time)) >>logic.PropSymbolExpr('G'+str(x), pos[0]+1, pos[1], time+1) cnf.append(logic.to_cnf(expression)) expression = (logic.PropSymbolExpr('G' + str(x), pos[0]+1, pos[1], time-1) & logic.PropSymbolExpr('G' + str(x), pos[0], pos[1], time)) >>logic.PropSymbolExpr('G' + str(x), pos[0]-1, pos[1], time+1) cnf.append(logic.to_cnf(expression)) for time in range(0, tLimit-1): for pos in ghosts: temp = [logic.PropSymbolExpr('P', pos[0], pos[1], time+1)] + [logic.PropSymbolExpr('G' + str(x), pos[0], pos[1], time)] cnf.append(atMostOne(temp)) temp = [logic.PropSymbolExpr('P', pos[0], pos[1], time)] + [logic.PropSymbolExpr('G' + str(x), pos[0], pos[1], time)] cnf.append(atMostOne(temp)) model = logic.pycoSAT(cnf) if model: return extractActionSequence(model, gameDirections)
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 FoodGhostSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e, w] width = problem.getWidth() + 1 height = problem.getHeight() + 1 #Starting State swag = problem.getStartState() startState = swag[0] ghostStartStateList = problem.getGhostStartStates() #Get positions of food foodGrid = swag[1] foodPosList = [] for x in range(width + 1): for y in range(height + 1): if foodGrid[x][y]: foodPosList.append((x, y)) pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x, y) == (startState[0], startState[1]): continue else: nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf( pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) stateList = [] for x in range(width + 1): for y in range(height + 1): if problem.isWall((x, y)): continue else: stateList.append((x, y)) for time in range(maxTime): oneStateList = [] for state in stateList: oneStateList.append( logic.PropSymbolExpr("P", state[0], state[1], time)) legalActionList = problem.actions((state, foodGrid)) illegalList = [] for action in DirectionsList: if action in legalActionList: nextState = problem.result((state, foodGrid), action)[0][0] # state & action >> new state nextLogic = (logic.PropSymbolExpr( "P", state[0], state[1], time) & logic.PropSymbolExpr( action, time)) >> logic.PropSymbolExpr( 'P', nextState[0], nextState[1], time + 1) cnf.append(logic.to_cnf(nextLogic)) else: illegalList.append(action) for action in illegalList: # state >> not illegal action cnf.append( logic.to_cnf( logic.PropSymbolExpr("P", state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time))) # uses oneStateList, makes sure we are not in two places at once oneState = exactlyOne(oneStateList) cnf.append((oneState)) # Exactly 1 move per turn Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) oneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(oneMove)) # goal state (must hit each pellet once) foodAllEaten = [] for food in foodPosList: foodOnce = [] for alltime in range(time + 1): foodOnce.append( logic.PropSymbolExpr('P', food[0], food[1], alltime)) atLeastOnce = logic.associate('|', foodOnce) foodAllEaten.append(atLeastOnce) goalLogic = logic.associate('&', foodAllEaten) cnf.append(goalLogic) #Pacman and Ghost not in same place def ghostPositionfinder(ghoststart, time): ghostposition = ghoststart x = ghoststart[0] y = ghoststart[1] East = True for t in range(time): if East == True: x += 1 if problem.isWall((x, y)): x -= 2 East = False elif East == False: x -= 1 if problem.isWall((x, y)): x += 2 East = True return (x, y) #logic.PropSymbolExpr("G", ghostPos[0], ghostPos[1], 0) for ghostStartState in ghostStartStateList: ghostPos = ghostStartState.getPosition() ghostCurrentPos = ghostPositionfinder(ghostPos, time) cnf.append( logic.PropSymbolExpr("G", ghostCurrentPos[0], ghostCurrentPos[1], time)) for pos in stateList: plsnodie = [logic.PropSymbolExpr("P", pos[0], pos[1], time) ] + [logic.PropSymbolExpr("G", pos[0], pos[1], time)] cnf.append(atMostOne(plsnodie)) plsnodie = [logic.PropSymbolExpr("P", pos[0], pos[1], time)] + [ logic.PropSymbolExpr("G", pos[0], pos[1], time - 1) ] cnf.append(atMostOne(plsnodie)) model = logic.pycoSAT(cnf) if model: path = extractActionSequence(model, DirectionsList) return path cnf.remove(goalLogic) print("you suck")
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" Directions = ['North', 'South', 'East', 'West'] cnf = [] finalTime = 0 startState = problem.getStartState() # Start at startState cnf.append( logic.PropSymbolExpr('P', startState[0], startState[1], finalTime)) #I have no idea why you can't go west initially but it doesnt work without it #successor axioms, use BFS q = util.Queue() q.push((startState, 0)) visited = [] while not q.isEmpty(): current = q.pop() if problem.terminalTest(current[0]): visited.append(current[0]) finalTime = current[1] break if current[0] in visited: continue else: visited.append(current[0]) actionList = [] actionList = problem.actions(current[0]) successorList = [] for action in actionList: nextState = problem.result(current[0], action)[0] successorList.append((nextState, action)) for successor in successorList: q.push((successor[0], current[1] + 1)) successorlogic = (logic.PropSymbolExpr( "P", current[0][0], current[0][1], current[1]) & logic.PropSymbolExpr( successor[1], current[1])) >> logic.PropSymbolExpr( 'P', successor[0][0], successor[0][1], current[1] + 1) # current state + current action >> next state cnf.append(logic.to_cnf(successorlogic)) # Goal at Goal state goalState = problem.getGoalState() cnf.append(logic.PropSymbolExpr('P', goalState[0], goalState[1], finalTime)) # One Place per time, One move per time for time in range(finalTime + 1): oneplaceList = [] oneturnList = [] for state in visited: oneplaceList.append( logic.PropSymbolExpr('P', state[0], state[1], time)) for action in Directions: oneturnList.append(logic.PropSymbolExpr(action, time)) oneplaceLogic = exactlyOne(oneplaceList) oneturnLogic = exactlyOne(oneturnList) cnf.append(oneplaceLogic) cnf.append(oneturnLogic) # No backtracking for state in visited: backtrackingList = [] for time in range(finalTime + 1): backtrackingList.append( logic.PropSymbolExpr('P', state[0], state[1], time)) backtrackingLogic = atMostOne(backtrackingList) cnf.append(backtrackingLogic) # No Illegal moves (each state >> no illegal actions) for state in visited: illegalList = [] for illegalmove in Directions: if illegalmove in problem.actions(state): continue else: illegalList.append(illegalmove) for time in range(finalTime + 1): for action in illegalList: # state > not action cnf.append( logic.to_cnf( logic.PropSymbolExpr('P', state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time))) model = logic.pycoSAT(cnf) if model: return extractActionSequence(model, Directions) """time = 0
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e , w] width = problem.getWidth()+1 height = problem.getHeight()+1 #Starting State startState = problem.getStartState() pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x,y) == (startState[0], startState[1]): continue else: nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) goalState = problem.getGoalState() stateList = [] for x in range(width+1): for y in range(height+1): if problem.isWall((x,y)): continue else: stateList.append((x,y)) for time in range(maxTime): oneStateList = [] for state in stateList: oneStateList.append(logic.PropSymbolExpr("P",state[0],state[1], time)) legalActionList = problem.actions(state) illegalList = [] for action in DirectionsList: if action in legalActionList: nextState = problem.result(state, action)[0] # state & action >> new state nextLogic = (logic.PropSymbolExpr("P",state[0],state[1], time) & logic.PropSymbolExpr(action,time)) >> logic.PropSymbolExpr('P',nextState[0],nextState[1], time+1) cnf.append(logic.to_cnf(nextLogic)) else: illegalList.append(action) for action in illegalList: # state >> not illegal action cnf.append(logic.to_cnf(logic.PropSymbolExpr('P',state[0],state[1], time) >> ~logic.PropSymbolExpr(action,time))) # uses oneStateList, makes sure we are not in two places at once oneState = exactlyOne(oneStateList) cnf.append((oneState)) # Exactly 1 move per turn Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) oneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(oneMove)) # goal state cnf.append(logic.PropSymbolExpr("P",goalState[0],goalState[1], time)) #print time model = logic.pycoSAT(cnf) if model: path = extractActionSequence(model, DirectionsList) return path cnf.remove(logic.PropSymbolExpr("P",goalState[0],goalState[1], time))
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e , w] width = problem.getWidth()+1 height = problem.getHeight()+1 #Starting State swag = problem.getStartState() startState = swag[0] #Get positions of food foodGrid = swag[1] foodPosList = [] for x in range(width+1): for y in range(height+1): if foodGrid[x][y]: foodPosList.append((x,y)) pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x,y) == (startState[0], startState[1]): continue else: nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) stateList = [] for x in range(width+1): for y in range(height+1): if problem.isWall((x,y)): continue else: stateList.append((x,y)) for time in range(maxTime): #print time oneStateList = [] for state in stateList: oneStateList.append(logic.PropSymbolExpr("P",state[0],state[1], time)) legalActionList = problem.actions((state, foodGrid)) illegalList = [] for action in DirectionsList: if action in legalActionList: nextState = problem.result((state, foodGrid), action)[0][0] # state & action >> new state nextLogic = (logic.PropSymbolExpr("P",state[0],state[1], time) & logic.PropSymbolExpr(action,time)) >> logic.PropSymbolExpr('P',nextState[0],nextState[1], time+1) cnf.append(logic.to_cnf(nextLogic)) else: illegalList.append(action) for action in illegalList: # state >> not illegal action cnf.append(logic.to_cnf(logic.PropSymbolExpr("P",state[0],state[1], time) >> ~logic.PropSymbolExpr(action,time))) # uses oneStateList, makes sure we are not in two places at once oneState = exactlyOne(oneStateList) cnf.append((oneState)) # Exactly 1 move per turn Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) oneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(oneMove)) # goal state (must hit each pellet once) foodAllEaten = [] for food in foodPosList: foodOnce = [] for alltime in range(time+1): foodOnce.append(logic.PropSymbolExpr('P',food[0],food[1],alltime)) atLeastOnce = logic.associate('|', foodOnce) foodAllEaten.append(atLeastOnce) goalLogic = logic.associate('&', foodAllEaten) cnf.append(goalLogic) model = logic.pycoSAT(cnf) if model: path = extractActionSequence(model, DirectionsList) return path cnf.remove(goalLogic) print("you suck")
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ "*** YOUR CODE HERE ***" # Initial Position of Pacman / Where he isn't # Food constraint, the food has been eaten if pacman has been there sym = logic.PropSymbolExpr time = 0 time_max = 50 kb = [] initialState_w_food = problem.getStartState() initialState = initialState_w_food[0] foodList = initialState_w_food[1].asList() goalState = problem.getGoalState() # get the legalStates (everything but walls) legalStates = [] walls = problem.walls.asList() for x in range(1, problem.getWidth() + 1): for y in range(1, problem.getHeight() + 1): position = (x, y) if position not in walls: legalStates.append(position) import pdb; pdb.set_trace() initialConstraint = sym("P", initialState[0], initialState[1], time) # GENERATE AND APPEND INITIAL CONSTRAINT # P[2,2,0] & ~P[2,1,0] & ~P[1,2,0] & ~P[1,1,0] for legalState in legalStates: if legalState == initialState: continue else: initialConstraint &= ~sym("P", legalState[0], legalState[1], time) # kb.append(initialConstraint) kb.append(logic.to_cnf(initialConstraint)) print "INITIAL CONSTRAINT" print initialConstraint #next_states = [ P[2,2,1] ] next_states = [initialState] for t in range(time, time_max): print "TTTTTTTTTTTTTTT" print t print "NEXT_STATES" print next_states symbolActions = [] actions = ['North', 'South', 'East', 'West'] for action in actions: symbolActions.append(sym(action, t)) kbActions = exactlyOne(symbolActions) print "kbACTIONS" print kbActions # kb.append(kbActions) kb.append(logic.to_cnf(kbActions)) # ADD GOAL STATE # (((P[1,1,0] & ~P[1,2,0]) & ~P[2,1,0]) & ~P[2,2,0]) if len(foodList) > 0: goalConstraint = foodList[0] for legalState in legalStates: if legalState not in foodList and legalState != foodList[0]: continue else: goalConstraint &= ~sym("F", legalState[0], legalState[1], t) # should already be in kb format kb.insert(0, logic.to_cnf(goalConstraint)) print "GOAL CONSTRAINT" print goalConstraint # import pdb; pdb.set_trace() # Add successor axioms and generate children for next_states # add P[1,1,T] & ~P[2,1,T] & ~P[1,2,T] & ~P[1,1,T] & (P(2,2,0) & South[0] <=> P[2,1,1]) & list_of_successors = {} # list_of_successor_state_axioms = [] kb_successors = [] for state in next_states: actions = problem.actions(state) # TODO: not sure if our existing exactlyOne method will work # another for loop to add successor constraints parent_state = sym("P", state[0], state[1], t) for action in actions: successor, cost = problem.result(state, action) kb_successor = sym("P", successor[0], successor[1], t + 1) kb_action = sym(action, t) if kb_successor in list_of_successors.keys(): list_of_successors[kb_successor].append((kb_action, parent_state)) print "list_of_successors" print list_of_successors else: kb_successors.append(kb_successor) list_of_successors[kb_successor] = [(kb_action, parent_state)] print "list_of_successors" print list_of_successors # successor_state_axiom = logic.Expr('<=>', (parent_state & kb_action), kb_successor) # print successor_state_axiom # list_of_successor_state_axioms.append(successor_state_axiom) # kb.append(logic.to_cnf(successor_state_axiom)) print "KB_SUCCESSORS" print kb_successors kb.append(logic.to_cnf(exactlyOne(kb_successors))) # attempt to add combinational ssa after you have all the actions # print 'YAY' for succ, actions_and_parents in list_of_successors.iteritems(): if len(actions_and_parents) < 2: print "SUCCESSOR STATE AXIOM" # successor state axioms that has only one way to get to the goal s = logic.Expr('<=>', (actions_and_parents[0][1] & actions_and_parents[0][0]), succ) print s kb.append(logic.to_cnf(s)) else: initial = (actions_and_parents[0][0] & actions_and_parents[0][1]) # print initial for tup in actions_and_parents[1:]: initial |= (tup[0] & tup[1]) comb_ssa = logic.Expr('<=>', initial, succ) kb.append(logic.to_cnf(exactlyOne([comb_ssa]))) # kb.append(logic.to_cnf(comb_ssa)) print "COMB_SSA" # combinational successor state axioms print comb_ssa # P(2,1,1) & North[1] V P(1,2,1) & East[1] <=> P[2,2,2] model = logic.pycoSAT(kb) print 'MODEL' print model if model: answer = extractActionSequence(model, ['North', 'South', 'East', 'West']) return answer # print 'answer' # print answer # if answer == []: # continue # else: # return answer else: next_states = [] for successor, actions_and_parents in list_of_successors.iteritems(): ns = (successor.getIndex()[0], successor.getIndex()[1]) # if case here to remove dupicate states if ns not in next_states: next_states.append(ns) kb.pop(0) # remove the goal constraint for this timeste[]
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e , w] width = problem.getWidth()+1 height = problem.getHeight()+1 #Starting State swag = problem.getStartState() startState = swag[0] ghostStartStateList = problem.getGhostStartStates() #Get positions of food foodGrid = swag[1] foodPosList = [] for x in range(width+1): for y in range(height+1): if foodGrid[x][y]: foodPosList.append((x,y)) pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x,y) == (startState[0], startState[1]): continue else: nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf(pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) stateList = [] for x in range(width+1): for y in range(height+1): if problem.isWall((x,y)): continue else: stateList.append((x,y)) for time in range(maxTime): oneStateList = [] for state in stateList: oneStateList.append(logic.PropSymbolExpr("P",state[0],state[1], time)) legalActionList = problem.actions((state, foodGrid)) illegalList = [] for action in DirectionsList: if action in legalActionList: nextState = problem.result((state, foodGrid), action)[0][0] # state & action >> new state nextLogic = (logic.PropSymbolExpr("P",state[0],state[1], time) & logic.PropSymbolExpr(action,time)) >> logic.PropSymbolExpr('P',nextState[0],nextState[1], time+1) cnf.append(logic.to_cnf(nextLogic)) else: illegalList.append(action) for action in illegalList: # state >> not illegal action cnf.append(logic.to_cnf(logic.PropSymbolExpr("P",state[0],state[1], time) >> ~logic.PropSymbolExpr(action,time))) # uses oneStateList, makes sure we are not in two places at once oneState = exactlyOne(oneStateList) cnf.append((oneState)) # Exactly 1 move per turn Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) oneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(oneMove)) # goal state (must hit each pellet once) foodAllEaten = [] for food in foodPosList: foodOnce = [] for alltime in range(time+1): foodOnce.append(logic.PropSymbolExpr('P',food[0],food[1],alltime)) atLeastOnce = logic.associate('|', foodOnce) foodAllEaten.append(atLeastOnce) goalLogic = logic.associate('&', foodAllEaten) cnf.append(goalLogic) #Pacman and Ghost not in same place def ghostPositionfinder(ghoststart, time): ghostposition = ghoststart x = ghoststart[0] y = ghoststart[1] East = True for t in range(time): if East == True: x += 1 if problem.isWall((x,y)): x -= 2 East = False elif East == False: x -= 1 if problem.isWall((x,y)): x += 2 East = True return (x,y) #logic.PropSymbolExpr("G", ghostPos[0], ghostPos[1], 0) for ghostStartState in ghostStartStateList: ghostPos = ghostStartState.getPosition() ghostCurrentPos = ghostPositionfinder(ghostPos, time) cnf.append(logic.PropSymbolExpr("G", ghostCurrentPos[0], ghostCurrentPos[1], time)) for pos in stateList: plsnodie = [logic.PropSymbolExpr("P",pos[0],pos[1],time)] + [logic.PropSymbolExpr("G",pos[0],pos[1],time)] cnf.append(atMostOne(plsnodie)) plsnodie = [logic.PropSymbolExpr("P",pos[0],pos[1],time)] + [logic.PropSymbolExpr("G",pos[0],pos[1],time-1)] cnf.append(atMostOne(plsnodie)) model = logic.pycoSAT(cnf) if model: path = extractActionSequence(model, DirectionsList) return path cnf.remove(goalLogic) print("you suck")
def foodGhostLogicPlan(problem): """ Given an instance of a FoodGhostSearchProblem, 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. """ "*** YOUR CODE HERE ***" def isValid(x,y): if (x<1) | x>problem.getWidth(): return False if problem.isWall((x,y)): return False return True for time in range(0, 50): exprs = [] start=problem.getStartState() ghostStates=problem.getGhostStartStates() pacman=start[0] food=start[1] exprs.append(logic.PropSymbolExpr("P",pacman[0],pacman[1],0)) allGhosts=[] ghostNumber=0 # for gx,gy,state in ghostStates.asList(): # for y in range(1,problem.getHeight()+1): # for t in time: # if y==gy: # exprs.append(logic.PropSymbolExpr("GY",ghostNumber,y,t)) # else: # exprs.append(~logic.PropSymbolExpr("GY",ghostNumber,y,t)) # for x in range(1,problem.getWidth()+1): # if x==gx: # exprs.append(logic.PropSymbolExpr("GX",ghostNumber,x,0)) # else: # exprs.append(~logic.PropSymbolExpr("GX",ghostNumber,x,0)) for location in ghostStates: # ghosts at certain states gx=location.getPosition()[0] gy=location.getPosition()[1] direction=logic.PropSymbolExpr("Gwest",ghostNumber,0) if(isValid(gx+1,gy)): exprs.append(~direction) else: exprs.append(direction) for y in range(1,problem.getHeight()+1): for x in range(1,problem.getWidth()+1): if (not problem.isWall((x,y))): if x==gx and y ==gy: exprs.append(logic.PropSymbolExpr("G"+str(ghostNumber),x,y,0)) else: a=logic.PropSymbolExpr("G"+str(ghostNumber),x,y,0) exprs.append(logic.Expr("~",a)) ghostNumber=ghostNumber+1 for t in range(0,time+1): exprs.append(logic.PropSymbolExpr("Alive",t)) #pacman is always alive for t in range(1,time+1): #meeting a ghost brings doom for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if (not problem.isWall((x,y))): alive =logic.PropSymbolExpr("Alive",t) was_alive=logic.PropSymbolExpr("Alive",t-1) pacman_here=logic.PropSymbolExpr("P",x,y,t) #| logic.PropSymbolExpr("P",x,y,t-1) ghostPresent=logic.PropSymbolExpr("False") for number in xrange(len(ghostStates)): ghost=logic.PropSymbolExpr("G"+str(number),x,y,t) | logic.PropSymbolExpr("G"+str(number),x,y,t-1) #if (isValid(x+1,y)): # ghost=ghost | (logic.PropSymbolExpr("G"+str(number),x+1,y,t) & logic.PropSymbolExpr("Gwest",number,t)) #if isValid(x-1,y): #ghost=ghost | (logic.PropSymbolExpr("G"+str(number),x-1,y,t) & ~logic.PropSymbolExpr("Gwest",number,t)) ghostPresent=ghostPresent | ghost appendToExprs(exprs, ~alive % (ghostPresent & pacman_here)) for t in range(1,time+1): for number in xrange(len(ghostStates)): west_walls=logic.PropSymbolExpr("False") east_walls=logic.PropSymbolExpr("False") for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): # y = ghostStates[number].getPosition()[1] #for y in range(1,problem.getHeight()+1): if(not problem.isWall((x,y))): ghost_here=logic.PropSymbolExpr("G"+str(number),x,y,t) ghost_direction=logic.PropSymbolExpr("Gwest",number,t-1) ghost_past=logic.Expr("False") if(isValid(x-1,y)): ghost_past = ghost_past | (logic.PropSymbolExpr("G"+str(number),x-1,y,t-1) & ~logic.PropSymbolExpr("Gwest",number,t-1)) else: west_walls= west_walls | logic.PropSymbolExpr("G"+str(number),x,y,t) #appendToExprs(exprs, logic.PropSymbolExpr("Gwest",number,t) % logic.PropSymbolExpr("Gwest",number,t-1) | (logic.PropSymbolExpr("G"+str(number),x,y,t) & ~logic.PropSymbolExpr("Gwest",number,t-1))) if(isValid(x+1,y)): ghost_past = ghost_past | (logic.PropSymbolExpr("G"+str(number),x+1,y,t-1) & logic.PropSymbolExpr("Gwest",number,t-1)) else: east_walls= east_walls | logic.PropSymbolExpr("G"+str(number),x,y,t) #appendToExprs(exprs,~logic.PropSymbolExpr("Gwest",number,t) % logic.PropSymbolExpr("Gwest",number, t-1) | (logic.PropSymbolExpr("G"+str(number),x,y,t) & logic.PropSymbolExpr("Gwest",number,t-1))) appendToExprs(exprs, ghost_here % ghost_past) west_now=logic.PropSymbolExpr("Gwest",number,t) west_before=logic.PropSymbolExpr("Gwest",number,t-1) appendToExprs(exprs, west_now % ((west_before & ~west_walls) | (~west_before & east_walls))) appendToExprs(exprs, ~west_now % ((~west_before & ~east_walls) | (west_before & west_walls))) for x,y in food.asList(): exprs.append(logic.PropSymbolExpr("F",x,y,0)) exprs.append(logic.Expr("~",logic.PropSymbolExpr("F",x,y,time))) for x,y in food.asList(): for t in range(1,time+1): pastFood=logic.PropSymbolExpr("F",x,y,t-1) currentFood=logic.PropSymbolExpr("F",x,y,t) pacmanHere=logic.PropSymbolExpr("P",x,y,t) isNotEaten=(~pastFood | (pastFood & pacmanHere)) appendToExprs(exprs,logic.Expr("<=>", ~currentFood, isNotEaten)) positions = [] for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if not problem.isWall((x,y)) and (x,y)!=pacman: positionSymbol = logic.Expr('~',logic.PropSymbolExpr("P",x,y,0)) exprs.append(positionSymbol) for t in range(0,time): northSymbol = logic.PropSymbolExpr("North", t) southSymbol = logic.PropSymbolExpr("South", t) westSymbol = logic.PropSymbolExpr("West", t) eastSymbol = logic.PropSymbolExpr("East", t) exactlyOneAction = exactlyOne([northSymbol, southSymbol, westSymbol, eastSymbol]) appendToExprs(exprs, exactlyOneAction) for t in range(1, time+1): for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if not problem.isWall((x,y)): actions = problem.actions(((x,y),food)) prevExprs = [] for action in actions: currentStatePropSymbolExpr = logic.PropSymbolExpr("P", x, y, t) prevState = () if action == 'North': action = 'South' prevState = (x,y+1) elif action == 'South': action = 'North' prevState = (x,y-1) elif action == 'West': action = 'East' prevState = (x-1,y) elif action == 'East': action = 'West' prevState = (x+1,y) actionPropSymbolExpr = logic.PropSymbolExpr(action, t-1) prevStatePropSymbolExpr = logic.PropSymbolExpr("P", prevState[0], prevState[1], t-1) prevExprs.append(logic.Expr("&", actionPropSymbolExpr, prevStatePropSymbolExpr)) prevExprsOrred = logic.Expr("|", *prevExprs) iff = logic.Expr("<=>", prevExprsOrred, currentStatePropSymbolExpr) appendToExprs(exprs, iff) result=False if DEBUG: pretty_print(exprs) pdb.set_trace() else: result = logic.pycoSAT(exprs) if result: return extractActionSequence(result, ["North", "South", "East", "West"]) print "QQ"
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ "*** YOUR CODE HERE ***" #manhattanDistance = util.manhattanDistance(problem.getStartState(), problem.getGoalState()) for time in range(0, 3000): exprs = [] start=problem.getStartState() pacman=start[0] food=start[1] exprs.append(logic.PropSymbolExpr("P",pacman[0],pacman[1],0)) for x,y in food.asList(): exprs.append(logic.PropSymbolExpr("F",x,y,0)) exprs.append(logic.Expr("~",logic.PropSymbolExpr("F",x,y,time))) #pdb.set_trace() for x,y in food.asList(): for t in range(1,time+1): pastFood=logic.PropSymbolExpr("F",x,y,t-1) currentFood=logic.PropSymbolExpr("F",x,y,t) pacmanHere=logic.PropSymbolExpr("P",x,y,t) isNotEaten=(~pastFood | (pastFood & pacmanHere)) appendToExprs(exprs,logic.Expr("<=>", ~currentFood, isNotEaten)) #pdb.set_trace() positions = [] for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if not problem.isWall((x,y)) and (x,y)!=pacman: positionSymbol = logic.Expr('~',logic.PropSymbolExpr("P",x,y,0)) exprs.append(positionSymbol) for t in range(0,time): northSymbol = logic.PropSymbolExpr("North", t) southSymbol = logic.PropSymbolExpr("South", t) westSymbol = logic.PropSymbolExpr("West", t) eastSymbol = logic.PropSymbolExpr("East", t) exactlyOneAction = exactlyOne([northSymbol, southSymbol, westSymbol, eastSymbol]) appendToExprs(exprs, exactlyOneAction) for t in range(1, time+1): for x in range(1,problem.getWidth()+1): for y in range(1,problem.getHeight()+1): if not problem.isWall((x,y)): actions = problem.actions(((x,y),food)) prevExprs = [] for action in actions: currentStatePropSymbolExpr = logic.PropSymbolExpr("P", x, y, t) prevState = () if action == 'North': action = 'South' prevState = (x,y+1) elif action == 'South': action = 'North' prevState = (x,y-1) elif action == 'West': action = 'East' prevState = (x-1,y) elif action == 'East': action = 'West' prevState = (x+1,y) actionPropSymbolExpr = logic.PropSymbolExpr(action, t-1) prevStatePropSymbolExpr = logic.PropSymbolExpr("P", prevState[0], prevState[1], t-1) prevExprs.append(logic.Expr("&", actionPropSymbolExpr, prevStatePropSymbolExpr)) prevExprsOrred = logic.Expr("|", *prevExprs) iff = logic.Expr("<=>", prevExprsOrred, currentStatePropSymbolExpr) appendToExprs(exprs, iff) result = logic.pycoSAT(exprs) if result: #pretty_print(result) return extractActionSequence(result, ["North", "South", "East", "West"])
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e, w] width = problem.getWidth() + 1 height = problem.getHeight() + 1 #Starting State swag = problem.getStartState() startState = swag[0] #Get positions of food foodGrid = swag[1] foodPosList = [] for x in range(width + 1): for y in range(height + 1): if foodGrid[x][y]: foodPosList.append((x, y)) pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x, y) == (startState[0], startState[1]): continue else: nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf( pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) stateList = [] for x in range(width + 1): for y in range(height + 1): if problem.isWall((x, y)): continue else: stateList.append((x, y)) for time in range(maxTime): #print time oneStateList = [] for state in stateList: oneStateList.append( logic.PropSymbolExpr("P", state[0], state[1], time)) legalActionList = problem.actions((state, foodGrid)) illegalList = [] for action in DirectionsList: if action in legalActionList: nextState = problem.result((state, foodGrid), action)[0][0] # state & action >> new state nextLogic = (logic.PropSymbolExpr( "P", state[0], state[1], time) & logic.PropSymbolExpr( action, time)) >> logic.PropSymbolExpr( 'P', nextState[0], nextState[1], time + 1) cnf.append(logic.to_cnf(nextLogic)) else: illegalList.append(action) for action in illegalList: # state >> not illegal action cnf.append( logic.to_cnf( logic.PropSymbolExpr("P", state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time))) # uses oneStateList, makes sure we are not in two places at once oneState = exactlyOne(oneStateList) cnf.append((oneState)) # Exactly 1 move per turn Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) oneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(oneMove)) # goal state (must hit each pellet once) foodAllEaten = [] for food in foodPosList: foodOnce = [] for alltime in range(time + 1): foodOnce.append( logic.PropSymbolExpr('P', food[0], food[1], alltime)) atLeastOnce = logic.associate('|', foodOnce) foodAllEaten.append(atLeastOnce) goalLogic = logic.associate('&', foodAllEaten) cnf.append(goalLogic) model = logic.pycoSAT(cnf) if model: path = extractActionSequence(model, DirectionsList) return path cnf.remove(goalLogic) print("you suck")
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_list = problem.getStartState()[1].asList() # print(food_list) actions = ['North', 'South', 'East', 'West'] final_cnf = [] loc_list = [] list_walls = walls.asList() for w in range(width + 1): for h in range(height + 1): if ((w, h) not in list_walls): loc_list.append((w, h)) else: pass final_list = [] food_con = [[] for n in range(len(food_list))] # print(food_con) final_list.append( logic.PropSymbolExpr(pacman_str, problem.getStartState()[0][0], problem.getStartState()[0][1], 0)) for i in range(50): for index, x in enumerate(food_list): food_con[index].append( logic.PropSymbolExpr(pacman_str, x[0], x[1], i)) ac_list = [ logic.PropSymbolExpr(actions[0], i), logic.PropSymbolExpr(actions[1], i), logic.PropSymbolExpr(actions[2], i), logic.PropSymbolExpr(actions[3], i) ] final_list.append(exactlyOne(ac_list)) pac_pos_list = [ logic.PropSymbolExpr(pacman_str, j[0], j[1], i) for j in loc_list ] final_list.append(exactlyOne(pac_pos_list)) food_disjoint = [] if (i != 0): for k in loc_list: final_list.append( pacmanSuccessorStateAxioms(k[0], k[1], i, walls)) else: pass for a in range(len(food_con)): food_disjoint.append(atLeastOne(food_con[a])) # print(food_disjoint) End_food_con = (logic.conjoin(food_disjoint)) cnf_s = logic.to_cnf(logic.conjoin(final_list)) final_cnf.append(cnf_s) if (logic.pycoSAT((logic.conjoin(final_cnf) & End_food_con)) == False): # if(i<3):print(logic.conjoin(final_list)) # print("pass") final_list = [] print(i) else: break # print("break") # print(food_con) # print(final_model) # print(final_express) # print(food_con) return extractActionSequence( logic.pycoSAT(logic.conjoin(final_cnf) & End_food_con), actions) # return extractActionSequence (final_model, actions) "*** YOUR CODE HERE ***" util.raiseNotDefined()
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" cnf = [] maxTime = 51 n = Directions.NORTH s = Directions.SOUTH e = Directions.EAST w = Directions.WEST DirectionsList = [n, s, e, w] width = problem.getWidth() + 1 height = problem.getHeight() + 1 #Starting State startState = problem.getStartState() pacmanStart = logic.PropSymbolExpr("P", startState[0], startState[1], 0) nonStartStates = [] for x in range(1, width): for y in range(1, height): if (x, y) == (startState[0], startState[1]): continue else: nonStartStates.append(logic.PropSymbolExpr("P", x, y, 0)) startLogic = logic.to_cnf( pacmanStart & ~(logic.associate('|', nonStartStates))) cnf.append(startLogic) goalState = problem.getGoalState() stateList = [] for x in range(width + 1): for y in range(height + 1): if problem.isWall((x, y)): continue else: stateList.append((x, y)) for time in range(maxTime): oneStateList = [] for state in stateList: oneStateList.append( logic.PropSymbolExpr("P", state[0], state[1], time)) legalActionList = problem.actions(state) illegalList = [] for action in DirectionsList: if action in legalActionList: nextState = problem.result(state, action)[0] # state & action >> new state nextLogic = (logic.PropSymbolExpr( "P", state[0], state[1], time) & logic.PropSymbolExpr( action, time)) >> logic.PropSymbolExpr( 'P', nextState[0], nextState[1], time + 1) cnf.append(logic.to_cnf(nextLogic)) else: illegalList.append(action) for action in illegalList: # state >> not illegal action cnf.append( logic.to_cnf( logic.PropSymbolExpr('P', state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time))) # uses oneStateList, makes sure we are not in two places at once oneState = exactlyOne(oneStateList) cnf.append((oneState)) # Exactly 1 move per turn Dir = [] for direction in DirectionsList: Dir.append(logic.PropSymbolExpr(direction, time)) oneMove = exactlyOne(Dir) cnf.append(logic.to_cnf(oneMove)) # goal state cnf.append(logic.PropSymbolExpr("P", goalState[0], goalState[1], time)) #print time model = logic.pycoSAT(cnf) if model: path = extractActionSequence(model, DirectionsList) return path cnf.remove(logic.PropSymbolExpr("P", goalState[0], goalState[1], time))
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() ghosts = problem.getGhostStartStates() ghost_positions = [] ghost_rows = [] for ghost in ghosts: p = ghost.getPosition() ghost_positions.append(p) ghost_rows.append(p[1]) ghost_num = len(ghost_positions) MAX_TIME_STEP = 50 actions = ['North', 'East', 'South', 'West'] initial_state = problem.getStartState() # Pacman's initial location pacman_initial_location = initial_state[0] # Food locations food_locations = initial_state[1].asList() # GET THE BLOCKED POSITIONS TO PASS INTO GHOST DIRECTION SSA blocked_east_positions = [] blocked_west_positions = [] wall = walls.asList() # ble = problem.walls.asList() for x in range(0, width + 2): for y in range(0, height + 1): if (x, y) in wall: if (x + 1, y) not in wall: if x <= width: blocked_west_positions.append((x + 1, y)) if (x - 1, y) not in wall: if x > 0: blocked_east_positions.append((x - 1, y)) i = 0 ghost_init = [] ghost1pos = [] ghost2pos = [] expression = list() for x in range(1, width + 1): for y in range(1, height + 1): if (x, y) == pacman_initial_location: e = 0 while e != ghost_num: if ghost2pos: ghost2pos = ghost2pos & ~logic.PropSymbolExpr( ghost_pos_str + str(e), x, y, 0) else: ~logic.PropSymbolExpr(ghost_pos_str + str(e), x, y, 0) e += 1 if expression: # v = expression.pop() expression = expression & logic.PropSymbolExpr( "P", x, y, 0) else: expression = logic.PropSymbolExpr("P", x, y, 0) if (x, y) in ghost_positions: east_str = ghost_east_str + str(i) j = 0 while j != ghost_num: if j != i: if ghost2pos: ghost2pos = ghost2pos & ~logic.PropSymbolExpr( ghost_pos_str + str(j), x, y, 0) else: ghost2pos = ~logic.PropSymbolExpr( ghost_pos_str + str(j), x, y, 0) j += 1 if (x, y) in blocked_east_positions: if ghost_init: # u = ghost_init.pop() # r = ghost1pos.pop() ghost_init = ghost_init & ~logic.PropSymbolExpr( east_str, 0) ghost1pos = ghost1pos & logic.PropSymbolExpr( ghost_pos_str + str(i), x, y, 0) i += 1 else: ghost_init = ~logic.PropSymbolExpr(east_str, 0) ghost1pos = logic.PropSymbolExpr( ghost_pos_str + str(i), x, y, 0) i += 1 else: if ghost_init: # u = ghost_init.pop() # r = ghost1pos.pop() ghost_init = ghost_init & logic.PropSymbolExpr( east_str, 0) ghost1pos = ghost1pos & logic.PropSymbolExpr( ghost_pos_str + str(i), x, y, 0) i += 1 else: ghost_init = logic.PropSymbolExpr(east_str, 0) ghost1pos = logic.PropSymbolExpr( ghost_pos_str + str(i), x, y, 0) i += 1 if (x, y) != pacman_initial_location: if (x, y) not in ghost_positions: e = 0 while e != ghost_num: if ghost2pos: ghost2pos = ghost2pos & ~logic.PropSymbolExpr( ghost_pos_str + str(e), x, y, 0) else: ghost2pos = ~logic.PropSymbolExpr( ghost_pos_str + str(e), x, y, 0) e += 1 if expression: # v = expression.pop() expression = expression & logic.Expr( "~", logic.PropSymbolExpr("P", x, y, 0)) else: expression = logic.Expr("~", logic.PropSymbolExpr("P", x, y, 0)) # not_ghost = logic.conjoin(ghost2pos) initial = expression & ghost_init & ghost1pos & ghost2pos pacman_ssa = [] pacman_alive_ssa = [] ghost_position_ssa = [] ghost_direction_ssa = [] only_one_action = [] for t in range(MAX_TIME_STEP): if t > 0: once = True for x in range(1, width + 1): for y in range(1, height + 1): if not walls[x][y]: pacman_ssa += [ pacmanSuccessorStateAxioms(x, y, t, walls) ] if y in ghost_rows: pacman_alive_ssa += [ pacmanAliveSuccessorStateAxioms( x, y, t, ghost_num) ] i = 0 while i != ghost_num: if once: ghost_direction_ssa += [ ghostDirectionSuccessorStateAxioms( t, i, blocked_west_positions, blocked_east_positions) ] ghost_position_ssa += [ ghostPositionSuccessorStateAxioms( x, y, t, i, walls) ] i += 1 once = False # ADD GHOST_DIRECTION_SSA i = 0 # CONJOIN PACMAN_SSA pacman_ssa_conjoined = logic.conjoin(pacman_ssa) # CONJOIN PACMAN_ALIVE_SSA pacman_alive_ssa_conjoined = logic.conjoin(pacman_alive_ssa) # CONJOIN GHOST_POSITION_SSA ghost_position_ssa_conjoined = logic.conjoin(ghost_position_ssa) # CONJOIN GHOST_DIRECTION_SSA ghost_direction_ssa_conjoined = logic.conjoin(ghost_direction_ssa) # MAKES SURE ONLY ONE ACTION IS TAKEN possible_actions = [] one_action = [] for action in actions: #exclusion axioms possible_actions.append(logic.PropSymbolExpr(action, t - 1)) one_action = exactlyOne(possible_actions) only_one_action.append(one_action) only_one_action_conjoined = logic.conjoin(only_one_action) # FIND OUT IF ALL THE FOOD HAS BEEN EATEN AS A GOAL TEST food_locations_eaten = list() for food_particle in food_locations: food_particles = list() for i in range(0, t + 1): food_particles.append( logic.PropSymbolExpr("P", food_particle[0], food_particle[1], i)) food_particles = logic.disjoin(food_particles) food_locations_eaten.append(food_particles) food_locations_eaten = logic.conjoin(food_locations_eaten) # PACMAN IS ALIVE AT TIME T pacman_alive = logic.to_cnf( logic.PropSymbolExpr(pacman_alive_str, t)) initial = logic.to_cnf(initial) food_locations_eaten = logic.to_cnf(food_locations_eaten) only_one_action_conjoined = logic.to_cnf(only_one_action_conjoined) pacman_ssa_conjoined = logic.to_cnf(pacman_ssa_conjoined) pacman_alive_ssa_conjoined = logic.to_cnf( pacman_alive_ssa_conjoined) ghost_position_ssa_conjoined = logic.to_cnf( ghost_position_ssa_conjoined) ghost_direction_ssa_conjoined = logic.to_cnf( ghost_direction_ssa_conjoined) j = logic.pycoSAT(pacman_alive & initial & food_locations_eaten & only_one_action_conjoined & pacman_ssa_conjoined & pacman_alive_ssa_conjoined & ghost_position_ssa_conjoined & ghost_direction_ssa_conjoined) else: food_locations_eaten = list() for food_particle in food_locations: food_locations_eaten.append( logic.PropSymbolExpr("P", food_particle[0], food_particle[1], 0)) food_locations_eaten = logic.conjoin(food_locations_eaten) j = logic.pycoSAT(logic.conjoin(initial, food_locations_eaten)) if j is not False: # for key, val in j.items(): # if val: # print key return extractActionSequence(j, actions) return None
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" start = problem.getStartState() goal = problem.getGoalState() allActions = ['North', 'South', 'East', 'West'] expr = [] states = [] for i in range(1, problem.getWidth() + 1): for j in range(1, problem.getHeight() + 1): if not problem.isWall((i, j)): states.append((i, j)) startingConstraint = logic.PropSymbolExpr("P", start[0], start[1], 0) for state in states: if state != start: startingConstraint = startingConstraint & ~logic.PropSymbolExpr( "P", state[0], state[1], 0) expr.append(startingConstraint) for t in range(1, 50): allStateSymbols = [] sentences = [] allActionSymbols = [] goalConstraint = logic.PropSymbolExpr("P", goal[0], goal[1], t) for action in allActions: actionSymbol = logic.PropSymbolExpr(action, t) allStateSymbols.append(actionSymbol) oneAction = exactlyOne(allStateSymbols) sentences.append(logic.to_cnf(oneAction)) for state in states: stateSymbol = logic.PropSymbolExpr("P", state[0], state[1], t) allStateSymbols.append(stateSymbol) actions = problem.actions(state) for action in allActions: if action in actions: actionSymbol = logic.PropSymbolExpr(action, t) result = problem.result(state, action) resultSymbol = logic.PropSymbolExpr( "P", result[0][0], result[0][1], t + 1) constraint = (stateSymbol & actionSymbol) >> resultSymbol sentences.append(logic.to_cnf(constraint)) else: actionSymbol = logic.PropSymbolExpr(action, t) constraint = stateSymbol >> ~actionSymbol sentences.append(logic.to_cnf(constraint)) if state != goal: goalConstraint = goalConstraint & ~stateSymbol oneState = exactlyOne(allStateSymbols) sentences.append(logic.to_cnf(oneState)) sentences.append(logic.to_cnf(goalConstraint)) expr += sentences model = logic.pycoSAT(expr) if model != False: print model return extractActionSequence(model, allActions) else: expr.remove(logic.to_cnf(goalConstraint))
def foodLogicPlan(problem): """ Given an instance of a FoodSearchProblem, 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. """ "*** YOUR CODE HERE ***" startState = problem.getStartState() Directions = ['North', 'South', 'East', 'West'] width = problem.getWidth() height = problem.getHeight() foodGrid = startState[1] allStates = [] foodSpots = [] for x in xrange(width + 1): for y in xrange(height + 1): if not problem.isWall((x, y)): allStates.append((x, y)) if foodGrid[x][y]: foodSpots.append((x, y)) max_time = 51 for time_limit in xrange(len(foodSpots), max_time): cnfList = [] for currentState in allStates: actions = problem.actions((currentState, foodGrid)) for action in actions: for time in xrange(time_limit): nextState = problem.result((currentState, foodGrid), action)[0] expr_and = logic.PropSymbolExpr( 'P', currentState[0], currentState[1], time) & logic.PropSymbolExpr(action, time) expression = expr_and >> logic.PropSymbolExpr( 'P', nextState[0][0], nextState[0][1], time + 1) # state + action > new state cnfList.append(logic.to_cnf(expression)) for action in list(set(Directions) - set(actions)): for time in xrange(time_limit): # state > not action cnfList.append( logic.to_cnf( logic.PropSymbolExpr('P', currentState[0], currentState[1], time) >> ~logic.PropSymbolExpr(action, time))) # start at startState cnfList.append( logic.PropSymbolExpr('P', startState[0][0], startState[0][1], 0)) # must make one move each turn for time in xrange(time_limit): cnfList.append( exactlyOne([ logic.PropSymbolExpr(action, time) for action in Directions ])) # not in two places at once for time in xrange(time_limit): cnfList.append( exactlyOne([ logic.PropSymbolExpr('P', state[0], state[1], time) for state in allStates ])) # hit at least each pellet once for food in foodSpots: cnfList.append( atLeastOne([ logic.PropSymbolExpr('P', food[0], food[1], time) for time in xrange(time_limit) ])) model = logic.pycoSAT(cnfList) if model: path = extractActionSequence(model, Directions) return path
def positionLogicPlan(problem): """ Given an instance of a PositionSearchProblem, 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. """ "*** YOUR CODE HERE ***" startState = problem.getStartState() goalState = problem.getGoalState() Directions = ['North', 'South', 'East', 'West'] width = problem.getWidth() height = problem.getHeight() allStates = [] for x in xrange(width + 1): for y in xrange(height + 1): if not problem.isWall((x, y)): allStates.append((x, y)) for count in xrange(util.manhattanDistance(startState, goalState), 51): cnfList = [] for time in xrange(count + 1): for state in allStates: actions = problem.actions(state) for action in actions: nextState = problem.result(state, action)[0] # state + action > new state expr_and = logic.PropSymbolExpr( 'P', state[0], state[1], time) & logic.PropSymbolExpr( action, time) expression = expr_and >> logic.PropSymbolExpr( 'P', nextState[0], nextState[1], time + 1) cnfList.append(logic.to_cnf(expression)) # not in two places at once for time in xrange(count + 1): cnfList.append( exactlyOne([ logic.PropSymbolExpr('P', state[0], state[1], time) for state in allStates ])) # must make one move each turn for time in xrange(count): cnfList.append( exactlyOne([ logic.PropSymbolExpr(action, time) for action in Directions ])) # no going back on path for state in allStates: cnfList.append( atMostOne([ logic.PropSymbolExpr('P', state[0], state[1], time) for time in xrange(count + 1) ])) # start at startState cnfList.append( logic.PropSymbolExpr('P', startState[0], startState[1], 0)) # goal state cnfList.append( logic.PropSymbolExpr('P', goalState[0], goalState[1], count)) # no illegal moves for state in allStates: for action in list(set(Directions) - set(problem.actions(state))): for time in xrange(count + 1): # state > not action cnfList.append( logic.to_cnf( logic.PropSymbolExpr('P', state[0], state[1], time) >> ~logic.PropSymbolExpr(action, time))) model = logic.pycoSAT(cnfList) if model: path = extractActionSequence(model, Directions) return path
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 FoodGhostSearchProblem, 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. """ "*** YOUR CODE HERE ***" startState = problem.getStartState() Directions = ['North', 'South', 'East', 'West'] width = problem.getWidth() height = problem.getHeight() foodGrid = startState[1] allStates = [] foodSpots = [] for x in xrange(width + 1): for y in xrange(height + 1): if not problem.isWall((x, y)): allStates.append((x, y)) if foodGrid[x][y]: foodSpots.append((x, y)) max_time = 51 for time_limit in xrange(len(foodSpots), max_time): cnfList = [] for currentState in allStates: actions = problem.actions((currentState, foodGrid)) for action in actions: for time in xrange(time_limit): nextState = problem.result((currentState, foodGrid), action)[0] expr_and = logic.PropSymbolExpr( 'P', currentState[0], currentState[1], time) & logic.PropSymbolExpr(action, time) expression = expr_and >> logic.PropSymbolExpr( 'P', nextState[0][0], nextState[0][1], time + 1) # state + action > new state cnfList.append(logic.to_cnf(expression)) for action in list(set(Directions) - set(actions)): for time in xrange(time_limit): # state > not action cnfList.append( logic.to_cnf( logic.PropSymbolExpr('P', currentState[0], currentState[1], time) >> ~logic.PropSymbolExpr(action, time))) # pacman start at startState cnfList.append( logic.PropSymbolExpr('P', startState[0][0], startState[0][1], 0)) # must make one move each turn for time in xrange(time_limit): cnfList.append( exactlyOne([ logic.PropSymbolExpr(action, time) for action in Directions ])) # not in two places at once for time in xrange(time_limit): cnfList.append( exactlyOne([ logic.PropSymbolExpr('P', state[0], state[1], time) for state in allStates ])) # hit at least each pellet once for food in foodSpots: cnfList.append( atLeastOne([ logic.PropSymbolExpr('P', food[0], food[1], time) for time in xrange(time_limit) ])) for index in xrange(len(problem.getGhostStartStates())): #ghost start state ghostStartState = problem.getGhostStartStates()[index] ghostPos = ghostStartState.getPosition() cnfList.append( logic.PropSymbolExpr('G' + str(index), ghostPos[0], ghostPos[1], 0)) # if no wall east, go east if not problem.isWall((ghostPos[0] + 1, ghostPos[1])): cnfList.append( logic.PropSymbolExpr('G' + str(index), ghostPos[0] + 1, ghostPos[1], 1)) else: cnfList.append( logic.PropSymbolExpr('G' + str(index), ghostPos[0] - 1, ghostPos[1], 1)) # get all ghost positions allGhostPos = [] ghostPosY = ghostPos[1] w = ghostPos[0] while (not problem.isWall((w, ghostPosY))): allGhostPos.append((w, ghostPosY)) w = w - 1 w = ghostPos[0] + 1 while (not problem.isWall((w, ghostPosY))): allGhostPos.append((w, ghostPosY)) w = w + 1 # ghost actions for time in xrange(1, time_limit + 2): for pos in allGhostPos: toEast = (pos[0] + 1, pos[1]) toWest = (pos[0] - 1, pos[1]) if problem.isWall(toWest): logic_symbol = logic.PropSymbolExpr( 'G' + str(index), pos[0], pos[1], time) >> logic.PropSymbolExpr( 'G' + str(index), pos[0] + 1, pos[1], time + 1) cnfList.append(logic.to_cnf(logic_symbol)) # cant go east elif problem.isWall(toEast): cnfList.append( logic.to_cnf( logic.PropSymbolExpr('G' + str(index), pos[0], pos[1], time) >> logic.PropSymbolExpr('G' + str(index), pos[0] - 1, pos[1], time + 1))) # can go either else: if (time != 0): expr_and = logic.PropSymbolExpr( 'G' + str(index), pos[0] - 1, pos[1], time - 1) & logic.PropSymbolExpr( 'G' + str(index), pos[0], pos[1], time) expr_implies = expr_and >> logic.PropSymbolExpr( 'G' + str(index), pos[0] + 1, pos[1], time + 1) cnfList.append(logic.to_cnf(expr_implies)) expr_and = logic.PropSymbolExpr( 'G' + str(index), pos[0] + 1, pos[1], time - 1) & logic.PropSymbolExpr( 'G' + str(index), pos[0], pos[1], time) expr_implies = expr_and >> logic.PropSymbolExpr( 'G' + str(index), pos[0] - 1, pos[1], time + 1) cnfList.append(logic.to_cnf(expr_implies)) # pacman and ghost cant be in same state for time in xrange(time_limit - 1): for pos in allGhostPos: temp = [ logic.PropSymbolExpr('P', pos[0], pos[1], time + 1) ] temp += [ logic.PropSymbolExpr('G' + str(index), pos[0], pos[1], time) ] cnfList.append(atMostOne(temp)) temp = [logic.PropSymbolExpr('P', pos[0], pos[1], time)] temp += [ logic.PropSymbolExpr('G' + str(index), pos[0], pos[1], time) ] cnfList.append(atMostOne(temp)) model = logic.pycoSAT(cnfList) if model: path = extractActionSequence(model, Directions) return path