Exemple #1
0
    def CreateNode(self, point, memObject):
        xNoise = Global.Randint(-Global.ELNodeAddNoise, Global.ELNodeAddNoise)
        yNoise = Global.Randint(-Global.ELNodeAddNoise, Global.ELNodeAddNoise)
        x = float(point.x + xNoise)
        y = float(point.y + yNoise)

        while not self.area.IsInside(Point(x, y)):
            xNoise = Global.Randint(-Global.ELNodeAddNoise,
                                    Global.ELNodeAddNoise)
            yNoise = Global.Randint(-Global.ELNodeAddNoise,
                                    Global.ELNodeAddNoise)
            x = float(point.x + xNoise)
            y = float(point.y + yNoise)

        newNode = EnergyLayerNode(self, x, y, self.nodeIndex)
        self.nodeIndex = self.nodeIndex + 1
        self.nodes.append(newNode)

        if Global.CreatePlaces:
            place = self.GetPlaceForNode(newNode)
            place.nodes.append(newNode)
            newNode.place = place

        memObject.AddLinkToNode(newNode)
        memObject.IntenseToNode(newNode, Global.MemObjIntenseToNewNode)
        self.stepELNodesCreated = self.stepELNodesCreated + 1
        return newNode
Exemple #2
0
    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
Exemple #3
0
 def SaveHeatMap(self):
     for n in self.nodes:
         nStr = "%d;%d;%.4f" % (int(n.x), int(n.y), n.usage)
         Global.LogData("elnodeheatmap", nStr)
     for n in self.nodes:
         nStr = "%d;%d;%.4f" % (int(n.x), int(n.y), n.AGamount)
         Global.LogData("elnodeheatmapag", nStr)
Exemple #4
0
    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
Exemple #5
0
 def stopSimulation(self):
     Global.Log("Stoping simulation...")
     self.exitLocks()
     Global.Reset()
     self.agent = None
     self.mapRenderer.Clear()
     self.mapRenderer = None
     self.lock = None
Exemple #6
0
 def ChooseProcessForIntention(self, emotion, intention, parentProcess):
     processes = intention.processes
     if parentProcess != None:
         processes = Global.SetDifference(processes, parentProcess.failedProcesses)
         
     if len(processes) == 0:
         return None
     if intention.name == "Want":    #for Want intention the order of process matters
         return processes[0]
     else:
         return Global.Choice(processes)
Exemple #7
0
    def StepUpdate(self):
        for ep in self.energyPoints:
            ep.StepUpdate(self.getNodesAround(ep, Global.ELGravityRange))
        for node in self.nodes:
            node.StepUpdate(
                self.getNodesAround(node, Global.ELAntigravityRange))
        for node in self.nodes:
            node.StepUpdateMove()

        if Global.CreatePlaces:
            placesToDelete = []
            for place in self.places:
                place.CalculateAG()
                if place.slowAGamount < Global.PlacesAGMin * (place.level - 1):
                    placesToDelete.append(place)
                    continue

                if place.AGamount > Global.PlacesAGNeeded * (2**(place.level) -
                                                             1):
                    self.createPlaces(place)

                if place.parent != None:
                    place.UpdateLocation()
                    place.CalculateRange()
                place.SaveStatus()

            for place in placesToDelete:
                place.Delete()

            for node in self.nodes:
                p = self.GetPlaceForNode(node)
                if p != node.place:
                    node.place.nodes.remove(node)
                    node.place = p
                    p.nodes.append(node)

        for ep in self.energyPointsToDelete:
            self.energyPoints.remove(ep)
        self.energyPointsToDelete = []

        self.forgetEnergy = self.forgetEnergy + Global.ELForgetNodeRate
        cost = self.GetNodeDeleteCost()
        chanceForget = 100 * float(self.forgetEnergy - cost) / cost

        diceRoll = Global.DiceRoll()
        if diceRoll < chanceForget and len(self.nodes) > 0:
            node = Global.Choice(self.nodes)
            self.forgetEnergy = self.forgetEnergy - (
                cost * log(max(2, node.usage), 2))
            self.DeleteNode(node)

        Global.LogData("nc", self.Status())
Exemple #8
0
    def CreateMap(self):
        areaArea = self.area.GetArea()
        nodeCount = areaArea / Global.ELDensity**2
        self.desiredNodeCount = nodeCount * 2
        self.minimalDesiredNodeCount = self.desiredNodeCount / 5
        self.maximalDesiredNodeCount = self.desiredNodeCount

        x = self.area.points[0].x
        y = self.area.points[0].y
        if Global.CreatePlaces:
            rootPlace = Place(self, self.placeIndex, self.area.width / 2 + x,
                              self.area.height / 2 + y)
            rootPlace.range = max(x + self.area.width,
                                  y + self.area.height) * sqrt(2) / 2
            rootPlace.range = ceil(rootPlace.range)
            rootPlace.startRange = rootPlace.range
            self.places.append(rootPlace)

        if Global.ELCreateNoise == -1:  #completely random distribution of nodes
            while len(self.nodes) < nodeCount:
                x = float(Global.Randint(0, self.area.width - 1))
                y = float(Global.Randint(0, self.area.height - 1))

                if self.area.IsInside(Point(x, y)):
                    node = EnergyLayerNode(self, x, y, self.nodeIndex)
                    self.nodeIndex = self.nodeIndex + 1
                    self.nodes.append(node)
                    if Global.CreatePlaces:
                        node.place = rootPlace
                        rootPlace.nodes.append(node)
        else:
            xCount = self.area.width / Global.ELDensity
            yCount = self.area.height / Global.ELDensity
            density = Global.ELDensity
            for y in range(yCount):
                for x in range(xCount):
                    xNoise = Global.Randint(-Global.ELCreateNoise,
                                            Global.ELCreateNoise)
                    yNoise = Global.Randint(-Global.ELCreateNoise,
                                            Global.ELCreateNoise)
                    xx = float(x * density + density / 2 + xNoise)
                    yy = float(y * density + density / 2 + yNoise)

                    if self.area.IsInside(Point(xx, yy)):
                        node = EnergyLayerNode(self, xx, yy, self.nodeIndex)
                        self.nodeIndex = self.nodeIndex + 1
                        self.nodes.append(node)
                        if Global.CreatePlaces:
                            node.place = rootPlace
                            rootPlace.nodes.append(node)
Exemple #9
0
    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)
Exemple #10
0
    def StepUpdateMove(self, normalStep=True):
        massCoef = 1.0 / max(1, self.usage)

        dx = self.stepDiffX * massCoef
        dy = self.stepDiffY * massCoef

        distToMove2 = dx * dx + dy * dy
        maxDif = Global.MaxELNodeMove
        if distToMove2 > (maxDif * maxDif):
            distToMove = sqrt(distToMove2)
            coef = maxDif / distToMove
            dx = dx * coef
            dy = dy * coef

        newX = self.x + dx
        newY = self.y + dy
        hit = self.area.CanMoveEx(self, newX, newY)
        if hit.hit:
            newX = hit.x
            newY = hit.y

            ldx = newX - self.x
            ldy = newY - self.y
            distToMove2 = ldx * ldx + ldy * ldy
            if distToMove2 < 0.0001:
                newX = self.x
                newY = self.y

        if normalStep and Global.SaveELNodesStatus:
            ldx = newX - self.x
            ldy = newY - self.y
            distToMove = sqrt(ldx * ldx + ldy * ldy)

        if self.area.IsInside(Point(newX, newY)):
            self.x = newX
            self.y = newY
        self.stepDiffX = self.stepDiffY = 0

        if normalStep:
            self.usage -= Global.ELNodeUsageFadeOut
            if self.usage < 0: self.usage = 0
            self.AGamount -= Global.ELAGFadeOut

        if normalStep and Global.SaveELNodesStatus:
            status = str(Global.GetStep()) + ";" + str(
                self.index) + ";%.4f;%.4f;%.4f" % (distToMove, self.usage,
                                                   self.AGamount)
            Global.LogData("elnode-status", status)
Exemple #11
0
 def GetAction(self, emotion):
     if self.processArea.HasNoIntention():
         self.ChooseIntention()
     #agent has intention (in self.PA.actInt)
     excIntention = self.processArea.GetActIntention()
     excProcess = self.processArea.GetActProcess()
     
     #what is active - I or P ?
     if excIntention.parentExcProcess == excProcess:
         #if I under P -> we have active I and need some process to do it  (or this is HL intention)
         process = self.ChooseProcessForIntention(emotion, excIntention.intention, excIntention.parentExcProcess)
         if process == None:
             self.processArea.TerminateIntentionFalse(emotion)
             #impossible to finish this intention -> terminate int and parent process, try to choose another process in parent intention
             return self.GetAction(emotion)
         excProcess = self.processArea.ActivateProcess(emotion, process, excIntention, excIntention.parentExcProcess)
     else:
         #if P under I -> we have already selected process for this intention previously, go on
         process = excProcess.process         
     
     #now we have intention and under it process to do
     
     #process atomic?
     if process.intentions != []:
         #process is not atomic -> choose first not completed sub-intention
         intention = Global.SetFirstDifference(process.intentions, excProcess.completedIntentions)
         self.processArea.ActivateIntention(intention, excProcess)
         return self.GetAction(emotion)    #go deeper for atomic process
     else:
         # process is atomic
         return self.GetAtomicAction(emotion, excProcess)
Exemple #12
0
 def TerminateProcess(self, emotion, successful=True):
     if self.actualProcess == None:
         self.actualIntention = None #there is no process left - HL intention finnished
         return
     
     self.actualProcess.TerminateProcess(successful)
     #commented in original: self.episodicMemory.StoreProcess(self.actualProcess, emotion)
     
     if not successful:
         # actual process went wrong, next step AS will select another in parent intention
         self.actualProcess = self.actualProcess.parent
     else:
         # actual process finnished, parent intention as well
         self.actualProcess = self.actualProcess.parent
             
         if self.actualProcess != None:
             notFinishedIntentions = Global.SetDifference(self.actualProcess.process.intentions, self.actualProcess.completedIntentions) 
             if len(notFinishedIntentions) == 0:
                 self.TerminateProcess(True)
             else:
                 # this would be otherwise called in AS next step via AS.ChooseProcessForIntention but randomly 
                 self.ActivateIntention(notFinishedIntentions[0], self.actualProcess)
         else:
             #there is no process left - HL intention finnished
             self.actualIntention = None
Exemple #13
0
 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)
Exemple #14
0
 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)
Exemple #15
0
 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)
Exemple #16
0
 def Status(self):
     strObjs = str(len(self.area.objects))
     s = str(Global.GetStep()) + ';' + str(len(self.nodes)) + ";" + str(
         self.stepEPCreated) + ";" + str(
             self.stepELNodesCreated) + ";" + str(
                 self.desiredNodeCount) + ";" + strObjs
     self.stepEPCreated = 0
     self.stepELNodesCreated = 0
     return s
Exemple #17
0
 def SetAllToRegardingAffs(self, rObjs, action, coef):
     sources = action.sources
     sourcesCount = len(sources)
     for rObj in rObjs:
         affs = []
         for aff in rObj.type.affordances:
             if aff in sources:
                 affs.append(aff)
         rObj.curAttractivity = Global.WeakCoef(
             coef * float(len(affs)) / sourcesCount, 2) * rObj.attractivity
Exemple #18
0
 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())
Exemple #19
0
    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()     
Exemple #20
0
 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())
Exemple #21
0
    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())
Exemple #22
0
 def RenderState(self, world):
     self.mapRenderer.RenderObjectVisibility()
     self.mapRenderer.RenderSpaceMap()
     self.mapRenderer.RenderAgent(world.agent)
     #self.mapRenderer.RenderObjects() - only for dynamic worlds
     if Global.RenderVisibilityHistory:
         self.mapRenderer.RenderVisibilityHistory()
     else:
         self.mapRenderer.HideVisibilityHistory()
     
     self.wxCanvas.delete("infotxt")
     txt =  "Step:  " + str(world.step).zfill(6) + "\nTime:  " + Global.TimeToHumanFormat(True)
     self.txtTime = self.wxCanvas.create_text(1080, 5, text=txt, width=200, anchor=NW, tags="infotxt")
     strXY = "%.4f,%.4f" % (self.agent.x, self.agent.y)
     txt =  "Agent:  " + strXY
     nc = len(world.agent.intelligence.spaceMap.Layer.nodes)
     txt = txt + "\nEnergyLayer.nodeCount: " + str(nc)
     self.txtAgentInfo = self.wxCanvas.create_text(1300, 5, text=txt, width=200, anchor=NW, tags="infotxt")
     pa = self.agent.intelligence.processArea
     txt = "ProcessArea:\n" + "\n".join(self.agent.paText)
     self.txtPA = self.wxCanvas.create_text(1050, 50, text=txt, width=200, anchor=NW, tags="infotxt")
     ma = self.agent.intelligence.memoryArea
     txt = "MemoryArea:\n  "
     for phantom in ma.memoryPhantoms:
         txt = txt + phantom.ToString() + "\n  "  
     self.txtMA = self.wxCanvas.create_text(1050, 200, text=txt, width=400, anchor=NW, tags="infotxt")
     pf = self.agent.intelligence.perceptionField
     txt = "PerceptionField:\n  "
     for phantom in pf.environmentPhantoms:
         txt = txt + phantom.ToString() + "\n  "
     self.txtPF = self.wxCanvas.create_text(1050, 300, text=txt, width=400, anchor=NW, tags="infotxt")
     txt = "Log:\n  "
     for line in Global.logLines:
         txt = txt + line + "\n  "
     self.txtLog = self.wxCanvas.create_text(1050, 550, text=txt, width=450, anchor=NW, tags="infotxt")
     
     Global.LogData("nc", world.agent.intelligence.spaceMap.Layer.Status())
Exemple #23
0
 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
Exemple #24
0
 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)
Exemple #25
0
    def StepUpdate(self, nodesAround):
        cost = self.layer.GetNodeCreateCost()
        chanceNew = 100 * float(self.energy - cost) / cost
        diceRoll = Global.DiceRoll()
        if diceRoll < chanceNew:
            self.layer.CreateNode(self, self.memObject)
            self.energy = self.energy - cost

        effect = self.energy / Global.EPCreateEnergy

        for node in nodesAround:
            node.Train(self, effect)

        self.intenseMemObjToNodes(effect)

        self.energy = self.energy * Global.EPFadeCoef
        if self.energy < Global.EPFadeLimit:
            self.layer.DeleteEnergyPoint(self)
Exemple #26
0
   def simulationThread(self):
       world = Global.World
       self.lockBack = Lock()
       self.lockBack.acquire()
       while True:
           world.Step()
           self.RenderState(world)
           self.mapRenderer.RenderToFile(world, "../../exs/PIL" + str(world.step).zfill(6) + ".png", ["agent", "ov", "eps", "info"])
           
           # used only to get EPS of test rooms
           #p=self.wxCanvas.postscript(width="1020",height="1020")
           #f=open("image" + str(world.step) + ".eps", "wb")
           #f.write(p)
           #f.close()
           
           if self.lock.acquire(False): break
           self.playbackLock.acquire()
           self.playbackLock.release()
 
       self.lockBack.release()
       Global.LogEnd()
       return
Exemple #27
0
 def GetRandomHighLevelIntention(self):
     return Global.Choice(self.highLevelIntentions)
Exemple #28
0
 def SaveScenario(self):
     for i in self.intentions:
         Global.LogData("scenario", i.name)
Exemple #29
0
 def SaveStatus(self):
     status = str(Global.GetStep()) + ";" + str(
         self.index) + ";%.4f;%.4f;%.4f;%.4f;%.4f;%.4f;%.4f" % (
             self.x, self.y, self.level, self.range, self.AGamount,
             self.totalAGamount, self.slowAGamount)
     Global.LogData("place-status", status)
Exemple #30
0
    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)