def save_30_buildings(self): ''' save the 30 building goals into the 30_problem_set_ijcai.pickle file ''' a = {} for k in range(0, 30): self.curr_goal_sets[:] = [] select_buildings = 0 index = [] objs_names = self.world.get_objects_names_by_type("BLOCK") # remove the object table since we need only blocks objs_names.remove("table") random.shuffle(objs_names) # builds the gaol sets #self.build_current_goal_sets(objs_names) self.build_current_goal_sets_same(objs_names) atoms = self.world.get_atoms() self.remove_bunch_atoms(atoms) stateread.apply_state_file(self.world, self.stateFile) stateread.apply_state_str(self.world, self.state_str) self.mem.add(self.mem.STATES, copy.deepcopy(self.world)) self.mem.set(self.mem.TIME_CONSTRUCTION, self.Time) #print(self.world) # empty the selected goals list del self.selected_goals[:] # generate some random goals through random function on current goal set # this random function is for no:of buildings select_buildings = random.randint(2, len(self.curr_goal_sets) - 1) print(("NO.OF BUILDINGS TO CONSTRUCT: " + str(select_buildings))) # this is for the random indexes , that should be taken from the variable self.curr_goal_sets # compute the index list with in the range of 0 and no:of buildings index = random.sample(list(range(0, len(self.curr_goal_sets))), select_buildings) print("THE BUILDINGS ARE: ") print("[") for i in index: # since self.curr_goal_sets is in a structure of list in a list # we should iterate through the list completely print(("Tower " + self.curr_goal_sets[i][0].args[0]), end=' ') if (len(self.curr_goal_sets[i]) == 1): print(("(" + str(len(self.curr_goal_sets[i])) + " Block)")) else: print( ("(" + str(len(self.curr_goal_sets[i])) + " Blocks)")) for j in self.curr_goal_sets[i]: #print(j) self.selected_goals.append(j) #print("") print("]") print("") random.shuffle(index) print(index) a[k] = [ self.curr_goal_sets, select_buildings, copy.deepcopy(index) ] with open('30_problem_set_ijcai.pickle', 'wb') as handle: pickle.dump(a, handle)
def createMIDCAObj(self): extinguish = False mortar = True thisDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) MIDCA_ROOT = thisDir + "/../" domainFile = MIDCA_ROOT + "worldsim/domains/arsonist_mortar.sim" stateFile = MIDCA_ROOT + "worldsim/states/defstate_mortar.sim" # load domain file like normal self.world = domainread.load_domain(domainFile) # for state file, need to add number of mortar blocks to begin with state_str = open(stateFile).read() # first read file # now add new mortar blocks for i in range(self.currMortarCount): state_str+="MORTARBLOCK(M"+str(i)+")\n" state_str+="available(M"+str(i)+")\n" # now load the state stateread.apply_state_str(self.world, state_str) # creates a PhaseManager object, which wraps a MIDCA object myMidca = base.PhaseManager(self.world, display=asqiiDisplay,verbose=0) #asqiiDisplay(world) # add phases by name for phase in ["Simulate", "Perceive", "Interpret", "Eval", "Intend", "Plan", "Act"]: myMidca.append_phase(phase) # add the modules which instantiate basic blocksworld operation myMidca.append_module("Simulate", simulator.MidcaActionSimulator()) myMidca.append_module("Simulate", simulator.ASCIIWorldViewer()) myMidca.append_module("Perceive", perceive.PerfectObserver()) myMidca.append_module("Interpret", note.ADistanceAnomalyNoter()) # need to make sure to disable all user input modules #myMidca.append_module("Interpret", guide.UserGoalInput()) myMidca.append_module("Eval", evaluate.SimpleEval()) myMidca.append_module("Intend", intend.SimpleIntend()) myMidca.append_module("Plan", planning.PyHopPlanner(extinguish, mortar)) myMidca.append_module("Act", act.SimpleAct()) #myMidca.insert_module('Simulate', simulator.ArsonSimulator(arsonChance=self.arsonChanceArg, arsonStart=10), 1) #myMidca.insert_module('Simulate', simulator.FireReset(), 0) myMidca.insert_module('Interpret', guide.TFStack(), 1) myMidca.insert_module('Eval', evaluate.MortarScorer(), 1) # this needs to be a 1 so that Scorer happens AFTER SimpleEval # tells the PhaseManager to copy and store MIDCA states so they can be accessed later. myMidca.storeHistory = False myMidca.initGoalGraph() ## note: myMidca.init() is NOT called here, instead in singlerun() self.myMidca = myMidca self.initialized = True
def next_goal(self): # empty the previous goals and set the money to default in memory self.mem.set(self.mem.MONEY, self.money) # remove all the atoms in the world atoms = self.world.get_atoms() self.remove_bunch_atoms(atoms) # whenever we get a new goal, first initialize the world to it's default state stateread.apply_state_file(self.world, self.stateFile) stateread.apply_state_str(self.world, self.state_str) self.mem.add(self.mem.STATES, copy.deepcopy(self.world)) # Create the random set of goals with random dishes and persons self.curr_goal_sets[:] = [] self.create_random_goals() #self.save_30_goal_sets() #self.write_memory_to_file() #self.select_random_goals_from_30_sets() # print the generated goals print("") for each_goal in self.curr_goal_sets: print(each_goal) print("") # return the generated goals return self.curr_goal_sets
DOMAIN_ROOT = MIDCA_ROOT + "domains/restaurant_domain/" DOMAIN_FILE = DOMAIN_ROOT + "restaurant.sim" STATE_FILE = DOMAIN_ROOT + "states/restaurant_state.sim" DISPLAY_FUNC = util.shopping_display DECLARE_METHODS_FUNC = restaurant_methods.declare_methods DECLARE_OPERATORS_FUNC = restaurant_operators.declare_ops GOAL_GRAPH_CMP_FUNC = util.preferApprehend world = domainread.load_domain(DOMAIN_FILE) # for state file, need to add number of mortar blocks to begin with state_str = open(STATE_FILE).read() # first read file # now load the state stateread.apply_state_str(world, state_str) stateread.apply_state_file(world, STATE_FILE) print(world) #creates a PhaseManager object, which wraps a MIDCA object myMidca = base.PhaseManager(world, display=DISPLAY_FUNC, verbose=4, metaEnabled=True) initial_world = copy.deepcopy(world) #add phases by name for phase in [ "Simulate", "Perceive", "Interpret", "Eval", "Intend", "Plan", "Act" ]: myMidca.append_phase(phase)
def applyStateChange(self, stateStr): stateread.apply_state_str(self.midca.world, stateStr)
DECLARE_METHODS_FUNC = methods_mortar.declare_methods DECLARE_OPERATORS_FUNC = operators_mortar.declare_ops GOAL_GRAPH_CMP_FUNC = util.preferApprehend extinguish=False mortar=True world = domainread.load_domain(DOMAIN_FILE) # for state file, need to add number of mortar blocks to begin with state_str = open(STATE_FILE).read() # first read file # now add new mortar blocks for i in range(MORTAR_COUNT): state_str+="MORTARBLOCK(M"+str(i)+")\n" state_str+="available(M"+str(i)+")\n" # now load the state stateread.apply_state_str(world, state_str) stateread.apply_state_file(world, STATE_FILE) #creates a PhaseManager object, which wraps a MIDCA object myMidca = base.PhaseManager(world, display = DISPLAY_FUNC, verbose=4, metaEnabled=True) #add phases by name for phase in ["Simulate", "Perceive", "Interpret", "Eval", "Intend", "Plan", "Act"]: myMidca.append_phase(phase) #add the modules which instantiate basic blocksworld operation myMidca.append_module("Simulate", simulator.MidcaActionSimulator()) myMidca.append_module("Simulate", simulator.ASCIIWorldViewer(display=DISPLAY_FUNC)) myMidca.append_module("Perceive", perceive.PerfectObserver()) myMidca.append_module("Interpret", note.ADistanceAnomalyNoter())
def run(self, cycle, verbose=2): ''' Read from the subscriber in the format "X:float,Y:float,SPEED:float" ''' world = self.observe() if not world: raise Exception("World observation failed.") ''' The following code gets the depth to create observed states for the world. ''' depth = self.robot_interface.senseDepth() states = "" if (depth <= 0.5): states += "at_pooldepth(grace, surface)\n" elif (depth >= 0.5 and depth <= 1.5): # depth is at surface states += "at_pooldepth(grace, veryshallow)\n" elif (depth >= 1.5 and depth <= 2.5): # depth is at veryshallow states += "at_pooldepth(grace, shallow)\n" elif (depth >= 2.5 and depth <= 3.5): states += "at_pooldepth(grace, medium)\n" elif (depth >= 3.5 and depth <= 4.5): states += "at_pooldepth(grace, deep)\n" elif (depth >= 4.5 and depth <= 5.5): states += "at_pooldepth(grace, verydeep)\n" else: states += "at_pooldepth(grace, bottom)\n" # remove previous states related to at_pooldepth # because grace can percieve and update them world_copy = copy.deepcopy(self.world) for atom in world_copy.atoms: if atom.predicate.name == "at_pooldepth": world.atoms.remove(atom) # this is to update the world into memory if not states == "": if verbose >= 1: print(states) stateread.apply_state_str(world, states) self.mem.add(self.mem.OBSERVED_STATES, world) states = self.mem.get(self.mem.OBSERVED_STATES) if len(states) > 400: # print "trimmed off 200 old stale states" states = states[200:] self.mem.set(self.mem.OBSERVED_STATES, states) # End Memory Usage Optimization if verbose >= 1: print "World observed." trace = self.mem.trace if trace: trace.add_module(cycle, self.__class__.__name__) trace.add_data("WORLD", copy.deepcopy(self.world))
def run(self, cycle, verbose=2): ''' Read from the subscriber in the format "X:float,Y:float,SPEED:float" ''' world = self.observe() if not world: raise Exception("World observation failed.") self.mem.add(self.mem.STATES, world) x = -1 y = -1 speed = -1 states = "" ''' The following code gets the current X,Y,Speed and updates the location of uuv. i.e., if the vehicle is in qroute or green area 1 or green area 2. the else part is to remove the state after the vehicle leaves the specific location ''' try: current_position = self.subscriber.recv() x,y,speed = current_position.split(",") x = float(x.split(":")[1]) y = float(y.split(":")[1]) speed = float(speed.split(":")[1]) if y >=-98 and y<=-48: states+="at_location(remus,qroute)\n" else: for atom in self.world.atoms: if atom.predicate.name == "at_location" \ and atom.args[0].name == "remus"\ and atom.args[1].name == "qroute": self.world.atoms.remove(atom) break if x>=-2 and x<=40 and y>=-96 and y<=-63: states+="at_location(remus,ga1)" else: for atom in self.world.atoms: if atom.predicate.name == "at_location" \ and atom.args[0].name == "remus"\ and atom.args[1].name == "ga1": self.world.atoms.remove(atom) break if x>=120 and x<=175 and y>=-96 and y<=-63: states+="at_location(remus,ga2)" else: for atom in self.world.atoms: if atom.predicate.name == "at_location" \ and atom.args[0].name == "remus"\ and atom.args[1].name == "ga2": self.world.atoms.remove(atom) break except: pass # this is to update the world into memory if not states == "": if verbose >= 1: print(states) stateread.apply_state_str(self.world, states) self.mem.add(self.mem.STATES, self.world) states = self.mem.get(self.mem.STATES) if len(states) > 400: # print "trimmed off 200 old stale states" states = states[200:] self.mem.set(self.mem.STATES, states) # End Memory Usage Optimization if verbose >= 1: print "World observed." trace = self.mem.trace if trace: trace.add_module(cycle, self.__class__.__name__) trace.add_data("WORLD", copy.deepcopy(self.world))
def create_meta_MIDCA(self): #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 GOAL_GRAPH_CMP_FUNC = nbeacons_util.preferFree WIND_ENABLED = True # Load domain world = domainread.load_domain(DOMAIN_FILE) # Load state stateread.apply_state_str(world, self.start_state) # Creates a PhaseManager object, which wraps a MIDCA object myMidca = base.PhaseManager(world, display=DISPLAY_FUNC, verbose=2, metaEnabled=True) # Add phases by name for phase in [ "Simulate", "Perceive", "Interpret1", "Interpret2", "Interpret3", "Eval", "Cleanup", "Intend", "Plan", "Act" ]: myMidca.append_phase(phase) # Add the modules which instantiate basic operation #myMidca.append_module("Simulate", simulator.MidcaActionSimulator()) myMidca.append_module( "Simulate", simulator.NBeaconsActionSimulator(wind=WIND_ENABLED, wind_dir=self.wind_dir, wind_strength=self.wind_strength, dim=DIMENSION, wind_schedule=WIND_SCHEDULE_1, logfilenm=DATADIR + "meta" + NOW_STR + ".log")) myMidca.append_module("Simulate", simulator.ASCIIWorldViewer(DISPLAY_FUNC)) myMidca.append_module("Perceive", perceive.PerfectObserver()) myMidca.append_module("Interpret1", note.StateDiscrepancyDetector()) myMidca.append_module("Interpret2", assess.SimpleNBeaconsExplain()) myMidca.append_module("Interpret3", guide.SimpleNBeaconsGoalManager()) #myMidca.append_module("Interpret", assess.SimpleNBeaconsExplain()) #myMidca.append_module("Interpret", assess.SimpleNBeaconsExplain()) #myMidca.append_module("Interpret", guide.UserGoalInput()) myMidca.append_module( "Interpret3", guide.NBeaconsGoalGenerator(numbeacons=2, goalList=self.goal_list)) myMidca.append_module("Eval", evaluate.NBeaconsDataRecorder()) myMidca.append_module( "Cleanup", simulator.NBeaconsSimulator(beacon_fail_rate=BEACON_FAIL_RATE)) myMidca.append_module("Intend", intend.SimpleIntend()) myMidca.append_module("Plan", planning.HeuristicSearchPlanner()) #myMidca.append_module("Plan", planning.PyHopPlanner(nbeacons_util.pyhop_state_from_world, # nbeacons_util.pyhop_tasks_from_goals, # DECLARE_METHODS_FUNC, # DECLARE_OPERATORS_FUNC)) # set up planner for sample domain myMidca.append_module("Act", act.NBeaconsSimpleAct()) for phase in ["Monitor", "Interpret", "Intend", "Plan", "Control"]: myMidca.append_meta_phase(phase) # add meta layer modules myMidca.append_meta_module("Monitor", monitor.MRSimpleMonitor()) myMidca.append_meta_module("Interpret", interpret.MRSimpleDetect()) #myMidca.append_meta_module("Interpret", interpret.MRSimpleGoalGenForGoalTrans()) myMidca.append_meta_module("Intend", metaintend.MRSimpleIntend()) myMidca.append_meta_module("Plan", plan.MRSimplePlanner()) myMidca.append_meta_module("Control", control.MRSimpleControl()) # Set world viewer to output text myMidca.set_display_function(nbeacons_util.drawNBeaconsScene) # Tells the PhaseManager to copy and store MIDCA states so they can be accessed later. # Note: Turning this on drastically increases MIDCA's running time. myMidca.storeHistory = False myMidca.mem.logEachAccess = False # Initialize and start running! myMidca.initGoalGraph(cmpFunc=GOAL_GRAPH_CMP_FUNC) return myMidca
def createMIDCAObj(self): extinguish = False mortar = True thisDir = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) MIDCA_ROOT = thisDir + "/../" domainFile = MIDCA_ROOT + "worldsim/domains/arsonist_mortar.sim" stateFile = MIDCA_ROOT + "worldsim/states/defstate_mortar.sim" # load domain file like normal self.world = domainread.load_domain(domainFile) # for state file, need to add number of mortar blocks to begin with state_str = open(stateFile).read() # first read file # now add new mortar blocks for i in range(self.currMortarCount): state_str += "MORTARBLOCK(M" + str(i) + ")\n" state_str += "available(M" + str(i) + ")\n" # now load the state stateread.apply_state_str(self.world, state_str) # creates a PhaseManager object, which wraps a MIDCA object myMidca = base.PhaseManager(self.world, display=asqiiDisplay, verbose=0) #asqiiDisplay(world) # add phases by name for phase in [ "Simulate", "Perceive", "Interpret", "Eval", "Intend", "Plan", "Act" ]: myMidca.append_phase(phase) # add the modules which instantiate basic blocksworld operation myMidca.append_module("Simulate", simulator.MidcaActionSimulator()) myMidca.append_module("Simulate", simulator.ASCIIWorldViewer()) myMidca.append_module("Perceive", perceive.PerfectObserver()) myMidca.append_module("Interpret", note.ADistanceAnomalyNoter()) # need to make sure to disable all user input modules #myMidca.append_module("Interpret", guide.UserGoalInput()) myMidca.append_module("Eval", evaluate.SimpleEval()) myMidca.append_module("Intend", intend.SimpleIntend()) myMidca.append_module("Plan", planning.PyHopPlanner(extinguish, mortar)) myMidca.append_module("Act", act.SimpleAct()) #myMidca.insert_module('Simulate', simulator.ArsonSimulator(arsonChance=self.arsonChanceArg, arsonStart=10), 1) #myMidca.insert_module('Simulate', simulator.FireReset(), 0) myMidca.insert_module('Interpret', guide.TFStack(), 1) myMidca.insert_module( 'Eval', evaluate.MortarScorer(), 1) # this needs to be a 1 so that Scorer happens AFTER SimpleEval # tells the PhaseManager to copy and store MIDCA states so they can be accessed later. myMidca.storeHistory = False myMidca.initGoalGraph() ## note: myMidca.init() is NOT called here, instead in singlerun() self.myMidca = myMidca self.initialized = True
def next_goal(self, write_to_file=False): actual_time = self.mem.get(self.mem.ACTUAL_TIME_CONSTRUCTION) expected_time = self.mem.get(self.mem.EXPECTED_TIME_CONSTRUCTION) selected_buildings = self.mem.get(self.mem.SELECTED_BUILDING_LIST) complete_buildings = self.mem.get(self.mem.COMPLETE_BUILDING_LIST) executed_buildings = self.mem.get(self.mem.EXECUTED_BUILDING_LIST) actual_scores = self.mem.get(self.mem.ACTUAL_SCORES) if executed_buildings: expected_scores = sum(executed_buildings) else: expected_scores = 0 if actual_time and expected_time: expected_p_t = float(expected_scores / expected_time[0]) actual_p_t = float(actual_scores / actual_time[0]) if write_to_file: with open("evaluation.txt", "a") as myfile: myfile.write( "%-5s %-5s %-5s %-5s " % (str(complete_buildings), str(selected_buildings), str(expected_time), str(actual_time))) myfile.write("%-5s %-5s %-5s %-5s %-5s " % (str([expected_scores]), str([actual_scores]), str([expected_p_t]), str( [actual_p_t]), str(executed_buildings))) myfile.write("\n") self.mem.set(self.mem.ACTUAL_TIME_CONSTRUCTION, None) self.mem.set(self.mem.EXPECTED_TIME_CONSTRUCTION, None) self.mem.set(self.mem.SELECTED_BUILDING_LIST, None) self.mem.set(self.mem.COMPLETE_BUILDING_LIST, None) self.mem.set(self.mem.EXECUTED_BUILDING_LIST, None) self.mem.set(self.mem.ACTUAL_SCORES, None) #print(self.mem.get(self.mem.STATES)[-1]) #print(self.initial_world) # initiate the world #predicateworld.asqiiDisplay(world) #self.world = self.initial_world.copy() #print("Modified world") #print(self.world) #base.MIDCA.update_world(self,self.initial_world.copy()) #self.mem.add(self.mem.STATES, self.initial_world.copy()) #print(self.mem.get(self.mem.STATES)[-1] #atoms = self.initial_world.get_atoms() #atoms1 = self.initial_world.get_atoms() #for atom in atoms1: # self.world.add_atom(atom) # get all the object names of type block self.curr_goal_sets[:] = [] objs_names = self.world.get_objects_names_by_type("BLOCK") # remove the object table since we need only blocks objs_names.remove("table") random.shuffle(objs_names) # builds the gaol sets #self.build_current_goal_sets(objs_names) self.build_current_goal_sets_same(objs_names) atoms = self.world.get_atoms() self.remove_bunch_atoms(atoms) stateread.apply_state_file(self.world, self.stateFile) stateread.apply_state_str(self.world, self.state_str) self.mem.add(self.mem.STATES, copy.deepcopy(self.world)) self.mem.set(self.mem.TIME_CONSTRUCTION, self.Time) #print(self.world) # empty the selected goals list del self.selected_goals[:] # generate some random goals through random function on current goal set # this random function is for no:of buildings select_buildings = random.randint(2, len(self.curr_goal_sets) - 1) print(("NO.OF BUILDINGS TO CONSTRUCT: " + str(select_buildings))) # this is for the random indexes , that should be taken from the variable self.curr_goal_sets # compute the index list with in the range of 0 and no:of buildings index = random.sample(list(range(0, len(self.curr_goal_sets))), select_buildings) print("THE BUILDINGS ARE: ") print("[") for i in index: # since self.curr_goal_sets is in a structure of list in a list # we should iterate through the list completely print(("Tower " + self.curr_goal_sets[i][0].args[0]), end=' ') if (len(self.curr_goal_sets[i]) == 1): print(("(" + str(len(self.curr_goal_sets[i])) + " Block)")) else: print(("(" + str(len(self.curr_goal_sets[i])) + " Blocks)")) for j in self.curr_goal_sets[i]: #print(j) self.selected_goals.append(j) print("]") print("") return self.selected_goals
def next_goal_30_goal_transformations(self, write_to_file=False): selected_buildings = self.mem.get(self.mem.SELECTED_BUILDING_LIST) executed_buildings = self.mem.get(self.mem.EXECUTED_BUILDING_LIST) actual_scores = self.mem.get(self.mem.ACTUAL_SCORES) if executed_buildings: myfile = open('evaluation.csv', "a") writer = csv.writer(myfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) with open("evaluation.csv", "a") as myfile: data = [(self.count), selected_buildings, actual_scores, executed_buildings] writer.writerow(data) self.mem.set(self.mem.SELECTED_BUILDING_LIST, None) self.mem.set(self.mem.EXECUTED_BUILDING_LIST, None) self.mem.set(self.mem.ACTUAL_SCORES, None) else: myfile = open('evaluation.csv', "a") writer = csv.writer(myfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) data = [ "S.NO", "PROBLEM SET", "ACTUAL SCORES", "CONSTRUCTED BUILDINGS" ] writer.writerow(data) self.curr_goal_sets[:] = [] objs_names = self.world.get_objects_names_by_type("BLOCK") # remove the object table since we need only blocks objs_names.remove("table") random.shuffle(objs_names) # builds the gaol sets self.build_current_goal_sets(objs_names) atoms = self.world.get_atoms() self.remove_bunch_atoms(atoms) stateread.apply_state_file(self.world, self.stateFile) stateread.apply_state_str(self.world, self.state_str) self.mem.add(self.mem.STATES, copy.deepcopy(self.world)) self.mem.set(self.mem.TIME_CONSTRUCTION, self.Time) print((self.world)) # empty the selected goals list del self.selected_goals[:] with open('30_problem_set.pickle', 'rb') as handle: a = pickle.load(handle) b = a[self.count] self.count = self.count + 1 select_buildings = b[1] print(("NO.OF BUILDINGS TO CONSTRUCT: " + str(select_buildings))) # this is for the random indexes , that should be taken from the variable self.curr_goal_sets # compute the index list with in the range of 0 and no:of buildings index = b[2] self.curr_goal_sets = b[0] for each in self.curr_goal_sets: for goal in each: if goal["predicate"] == "on": goal["predicate"] = "stable-on" print("THE BUILDINGS ARE: ") print("[") for i in index: # since self.curr_goal_sets is in a structure of list in a list # we should iterate through the list completely print(("Tower " + self.curr_goal_sets[i][0].args[0]), end=' ') if (len(self.curr_goal_sets[i]) == 1): print(("(" + str(len(self.curr_goal_sets[i])) + " Block)")) else: print(("(" + str(len(self.curr_goal_sets[i])) + " Blocks)")) for j in self.curr_goal_sets[i]: #print(j) self.selected_goals.append(j) #print("") print("]") print("") return self.selected_goals
def next_goal_30(self): ''' Generate the goals from the 30 sets ''' actual_time = self.mem.get(self.mem.ACTUAL_TIME_CONSTRUCTION) expected_time = self.mem.get(self.mem.EXPECTED_TIME_CONSTRUCTION) selected_buildings = self.mem.get(self.mem.SELECTED_BUILDING_LIST) complete_buildings = self.mem.get(self.mem.COMPLETE_BUILDING_LIST) executed_buildings = self.mem.get(self.mem.EXECUTED_BUILDING_LIST) actual_scores = self.mem.get(self.mem.ACTUAL_SCORES) P = self.mem.get(self.mem.P) t = self.mem.get(self.mem.t) P = str(P) t = str(t) P = P.replace("[...]", "") t = t.replace("[...]", "") if not actual_scores: actual_scores = 0 if executed_buildings: expected_scores = sum(selected_buildings) else: expected_scores = 0 if complete_buildings: if expected_time: expected_p_t = float(expected_scores / expected_time) else: e_t = None e_p_t = None e_s = None if actual_time: actual_p_t = float(actual_scores / actual_time) else: a_t = None a_s = None a_p_t = None myfile = open('evaluation.csv', "a") writer = csv.writer(myfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) with open("evaluation.csv", "a") as myfile: if expected_time: e_t = round(expected_time, 2) e_p_t = round(expected_p_t, 2) if actual_time: a_t = round(actual_time, 2) a_p_t = round(actual_p_t, 2) if expected_scores: e_s = round(expected_scores, 2) if expected_scores == 0: e_s = 0 if actual_scores: a_s = round(actual_scores, 2) if actual_scores == 0: a_s = 0 e_b = executed_buildings data = [ self.count, complete_buildings, selected_buildings, e_t, a_t, e_s, a_s, e_p_t, a_p_t, e_b, str(P), str(t) ] writer.writerow(data) self.mem.set(self.mem.ACTUAL_TIME_CONSTRUCTION, None) self.mem.set(self.mem.EXPECTED_TIME_CONSTRUCTION, None) self.mem.set(self.mem.SELECTED_BUILDING_LIST, None) self.mem.set(self.mem.COMPLETE_BUILDING_LIST, None) self.mem.set(self.mem.EXECUTED_BUILDING_LIST, None) self.mem.set(self.mem.ACTUAL_SCORES, None) self.mem.set(self.mem.P, None) self.mem.set(self.mem.t, None) else: myfile = open('evaluation.csv', "a") writer = csv.writer(myfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) data = [ "S.NO", "PROBLEM SET", "SELECTED TOWERS", "EXPECTED TIME", "ACTUAL TIME", "EXPECTED SCORES", "ACTUAL SCORES", "EXPECTED(P/T)", "ACTUAL(P/T) ", "CONSTRUCTED BUILDINGS", "P", "t" ] writer.writerow(data) self.curr_goal_sets[:] = [] objs_names = self.world.get_objects_names_by_type("BLOCK") # remove the object table since we need only blocks objs_names.remove("table") random.shuffle(objs_names) # builds the gaol sets self.build_current_goal_sets(objs_names) atoms = self.world.get_atoms() self.remove_bunch_atoms(atoms) stateread.apply_state_file(self.world, self.stateFile) stateread.apply_state_str(self.world, self.state_str) self.mem.add(self.mem.STATES, copy.deepcopy(self.world)) self.mem.set(self.mem.TIME_CONSTRUCTION, self.Time) #print(self.world) # empty the selected goals list del self.selected_goals[:] with open('30_problem_set_ijcai.pickle', 'rb') as handle: a = pickle.load(handle) b = a[self.count] self.count = self.count + 1 select_buildings = b[1] print(("NO.OF BUILDINGS TO CONSTRUCT: " + str(select_buildings))) # this is for the random indexes , that should be taken from the variable self.curr_goal_sets # compute the index list with in the range of 0 and no:of buildings index = b[2] self.curr_goal_sets = b[0] print("THE BUILDINGS ARE: ") print("[") for i in index: # since self.curr_goal_sets is in a structure of list in a list # we should iterate through the list completely print(("Tower " + self.curr_goal_sets[i][0].args[0]), end=' ') if (len(self.curr_goal_sets[i]) == 1): print(("(" + str(len(self.curr_goal_sets[i])) + " Block)")) else: print(("(" + str(len(self.curr_goal_sets[i])) + " Blocks)")) for j in self.curr_goal_sets[i]: #print(j) self.selected_goals.append(j) #print("") print("]") print("") return self.selected_goals
def run(self, cycle, verbose=2): ''' Read from the subscriber in the format "X:float,Y:float,SPEED:float" ''' world = self.observe() if not world: raise Exception("World observation failed.") self.mem.add(self.mem.STATES, world) ''' The following code gets the depth and the acknowledgement from grace to create states for the world. For example : Should comeback and complete this later ''' states = "" try: # write the function to aquire depth and acknowledgement GP = self.GracePerception atSurface = GP.checkAtSurfaceDepth( ) # checks if depth is close to surface depth if not self.runningBottomCheck and not atSurface: # only check for bottom if we are not already doing it GP.beginBottomCheck() self.runningBottomCheck = True acknowledge = GP.checkCommunicationAck( ) # check if we have recieved acknowledgment from fumin atBottom = GP.checkAtBottom( ) # check if we have determined that we are at the bottom if atSurface or acknowledge: states += "at_surface(grace)\n" # similarly for bottom elif atBottom: states += "at_bottom(grace)\n" self.runningBottomCheck = False # for pool depth (there can be multiple pooldepths) # we should discuss on how many pool depths we should have if acknowledge: states += "knows(fumin, pooldepth1)\n" except: # if there is any failure to acess the grace functions, lets # use this block (to be completed later) pass # this is to update the world into memory if not states == "": if verbose >= 1: print(states) stateread.apply_state_str(self.world, states) self.mem.add(self.mem.STATES, self.world) states = self.mem.get(self.mem.STATES) if len(states) > 400: # print "trimmed off 200 old stale states" states = states[200:] self.mem.set(self.mem.STATES, states) # End Memory Usage Optimization if verbose >= 1: print "World observed." trace = self.mem.trace if trace: trace.add_module(cycle, self.__class__.__name__) trace.add_data("WORLD", copy.deepcopy(self.world))