Beispiel #1
0
def sentence3():
    """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0],
    created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr
    instance that encodes the following English sentences (in this order):

    The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was
    not killed at time 0 or it was not alive and time 0 and it was born at time 0.

    The Wumpus cannot both be alive at time 0 and be born at time 0.

    The Wumpus is born at time 0.
    """
    "*** YOUR CODE HERE ***"
    #know the use of the PropSymbolExpr from logic.py
    Alive_1 = logic.PropSymbolExpr("WumpusAlive", 1)
    #print (Alive_1)
    Alive_0 = logic.PropSymbolExpr("WumpusAlive", 0)
    Born_0 = logic.PropSymbolExpr("WumpusBorn", 0)
    Killed_0 = logic.PropSymbolExpr("WumpusKilled", 0)
    One = Alive_1 % logic.disjoin(logic.conjoin(Alive_0, ~Killed_0),
                                  logic.conjoin(~Alive_0, Born_0))
    Two = ~logic.conjoin(Alive_0, Born_0)
    Three = Born_0
    return logic.conjoin(One, Two, Three)
    util.raiseNotDefined()
Beispiel #2
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 []
Beispiel #3
0
def getFoodSentence(startState, action_delata, walls):
    s = util.Queue()
    visited = set()
    startPosition, startFoodGrid = startState
    StartExpr = logic.PropSymbolExpr(pacman_str, startPosition[0],
                                     startPosition[1], 0)
    s.push((startState, 0, StartExpr))
    while not s.isEmpty():
        curState, t, sentence = s.pop()
        curPosition, curFoodGrid = curState
        if (curFoodGrid.count() == 0):
            return sentence
        if curState in visited:
            continue
        visited.add(curState)
        for action, v in action_delata.items():
            nextPosition = (curPosition[0] + v[0], curPosition[1] + v[1])
            nextFoodGrid = curFoodGrid.copy()
            if nextFoodGrid[nextPosition[0]][nextPosition[1]]:
                nextFoodGrid[nextPosition[0]][nextPosition[1]] = False
            nextState = (nextPosition, nextFoodGrid)
            Action_expr = logic.PropSymbolExpr(action, t)
            Position_expr = logic.PropSymbolExpr(pacman_str, nextPosition[0],
                                                 nextPosition[1], t + 1)
            nextSentence = logic.conjoin(
                [sentence, Action_expr, Position_expr])
            if not walls[nextPosition[0]][nextPosition[1]]:
                s.push((nextState, t + 1, nextSentence))
Beispiel #4
0
def pacmanAliveSuccessorStateAxioms(x, y, t, num_ghosts):
    """
    Successor state axiom for patrolling ghost state (x,y,t) (from t-1).
    Current <==> (causes to stay) | (causes of current)
    """
    ghost_strs = [
        ghost_pos_str + str(ghost_num) for ghost_num in xrange(num_ghosts)
    ]

    "*** YOUR CODE HERE ***"

    no_ghost = []

    for ghost in ghost_strs:
        ghost_position_before = ~logic.PropSymbolExpr(ghost, x, y, t - 1)
        no_ghost.append(ghost_position_before)
        ghost_position_now = ~logic.PropSymbolExpr(ghost, x, y, t)
        no_ghost.append(ghost_position_now)

    no_ghost_here = logic.conjoin(no_ghost)
    ghost_exists = ~(logic.conjoin(no_ghost))
    pacman_alive_prev = logic.PropSymbolExpr(pacman_alive_str, t - 1)
    pacman_not_there = ~logic.PropSymbolExpr(pacman_str, x, y, t)

    return logic.PropSymbolExpr(pacman_alive_str, t) % (pacman_alive_prev & (
        (no_ghost_here) | (ghost_exists & pacman_not_there)))
Beispiel #5
0
def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions,
                                       blocked_east_positions):
    """
    Successor state axiom for patrolling ghost direction state (t) (from t-1).
    west or east walls.
    Current <==> (causes to stay) | (causes of current)
    """
    pos_str = ghost_pos_str + str(ghost_num)
    east_str = ghost_east_str + str(ghost_num)

    "*** YOUR CODE HERE ***"

    west_action = ~(logic.PropSymbolExpr(east_str, t - 1))
    east_action = logic.PropSymbolExpr(east_str, t - 1)

    west_list = []
    east_list = []

    for pos in blocked_east_positions:
        x, y = pos
        not_blocked_east = ~logic.PropSymbolExpr(pos_str, x, y, t)
        lst = logic.conjoin(east_action, not_blocked_east)
        east_list.append(lst)

    for pos in blocked_west_positions:
        x, y = pos
        blocked_west = logic.PropSymbolExpr(pos_str, x, y, t)
        lst = logic.conjoin(west_action, blocked_west)
        west_list.append(lst)

    east_list = logic.conjoin(east_list)
    west_list = logic.disjoin(west_list)

    return logic.PropSymbolExpr(east_str, t) % logic.disjoin(
        east_list, west_list)
Beispiel #6
0
def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions,
                                       blocked_east_positions):
    """
    Successor state axiom for patrolling ghost direction state (t) (from t-1).
    west or east walls.
    Current <==> (causes to stay) | (causes of current)
    """
    pos_str = ghost_pos_str + str(ghost_num)
    east_str = ghost_east_str + str(ghost_num)
    move = logic.PropSymbolExpr(east_str, t - 1)
    moveT = logic.PropSymbolExpr(east_str, t)
    west_not_block = []
    condition = []
    for position in blocked_west_positions:
        west_not_block += [
            ~logic.PropSymbolExpr(pos_str, position[0], position[1], t)
        ]
    west_not_block = logic.conjoin(west_not_block)
    east_not_block = []
    for position in blocked_east_positions:
        east_not_block += [
            ~logic.PropSymbolExpr(pos_str, position[0], position[1], t)
        ]
    east_not_block = logic.conjoin(east_not_block)
    if t == 0:
        return east_not_block % moveT
    return moveT % ((move & east_not_block) |
                    (~west_not_block & east_not_block) |
                    (~west_not_block & ~east_not_block & ~move))
Beispiel #7
0
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"

    def noWallHere(coord):
        return not walls_grid[coord[0]][coord[1]]

    listPrev = []
    directions = ["East", "West", "South", "North"]
    at = [(x - 1, y), (x + 1, y), (x, y + 1), (x, y - 1)]
    for i in xrange(len(directions)):
        direc = directions[i]
        coord = at[i]
        if noWallHere(coord):
            prevAtHere = logic.PropSymbolExpr(pacman_str, coord[0], coord[1],
                                              t - 1)
            prevGoThere = logic.PropSymbolExpr(direc, t - 1)
            listPrev.append(logic.conjoin(prevAtHere, prevGoThere))

    pacmanNow = logic.PropSymbolExpr(pacman_str, x, y, t)

    return pacmanNow % logic.disjoin(i for i in listPrev)
Beispiel #8
0
def sentence3():
    """Using the symbols WumpusAlive[1], WumpusAlive[0], WumpusBorn[0], and WumpusKilled[0],
    created using the logic.PropSymbolExpr constructor, return a logic.PropSymbolExpr
    instance that encodes the following English sentences (in this order):

    The Wumpus is alive at time 1 if and only if the Wumpus was alive at time 0 and it was
    not killed at time 0 or it was not alive and time 0 and it was born at time 0.

    The Wumpus cannot both be alive at time 0 and be born at time 0.

    The Wumpus is born at time 0.
    """
    "*** YOUR CODE HERE ***"
    WumpusAlive_1 = logic.PropSymbolExpr("WumpusAlive", 1)
    WumpusAlive_0 = logic.PropSymbolExpr("WumpusAlive", 0)
    WumpusBorn_0 = logic.PropSymbolExpr("WumpusBorn", 0)
    WumpusKilled_0 = logic.PropSymbolExpr("WumpusKilled", 0)

    clause_one = WumpusAlive_1 % ((WumpusAlive_0 & (~WumpusKilled_0)) | \
                ((~WumpusAlive_0) & WumpusBorn_0) )
    clause_two = ~(WumpusAlive_0 & WumpusBorn_0)
    clause_three = WumpusBorn_0

    instance = logic.conjoin(clause_one, clause_two, clause_three)

    return instance
def ghostDirectionSuccessorStateAxioms(t, ghost_num, blocked_west_positions,
                                       blocked_east_positions):
    """
    Successor state axiom for patrolling ghost direction state (t) (from t-1).
    west or east walls.
    Current <==> (causes to stay) | (causes of current)
    """
    pos_str = ghost_pos_str + str(ghost_num)
    east_str = ghost_east_str + str(ghost_num)
    west_positions = list()
    east_positions = list()
    blocked_west_positions_copy = blocked_west_positions[:]
    blocked_east_positions_copy = blocked_east_positions[:]

    while blocked_west_positions_copy:
        position = blocked_west_positions_copy.pop()
        west_positions.append(
            logic.PropSymbolExpr(pos_str, position[0], position[1], t))

    while blocked_east_positions_copy:
        position = blocked_east_positions_copy.pop()
        east_positions.append(
            logic.PropSymbolExpr(pos_str, position[0], position[1], t))

    west_positions = logic.disjoin(west_positions)
    east_positions = logic.disjoin(east_positions)

    conditions = (west_positions & ~logic.PropSymbolExpr(east_str, t - 1)) | (
        ~east_positions & logic.PropSymbolExpr(east_str, t - 1))
    final_axiom = logic.PropSymbolExpr(east_str, t) % conditions

    return final_axiom
Beispiel #10
0
def get_ghost_axioms(locations, time):
    axioms = []
    for location in locations:
        axioms.append(
            ~logic.PropSymbolExpr('P', location[0], location[1], time))
        axioms.append(
            ~logic.PropSymbolExpr('P', location[0], location[1], time + 1))
    return axioms
def positionLogicPlan(problem):
    """
    Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    walls = problem.walls
    width, height = problem.getWidth(), problem.getHeight()
    MAX_TIME = 50
    start_pos = problem.getStartState()
    goal_pos = problem.getGoalState()
    actions = ['North', 'South', 'East', 'West']

    # pacman can only start at one position (with this and other constarin, there is no need to generate knowledge that pacman can not in two place at one time)
    start_one_list = []
    for x in range(1, width + 1):
        for y in range(1, height + 1):
            if (x, y) != start_pos:
                start_one_list.append(
                    ~logic.PropSymbolExpr(pacman_str, x, y, 0))

    start_one = logic.conjoin(start_one_list)

    #pacman start state
    start_state = logic.PropSymbolExpr(pacman_str, start_pos[0], start_pos[1],
                                       0)

    #pacman is in start_pos and not in any other position
    start = logic.conjoin(start_state, start_one)

    one_action_list = []
    transition_list = []
    #update knowledge base through time
    for t in range(1, MAX_TIME + 1):
        goal = logic.PropSymbolExpr(pacman_str, goal_pos[0], goal_pos[1], t)
        #can only take one action to get to current state
        temp = []
        for action in actions:
            one = logic.PropSymbolExpr(action, t - 1)
            temp.append(one)
        step_one_action = exactlyOne(temp)
        one_action_list.append(step_one_action)

        for x in range(1, width + 1):
            for y in range(1, height + 1):
                if not walls[x][y]:
                    transition_list.append(
                        pacmanSuccessorStateAxioms(x, y, t, walls))

        one_action = logic.conjoin(one_action_list)
        one_action_list = [one_action]
        transition = logic.conjoin(transition_list)
        transition_list = [transition]

        result = findModel(logic.conjoin(start, one_action, transition, goal))

        if result is not False:
            return extractActionSequence(result, actions)
Beispiel #12
0
def foodLogicPlan(problem):
    """
    Given an instance of a FoodPlanningProblem, return a list of actions that help Pacman
    eat all of the food.
    Available actions are ['North', 'East', 'South', 'West']
    Note that STOP is not an available action.

    P[X,Y,Z,t] Z:food number
    """

    walls = problem.walls
    w, h = problem.getWidth(), problem.getHeight()
    (x0, y0), food = problem.start
    foodList = food.asList()

    print("foodList", foodList)
    cond = None

    for max in range(1, 50):
        if (len(foodList) == 0):
            return []
        lg = logic.PropSymbolExpr(pacman_str, x0, y0, 50 - max)

        if cond == None:
            cond = logic.to_cnf(precond(problem, max))
            lg = lg & cond
        else:
            cond = cond & logic.to_cnf(precond(problem, max))
            lg = logic.conjoin([lg, cond])
        #print(lg)

        print(max)

        for t in range(50 - max + 1, 51):
            for x in range(1, w + 1):
                for y in range(1, h + 1):
                    if (not walls[x][y]):
                        axiom = pacmanSuccessorStateAxioms(x, y, t, walls)
                        lg = lg & logic.to_cnf(axiom)
        #print(lg)
        for f in foodList:
            tmp = []
            for t in range(50 - max, 50):
                tmp.append(logic.PropSymbolExpr(pacman_str, f[0], f[1], t))
            if len(tmp) != 0:
                lg = lg & atLeastOne(tmp)

        res = findModel(lg)
        #print("res: ", res, "\n")

        if res != False:
            print(
                "actions:",
                extractActionSequence(res, ['North', 'East', 'South', 'West']))
            return extractActionSequence(res,
                                         ['North', 'East', 'South', 'West'])
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a 
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"
    current_pos = logic.PropSymbolExpr(pacman_str, x, y, t)
    pre = []

    if not walls_grid[x][y - 1]:
        pre_pos = logic.PropSymbolExpr(pacman_str, x, y - 1, t - 1)
        move = logic.PropSymbolExpr("North", t - 1)
        pre.append(move & pre_pos)

    if not walls_grid[x][y + 1]:
        pre_pos = logic.PropSymbolExpr(pacman_str, x, y + 1, t - 1)
        move = logic.PropSymbolExpr("South", t - 1)
        pre.append(move & pre_pos)

    if not walls_grid[x - 1][y]:
        pre_pos = logic.PropSymbolExpr(pacman_str, x - 1, y, t - 1)
        move = logic.PropSymbolExpr("East", t - 1)
        pre.append(move & pre_pos)

    if not walls_grid[x + 1][y]:
        pre_pos = logic.PropSymbolExpr(pacman_str, x + 1, y, t - 1)
        move = logic.PropSymbolExpr("West", t - 1)
        pre.append(move & pre_pos)

    all_pre = logic.disjoin(pre)
    return current_pos % all_pre
Beispiel #14
0
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a 
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    moves = []
    if not walls_grid[x + 1][y]:
        moves.append(
            logic.PropSymbolExpr(pacman_str, x + 1, y, t - 1)
            & logic.PropSymbolExpr('West', t - 1))
    if not walls_grid[x - 1][y]:
        moves.append(
            logic.PropSymbolExpr(pacman_str, x - 1, y, t - 1)
            & logic.PropSymbolExpr('East', t - 1))
    if not walls_grid[x][y + 1]:
        moves.append(
            logic.PropSymbolExpr(pacman_str, x, y + 1, t - 1)
            & logic.PropSymbolExpr('South', t - 1))
    if not walls_grid[x][y - 1]:
        moves.append(
            logic.PropSymbolExpr(pacman_str, x, y - 1, t - 1)
            & logic.PropSymbolExpr('North', t - 1))

    return logic.PropSymbolExpr(pacman_str, x, y, t) % (logic.disjoin(moves))
Beispiel #15
0
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
Beispiel #16
0
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"
    expr = []
    if (not walls_grid[x][y - 1]):
        expr += [
            logic.PropSymbolExpr(pacman_str, x, y - 1, t - 1)
            & logic.PropSymbolExpr('North', t - 1)
        ]
    if (not walls_grid[x][y + 1]):
        expr += [
            logic.PropSymbolExpr(pacman_str, x, y + 1, t - 1)
            & logic.PropSymbolExpr('South', t - 1)
        ]
    if (not walls_grid[x - 1][y]):
        expr += [
            logic.PropSymbolExpr(pacman_str, x - 1, y, t - 1)
            & logic.PropSymbolExpr('East', t - 1)
        ]
    if (not walls_grid[x + 1][y]):
        expr += [
            logic.PropSymbolExpr(pacman_str, x + 1, y, t - 1)
            & logic.PropSymbolExpr('West', t - 1)
        ]
    return logic.PropSymbolExpr(pacman_str, x, y, t) % logic.disjoin(
        expr)  # Replace this with your expression
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a 
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"
    # init current/final position
    current = logic.PropSymbolExpr(pacman_str, x, y, t)
    test = []
    if walls_grid[x+1][y] != True:
        action = logic.PropSymbolExpr(pacman_str, x+1, y, t-1) & logic.PropSymbolExpr('West', t-1)
        test.append(action)
        successor_nodes.append((x+1, y, t))
    if walls_grid[x-1][y] != True:
        action2 = logic.PropSymbolExpr(pacman_str, x-1, y, t-1) & logic.PropSymbolExpr('East', t-1)
        test.append(action2)
        successor_nodes.append((x+1, y, t))
    if walls_grid[x][y+1] != True:
        action3 = logic.PropSymbolExpr(pacman_str, x, y+1, t-1) & logic.PropSymbolExpr('South', t-1)
        test.append(action3)
        successor_nodes.append((x+1, y, t))
    if walls_grid[x][y-1] != True:
        action4 = logic.PropSymbolExpr(pacman_str, x, y-1, t-1) & logic.PropSymbolExpr('North', t-1)
        test.append(action4)
        successor_nodes.append((x+1, y, t))
    return current % logic.disjoin(test)
Beispiel #18
0
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a 
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"
    successor_list = []
    if 0 <= x - 1 < walls_grid.width and 0 <= y < walls_grid.height:
        if not walls_grid.data[x - 1][y]:
            location = logic.PropSymbolExpr('P', x - 1, y, t - 1)
            action = logic.PropSymbolExpr('East', t - 1)
            successor_list.append(location & action)
    if 0 <= x + 1 < walls_grid.width and 0 <= y < walls_grid.height:
        if not walls_grid.data[x + 1][y]:
            location = logic.PropSymbolExpr('P', x + 1, y, t - 1)
            action = logic.PropSymbolExpr('West', t - 1)
            successor_list.append(location & action)
    if 0 <= x < walls_grid.width and 0 <= y - 1 < walls_grid.height:
        if not walls_grid.data[x][y - 1]:
            location = logic.PropSymbolExpr('P', x, y - 1, t - 1)
            action = logic.PropSymbolExpr('North', t - 1)
            successor_list.append(location & action)
    if 0 <= x < walls_grid.width and 0 <= y + 1 < walls_grid.height:
        if not walls_grid.data[x][y + 1]:
            location = logic.PropSymbolExpr('P', x, y + 1, t - 1)
            action = logic.PropSymbolExpr('South', t - 1)
            successor_list.append(location & action)
    return logic.PropSymbolExpr('P', x, y, t) % logic.associate(
        '|', successor_list)
def positionLogicPlan(problem):
    """
    Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    walls = problem.walls
    width, height = problem.getWidth(), problem.getHeight()
    available_action = ['North', 'East', 'South', 'West'] # evacuate STOP
    "*** YOUR CODE HERE ***"
    # get start/goal loaction
    start = problem.getStartState()
    goal = problem.getGoalState()

    start_state = logic.PropSymbolExpr("P", start[0], start[1], 0)
    start_logic = []
    for i in range(1, width+1):
        for j in range(1, height+1):
            start_logic.append(logic.PropSymbolExpr("P", i, j, 0))
    start_logic = exactlyOne(start_logic)
    start_logic = logic.conjoin(start_logic, start_state)
    # note that we must assert any other position is not allowed, otherwise it will cause weird error

    t = 1 # initial time
    # note that time start from 1 but not 0
    path = False

    while not path:
        # goal state
        goal_state = logic.PropSymbolExpr("P", goal[0], goal[1], t+1)
        # build succession logic
        successor = []
        for k in range(1, t+2): # note here must be t+2
            for i in range(1, width + 1): # skip the most-outside wall
                for j in range(1, height + 1):
                    if not walls[i][j]: # if (x, y) is not a wall
                        successor.append(pacmanSuccessorStateAxioms(i, j, k, walls))
        successor = logic.conjoin(successor)

        action_taken = []
        for i in range(0, t + 1):# last one is t
            all_action = []
            for action in available_action:
                all_action += [logic.PropSymbolExpr(action, i)]
            # one step must take exactly one action
            action_taken.append(exactlyOne(all_action))
        # each step must take action
        each_step_action = logic.conjoin(action_taken)
        # assemble model
        model = logic.conjoin(start_logic, goal_state, each_step_action, successor)
        path = findModel(model) 
        # complicated init state & goal state & way to achieve goal & all possible action can be taken & all possible successors to any point 
        t += 1
    return extractActionSequence(path, available_action)
Beispiel #20
0
def food_goal_sentence(problem, time):
    goal = []
    food_list = problem.getStartState()[1].asList()
    for food in food_list:
        goal.append(~logic.PropSymbolExpr("F", food[0], food[1]))
    expressions = []
    for position in food_list:
        expressions.append(
            logic.PropSymbolExpr("P", position[0], position[1], time))
    goal.append(atLeastOne(expressions))
    return goal
Beispiel #21
0
def generate_initial_statements(problem):
    temp_list = []
    initial_position_expr = logic.PropSymbolExpr("P", start[0], start[1], time)
    for x in range(0, problem.getWidth()):
        for y in range(0, problem.getHeight()):
            if (x,y) == (start[0], start[1]):
                continue
            else:
                temp_list.append(logic.PropSymbolExpr("P", x, y, time))
    initial_position_expr = initial_position_expr & ~(logic.associate('|', temp_list))
    return initial_position_expr
Beispiel #22
0
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()
    end = problem.getGoalState()
    actions = ['North', 'South', 'East', 'West']
    not_walls = [(x, y)
                 for x, y in product(range(1, width + 1), range(1, height + 1))
                 if not walls[x][y]]

    # init^0
    init = logic.PropSymbolExpr(pacman_str, start[0], start[1], 0)
    for i in range(1, width + 1):
        for j in range(1, height + 1):
            if (i, j) != start:
                init = logic.conjoin(
                    init, (~logic.PropSymbolExpr(pacman_str, i, j, 0)))

    t = 1
    assertion = lambda t: logic.PropSymbolExpr(pacman_str, end[0], end[1], t)
    transition = lambda t: logic.conjoin(
        [pacmanSuccessorStateAxioms(x, y, t, walls) for x, y in not_walls])
    constraint_action = lambda t: exactlyOne(
        [logic.PropSymbolExpr(action, t - 1) for action in actions])
    constraint_position = lambda t: exactlyOne(
        [logic.PropSymbolExpr(pacman_str, x, y, t - 1) for x, y in not_walls])

    transition_all = transition(1)
    constraint_action_all = constraint_action(1)
    constraint_position_all = constraint_position(1)

    while True:
        if t != 1:
            transition_all = logic.conjoin(transition_all, transition(t))
            constraint_action_all = logic.conjoin(constraint_action_all,
                                                  constraint_action(t))
            constraint_position_all = logic.conjoin(constraint_position_all,
                                                    constraint_position(t))
        model = findModel(
            logic.conjoin(init, transition_all, assertion(t),
                          constraint_action_all, constraint_position_all))
        # print(model)
        if model is not False:
            # print(extractActionSequence(model, actions))
            return extractActionSequence(model, actions)
        else:
            t += 1
Beispiel #23
0
def possActs(x, y, t, walls_grid, problem):
    ls = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    dir = ["East", "West", "North", "South"]
    acts = []
    for i in range(4):
        (mx, my) = ls[i]
        #print("xfs, yf", (mx + x, my + y))
        if (validIdx(mx + x, my + y, problem)
                and not walls_grid[mx + x][my + y]):
            at = logic.PropSymbolExpr(pacman_str, mx + x, my + y, t - 1)
            mv = logic.PropSymbolExpr(dir[i], t - 1)
            acts.append((at & mv))
    return acts
Beispiel #24
0
def get_food_axioms(problem, max_time):
    models = []
    food_list = problem.getStartState()[1].asList()
    for food in food_list:
        expressions = []
        for t in xrange(max_time + 1):
            expressions.append(logic.PropSymbolExpr("P", food[0], food[1], t))
        if expressions:
            position_sentences = atLeastOne(expressions)
            before_cnf = ~logic.PropSymbolExpr("F", food[0],
                                               food[1]) % position_sentences
            models.append(logic.to_cnf(before_cnf))
    return models
Beispiel #25
0
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 []
Beispiel #26
0
def transition_models(problem, time, actions, legal_actions):
    """
    Most important function, writes axioms about our fluents
    """
    models = []
    for i in xrange(1, problem.getWidth() + 1):
        for j in xrange(1, problem.getHeight() + 1):
            if not problem.isWall((i, j)):
                current_symbol = logic.PropSymbolExpr('P', i, j, time)
                expressions = []
                for action in actions:
                    previous_symbol = None
                    action_symbol = None
                    if action == Directions.EAST:
                        if (i - 1, j, action) in legal_actions:
                            previous_symbol = logic.PropSymbolExpr(
                                'P', i - 1, j, time - 1)
                            action_symbol = logic.PropSymbolExpr(
                                action, time - 1)
                        else:
                            continue
                    elif action == Directions.WEST:
                        if (i + 1, j, action) in legal_actions:
                            previous_symbol = logic.PropSymbolExpr(
                                'P', i + 1, j, time - 1)
                            action_symbol = logic.PropSymbolExpr(
                                action, time - 1)
                        else:
                            continue
                    elif action == Directions.NORTH:
                        if (i, j - 1, action) in legal_actions:
                            previous_symbol = logic.PropSymbolExpr(
                                'P', i, j - 1, time - 1)
                            action_symbol = logic.PropSymbolExpr(
                                action, time - 1)
                        else:
                            continue
                    elif action == Directions.SOUTH:
                        if (i, j + 1, action) in legal_actions:
                            previous_symbol = logic.PropSymbolExpr(
                                'P', i, j + 1, time - 1)
                            action_symbol = logic.PropSymbolExpr(
                                action, time - 1)
                        else:
                            continue
                        # NOTE: SHOULD NOT NEED TO STOP!
                        # elif action == Directions.STOP:
                        #     pass
                    expressions.append(previous_symbol & action_symbol)
            # before_cnf = current_symbol  % atLeastOne(expressions)

            models.append(
                logic.to_cnf(
                    current_symbol %
                    atLeastOne(expressions)))  # % means <=>, this is VERY UGLY
    return models
Beispiel #27
0
def positionLogicPlan(problem):
    """
    Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
    Available actions are game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    walls = problem.walls
    width, height = problem.getWidth(), problem.getHeight()

    "*** YOUR CODE HERE ***"
    actions = ['North', 'South', 'East', 'West']
    startState = []
    initialX, initialY = problem.getStartState()
    initial = logic.PropSymbolExpr(pacman_str, initialX, initialY, 0)
    goalX, goalY = problem.getGoalState()
    goalSuccessors = []
    goalActions = []

    steps = 50
    for x in range(1, width + 1):
        for y in range(1, height + 1):
            if not (x, y) in walls.asList():
                startState.append(logic.PropSymbolExpr(pacman_str, x, y, 0))
    for i in range(1, steps):
        successors = []
        start = exactlyOne(startState)  # needed for goal
        goal = logic.PropSymbolExpr(pacman_str, goalX, goalY, i)
        for x in range(1, width + 1):
            for y in range(1, height + 1):
                if (x, y) not in walls.asList():
                    successors.append(
                        pacmanSuccessorStateAxioms(x, y, i, walls))
        successor = logic.conjoin(successors)
        action = []
        for a in actions:
            action.append(logic.PropSymbolExpr(a, i - 1))
        goalActions.append(exactlyOne(action))
        goalSuccessors.append(successor)
        # print("start: ", start)
        # print("initial: ", initial)
        # print("goal: ", goal)
        # print("goalActions: ", goalActions)
        # print("goalSuccessors: ", goalSuccessors)
        isGoal = findModel(
            logic.conjoin([
                start, initial, goal,
                logic.conjoin(goalSuccessors),
                logic.conjoin(goalActions)
            ]))
        if isGoal:
            return extractActionSequence(isGoal, actions)
Beispiel #28
0
def pacmanSuccessorStateAxioms(x, y, t, walls_grid):
    """
    Successor state axiom for state (x,y,t) (from t-1), given the board (as a 
    grid representing the wall locations).
    Current <==> (previous position at time t-1) & (took action to move to x, y)
    """
    "*** YOUR CODE HERE ***"
    P_x_y_t = logic.PropSymbolExpr(pacman_str, x, y, t)

    neighbor = [(i, j) for i, j in zip([(x, y - 1), (x, y + 1), (
        x - 1, y), (x + 1, y)], ['North', 'South', 'East', 'West'])
                if not walls_grid[i[0]][i[1]]]

    return P_x_y_t % logic.disjoin(
        [(logic.PropSymbolExpr(pacman_str, i[0][0], i[0][1], t - 1)
          & logic.PropSymbolExpr(i[1], t - 1)) for i in neighbor])
Beispiel #29
0
def extractActionSequence(model, actions):
    """
    Convert a model in to an ordered list of actions.
    model: Propositional logic model stored as a dictionary with keys being
    the symbol strings and values being Boolean: True or False
    Example:
    >>> model = {"North[3]":True, "P[3,4,1]":True, "P[3,3,1]":False, "West[1]":True, "GhostScary":True, "West[3]":False, "South[2]":True, "East[1]":False}
    >>> actions = ['North', 'South', 'East', 'West']
    >>> plan = extractActionSequence(model, actions)
    >>> print plan
    ['West', 'South', 'North']
    """
    "*** YOUR CODE HERE ***"
    if not model:
        return []
    ret = []
    i = 0
    while True:
        flag = False
        for action in actions:
            symbol = logic.PropSymbolExpr(action, i)
            if symbol in model and model[symbol]:
                ret += [action]
                flag = True
        if not flag:
            break
        i += 1
    print ret
    return ret
def extractActionSequence(model, actions):
    """
    Convert a model in to an ordered list of actions.
    model: Propositional logic model stored as a dictionary with keys being
    the symbol strings and values being Boolean: True or False
    Example:
    >>> model = {"North[3]":True, "P[3,4,1]":True, "P[3,3,1]":False, "West[1]":True, "GhostScary":True, "West[3]":False, "South[2]":True, "East[1]":False}
    >>> actions = ['North', 'South', 'East', 'West']
    >>> plan = extractActionSequence(model, actions)
    >>> print plan
    ['West', 'South', 'North']
    """
    "*** YOUR CODE HERE ***"
    plan = []
    my_actions = []
    for i in model:
        my_string = str(i)
        tmp1 = my_string.index('[')
        tmp2 = my_string.index(']')
        if my_string[:tmp1] in actions:
            expr = logic.PropSymbolExpr(my_string[:tmp1],
                                        int(my_string[tmp1 + 1:tmp2]))
            if model[expr] == True:
                my_actions.append(
                    (my_string[:tmp1], int(my_string[tmp1 + 1:tmp2])))
    for i in range(len(my_actions)):
        for j in range(len(my_actions)):
            if my_actions[j][1] == i:
                plan.append(my_actions[j][0])
    return plan