Esempio n. 1
0
    def build_current_goal_sets_same(self, objs):
        '''
        input : generate the goals
        functionality : generate the building goals,
                         might be same number of goals in towers as well
        output: update self.curr_goal_sets with building goals
        '''
        number = self.find_sum_natural_numbers_nearest_number(len(objs))
        index = 0
        for goals_number in range(1, number - 1):
            each_goal_set = []
            goals_no = random.randint(1, number - 1)
            if (index > (len(objs) - 1)):
                break
            for i in range(0, goals_no):
                if (index > (len(objs) - 1)):
                    break

                if i == 0:
                    each_goal_set.append(
                        goals.Goal(*[objs[index]], predicate='on-table'))
                    index = index + 1
                else:
                    each_goal_set.append(
                        goals.Goal(*[objs[index], objs[index - 1]],
                                   predicate='stable-on'))
                    index = index + 1
            self.curr_goal_sets.append(each_goal_set)
Esempio n. 2
0
 def parseGoal(self, txt):
     if not txt.endswith(")"):
         print(
             "Error reading goal. Goal must be given in the form: predicate(arg1, arg2,...,argi-1,argi), where each argument is the name of an object in the world"
         )
         return None
     try:
         if txt.startswith('!'):
             negate = True
             txt = txt[1:]
         else:
             negate = False
         predicateName = txt[:txt.index("(")]
         args = [
             arg.strip() for arg in txt[txt.index("(") + 1:-1].split(",")
         ]
         #use on-table predicate
         if predicateName == 'on' and len(args) == 2 and 'table' == args[1]:
             predicateName = 'on-table'
             args = args[:1]
         if negate:
             goal = goals.Goal(*args, predicate=predicateName, negate=True)
         else:
             goal = goals.Goal(*args, predicate=predicateName)
         return goal
     except Exception:
         print(
             "Error reading goal. Goal must be given in the form: predicate(arg1, arg2,...,argi-1,argi), where each argument is the name of an object in the world"
         )
         return None
Esempio n. 3
0
    def handle_armed_agent(self, agent, state, verbose):
        """Determine the goal of an armed agent by looking at the enemies around it."""
        agentLoc = agent.at
        worldMap = state.map
        enemies = worldMap.filter_objects(civi=False)
        self.logger.info("Determining agent {}'s goal".format(agent))
        target = None
        for enemy in enemies:
            self.logger.info('Checking enemy {}'.format(enemy))
            if state.map.adjacent(enemy.location, agentLoc):
                target = enemy
                self.logger.info('Found potential target {}'.format(target))
                break

        if target is None:
            if verbose >= 1:
                print 'Allied agent {} is arming but no target is visible'.format(
                    agent)
            self.logger.info(
                "Saw agent {} arming, but didn't see target".format(agent))
            return
        else:
            agentGoal = goals.Goal(target.id, predicate='killed', user=None)
            self.logger.info('Identified goal {} for {}'.format(
                agentGoal, agent))
            return agentGoal
Esempio n. 4
0
    def run(self, cycle, verbose=2):
        """
        Create a goal for each inactive agent and remember the pairings.

        This function looks at each inactive agent, calculates the closest living
        enemy to that agent, and assigns the goal of killing that enemy to the
        agent. It does **not** actually order the agents to complete the goals,
        though.
        """
        self.logger.info('Retrieving available agents, living enemies, and the op')
        availAgents = self.mem.get('AVAIL_AGENTS')
        enemies = self.mem.get('ENEMIES')
        optr = self.client.operator()
        while optr is None:
            optr = self.client.operator()

        goalPairs = []
        for agt in availAgents:
            self.logger.info('Finding goal for {}'.format(agt))
            target = self.get_closest_enemy(agt, enemies)
            if target is None:
                continue
            goal = goals.Goal(target.id, predicate='killed', user=optr.id)
            self.logger.info('Found goal {}'.format(goal))
            goalPairs.append((agt, goal))

        self.mem.set('PLANNED_GOALS', goalPairs)
        self.logger.info('Saved planned goals')
        return
Esempio n. 5
0
def specailization(mem, goal, canexec):
    '''
	get the world from memory , create a dictionary of its preconditions and check the second precondition and later both the first and 		the third preconditions . The second precondition returns the children node , while the first checks whether the predicate and the 		objects are in the world or not . The third pre condition checks the resources. The canexec is 0 for choose checking it else it should 		be 1 
	'''
    world = mem.myMidca.midca.world
    cond = preconditions_all(mem)
    preconditions = {
        'pre': cond.genral_precondition1,
        'pre1': cond.specail_precondition2,
        'pre2': cond.genral_precondition3
    }
    p1 = preconditions['pre1'](world, goal.get_pred())
    if p1 == False:
        return False

    else:
        result_goal = goals.Goal(*goal.get_args(), predicate=p1.predicate)

    if preconditions['pre'](world, goal.get_pred(),
                            goal.get_args()) and preconditions['pre2'](mem):
        if canexec:
            world.cltree['checked'].append(p1.predicate)
        return result_goal
    else:
        return False
Esempio n. 6
0
 def run(self, cycle, verbose=2):
     arsonist = self.free_arsonist()
     if arsonist and self.is_fire():
         goal = goals.Goal(arsonist, predicate="free", negate=True)
         inserted = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
         if verbose >= 2:
             print("Meta-AQUA simulation goal generated:", goal, end=' ')
             if inserted:
                 print()
             else:
                 print(". This goal was already in the graph.")
Esempio n. 7
0
    def parse_input(self, userIn, senderID):
        """Turn user input into a goal."""
        acceptable_goals = ['agent-at', 'open', 'killed']
        if userIn == 'q' or userIn == '':
            return userIn
        else:
            goalData = userIn.split()
            self.logger.info("Recv'd goal data {}".format(goalData))
            if goalData[0] not in acceptable_goals:
                error = '{} is not a valid goal command'.format(goalData[0])
                return (False, error)
            goalPred = goalData[0]
            if goalPred in ('agent-at', 'open'):
                x, y = goalData[1].strip('()').split(',')
                try:
                    x = int(x)
                    y = int(y)
                except ValueError:
                    error = 'x and y must be integers'
                    return (False, error)

                goalLoc = (x, y)
                if not self.state.map.loc_valid(
                        goalLoc) or not self.state.map.loc_is_free(goalLoc):
                    error = 'Invalid location {} for goal {}'.format(
                        goalLoc, goalPred)
                    return (False, error)
                goal = goals.Goal(goalLoc, predicate=goalPred, user=senderID)
            elif goalPred in ('killed', ):
                targetID = goalData[1].strip('()')
                target = None
                for obj in self.state.known_objects:
                    if obj.id == targetID:
                        target = obj
                        break

                if target is None:
                    error = "Don't know of target {}".format(targetID)
                    return (False, error)
                goal = goals.Goal(targetID, predicate=goalPred, user=senderID)
            return (goal, '')
Esempio n. 8
0
 def parseGoal(self, txt):
     if not txt.endswith(")"):
         print "Error reading input. Atom must be given in the form: predicate(arg1, arg2,...,argi-1,argi), where each argument is the name of an object in the world"
         return None
     try:
         predicateName = txt[:txt.index("(")]
         args = [arg.strip() for arg in txt[txt.index("(") + 1:-1].split(",")]
         goal = goals.Goal(*args, predicate = predicateName)
         return goal
     except Exception:
         print "Error reading input. Atom must be given in the form: predicate(arg1, arg2,...,argi-1,argi), where each argument is the name of an object in the world"
         return None
Esempio n. 9
0
 def build_current_goal_sets(self, objs):
     '''
     input : generate the goals
     functionality : generate the building goals in the oreder of 1,2 -- nearest natural number
     output: update self.curr_goal_sets with building goals
     '''
     number = self.find_sum_natural_numbers_nearest_number(len(objs))
     index = 0
     for goals_number in range(1, number):
         each_goal_set = []
         for i in range(0, goals_number):
             if i == 0:
                 each_goal_set.append(
                     goals.Goal(*[objs[index]], predicate='on-table'))
                 index = index + 1
             else:
                 each_goal_set.append(
                     goals.Goal(*[objs[index], objs[index - 1]],
                                predicate='stable-on'))
                 index = index + 1
         self.curr_goal_sets.append(each_goal_set)
    def gen_alt_goals(self, oldGoal, reason, verbose):
        """Create and return possible alternate goals to a rejected goal."""
        altGoals = []
        if reason == 'civi-in-AOE':
            for enemy in self.agent.filter_objects(objType='NPC', civi=False, alive=True):
                altGoal = goals.Goal(enemy.id, predicate='killed', user=oldGoal['user'])
                if verbose >= 2:
                    print 'Generated single alt goal {} from enemy id {}'.format(altGoal, enemy.id)
                if self.agent.valid_goal(altGoal)[0]:
                    altGoals.append(altGoal)

        altGoals.append(oldGoal)
        altGoals.append('None')
        return altGoals
Esempio n. 11
0
    def run(self, cycle, verbose=2):
        trace = self.mem.trace
        if trace:
            trace.add_module(cycle, self.__class__.__name__)
        self.verbose = verbose
        # get discrepancies
        discrep = self.mem.get(self.mem.DISCREPANCY)
        # if discrepancy, get explanation
        if discrep and (len(discrep[0]) > 0 or len(discrep[1]) > 0):
            # first remove old
            # go ahead and remove old plans for any goals the agent has
            # refresh the goals to trigger replanning
            goalgraph = self.mem.get(self.mem.GOAL_GRAPH)
            curr_goals = self.mem.get(self.mem.CURRENT_GOALS)

            if type(curr_goals) is not list:
                curr_goals = [curr_goals]
            for goal in curr_goals:
                # get any plans associated with this goal, and remove them
                plan = goalgraph.getMatchingPlan([goal])
                if plan:
                    goalgraph.removePlan(plan)
                    if self.verbose >= 1:
                        print("Just removed a plan for goal " + str(goal))

            #print "aware of actual discrepancy, retrieving explanation"
            explain_exists = self.mem.get(self.mem.EXPLANATION)
            explanation = self.mem.get(self.mem.EXPLANATION_VAL)
            if explain_exists:

                # now do stuff based on explanation
                if 'stuck' in explanation:
                    # remove current goal from goal graph
                    # insert goal to become free
                    # The priority will automatically be shifted to
                    goalgraph = self.mem.get(self.mem.GOAL_GRAPH)
                    free_goal = goals.Goal('Curiosity', predicate="free")
                    goalgraph.insert(free_goal)
                    if self.verbose >= 1:
                        print("Just inserted goal " + str(free_goal))
                    return
                else:  #if 'wind' in explanation:
                    # do nothing for other explanations, this will just lead to replanning
                    return
            else:
                if self.verbose >= 1:
                    print(
                        "No explanation, old plans removed, but no goal management actions"
                    )
                return
Esempio n. 12
0
    def generate_new_goals(self):
        if self.currGoalIndex < len(self.goalList):
            curr_goal = self.goalList[self.currGoalIndex]
            #if self.verbose >= 1: print "inserting goal "+str(curr_goal)
            self.currGoalIndex += 1
            return [curr_goal]
        if self.currGoalIndex == len(self.goalList):
            print("No more goals...")
            self.currGoalIndex += 1
        return []

        # this is a safety check to make sure experiments are running correctly.
        # if running manual (like running from examples/nbeacons...agentx.py remove this line
        raise Exception(
            "randomly inserting goals, shouldn't be here when running from nbeacons_experiment_1.py"
        )
        world = self.mem.get(self.mem.STATES)[-1]
        goal_b_ids = []
        # get all beacon ids
        unactivated_b_ids = []
        for obj in world.get_possible_objects("", ""):
            # test if a beacon id
            if str(obj).startswith("B"):
                # now test to see if it's activated
                if not world.is_true('activated', [str(obj)]):
                    unactivated_b_ids.append(str(obj))

        if len(unactivated_b_ids) == 0:
            if self.verbose >= 1:
                print(
                    "All beacons are activated. No activation goals will be generated."
                )
            return []

        num_chosen_beacons = 0
        while len(unactivated_b_ids
                  ) > 0 and num_chosen_beacons < self.numbeacons:
            b = random.choice(unactivated_b_ids)
            unactivated_b_ids.remove(b)
            goal_b_ids.append(b)
            num_chosen_beacons += 1

        # turn into goals
        new_goals = [
            goals.Goal(str(x), predicate="activated") for x in goal_b_ids
        ]

        return new_goals
Esempio n. 13
0
    def create_current_goal_sets(self, count_goals, persons_names,
                                 dishes_names):
        # generate random sets of goals and append it to the variable curr_goal_sets
        # create "count_goals" number of goals and append it to self.curr_goal_sets
        # get random goals for each person
        # get random no:of dishes ordered by a person

        for i in range(count_goals):
            random.shuffle(dishes_names)
            count_dishes = random.randint(1, len(dishes_names) - 1)
            for j in range(count_dishes):
                dish_choice = dishes_names[j]
                person = persons_names[i]
                random_goal = goals.Goal(*[person, dish_choice],
                                         predicate='order_serve')
                self.curr_goal_sets.append(random_goal)
Esempio n. 14
0
class SimpleMortarGoalGen(base.BaseModule):
    '''
    MIDCA module that cycles through goals for the agent to achieve.
    '''

    curr_goal_index = 0

    curr_goal_sets = [[
        goals.Goal(*['A_', 'B_'], predicate='stable-on'),
        goals.Goal(*['C_', 'A_'], predicate='stable-on'),
        goals.Goal(*['D_', 'C_'], predicate='stable-on')
    ],
                      [
                          goals.Goal(*['D_', 'B_'], predicate='stable-on'),
                          goals.Goal(*['B_', 'A_'], predicate='stable-on'),
                          goals.Goal(*['A_', 'C_'], predicate='stable-on')
                      ]]

    # starting state: on(D,B), on(B,A), ontable(A) ontable(C)
    # first goal: on(C,B)
    # second goal

    def next_goal(self):
        # get the next goal
        curr_goal_set = self.curr_goal_sets[self.curr_goal_index]
        # update index for next time around
        if self.curr_goal_index == len(self.curr_goal_sets) - 1:
            self.curr_goal_index = 0
        else:
            self.curr_goal_index += 1
        return curr_goal_set

    def run(self, cycle, verbose=2):
        trace = self.mem.trace
        if trace:
            trace.add_module(cycle, self.__class__.__name__)

        # first, check to see if we need a new goal, and only then insert a new one
        if len(self.mem.get(self.mem.GOAL_GRAPH).getAllGoals()) == 0:
            # get the next goal
            goal_set = self.next_goal()
            # insert that goal
            for g in goal_set:
                self.mem.get(self.mem.GOAL_GRAPH).insert(g)
            # update trace
            if trace:
                trace.add_data("NEXT GOAL(s)", goal_set)
                trace.add_data("GOAL GRAPH",
                               copy.deepcopy(self.mem.GOAL_GRAPH))
        else:
            if trace:
                trace.add_data("NEXT GOAL", 'goals not empty; no goal chosen')
                trace.add_data("GOAL GRAPH",
                               copy.deepcopy(self.mem.GOAL_GRAPH))
Esempio n. 15
0
 def run(self, cycle, verbose=2):
     try:
         text = self.readS.recv(self.readSize)
         if text != "None\n":
             p = Parser()
             # create frames
             frames = p.makeframegraph(text)
             noem = {}  # Node Operator Effect Mapping
             noem['CRIMINAL-VOLITIONAL-AGENT'] = [[
                 'apprehend', OPERATOR_EFFECT_NEGATION
             ]]
             # traverser class, initializes frames and noem
             t = Traverser(frames, noem)
             # gets the frame operator and effect
             (frame, operator, effect) = t.traverse()
             if operator == "apprehend":
                 apprehendGoal = goals.Goal("Gui Montag",
                                            predicate="free",
                                            negate=True)
                 inserted = self.mem.get(
                     self.mem.GOAL_GRAPH).insert(apprehendGoal)
                 if verbose >= 2:
                     print "Meta-AQUA goal generated:", apprehendGoal,
                     if inserted:
                         print
                     else:
                         print ". This goal was already in the graph."
             else:
                 if verbose >= 2:
                     print "Meta-AQUA output unrecognized. No goal generated. Output:\n",
                     text
     except socket.timeout:
         if verbose >= 1:
             print "Error: no data received from Meta-AQUA before timeout."
     except:
         if verbose >= 1:
             print "Error reading from Meta-AQUA.", +str(text)
             try:
                 #print " Got:\n" + text
                 pass
             except NameError:
                 print " Unable to read from socket."
Esempio n. 16
0
    def parse_input(self, userIn):
        """Turn user input into a goal."""
        acceptable_goals = ['agent-at', 'open']
        if userIn == 'q' or userIn == '':
            return userIn
        goalData = userIn.split()
        if goalData[0] not in acceptable_goals:
            print '{} is not a valid goal command'.format(goalData[0])
            return False
        goalPred = goalData[0]
        if goalPred in ('agent-at', 'open'):
            x, y = goalData[1].strip('()').split(',')
            try:
                x = int(x)
                y = int(y)
            except ValueError:
                print 'x and y must be integers'
                return False

            goalLoc = (x, y)
            goal = goals.Goal(goalLoc, predicate=goalPred)
        return goal
Esempio n. 17
0
import random
# Domain Specific Imports
from midca.domains.nbeacons import nbeacons_util
from midca.domains.nbeacons.plan import methods_nbeacons, operators_nbeacons

'''
Simulation of the NBEACONS domain (adapted from marsworld in [Dannenhauer and Munoz-Avila 2015]).

THIS IS THE START SCRIPT FOR THE GDA AGENT (no meta)

'''
wind_schedule = [[20,1],[40,2]]

goal_list = range(10)*10 # give 100 goals 
random.shuffle(goal_list)
goal_list = map(lambda x: goals.Goal('B'+str(x), predicate = "activated"), goal_list)
print "goal list is "
for g in goal_list:
    print "  "+str(g)

# Setup
thisDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
MIDCA_ROOT = thisDir + "/../"

### Domain Specific Variables
DOMAIN_ROOT = MIDCA_ROOT + "domains/nbeacons/"
DOMAIN_FILE = DOMAIN_ROOT + "domains/nbeacons.sim"
#STATE_FILE = DOMAIN_ROOT + "states/.sim" # state file is generated dynamically
DISPLAY_FUNC = nbeacons_util.drawNBeaconsScene
DECLARE_METHODS_FUNC = methods_nbeacons.declare_methods
DECLARE_OPERATORS_FUNC = operators_nbeacons.declare_operators
    def run(self, cycle, verbose=2):
        """Check each explanation and if it's about a goal solve that."""
        if self.mem.trace:
            self.mem.trace.add_module(cycle, self.__class__.__name__)
        state = self.mem.get(self.mem.STATE)
        if not self.mem.get(self.mem.EXPLANATION):
            if verbose >= 1:
                print 'No explanations to manage, continuing'
            self.logger.info('No explanations to manage, continuing')
            return
        goalGraph = self.mem.get(self.mem.GOAL_GRAPH)
        if not goalGraph:
            if verbose >= 1:
                print 'There are no goals, continuing'
                self.logger.info('There are no goals, continuing')
            return
        self.logger.info('Getting explanations to handle')
        explans = self.mem.get(self.mem.EXPLANATION_VAL)
        for explan in explans:
            self.logger.info('Handling explanation:\n\t{}'.format(explan))
            if not isinstance(explan[0], goals.Goal):
                continue
            goal = explan[0]
            reason = explan[1]
            if goal.kwargs['predicate'] == 'agent-at':
                if reason == 'unpassable':
                    goalGraph.remove(goal)
                    self.world.dialog(goal.kwargs['user'], 'removing invalid goal {}'.format(goal))
                    if verbose >= 1:
                        print 'removing invalid goal {}'.format(goal)
                    if self.mem.trace:
                        self.mem.trace.add_data('REMOVED GOAL', goal)
                    self.logger.info('\tRemoved invalid goal')
                elif reason == 'door-blocking':
                    doors = self.findDoorsFor(goal)
                    for door in doors:
                        newGoal = goals.Goal(door.location, predicate='open', parent=goal)
                        goalGraph.add(newGoal)
                        if verbose >= 1:
                            print 'added a new goal {}'.format(newGoal)
                        if self.mem.trace:
                            self.mem.trace.add_data('ADDED GOAL', newGoal)
                        self.world.dialog(goal['user'], 'added a new goal {}'.format(newGoal))
                        self.logger.info('\tAdded new goal {}'.format(newGoal))

                else:
                    raise Exception("Discrepancy reason {} shouldn't exist".format(reason))
            elif goal.kwargs['predicate'] == 'open':
                if reason == 'no-object':
                    goalGraph.remove(goal)
                    self.world.dialog(goal.kwargs['user'], 'removing invalid goal {}'.format(goal))
                    if verbose >= 1:
                        print 'removing invalid goal {}'.format(goal)
                    if self.mem.trace:
                        self.mem.trace.add_data('REMOVED GOAL', goal)
                    self.logger.info('\tRemoved invalid goal')
                else:
                    raise Exception("Discrepancy reason {} shouldn't exist".format(reason))
            elif goal.kwargs['predicate'] == 'killed':
                if reason == 'target-not-found':
                    goalGraph.remove(goal)
                    self.world.dialog(goal.kwargs['user'], 'removing invalid goal {}'.format(goal))
                    if verbose >= 1:
                        print 'removing invalid goal {}'.format(goal)
                    if self.mem.trace:
                        self.mem.trace.add_data('REMOVED GOAL', goal)
                    self.logger.info('\tRemoved invalid goal')
                elif reason == 'civi-in-AOE':
                    civilians = self.agent.get_civs_in_blast()
                    rebellion = Rebellion(goal, reason=reason, civilians=civilians, target=state.map.get_object(goal[0]), agent=self.agent)
                    self.logger.info('\tGenerated rebellion:\n\t{}'.format(rebellion))
                    if verbose >= 1:
                        print 'rejecting goal {}'.format(goal)
                        print str(rebellion)
                    if self.mem.trace:
                        self.mem.trace.add_data('REBELLION', rebellion)
                    if not self.mem.get('REBELLION'):
                        self.mem.set('REBELLION', [rebellion])
                    else:
                        self.mem.add('REBELLION', rebellion)
                else:
                    raise Exception("Discrepancy reason {} shouldn't exist".format(reason))
            else:
                raise NotImplementedError('Goal {} is not there yet'.format(goal))

        if verbose >= 1:
            print 'Done managing goals \n'
        self.logger.info('Done managing goals')
        if self.mem.trace:
            self.mem.trace.add_data('GOALS', goalGraph)
Esempio n. 19
0
from midca.worldsim import domainread, stateread
import inspect, os
import random
# Domain Specific Imports
from midca.domains.nbeacons import nbeacons_util
from midca.domains.nbeacons.plan import methods_nbeacons, operators_nbeacons

'''
Simulation of the NBEACONS domain (adapted from marsworld in [Dannenhauer and Munoz-Avila 2015]).

THIS IS THE START SCRIPT FOR THE VANILLA AGENT (no gda, no meta)
'''
wind_schedule = [[20,1],[40,2]]
goal_list = list(range(10))*10 # give 100 goals 
random.shuffle(goal_list)
goal_list = [goals.Goal('B'+str(x), predicate = "activated") for x in goal_list]
print("goal list is ")
for g in goal_list:
    print("  "+str(g))

# Setup
thisDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
MIDCA_ROOT = thisDir + "/../"

### Domain Specific Variables
DOMAIN_ROOT = MIDCA_ROOT + "domains/nbeacons/"
DOMAIN_FILE = DOMAIN_ROOT + "nbeacons.sim"
#STATE_FILE = DOMAIN_ROOT + "states/.sim" # state file is generated dynamically
DISPLAY_FUNC = nbeacons_util.drawNBeaconsScene
DECLARE_METHODS_FUNC = methods_nbeacons.declare_methods
DECLARE_OPERATORS_FUNC = operators_nbeacons.declare_operators
Esempio n. 20
0
def runexperiment():
    # reset in case we run multiple experiments
    DATADIR = "experiments/nbeacons-experiment-1-data/"
    NOW_STR = datetime.datetime.strftime(datetime.datetime.now(),
                                         '%Y-%m-%d--%H-%M-%S')
    DATA_FILENAME = DATADIR + "NBeaconsExperiment1" + NOW_STR + ".csv"
    DATA_FILE_HEADER_STR = "runID,numCycles,agentType,windDir,windStrength,goalsActionsAchieved\n"
    SCENARIO_FILENAME = DATADIR + "NBeaconsScenario" + NOW_STR + ".txt"

    runs = []

    # generate goals randomly, such that no goal is repeated twice
    num_goals = 1000
    goal_list = []
    i = 0
    possible_goals = list(range(10))
    last_chosen_goal = -1
    while i < num_goals:
        if last_chosen_goal == -1:
            curr_goal = random.choice(possible_goals)
            goal_list.append(curr_goal)
            last_chosen_goal = curr_goal
        else:
            tmp_possible_goals = set(possible_goals) - set([last_chosen_goal])
            curr_goal = random.sample(tmp_possible_goals, 1)[0]
            goal_list.append(curr_goal)
            last_chosen_goal = curr_goal
        i += 1

    goal_list = [
        goals.Goal('B' + str(x), predicate="activated") for x in goal_list
    ]
    #print("goal list is ")
    #for g in goal_list:
    #    print("  "+str(g))
    state1 = nbeacons_util.NBeaconGrid()
    #state1.generate_good_test()
    state1.generate(width=DIMENSION,
                    height=DIMENSION,
                    num_beacons=NUM_BEACONS,
                    num_quicksand_spots=NUM_QUICKSAND)
    state1_str = state1.get_STRIPS_str()

    # args are [runID, agentType, windDir, windStrength, startingState, goalList]
    individual_runs = [
        # no wind, same starting state, same starting goals
        [0, 'v', 'east', 0, state1_str, goal_list],
        [1, 'g', 'east', 0, state1_str, goal_list],
        [2, 'm', 'east', 0, state1_str, goal_list],
    ]

    runs = individual_runs

    # Uses multiprocessing to give each run its own python process
    print(("-- Starting experiment using " + str(NUM_PROCESSES) +
           " processes..."))
    t0 = time.time()
    # **** NOTE: it is very important chunksize is 1 and maxtasksperchild is 1
    # **** (each MIDCA must use its own python process)
    pool = Pool(processes=NUM_PROCESSES, maxtasksperchild=1)
    results = pool.map(singlerun, runs, chunksize=1)
    t1 = time.time()
    timestr = '%.2f' % (t1 - t0)
    print(("-- Experiment finished! Took " + timestr + "s, generated " +
           str(len(results)) + " data points"))
    print("-- Writing data to file...")
    f = open(DATA_FILENAME, 'w')
    f.write(DATA_FILE_HEADER_STR)
    for r in results:
        f.write(r)
    print(("-- Data written to file " + str(DATA_FILENAME)))
    print("-- Experiment complete!")

    # if you have pyttsx installed, a voice will tell you your experiments are finished
    try:
        import pyttsx
        engine = pyttsx.init()
        engine.setProperty('rate', 70)
        engine.say('Your experiments are have finished running')
        engine.runAndWait()
    except:
        pass  # do nothing
Esempio n. 21
0
    def act(self, action, verbose=2):
        # TODO: figure out a way to make the init_args more general (so actions can be kept separate)
        if action[0] == "REMOVE-MODULE":
            # find the component
            module_index = -1
            phase = None
            mod_str = ""

            class Found(Exception):
                pass  # is this bad python? should this go at top of my file?

            try:
                for phasei in self.mem.myMidca.get_phases():
                    i = 0
                    for mod in self.mem.myMidca.get_modules(phasei):
                        mod_str = str(mod.__class__.__name__)
                        print("-*-*- act():  mod = " + mod_str +
                              ", action[1] = " + str(action[1]))
                        if mod_str == action[1]:
                            print("-*-*- act(): we got a match!")
                            module_index = i
                            phase = phasei
                            raise Found
                        i += 1
            except Found:

                # remove the component
                #print("-*-*- act():  phase = "+str(phase)+", module_index = "+str(module_index))
                if phase and module_index > -1:
                    mod = self.mem.myMidca.remove_module(phase, module_index)
                    print "mod is " + str(mod)
                    self.prev_init_args = mod.get_init_args(
                    )  # TODO: only works for modules implementing get_init_args
                    print "got init args: " + str(self.prev_init_args)
                    is_success = mod_str not in map(
                        lambda x: x.__class__.__name__,
                        self.mem.myMidca.get_modules(phase))
                    if is_success:
                        print("    Metareasoner removed " + mod_str
                              )  # report any actions metareasoner carried out
                    return is_success
        elif action[0] == "ADD-MODULE":
            if action[2] == "PyHopPlanner":
                #print("current directory: "+str(os.getcwd()))
                #print("str(dir(modules)) = "+str(dir(modules)))
                planningModuleInstance = importlib.import_module(
                    "midca.modules.planning")
                print("loaded planning module, it has following attributes: " +
                      str(dir(planningModuleInstance)))
                # get the args used to init the old module and use them to init this one
                print "init args is " + str(self.prev_init_args)

                # **** BEGIN: MAGIC! Transform the args *****
                # This is where the real magic happens
                # Hardcoded for now
                # Very Important TODO but likely requires serious research effort
                from midca.domains.blocksworld.plan import methods
                working_methods = methods.declare_methods
                corrected_args = self.prev_init_args
                hardcoded_index_of_methods_arg = 2  # TODO: I know, so hacky, ahhh magic numbers
                corrected_args[2] = working_methods
                # **** END: MAGIC! Transform the args *****

                pyHopPlannerInstance = planningModuleInstance.PyHopPlanner(
                    *corrected_args)
                self.mem.myMidca.runtime_append_module(
                    "Plan", pyHopPlannerInstance
                )  # TODO: hardcoded knowledge of Plan phase
                is_success = "PyHopPlanner" in map(
                    lambda x: x.__class__.__name__,
                    self.mem.myMidca.get_modules("Plan"))
                if is_success:
                    print("    Metareasoner added PyHopPlanner"
                          )  # report any actions metareasoner carried out
                return is_success
            elif action[2] == "AsynchPyhopPlanner":
                #print("current directory: "+str(os.getcwd()))
                #print("str(dir(modules)) = "+str(dir(modules)))
                planningModuleInstance = importlib.import_module(
                    "midca.modules.planning")
                print(
                    "loaded asynchronous planning module, it has following attributes: "
                    + str(dir(planningModuleInstance)))
                # get the args used to init the old module and use them to init this one
                #print "init args is "+str(self.prev_init_args)
                ###### HACK: hardcoded for now as a demo, this is because the initial broken
                # planner had different parameters for instantiating it, so we cant use the\
                # same prev_init_args, and thus changing them here
                from midca.modules._plan.asynch import operators_sr, methods_sr
                self.prev_init_args = [
                    methods_sr.declare_methods, operators_sr.declare_ops
                ]

                # **** BEGIN: MAGIC! Transform the args *****
                # This is where the real magic happens
                # Hardcoded for now
                # Very Important TODO but likely requires serious research effort
                #from midca.domains.blocksworld.plan import methods
                #working_methods = methods.declare_methods
                corrected_args = self.prev_init_args
                #hardcoded_index_of_methods_arg = 2 # TODO: I know, so hacky, ahhh magic numbers
                #corrected_args[2] = working_methods
                # **** END: MAGIC! Transform the args *****

                pyHopPlannerInstance = planningModuleInstance.AsynchPyhopPlanner(
                    *corrected_args)
                self.mem.myMidca.runtime_append_module(
                    "Plan", pyHopPlannerInstance
                )  # TODO: hardcoded knowledge of Plan phase
                is_success = "AsynchPyhopPlanner" in map(
                    lambda x: x.__class__.__name__,
                    self.mem.myMidca.get_modules("Plan"))
                if is_success:
                    print("    Metareasoner added AsynchPyhopPlanner"
                          )  # report any actions metareasoner carried out
                return is_success
        elif action[0] == "TRANSFORM-GOAL":
            # really: its going to have this meta plan by changing the things in orange -
            # you don't monitor and look at the trace to see if the goal transformation achieved something
            # at the ground level, so then meta-evaluate can know if the metagoal succeeded. What if I made the
            # wrong transformation?

            # specific to mortar and blocks world, not general
            # get the highest blocks
            goal_atoms = action[1]
            goal_args = map(lambda x: x.get_args(), goal_atoms)

            # figure out how much mortar we have using the world state
            num_available_mortar = 0
            for atom in map(str,
                            self.mem.get("__world states")[-1].get_atoms()):
                if 'available(' in atom:
                    num_available_mortar += 1
                    if verbose >= 3:
                        print("found available mortar: " + str(atom))

            # transform 'stable-on' to 'on' predicates ensuring there is enough mortar for each
            bottom_blks = []
            top_blks = []
            for a_tpl in goal_args:
                bottom_blks.append(a_tpl[1])
                top_blks.append(a_tpl[0])

            bottommost_blk = [b for b in bottom_blks if b not in top_blks][0]

            transformed_goal_atoms = []

            # transform goal atoms
            curr_bottom_blk = bottommost_blk
            while curr_bottom_blk in bottom_blks:
                i = bottom_blks.index(curr_bottom_blk)
                top_blks[i]
                if num_available_mortar > 0:
                    transformed_goal_atoms.append("stable-on," + top_blks[i] +
                                                  "," + curr_bottom_blk)
                    num_available_mortar -= 1
                else:
                    transformed_goal_atoms.append("on," + top_blks[i] + "," +
                                                  curr_bottom_blk)
                curr_bottom_blk = top_blks[i]

            # now make actual MIDCA goal objects
            transformed_goals = []
            for atom_str in transformed_goal_atoms:
                vals = atom_str.split(",")
                transformed_goals.append(
                    goals.Goal(*[vals[1], vals[2]], predicate=vals[0]))

            goalGraph = self.mem.get(self.mem.GOAL_GRAPH)

            # do removal first
            for g in goal_atoms:
                goalGraph.remove(g)
            if verbose >= 2:
                # now display success statement
                print("Removed from the goal graph the previous goal:")
                for g in goal_atoms:
                    print("    " + str(g))

            # now display transformed goal
            if verbose >= 2:
                print("Goal has been transformed to:")
                for g in transformed_goals:
                    print("    " + str(g))

            # now insert the new goal
            for g in transformed_goals:
                goalGraph.insert(g)
            if verbose >= 2:
                print("Transformed goal has been inserted into goal graph.")

            return True
Esempio n. 22
0
    def run(self, cycle, verbose=2):
        world = self.mem.get(self.mem.STATE)
        i = len(world.utterances)
        while i > 0:
            if self.lastTime - world.utterances[i - 1].time > 0:
                break
            i -= 1
        newUtterances = [
            utterance.utterance for utterance in world.utterances[i:]
        ]
        #now add goals based on new utterances
        for utterance in newUtterances:
            if verbose >= 2:
                print("received utterance:", utterance)
            if utterance == "point to the quad" or utterance == "goodbye baxter":
                goal = goals.Goal(objective="show-loc",
                                  subject="self",
                                  directObject="quad",
                                  indirectObject="observer")
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")
            if utterance == "get the red block":
                goal = goals.Goal(objective="holding",
                                  subject="self",
                                  directObject="red block",
                                  indirectObject="observer",
                                  pos='red block:arm')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "get the green block":
                goal = goals.Goal(objective="holding",
                                  subject="self",
                                  directObject="green block",
                                  indirectObject="observer",
                                  pos='green block:arm')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "get the blue block":
                goal = goals.Goal(objective="holding",
                                  subject="self",
                                  directObject="blue block",
                                  indirectObject="observer",
                                  pos='blue block:arm')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")
            if utterance == "put the green block on table":
                goal = goals.Goal(objective="moving",
                                  subject="self",
                                  directObject="green block",
                                  indirectObject="observer",
                                  pos='green block:table')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")
            if utterance == "put the blue block on table":
                goal = goals.Goal(objective="moving",
                                  subject="self",
                                  directObject="blue block",
                                  indirectObject="observer",
                                  pos='blue block:table')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "put the red block on table":
                goal = goals.Goal(objective="moving",
                                  subject="self",
                                  directObject="red block",
                                  indirectObject="observer",
                                  pos='red block:table')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "stack the green block on the red block":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="red block",
                                  indirectObject="observer",
                                  pos='green block:red block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "stack the blue block on the red block":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="red block",
                                  indirectObject="observer",
                                  pos='blue block:red block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "stack the blue block on the green block":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="green block",
                                  indirectObject="observer",
                                  pos='blue block:green block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "stack the red block on the blue block":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="blue block",
                                  indirectObject="observer",
                                  pos='red block:blue block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "stack the green block on the blue block":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="blue block",
                                  indirectObject="observer",
                                  pos='green block:blue block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print("generated goal:", str(goal),
                              "but it is already in the \ goal graph")

            if utterance == "stack the red block on the green block":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="green block",
                                  indirectObject="observer",
                                  pos='red block:green block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

            if utterance == "stack":
                goal = goals.Goal(objective="stacking",
                                  subject="self",
                                  directObject="green block",
                                  indirectObject="observer",
                                  pos='red block:green block')
                added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
                if verbose >= 2:
                    if added:
                        print("adding goal:", str(goal))
                    else:
                        print(
                            "generated goal:", str(goal),
                            "but it is already in the \
                        goal graph")

#                       else:
#                               print "message is unknown"

        self.lastTime = midcatime.now()