示例#1
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'])
示例#2
0
def generateSuccessorState(predecessors={}, time=0):
    actions = [game.Directions.EAST,game.Directions.SOUTH,game.Directions.WEST,game.Directions.NORTH]

    # this is a list of all possible actions, exactlyOne forces us to pick one of them
    t_actions = exactlyOne([logic.PropSymbolExpr(a, time-1) for a in actions])

    if time <= 0:
        return []

    return [exactlyOne([logic.PropSymbolExpr("P",pos[0],pos[1],time) for pos in predecessors.keys()])] +\
           [logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P",pos[0],pos[1],time), \
            exactlyOne([logic.Expr("&", logic.PropSymbolExpr(a, time-1), logic.PropSymbolExpr("P",p[0],p[1],time-1))\
            for (a, p) in preds]))) for (pos, preds) in predecessors.items()] + [logic.to_cnf(t_actions)] +\
           generateSuccessorState(predecessors,time-1)
示例#3
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 ***"
    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)
示例#4
0
def sentence1():
    """Returns a logic.Expr instance that encodes that the following expressions are all true.
    
    A or B
    (not A) if and only if ((not B) or C)
    (not A) or (not B) or C
    """
    "*** YOUR CODE HERE ***"
    A = logic.Expr('A')
    B = logic.Expr('B')
    C = logic.Expr('C')
    s1 = logic.to_cnf(A | B)
    s2 = ~A % (~B | C)
    s3 = logic.to_cnf(~A | ~B | C)
    return logic.conjoin(s1, s2, s3)
    util.raiseNotDefined()
示例#5
0
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 ***"
示例#6
0
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)
示例#7
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 []
示例#8
0
def parse_file(file):
    # parse file
    # form initial KB
    # add additional rules
    # return KB, and queries
    inp = open(file, "r")
    KB = []
    query = []
    query_start = False
    i = 0
    for line in inp:
        # first not comment is the size of the board
        if not line.startswith("#") and i == 0:
            i += 1
            cur_line = line.replace('\n', '')
            s = cur_line.split('x')
            size = (int(s[0]), int(s[1]))
        elif not line.startswith("#") and not query_start:
            cur_line = line.replace('\n', '')
            KB.append(cur_line)
        elif line.replace('\n', '') == '# Query Sentences' or line.replace(
                '\n', '') == '#Query Sentences':
            query_start = True
        elif query_start and not line.startswith("#"):
            cur_line = line.replace('\n', '')
            query.append(
                to_cnf(cur_line)
            )  # makes the query into CNF and understandable by the program
    return size, KB, query
示例#9
0
def run_minisat_test():
    """
    Test connection to MiniSat
    """
    import logic

    queries = [("(P | ~P)", True), # SAT
               ("(P & ~P)", False), # UNSAT
               ("(P | R) <=> (~(Q | R) & (R >> ~(S <=> T)))", True) # SAT
               ]
    
    print "Running simple MiniSat test:"
    t = 1
    failed = []
    for query, expected_result in queries:
        print "-----------------------------------------------------"
        print "Test {0}".format(t)
        print "  Query:      '{0}'".format(query)
        query = logic.conjuncts(logic.to_cnf(logic.expr(query)))
        result = minisat(query, None, variable=None, value=True, verbose=False)
        print "  Query CNF:  {0}".format(query)
        print "  Result:     {0}   (Expected: {1})".format(result.success, expected_result)
        if result.success != expected_result:
            print "    FAILURE: unexpected result."
            failed.append(t)
        if result.success:
            print "  Variable Assignment: {0}".format(result.varmap)
        t += 1
    print "-----------------------------------------------------"
    if not failed:
        print "Successfully passed {0} tests.".format(len(queries))
    else:
        print "Passed {0} test(s).".format(len(queries) - len(failed))
        print "The following tests failed: {0}".format(failure)
    print "DONE."
示例#10
0
def run_minisat_test():
    """
    Test connection to MiniSat
    """
    import logic

    queries = [("(P | ~P)", True), # SAT
               ("(P & ~P)", False), # UNSAT
               ("(P | R) <=> (~(Q | R) & (R >> ~(S <=> T)))", True) # SAT
               ]
    
    print "Running simple MiniSat test:"
    t = 1
    failed = []
    for query, expected_result in queries:
        print "-----------------------------------------------------"
        print "Test {0}".format(t)
        print "  Query:      '{0}'".format(query)
        query = logic.conjuncts(logic.to_cnf(logic.expr(query)))
        result = minisat(query, None, variable=None, value=True, verbose=False)
        print "  Query CNF:  {0}".format(query)
        print "  Result:     {0}   (Expected: {1})".format(result.success, expected_result)
        if result.success != expected_result:
            print "    FAILURE: unexpected result."
            failed.append(t)
        if result.success:
            print "  Variable Assignment: {0}".format(result.varmap)
        t += 1
    print "-----------------------------------------------------"
    if not failed:
        print "Successfully passed {0} tests.".format(len(queries))
    else:
        print "Passed {0} test(s).".format(len(queries) - len(failed))
        print "The following tests failed: {0}".format(failure)
    print "DONE."
示例#11
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 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)
示例#12
0
def ghostPositionSuccessorStateAxioms(x, y, t, ghost_num, walls_grid):
    """
    Successor state axiom for patrolling ghost state (x,y,t) (from t-1).
    Current <==> (causes to stay) | (causes of current)
    GE is going east, ~GE is going west 
    """
    pos_str = ghost_pos_str+str(ghost_num)
    east_str = ghost_east_str+str(ghost_num)
    disjoin = []
    if not walls_grid[x-1][y]:
        disjoin.append(logic.PropSymbolExpr(pos_str,x - 1,y, t-1) & logic.PropSymbolExpr(east_str,t-1))
    if not walls_grid[x+1][y]: 
        disjoin.append(logic.PropSymbolExpr(pos_str,x + 1,y, t-1) & ~logic.PropSymbolExpr(east_str,t-1))
    if walls_grid[x-1][y] and walls_grid[x+1][y]:
        disjoin.append(logic.PropSymbolExpr(pos_str, x, y, t-1))
    disjoin = logic.disjoin(disjoin)
    return logic.to_cnf(~logic.PropSymbolExpr(pos_str, x, y, t) | disjoin) & logic.to_cnf(~disjoin|logic.PropSymbolExpr(pos_str, x, y, t))
示例#13
0
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 []
示例#14
0
def generateSuccessorState(predecessors={}, time=0):
    actions = [
        game.Directions.EAST, game.Directions.SOUTH, game.Directions.WEST,
        game.Directions.NORTH
    ]

    # this is a list of all possible actions, exactlyOne forces us to pick one of them
    t_actions = exactlyOne(
        [logic.PropSymbolExpr(a, time - 1) for a in actions])

    if time <= 0:
        return []

    return [exactlyOne([logic.PropSymbolExpr("P",pos[0],pos[1],time) for pos in predecessors.keys()])] +\
           [logic.to_cnf(logic.Expr(">>", logic.PropSymbolExpr("P",pos[0],pos[1],time), \
            exactlyOne([logic.Expr("&", logic.PropSymbolExpr(a, time-1), logic.PropSymbolExpr("P",p[0],p[1],time-1))\
            for (a, p) in preds]))) for (pos, preds) in predecessors.items()] + [logic.to_cnf(t_actions)] +\
           generateSuccessorState(predecessors,time-1)
示例#15
0
def resolution(KB, alpha):
    """Apply the resolution algorithm to determine if alpha can be inferred from KB.

  Args:
    KB: an instance of logic.PropKB
    alpha: an instance of logic.Expr

  Return True if KB |- alpha
  """
    # We do not want to waste effort resolving clauses of the KB against
    # one another directly, we only want to resolve clauses that contain
    # information derived from alpha.  tainted_clauses will be the set
    # we grow.
    tainted_clauses = set(
        normalize(clause) for clause in logic.conjuncts(logic.to_cnf(~alpha)))
    KB_clauses = [normalize(clause) for clause in KB.clauses]
    new = set()
    while True:
        # clausesWith is a map from literals to clauses containing that literal.
        clausesWith = collections.defaultdict(list)
        for clause in list(tainted_clauses) + KB_clauses:
            for literal in clause:
                clausesWith[literal].append(clause)

        # For each tainted clause, add a pair of that clause and any
        # tainted or KB clause that matches it (i.e. opposes on one literal).
        pairs = []
        for clause0 in tainted_clauses:
            for literal in clause0:
                for clause1 in clausesWith[negate(literal)]:
                    pairs.append((literal, clause0, clause1))

        # Resolve all the pairs found above.  If any result in None, the
        # resolution is a bust (provides no new information).
        # If any result in False (empty set), we have reached a contradiction
        # and proven our goal.
        for literal, clause0, clause1 in pairs:
            result = resolve(clause0, clause1, literal)
            if result is not None:
                if result == set(): return True
                else: new.add(frozenset(result))

        # We now survey all the new clauses.  In order to want to keep them,
        # they must not be a superset of any already-known clause (since that
        # would provide no new information).
        added = False
        for clause in new:
            if not any(
                    old_clause.issubset(clause)
                    for old_clause in list(tainted_clauses) + KB_clauses):
                tainted_clauses.add(clause)
                added = True

        # If we have not found any new information, we've reached the end
        # and cannot prove our goal (it may be True, it may be False, but we
        # can't definitively say either way).
        if not added: return False
示例#16
0
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
示例#17
0
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()
示例#18
0
def positionLogicPlan(problem):
    """
    Given an instance of a PositionPlanningProblem, return a list of actions that lead to the goal.
    Available actions are ['North', 'East', 'South', 'West']
    Note that STOP is not an available action.
    """
    walls = problem.walls
    w, h = problem.getWidth(), problem.getHeight()
    walls_list = walls.asList()
    x0, y0 = problem.startState
    xg, yg = problem.goal
    print("x0, y0", x0, y0)
    cond = None

    for max in range(1, 50):
        lg = logic.PropSymbolExpr(pacman_str, x0, y0,
                                  50 - max) & logic.PropSymbolExpr(
                                      pacman_str, xg, yg, 50)

        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)
        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'])
示例#19
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
示例#20
0
def resolution(KB, alpha):
  """Apply the resolution algorithm to determine if alpha can be inferred from KB.

  Args:
    KB: an instance of logic.PropKB
    alpha: an instance of logic.Expr

  Return True if KB |- alpha
  """
  # We do not want to waste effort resolving clauses of the KB against
  # one another directly, we only want to resolve clauses that contain
  # information derived from alpha.  tainted_clauses will be the set
  # we grow.
  tainted_clauses = set(normalize(clause)
      for clause in logic.conjuncts(logic.to_cnf(~alpha)))
  KB_clauses = [normalize(clause) for clause in KB.clauses]
  new = set()
  while True:
    # clausesWith is a map from literals to clauses containing that literal.
    clausesWith = collections.defaultdict(list)
    for clause in list(tainted_clauses) + KB_clauses:
      for literal in clause:
        clausesWith[literal].append(clause)

    # For each tainted clause, add a pair of that clause and any
    # tainted or KB clause that matches it (i.e. opposes on one literal).
    pairs = []
    for clause0 in tainted_clauses:
      for literal in clause0:
        for clause1 in clausesWith[negate(literal)]:
          pairs.append((literal, clause0, clause1))

    # Resolve all the pairs found above.  If any result in None, the 
    # resolution is a bust (provides no new information).
    # If any result in False (empty set), we have reached a contradiction
    # and proven our goal.
    for literal, clause0, clause1 in pairs:
      result = resolve(clause0, clause1, literal)
      if result is not None:
        if result == set(): return True
        else: new.add(frozenset(result))

    # We now survey all the new clauses.  In order to want to keep them,
    # they must not be a superset of any already-known clause (since that
    # would provide no new information).
    added = False
    for clause in new:
      if not any(old_clause.issubset(clause)
          for old_clause in list(tainted_clauses) + KB_clauses):
        tainted_clauses.add(clause)
        added = True

    # If we have not found any new information, we've reached the end
    # and cannot prove our goal (it may be True, it may be False, but we
    # can't definitively say either way).
    if not added: return False
示例#21
0
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()
示例#22
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
示例#23
0
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 ***"
示例#24
0
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()
示例#25
0
    def ask(self, prop):
        to_prove = frozenset(map(frozenset,
                                 map(set,
                                     map(disjuncts,
                                         conjuncts(to_cnf(~prop)))))) \
                    | self.clauses #把要证明的结论先否定再整理成CNF的形式,再和原来KB中的子句们并一下

        if fast_dpll(to_prove):
            return False  #是否有contradiction,若没有(fast_dpll()为True)
        else:
            self.tell(prop)  #如果结论成立(有contradiction),那么就把新的推论给到KB
            return True
示例#26
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
示例#27
0
文件: kb.py 项目: Zchappie/Garage
    def ask(self, prop):
        to_prove = frozenset(map(frozenset,
                                 map(set,
                                     map(disjuncts,
                                         conjuncts(to_cnf(~prop)))))) \
                    | self.clauses

        if fast_dpll(to_prove):
            return False
        else:
            self.tell(prop)
            return True
示例#28
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)]
    killed_by_ghost = []
    new_location = logic.PropSymbolExpr(pacman_str, x, y, t)
    for ghost in ghost_strs:
        killed_by_ghost.append(logic.PropSymbolExpr(ghost, x, y, t) & new_location)
        killed_by_ghost.append(logic.PropSymbolExpr(ghost, x, y, t-1) & new_location)
    return logic.to_cnf((~logic.PropSymbolExpr(pacman_alive_str, t)) % ((atLeastOne(killed_by_ghost) | ~logic.PropSymbolExpr(pacman_alive_str, t-1))))
示例#29
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 game.Directions.{NORTH,SOUTH,EAST,WEST}
    Note that STOP is not an available action.
    """
    walls = problem.walls
    width, height = problem.getWidth(), problem.getHeight()
    food = problem.startingGameState.getFood()
    startState = problem.getStartState()
    expr1 = [
        logic.PropSymbolExpr(pacman_str, startState[0][0], startState[0][1], 0)
    ]
    expr2 = []
    for i in xrange(1, width + 1):
        for j in xrange(1, height + 1):
            if (i, j) != (startState[0]):
                expr1 += [~logic.PropSymbolExpr(pacman_str, i, j, 0)]
    for m in xrange(0, 51):
        for i in xrange(1, width + 1):
            for j in xrange(1, height + 1):
                if m > 0:
                    if not walls[i][j]:
                        expr1 += [pacmanSuccessorStateAxioms(i, j, m, walls)]

        if m > 0:
            expr3 = []
            expr3 += [logic.PropSymbolExpr('North', m - 1)]
            expr3 += [logic.PropSymbolExpr('South', m - 1)]
            expr3 += [logic.PropSymbolExpr('West', m - 1)]
            expr3 += [logic.PropSymbolExpr('East', m - 1)]
            expr2 += [exactlyOne(expr3)]

        finalState = []
        for i in xrange(1, width + 1):
            for j in xrange(1, height + 1):
                if food[i][j]:
                    aux = []
                    for k in xrange(0, m + 1):
                        aux += [logic.PropSymbolExpr(pacman_str, i, j, k)]
                    finalState += [logic.disjoin(aux)]
        auxx = expr1 + expr2 + [logic.conjoin(finalState)]
        cnf = logic.to_cnf(logic.conjoin(auxx))
        model = findModel(cnf)
        if (model != False):
            return extractActionSequence(model,
                                         ['West', 'South', 'North', 'East'])
    return False

    "*** YOUR CODE HERE ***"
    util.raiseNotDefined()
示例#30
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
示例#31
0
def lineToCnf(line):
    '''
        converts a single LTL formula into CNF form compatible with DIMACS
        '''
    line = stripLTLLine(line)
    if line != '':
        line = stripPrefixes(line)
        line = formatForToCnf(line)
        cnf = str(to_cnf(line))
        cnf = formatForDimacs(cnf)
        return cnf
    else:
        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
示例#33
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 []
示例#34
0
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
示例#36
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 []
示例#37
0
def lineToCnf(line):
        #converts a single LTL formula into CNF form 
        line = stripLTLLine(line)
        if line!='':
            line = re.sub('s\.','',line)
            line = re.sub('e\.','',line)   
            line = re.sub(r'(next\(\s*!)', r'(!next_', line)         
            line = re.sub(r'(next\(\s*)', r'(next_', line)
            line = re.sub('!', '~', line)
            #line = re.sub('&\s*\n', '', line)
            line = re.sub('[\s]+', ' ', line)        
            line = re.sub('\<-\>', '<=>', line)
            line = re.sub('->', '>>', line)
            line = line.strip() 
            cnf = str(to_cnf(line))            
            return cnf
        else:
            return None        
示例#38
0
def lineToCnf(line):
    #converts a single LTL formula into CNF form
    line = stripLTLLine(line)
    if line != '':
        line = re.sub('s\.', '', line)
        line = re.sub('e\.', '', line)
        line = re.sub(r'(next\(\s*!)', r'(!next_', line)
        line = re.sub(r'(next\(\s*)', r'(next_', line)
        line = re.sub('!', '~', line)
        #line = re.sub('&\s*\n', '', line)
        line = re.sub('[\s]+', ' ', line)
        line = re.sub('\<-\>', '<=>', line)
        line = re.sub('->', '>>', line)
        line = line.strip()
        cnf = str(to_cnf(line))
        return cnf
    else:
        return None
示例#39
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)
    """

    literals = []
    if not walls_grid[x][y + 1]:
        literals.append(logic.PropSymbolExpr(pacman_str, x, y + 1, t-1)&logic.PropSymbolExpr('South', t-1))
    if not walls_grid[x][y - 1]:
        literals.append(logic.PropSymbolExpr(pacman_str, x, y - 1, t-1)&logic.PropSymbolExpr('North', t-1))
    if not walls_grid[x + 1][y]:
        literals.append(logic.PropSymbolExpr(pacman_str, x + 1, y, t-1)&logic.PropSymbolExpr('West', t-1))
    if not walls_grid[x - 1][y]:
        literals.append(logic.PropSymbolExpr(pacman_str, x - 1, y, t-1)&logic.PropSymbolExpr('East', t-1))
    expression = logic.PropSymbolExpr(pacman_str, x, y, t) % logic.disjoin(literals)
    return logic.to_cnf(expression)
示例#40
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()
    goalState = problem.getGoalState()
    startState = problem.getStartState()
    expr1 = [logic.PropSymbolExpr(pacman_str, startState[0], startState[1], 0)]
    expr2 = []
    finalState = [
        logic.PropSymbolExpr(pacman_str, goalState[0], goalState[1], 0)
    ]
    for i in xrange(1, width + 1):
        for j in xrange(1, height + 1):
            if (i, j) != (startState):
                expr1 += [~logic.PropSymbolExpr(pacman_str, i, j, 0)]
    for m in xrange(0, 51):
        for i in xrange(1, width + 1):
            for j in xrange(1, height + 1):
                if m > 0:
                    if not walls[i][j]:
                        expr1 += [pacmanSuccessorStateAxioms(i, j, m, walls)]
        if m > 0:
            expr3 = []
            expr3 += [logic.PropSymbolExpr('North', m - 1)]
            expr3 += [logic.PropSymbolExpr('South', m - 1)]
            expr3 += [logic.PropSymbolExpr('West', m - 1)]
            expr3 += [logic.PropSymbolExpr('East', m - 1)]
            expr2 += [exactlyOne(expr3)]
            finalState += [
                logic.PropSymbolExpr(pacman_str, goalState[0], goalState[1], m)
            ]
        aux = expr1 + expr2 + [logic.disjoin(finalState)]
        cnf = logic.to_cnf(logic.conjoin(aux))
        model = findModel(cnf)
        if (model != False):
            return extractActionSequence(model,
                                         ['West', 'South', 'North', 'East'])
    return False
示例#41
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
示例#42
0
def precond(problem, T):
    ls = None
    walls = problem.walls
    pos = [(1, 0), (-1, 0), (0, 1), (0, -1)]
    dir = ["East", "West", "North", "South"]
    width, height = problem.getWidth(), problem.getHeight()

    for t in range(T, T + 1):
        tmp = []
        for act in ['North', 'East', 'South', 'West']:
            tmp.append(logic.PropSymbolExpr(act, 50 - t))
        if tmp != []:
            if ls == None:
                ls = exactlyOne(tmp)
            else:
                ls = ls & logic.to_cnf(exactlyOne(tmp))

        tmp = []
        for i in range(1, width + 1):
            for j in range(1, height + 1):
                if not walls[i][j]:
                    tmp.append(logic.PropSymbolExpr(pacman_str, i, j, 50 - t))

                for m in range(4):
                    (a, b) = pos[m]
                    d = dir[m]
                    if not validIdx(i + a, j + b, problem) or walls[i + a][j +
                                                                           b]:
                        ls = ls & (
                            (~logic.PropSymbolExpr(pacman_str, i, j, 50 - t))
                            | (~logic.PropSymbolExpr(d, 50 - t)))

        if tmp == []:
            continue
        if ls == None:
            ls = exactlyOne(tmp)
        else:
            ls = ls & exactlyOne(tmp)
    #print("ls", ls)
    return ls
示例#43
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)
    at_west_block = []
    at_east_block = []
    for west_block in blocked_west_positions:
        at_west_block.append(logic.PropSymbolExpr(pos_str,west_block[0], west_block[1],t))
    for east_block in blocked_east_positions:
        at_east_block.append(logic.PropSymbolExpr(pos_str,east_block[0], east_block[1],t))
    at_west_block = atLeastOne(at_west_block)
    at_east_block = atLeastOne(at_east_block)
    at_both = at_east_block & at_west_block
    prev = logic.PropSymbolExpr(east_str, t-1)
    return logic.to_cnf(logic.PropSymbolExpr(east_str, t) % ((~at_east_block & prev) 
                                                    | (at_both & ~prev)
                                                    | (at_west_block & ~at_east_block)))
示例#44
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 []
示例#45
0
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))
示例#46
0
文件: second.py 项目: jannza/aima
seventh = seventh[:-2]
 
KB.tell(logic.expr(seventh))



#add goal
KB.tell(logic.expr("At_1(Flat, Ground)"))



#some manual cnf
string = ""
for elem in KB.clauses:
#     print(elem)
    elem = logic.to_cnf(str(elem))
    string = string + str(elem) + " & "
    
string = string[:-2]    


# print(string)


#print only true values
answer = logic.dpll_satisfiable(string)
if answer != False: 
    for elem in answer:
        if answer[elem]:
            print(str(elem)+ " : " +str(answer[elem]))
else:
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
示例#48
0
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()
示例#49
0
def appendToExprs(exprs, rule):
    #pretty_print(exprs)
    if DEBUG:
        exprs.append(rule)
    else:
        exprs.append(logic.to_cnf(rule))
示例#50
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.
    """
    "*** 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")
示例#51
0
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()
示例#52
0
文件: kb.py 项目: Zchappie/Garage
 def tell(self, sentence):
     self.clauses.update(
         map(frozenset, map(set, map(disjuncts,
                                     conjuncts(to_cnf(sentence))))))
示例#53
0
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)
示例#54
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))
示例#55
0
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")
示例#56
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.
    """
    "*** 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[]
示例#57
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 ***"
    
    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))
示例#58
0
文件: second_1.py 项目: jannza/aima
def solve(steps):
    for moves in  range(0, steps+1):
        

        print("trying with "+str(moves)+" moves")
        KB = logic.PropKB()
        
        #initial state
        KB.tell(logic.expr("~At_0(Spare, Ground)"))
        KB.tell(logic.expr("At_0(Spare, Trunk)"))
        KB.tell(logic.expr("~At_0(Spare, Axle)"))
        KB.tell(logic.expr("At_0(Flat, Axle)"))
        KB.tell(logic.expr("~At_0(Flat, Ground)"))
        KB.tell(logic.expr("~At_0(Flat, Trunk)"))
        
        
        #first preconditions
        
        
        for i in range(0,moves):
            KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Trunk) | At_"+str(i)+"(Spare, Trunk)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | At_"+str(i)+"(Spare, Ground)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | ~At_"+str(i)+"(Flat, Axle) "))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Axle) | At_"+str(i)+"(Spare, Axle)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Axle) | At_"+str(i)+"(Flat, Axle)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | At_"+str(i)+"(Flat, Ground) "))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | ~At_"+str(i)+"(Flat, Axle) "))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Trunk) | At_"+str(i)+"(Flat, Trunk)"))
        
        
        
        #second positive effects
        for i in range(0,moves):
            KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Trunk) | At_"+str(i+1)+"(Spare, Ground)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | At_"+str(i+1)+"(Spare, Axle)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Axle) | At_"+str(i+1)+"(Spare, Ground)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Axle) | At_"+str(i+1)+"(Flat, Ground)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | At_"+str(i+1)+"(Flat, Axle)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Trunk) | At_"+str(i+1)+"(Flat, Ground)"))
        
        
        
        #third negative effects
        
        for i in range(0,moves):
        
            KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Trunk) | ~At_"+str(i+1)+"(Spare, Trunk)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Spare, Axle) | ~At_"+str(i+1)+"(Spare, Ground)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Spare, Axle) | ~At_"+str(i+1)+"(Spare, Axle)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Axle) | ~At_"+str(i+1)+"(Flat, Axle)"))
            KB.tell(logic.expr("~PutOn_"+str(i)+"(Flat, Axle) | ~At_"+str(i+1)+"(Flat, Ground)"))
            KB.tell(logic.expr("~Remove_"+str(i)+"(Flat, Trunk) | ~At_"+str(i+1)+"(Flat, Trunk)"))
            
            
            KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Spare, Ground)"))
            KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Spare, Axle)"))
            KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Spare, Trunk)"))
            KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Flat, Ground)"))
            KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Flat, Axle)"))
            KB.tell(logic.expr("~LeaveOvernight_"+str(i)+" | ~At_"+str(i+1)+"(Flat, Trunk)"))
        
        
        
        #fourth from false to true
        
        for i in range(0,moves):
            KB.tell(logic.expr("At_"+str(i)+"(Spare, Ground) | ~At_"+str(i+1)+"(Spare, Ground) | Remove_"+str(i)+"(Spare, Trunk) | Remove_"+str(i)+"(Spare, Axle)"))
            KB.tell(logic.expr("At_"+str(i)+"(Spare, Trunk) | ~At_"+str(i+1)+"(Spare, Trunk)"))
            KB.tell(logic.expr("At_"+str(i)+"(Spare, Axle) | ~At_"+str(i+1)+"(Spare, Axle) | PutOn_"+str(i)+"(Spare, Axle)"))
            KB.tell(logic.expr("At_"+str(i)+"(Flat, Axle) | ~At_"+str(i+1)+"(Flat, Axle) | PutOn_"+str(i)+"(Flat, Axle)"))
            KB.tell(logic.expr("At_"+str(i)+"(Flat, Ground) | ~At_"+str(i+1)+"(Flat, Ground) | Remove_"+str(i)+"(Flat, Axle) | Remove_"+str(i)+"(Flat, Trunk)"))
            KB.tell(logic.expr("At_"+str(i)+"(Flat, Trunk) | ~At_"+str(i+1)+"(Flat, Trunk)"))
        
        
        
        #fifth from true to false
        for i in range(0,moves):
            KB.tell(logic.expr("~At_"+str(i)+"(Spare, Ground) | At_"+str(i+1)+"(Spare, Ground) | PutOn_"+str(i)+"(Spare, Axle) | LeaveOvernight_"+str(i)+""))
            KB.tell(logic.expr("~At_"+str(i)+"(Spare, Trunk) | At_"+str(i+1)+"(Spare, Trunk) | Remove_"+str(i)+"(Spare, Trunk) | LeaveOvernight_"+str(i)+""))
            KB.tell(logic.expr("~At_"+str(i)+"(Spare, Axle) | At_"+str(i+1)+"(Spare, Axle) | Remove_"+str(i)+"(Spare, Axle)  | LeaveOvernight_"+str(i)+""))
            KB.tell(logic.expr("~At_"+str(i)+"(Flat, Axle) | At_"+str(i+1)+"(Flat, Axle) | Remove_"+str(i)+"(Flat, Axle) | LeaveOvernight_"+str(i)+""))
            KB.tell(logic.expr("~At_"+str(i)+"(Flat, Ground) | At_"+str(i+1)+"(Flat, Ground) | PutOn_"+str(i)+"(Flat, Axle) | LeaveOvernight_"+str(i)+""))
            KB.tell(logic.expr("~At_"+str(i)+"(Flat, Trunk) | At_"+str(i+1)+"(Flat, Trunk) | Remove_"+str(i)+"(Flat, Trunk) | LeaveOvernight_"+str(i)+""))
            
        
        #list of all possible actions
        #actions without timestamp, will be added later
        
        actions = ["Remove_(Spare, Trunk)", "PutOn_(Spare, Axle)", "Remove_(Spare, Axle)", 
                   "Remove_(Flat, Axle)", "PutOn_(Flat, Axle)", "Remove_(Flat, Trunk)", "LeaveOvernight_"]
        
        
        
        #sixth, only one action can take place
        
        for i in range(0,moves):
            for elem in itertools.combinations(actions, 2):
                KB.tell(logic.expr("~"+elem[0].replace("_","_"+str(i))+" | ~"+elem[1].replace("_","_"+str(i))))
        
        
        
        #seventh, one action must take place
        
        for i in range(0,moves):
            seventh = ""
            for elem in actions:    
                seventh += elem.replace("_","_"+str(i)) + " | " 
            seventh = seventh[:-2]
            KB.tell(logic.expr(seventh))
        
        
        
        #add goal
        KB.tell(logic.expr("At_"+str(moves)+"(Spare, Axle)"))
        
        
        
        #some manual cnf just to be sure
        string = ""
        for elem in KB.clauses:
            elem = logic.to_cnf(str(elem))
            string = string + str(elem) + " & "
            
        string = string[:-2]    
        
        
        action_stubs = ["Remove", "PutOn", "LeaveOvernight"]
        
        
        
        #print only true values
        answer = logic.dpll_satisfiable(logic.expr(string))
        if answer == False:
            print("Couldn't solve problem in "+str(moves)+" turns")
        else:
            print("Found solution with "+str(moves)+" turns")
            for elem in answer:
                if answer[elem]:
                    if any(sub in str(elem) for sub in action_stubs):
                        print(str(elem)+ " : " +str(answer[elem]))
            break