예제 #1
0
def run_test_plan(world_spec, plan, expression_spec, result, sets={}):
    global run, passed
    run += 1
    try:
        world = make_world(world_spec, sets)
        i = 1
        for p in plan:
            run += 1
            (pre, eff, subst) = p

            preexp = make_expression(pre)
            effexp = make_expression(eff)

            for s in subst:
                (var, val) = s
                preexp = substitute(preexp, var, val)
                effexp = substitute(effexp, var, val)
            if not models(world, preexp):
                print("precondition failed at step", i)
                return False
            world = apply(world, effexp)
            passed += 1
            i += 1
        exp = make_expression(expression_spec)
        res = models(world, exp)
        if res == result:
            passed += 1
            return True
    except Exception:
        traceback.print_exc()
    return False
def run_test_planp(world_spec, plan, expression_spec, result, sets={}):
    global run, passed
    run += 1
    try:
        world = make_world(world_spec, sets)
        i = 1
        for p in plan:
            run += 1
            (pre, eff, subst) = p

            preexp = make_expression(sub(pre, subst))
            effexp = make_expression(sub(eff, subst))
            printNAryTree(effexp.getRoot())

            if not models(world, preexp):
                print("precondition failed at step", i, preexp)
                return False
            world = apply(world, effexp)
            passed += 1
            i += 1
        exp = make_expression(expression_spec)
        res = models(world, exp)
        if res == result:
            passed += 1
            return True
        else:
            print('Not pass planp')
            print('world')
            print(world_spec)
            print('plan')
            print(plan)
            print('exp')
            print(expression_spec)
            print('result')
            print(result)
            print('set')
            print(sets)
    except Exception:
        print('error 5')
        traceback.print_exc()
    return False
예제 #3
0
def run_test_simple(world_spec, expression_spec, result, sets={}):
    global run, passed
    run += 1
    try:
        world = make_world(world_spec, sets)
        exp = make_expression(expression_spec)
        res = models(world, exp)
        if res == result:
            passed += 1
            return True
    except Exception:
        traceback.print_exc()
    return False
예제 #4
0
 def get_neighbors(self):
     # for each grounded action
     for ac in groundedActions:
         # if the action is modeled in the state
         if expressions.models(self.state,
                               expressions.make_expression(
                                   ac.precondition)):
             ## apply the effect to the world
             newstate = expressions.apply(
                 self.state, expressions.make_expression(ac.effect))
             ## add state to the neighbours list as an edge
             nt = PlanNode(ac.name, newstate, self.objs)
             ne = graph.Edge(nt, 1, ac.name)
             self.neighbours.append(ne)
     return self.neighbours
예제 #5
0
def run_test_substitute(world_spec, expression_spec, subst, result, sets={}):
    global run, passed
    run += 1
    try:

        world = make_world(world_spec, sets)
        action = make_expression(action_spec)
        world1 = apply(world, action)
        exp = make_expression(expression_spec)
        res = models(world1, exp)
        if res == result:
            passed += 1
            return True
    except Exception:
        traceback.print_exc()
    return False
예제 #6
0
def computeRPG(actions, start, isgoal):

    fluents = []
    actionsApplied = []
    executedActionEffects = {}

    #initialize
    fluents.append(copy.deepcopy(start))
    actionsApplied.append([])
    t = 0

    while not isgoal(fluents[t]):  # while goal is not in the layer
        t += 1
        actionsApplied.append([])
        for rac in groundedActions:  # find the actions that can be applied
            if expressions.models(
                    fluents[t - 1].state,
                    expressions.make_expression(rac.precondition)):
                actionsApplied[t].append(rac)

        fluents.append(copy.deepcopy(
            fluents[t - 1]))  # copy the fluents of last layer

        for act in actionsApplied[t]:  #apply the actions to this  layer
            actionEffects = expressions.apply(
                fluents[t].state,
                expressions.make_expression(act.effect, True))
            aef = []
            for atm in actionEffects.formulas:
                if atm not in fluents[t].state.formulas:
                    aef.append(atm)
                    fluents[t].state.formulas.append(atm)
                if len(aef) > 0:
                    executedActionEffects[str(t) + act.name] = aef

        if t > 0 and fluents[t].state == fluents[
                t -
                1].state:  # if the new state is no different than the last one, fail
            return None, None, None

    return fluents, actionsApplied, executedActionEffects
def run_test_apply(world_spec, action_spec, expression_spec, result, sets={}):
    global run, passed
    run += 1
    try:
        world = make_world(world_spec, sets)
        action = make_expression(action_spec)
        world1 = apply(world, action)
        exp = make_expression(expression_spec)
        res = models(world1, exp)
        if res == result:
            passed += 1
            return True
        else:
            print('Not pass apply')
            print(world_spec)
            print(action_spec)
            print(expression_spec)
            print(sets)
            print(result)
    except Exception:
        print('error 2')
        traceback.print_exc()

    return False
예제 #8
0
    def createNeighbors_PlanNode(self, allPossibleActions, actionsDictionary, useheuristic):
        allKeys = allPossibleActions.keys()
        actionsKeys = actionsDictionary.keys()      
        #print('')
        #print(allPossibleActions)
        #print(actionsKeys)

        for key in allKeys:
            #print(key)
            #print(actionsDictionary[key][1])
            #print("--------------------------")
            #print(actionsDictionary[key][2])
            expTree = expressions.make_expression(actionsDictionary[key][1])

            if len(allPossibleActions[key]) < 1:
                neighName = ''
                neighName = '' + key + '()'
                precondition = []
                #print(neighName)
                if expressions.models(self.world, expTree):
                    #print('models')
                    tempworld = deepcopy(self.world)
                    if len(actionsDictionary[key][2]) == 1:
                        expEffect = actionsDictionary[key][2]
                        expressions.applyToWorld(tempworld, expEffect, useheuristic)
                        self.neighbors.append(Edge(PlanNode(self.initialStates, self.domainTypes, None, tempworld, neighName), 1, neighName))
                    else:
                        expEffect = expressions.make_expression(actionsDictionary[key][2])
                        for tuple in precondition:
                            expressions.substitute(expEffect, tuple[0], tuple[1])
                        expressions.applyToWorld(tempworld, expEffect, useheuristic)
                        self.neighbors.append(Edge(PlanNode(self.initialStates, self.domainTypes, None, tempworld, neighName), 1, neighName))
                #else:
                    #print(self.world)
                    #print('Does not models')

            else:
                for action in allPossibleActions[key]:
                
                    #print(actionsDictionary[key][1])
                    precondition = []
                    neighName = ''
                    neighName = '' + key + '('
                    first = True
                    second = True
                    allActionKeys = action.keys()
                    for ak in allActionKeys:
                        if first:
                            neighName = neighName + action[ak] + ', '
                            precondition.append((ak,action[ak]))
                            first = False
                        elif second:
                            neighName = neighName + action[ak]
                            precondition.append((ak,action[ak]))
                            second = False
                        else:
                            neighName = neighName+ ', ' + action[ak]
                            precondition.append((ak,action[ak]))
                    neighName = neighName + ')'

                    tempcopy = deepcopy(expTree)
                    for tuple in precondition:
                        expressions.substitute(tempcopy, tuple[0], tuple[1])
                
                    #print(neighName)
                    if expressions.models(self.world, tempcopy):
                        #print('')
                        #print(neighName)
                        #print(precondition)
                        #print(self.world)
                        tempworld = deepcopy(self.world)



                        #print('Applying: ')

                        if len(actionsDictionary[key][2]) == 1:
                            expEffect = actionsDictionary[key][2]
                            #print(tempworld)
                            expressions.applyToWorld(tempworld, expEffect, useheuristic)
                            #print(tempworld)
                            self.neighbors.append(Edge(PlanNode(self.initialStates, self.domainTypes, None, tempworld, neighName), 1, neighName))
                        else:
                            #print(tempworld)
                            expEffect = expressions.make_expression(actionsDictionary[key][2])
                            for tuple in precondition:
                                expressions.substitute(expEffect, tuple[0], tuple[1])
                            expressions.applyToWorld(tempworld, expEffect, useheuristic)
                            #print(tempworld)
                            self.neighbors.append(Edge(PlanNode(self.initialStates, self.domainTypes, None, tempworld, neighName), 1, neighName))
예제 #9
0
def astar(start, heuristic, goal, allActions, actionsDictionary, useheuristic):
    """
    A* search algorithm. The function is passed a start graph.Node object, a heuristic function, and a goal predicate.
    
    The start node can produce neighbors as needed, see graph.py for details.
    
    The heuristic is a function that takes two parameters: a node, and an edge. The algorithm uses this heuristic to determine which node to expand next.
    Note that, unlike in classical A*, the heuristic can also use the edge used to get to a node to determine the node's heuristic value. This can be beneficial when the 
    edges represent complex actions (as in the planning case), and we want to take into account the differences produced by that action.
    
    The goal is also represented a function, that is passed a node, and returns True if that node is a goal node, otherwise False. This representation was also chosen to
    simplify implementing the planner later, which can use the functions developed in task 1 to determine if a state models the goal condition, 
    but is otherwise equivalent to classical A*. 
    
    The function should return a 4-tuple (path,distance,visited,expanded):
        - path is a sequence of graph.Edge objects that have to be traversed to reach a goal state from the start.
        - distance is the sum of costs of all edges in the path 
        - visited is the total number of nodes that were added to the frontier during the execution of the algorithm 
        - expanded is the total number of nodes that were expanded (i.e. whose neighbors were added to the frontier)
    """

    #get_neighbors(self, allActions, actionDictionary)

    startingPathCost = 0
    startingHeuristic = 0
    startingPriority = startingPathCost + startingHeuristic

    startingPath = Path(startingPriority, startingPathCost, start)

    possiblePaths = PriorityQueue()
    possiblePaths.put(startingPath)

    priorityNode = possiblePaths.get()

    priorityNode.visitedNodes.add(priorityNode.node.get_id())

    expandedNodes = 0
    numFrontier = 0

    if expressions.models(priorityNode.node.world, goal):
        return priorityNode.edgesPassed, priorityNode.currentPathCost, numFrontier, expandedNodes

    while not expressions.models(priorityNode.node.world, goal):

        expandedNodes = expandedNodes + 1

        #print("------------Expanding: ",end='')
        #print(priorityNode.node.get_id())
        expandedNodesToAdd = []
        for edges in priorityNode.node.get_neighbors(allActions,
                                                     actionsDictionary,
                                                     useheuristic):
            #print(edges.target.get_id())
            #print(priorityNode.visitedNodes)
            if edges.target.get_id() not in priorityNode.visitedNodes:
                #print(type(priorityNode.node),type(edges))
                currentPathCost = priorityNode.currentPathCost + edges.cost
                currentHeuristic = heuristic(priorityNode.node, edges)
                #print(currentHeuristic)
                currentPriority = currentPathCost + currentHeuristic

                currentPath = Path(currentPriority, currentPathCost,
                                   edges.target)
                currentPath.nodesVisited = priorityNode.nodesVisited + 1
                currentPath.edgesPassed = copy.copy(priorityNode.edgesPassed)
                currentPath.edgesPassed.append(edges)
                currentPath.visitedNodes = copy.copy(priorityNode.visitedNodes)
                expandedNodesToAdd.append(currentPath)

        for nodesToAdd in expandedNodesToAdd:
            nodesToAdd.visitedNodes.add(priorityNode.node.get_id())
            possiblePaths.put(nodesToAdd)
        priorityNode = possiblePaths.get()
        numFrontier = numFrontier + possiblePaths.qsize()

    return priorityNode.edgesPassed, priorityNode.currentPathCost, numFrontier, expandedNodes
예제 #10
0
 def isgoal(state):
     return expressions.models(state.state, goalExp)