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
def run(self, cycle, verbose=2): if self.deliveringGoalsExist(): if verbose >= 2: print "MIDCA already has a delivering goal. Skipping delivering goal generation" return if self.alreadygenerated(): if verbose >= 2: print "MIDCA already generated the goals for this problem" return #if obj-at(p,l) is in the state, it means it needs to be delivered! world = self.mem.get(self.mem.STATES)[-1] orders = deliverstate.get_order_list(world) #\ goal = self.tree.givegoal(blocks) for order in orders: goal = goals.Goal(order.id, order.destination, order.location, predicate="obj-at") added = self.mem.get(self.mem.GOAL_GRAPH).insert(goal) if goal: if verbose >= 2: print "goal generated:", goal ##call monitors m = Monitor(self.mem, "m" + order.id, order.id, goal) # Thread(target=m.goalmonitor, args=[order.id, order.location, "obj-at"]).start() self.mem.get(self.mem.GOAL_GRAPH).insert(goal)
def run(self, cycle, verbose = 2): try: text = self.readS.recv(self.readSize) if text != "None\n": p = Parser() frames = p.makeframegraph(text) noem = {} # Node Operator Effect Mapping noem['CRIMINAL-VOLITIONAL-AGENT.4697'] = [['apprehend', OPERATOR_EFFECT_NEGATION]] t = Traverser(frames, noem) (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(goal) if verbose >= 2: print "Meta-AQUA goal generated:", goal, 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.", try: print " Got:\n" + text except NameError: print " Unable to read from socket."
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, if inserted: print else: print ". This goal was already in the graph."
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
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
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 = map(lambda x: goals.Goal(str(x), predicate="activated"), goal_b_ids) return new_goals
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))
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 == "point at max": 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" self.lastTime = midcatime.now()
from MIDCA.modules import simulator, guide, evaluate, perceive, intend, planning, act, note, assess 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 = 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
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 = 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 = map(lambda x: goals.Goal('B' + str(x), predicate="activated"), 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
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()
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[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