def LookForObject(self, memoryPhantom): memObject = memoryPhantom.object map = Global.Map visibleObjects = map.GetVisibleObjects(self.agent) foundObj = None for obj in visibleObjects: if obj == memObject.object: foundObj = obj if foundObj == None: self.spaceMap.ObjectNotFound(memoryPhantom.object) self.memoryArea.RemovePhantom(memoryPhantom) memoryPhantom.MemoryObjectNotFound() return None #else: found: phantom = self.GetPhantomForObj(foundObj) if phantom != None: phantom.Update(foundObj) phantom.memoryPhantom = memoryPhantom self.spaceMap.ObjectNoticedAgain(foundObj) Global.Log("PF: RE-adding phantom(lookFor) for object " + foundObj.ToString()) else: phantom = Phantom(foundObj, memoryPhantom) self.environmentPhantoms.append(phantom) self.processArea.PhantomAddedForMemoryPhantom( phantom, memoryPhantom) self.spaceMap.ObjectFound(foundObj) Global.Log("PF: Adding phantom(lookFor) for object " + foundObj.ToString()) return foundObj
def runOneSimulation(self, savePath, configName, randomSeed): savePath = savePath + str(randomSeed) + "-" + configName + "/" os.makedirs(savePath) Global.LogStart(savePath) Global.Log("Starting new simulation and world for Config: " + configName) try: seed(randomSeed) config = Config.Get(configName) world = World(config) Global.World = world self.agent = Agent(config) world.SetAgent(self.agent) self.mapRenderer = MapRenderer(self.wxCanvas, Global.Map, self.agent, self, False) self.currentTestIndex = self.currentTestIndex + 1 self.mapRenderer.RenderProgress(self, configName) self.mapRenderer.RenderProgressInTest(world.step, Global.MaxTestSteps) time.sleep(0.1) elayer = world.agent.intelligence.spaceMap.Layer while world.step < Global.MaxTestSteps: world.Step() self.mapRenderer.RenderToFile(world, savePath + "PIL" + str(world.step).zfill(6) + ".png") self.mapRenderer.RenderProgressInTest(world.step, Global.MaxTestSteps) world.SendAgentOut() while world.step < Global.MaxTestSteps + Global.MaxTestStepAfter: world.Step() self.mapRenderer.RenderToFile(world, savePath + "PIL" + str(world.step).zfill(6) + ".png") self.mapRenderer.RenderProgressInTest(world.step, Global.MaxTestSteps) if Global.CalculateVisibilityHistory: self.mapRenderer.RenderToFile(world, savePath + "visibilityheatmap.png", ["vh"]) self.mapRenderer.RenderToFile(world, savePath + "visibilityobjectheatmap.png", ["ovh"]) map = Global.Map map.SaveHeatMap() self.agent.intelligence.spaceMap.Layer.SaveHeatMap() except: Global.Log("FATAL ERROR occured: ") ss = traceback.format_exc() Global.Log(ss) time.sleep(1) raise finally: Global.Log("Stoping simulation...") Global.LogEnd() Global.Reset() self.agent = None self.mapRenderer.Clear() self.mapRenderer = None
def NoticeObjects(self, visibleObjects, actProcess): self.perceptionFilter.ProcessObjects(visibleObjects, actProcess) phantomsToSpaceMap = {} for rObj in visibleObjects: if rObj.curAttractivity == 0: continue phantom = self.GetPhantomForObj(rObj) if phantom != None: phantom.Update(rObj) phantomsToSpaceMap[phantom] = "ObjectNoticedAgain" else: memPhantom = self.memoryArea.GetPhantomForObject(rObj) if memPhantom != None and self.processArea.LookingForPhantom( memPhantom): phantom = Phantom(rObj, memPhantom) self.environmentPhantoms.append(phantom) #self.processArea.PhantomAddedForMemoryPhantom(phantom, memPhantom) - later phantomsToSpaceMap[phantom] = "ObjectFound" Global.Log("PF: Adding phantom for object " + rObj.ToString() + " instead of " + memPhantom.ToString()) else: phantom = Phantom(rObj) self.environmentPhantoms.append(phantom) #self.processArea.PhantomAdded(phantom) - later phantomsToSpaceMap[phantom] = "ObjectNoticed" Global.Log("PF: Adding phantom for object " + rObj.ToString()) #phantoms updated, truncate to PF.Size phantoms = self.environmentPhantoms phantoms.sort(lambda b, a: cmp(a.habituation, b.habituation)) phantomsToDelete = phantoms[Global.PFSize:] for phantomToDelete in phantomsToDelete: self.environmentPhantoms.remove(phantomToDelete) phantomToDelete.DeletedOrLost() Global.Log("PF: removing(over PF.size) phantom for object " + phantomToDelete.object.ToString()) for phantom in self.environmentPhantoms: if phantom not in phantomsToSpaceMap: #happens when agent changes viewCones and object is not in normal VCs (was added by explore VCs) - ignore continue if phantomsToSpaceMap[phantom] == "ObjectNoticedAgain": self.spaceMap.ObjectNoticedAgain(phantom.object) elif phantomsToSpaceMap[phantom] == "ObjectFound": self.processArea.PhantomAddedForMemoryPhantom( phantom, phantom.memoryPhantom) self.spaceMap.ObjectFound(phantom.object) elif phantomsToSpaceMap[phantom] == "ObjectNoticed": self.processArea.PhantomAdded(phantom) self.spaceMap.ObjectNoticed(phantom.object)
def SetOwnerProcess(self, process): if self.ownerProcess != None: Global.Log( "Programmer.Error: Phantom with owner process set again: " + self.object.ToString()) self.ownerProcess = process process.resources.append(self)
def updateMemoryObjectLocation(self, memObject): links = memObject.linkToNodes x = 0 y = 0 if 0 == len(links): return memObject sumIntensity = 0 for link in links: x += (link.node.x * link.intensity) y += (link.node.y * link.intensity) sumIntensity += link.intensity x = x / sumIntensity y = y / sumIntensity p = Point(x, y) if not self.map.IsInside( p): #this should not happen, quick hack - go closer to memObj hit = self.map.CanMoveEx(memObject, p.x, p.y) if hit.hit: p = hit else: Global.Log( "Programmer.Error: SpaceMap: not inside but canMove-not-hit" ) memObject.x = p.x memObject.y = p.y step = Global.GetStep() error = self.map.DistanceObjs(p, memObject.object) errorStr = '%.2f' % error trained = memObject.object.trainHistory line = str(step) + ";" + str( trained) + ";" + errorStr + ";" + memObject.object.IdStr() Global.LogData("rememberinfo", line) return memObject
def RemovePhantom(self, memoryPhantom): if memoryPhantom == None: return if memoryPhantom not in self.memoryPhantoms: Global.Log( "Programmer.Error: MemoryArea.RemovePhantom not in MA: " + memoryPhantom.object.ToString()) return self.memoryPhantoms.remove(memoryPhantom)
def stopSimulation(self): Global.Log("Stoping simulation...") self.exitLocks() Global.Reset() self.agent = None self.mapRenderer.Clear() self.mapRenderer = None self.lock = None
def PhantomAddedForMemoryPhantom(self, phantom, memoryPhantom): phantom.affordance = memoryPhantom.affordance realProcess = self.actualBasicProcess if realProcess != memoryPhantom.ownerProcess: Global.Log("Programmer.Error: PA.PhantomAddedForMemoryPhantom relinking memPhantom for in-active process") phantom.ownerProcess = realProcess realProcess.resources.append(phantom) realProcess.resources.remove(memoryPhantom)
def UpdatePhantomsBecauseOfMove(self, agent): map = Global.Map lostPhantoms = [] for phantom in self.environmentPhantoms: if not map.IsObjectVisible(agent, phantom.object): lostPhantoms.append(phantom) for phantom in lostPhantoms: self.environmentPhantoms.remove(phantom) phantom.DeletedOrLost() Global.Log("PF: removing(lost) phantom for object " + phantom.object.ToString())
def UseObjectPhantoms(self, excProcess): for phantom in excProcess.resources: if phantom.GetType() != "e": Global.Log( "Programmer.Error: using memory phantom and memory object: " + phantom.ToString()) continue self.spaceMap.ObjectUsed(phantom.object) map = Global.Map usedSources = [ ] #excProcess.process.usedSources Future: object.amount TBD. for usedSource in usedSources: for phantom in excProcess.resources: if usedSource == phantom.affordance: if map.UseObject( excProcess, phantom.object): #true means object is used Up self.spaceMap.ObjectUsedUp(phantom.object) self.environmentPhantoms.remove(phantom) Global.Log("PF: removing(used) phantom for object " + phantom.object.ToString())
def Update(self, action): habituatedPhantoms = [] for phantom in self.environmentPhantoms: #if self.processArea.IsPhantomUsedNow(phantom): continue - not enough if phantom.ownerProcess == None or ( not phantom.ownerProcess.IsInProgress()): if phantom.Habituate(action.duration): habituatedPhantoms.append(phantom) for habituatedPhantom in habituatedPhantoms: self.environmentPhantoms.remove(habituatedPhantom) habituatedPhantom.DeletedOrLost() Global.Log("PF: removing(habituated) phantom for object " + habituatedPhantom.object.ToString())
def ProcessObjects(self, rObjs, action): name = action.process.name if name == "Remember": self.SetAllTo(rObjs, 0) elif name == "LookForObject": self.SetAllTo(rObjs, 0) elif name == "MoveToPartial": self.SetAllTo(rObjs, 1) elif name == "Explore": self.SetAllToRegardingAffs(rObjs, action, 1) elif name == "ExecuteReal": self.SetAllToRegardingAffs(rObjs, action, 0.5) else: Global.Log( "Programmer.Error: PerceptionFilter process name unknown: " + name)
def startSimulation(self, configName): if not os.path.exists("../../exs/"): os.makedirs("../../exs/") dirList = os.listdir("../../exs/") for fname in dirList: os.remove("../../exs/" + fname) Global.LogStart("../../exs/") Global.Log("Starting new simulation and world for Config: " + configName) seed(Global.RandomSeeds[0]) config = Config.Get(configName) world = World( config ) Global.World = world self.agent = Agent(config) world.SetAgent(self.agent) self.mapRenderer = MapRenderer(self.wxCanvas, Global.Map, self.agent, self) self.lock = Lock() self.lock.acquire() self.playbackLock = Lock() th = Thread(None, self.simulationThread, name="simulationThread") th.start()
def Step(self): action = self.intelligence.GetAction() map = Global.Map self.x = self.newX self.y = self.newY self.viewCones = self.viewConesNormal #fake else-than-Explore/LookForObject-action branch self.viewConeMaxDist = self.viewConeNormalMaxDist #execute action - world/agent-impacting part of atomic process if action.process.name == "ExecuteReal": action.sources = action.parent.parent.process.sources Global.Log("AGENT is doing " + action.data['process'].name + " for " + str(action.duration) + " seconds") self.intelligence.UseObjects(action.parent.parent) #map.UseObjects(self, action.parent) done in PF.UseObjects elif action.process.name == "Execute": pass #never happen - done as ExecuteReal or MoveTo(Partial) elif action.process.name == "SearchRandom": pass #never happens - done as MoveTo or Explore child process elif action.process.name == "LookUpInMemory": pass #never happens - done as Remember, MoveTo or LookForObject child process elif action.process.name == "Remember": action.duration = Global.Randint(1, 10) action.data["phantom"] = self.intelligence.RememberObjectsFor( action.data["affordance"]) if action.data["phantom"] != None: Global.Log("AGENT is remembering for " + action.data["affordance"].name + "(there should be " + action.data["phantom"].object.type.name + " at " + str(action.data["phantom"].object.x) + "," + str(action.data["phantom"].object.y) + ") for " + str(action.duration) + " seconds") else: Global.Log("AGENT is remembering for " + action.data["affordance"].name + "(nothing in SM/MA) for " + str(action.duration) + " seconds") elif action.process.name == "LookForObject": self.viewCones = self.viewConesForExplore self.viewConeMaxDist = self.viewConeForExploreMaxDist action.duration = Global.Randint(1, 5) action.data["object"] = self.intelligence.LookForObject( action.data["phantom"]) if action.data["object"] != None: Global.Log("AGENT is looking for " + action.data["phantom"].object.type.name + "(Found) for " + str(action.duration) + " seconds") else: Global.Log("AGENT is looking for " + action.data["phantom"].object.type.name + "(NotFound) for " + str(action.duration) + " seconds") elif action.process.name == "MoveTo": pass #never happens - done as MoveToPartial elif action.process.name == "MoveToPartial": dx = action.data['newx'] - self.newX dy = action.data['newy'] - self.newY angle = atan2(dx, dy) self.dirAngle = angle action.duration = map.MoveAgent(self, action.data['newx'], action.data['newy']) self.intelligence.UpdatePhantomsBecauseOfMove() Global.Log("AGENT is moving to " + str(action.data['newx']) + "," + str(action.data['newy']) + " for " + str(action.duration) + " seconds") elif action.process.name == "Explore": self.viewCones = self.viewConesForExplore self.viewConeMaxDist = self.viewConeForExploreMaxDist action.duration = Global.Randint(5, 20) action.sources = [action.data['affordance']] Global.Log("AGENT is exploring for " + action.data['affordance'].name + " for " + str(action.duration) + " seconds") else: Global.Log("AGENT is a bit CONFUSED doing " + action.process.name) #sees object around visibleObjects = map.GetVisibleObjects(self) self.intelligence.NoticeObjects(visibleObjects, action) self.intelligence.perceptionField.Update(action) self.intelligence.memoryArea.Update(action) self.paText = self.intelligence.processArea.GetText() Global.Time.AddSeconds(action.duration) self.intelligence.ActionDone() self.intelligence.spaceMap.StepUpdate(action)
def ObjectNotFound(self, rObject): Global.Log("SM.ObjectNotFound: object not found: " + rObject.ToString())
def ChooseIntention(self): mostActiveIntention = self.scenario.GetActiveIntention() if mostActiveIntention == None: Global.Log("Programmer.Error: no HL intention form pre-generated fixed scenario") mostActiveIntention = self.intentions.GetRandomHighLevelIntention() self.processArea.ActivateIntention(mostActiveIntention, None)