示例#1
0
    def resonance(self, chunk):
        self.busy = True
        if self.error: self.error = False
        self._request_count += 1

        # convert chunk to string (if it isn't already a string)
        chunk = self.chunk2str(chunk)
        # assign any unassigned values in chunk string
        chunk = self.assignValues(chunk)

        if '?' in chunk:
            raise Exception(
                "Use the resonanuce function when the chunk has no '?'. If there is a '?' use request instead"
            )

        # keep track of the number of occurrences of a particular value in case of repeats
        occurrences = {}
        # keep a running sum of the cosines and a count of the values in the chunk
        sumOfCosines = 0
        numOfValues = 0
        # perform a query for each value in chunk
        for slotvalue in chunk.split():
            # create a query by removing the value and replacing it with '?'
            query = chunk.split()  # turn chunk into list
            query.pop(numOfValues)  # remove this list item
            # check if chunk has slots by checking for colons (which separate slots from values)
            if ':' in slotvalue:
                slot, value = slotvalue.split(':')
                query.insert(numOfValues, slot + ':?')  # replace value with ?
                query = ' '.join(query)  # convert query to a string
                queryVec, queryStr = self.queryWithSlots(query)
            else:
                value = slotvalue
                query.insert(numOfValues, '?')  # replace value with ?
                query = ' '.join(query)  # convert query to a string
                queryVec, queryStr = self.queryJustValues(query)
            numOfValues = numOfValues + 1

            # find the match between the query vector and the value's memory vector
            match = self.memory[value].compare(queryVec)
            sumOfCosines = sumOfCosines + match
            if self.verbose:
                print 'The query is ' + queryStr
                print 'Match is ' + str(
                    match) + ' for ' + value + ' = ' + self.memStr[value]
        coherence = sumOfCosines / numOfValues
        if self.verbose:
            print 'The coherence is ' + str(coherence)
        if coherence <= self.threshold:
            self.fail(self._request_count)
        else:
            chunkObj = Chunk(chunk)
            chunkObj.activation = coherence
            self.recall(chunkObj,
                        matches=[],
                        request_number=self._request_count)
示例#2
0
    def set(self, chunk):
        if self.busy: return
        self.busy = True

        try:
            chunk = Chunk(chunk, self.sch.bound)
        except AttributeError:
            chunk = Chunk(chunk, {})
        yield self.delay_time()

        self._buffer.chunk = chunk
        self.busy = False
示例#3
0
文件: hdm.py 项目: KoreyMac54/HDM
  def resonance(self,chunk):
     self.busy=True
     if self.error: self.error=False
     self._request_count+=1


     # convert chunk to string (if it isn't already a string)
     chunk = self.chunk2str(chunk)
     # assign any unassigned values in chunk string
     chunk = self.assignValues(chunk)

     if '?' in chunk:
        raise Exception("Use the resonanuce function when the chunk has no '?'. If there is a '?' use request instead")
          
     # keep track of the number of occurrences of a particular value in case of repeats
     occurrences = {}
     # keep a running sum of the cosines and a count of the values in the chunk
     sumOfCosines = 0;
     numOfValues  = 0; 
     # perform a query for each value in chunk
     for slotvalue in chunk.split():
        # create a query by removing the value and replacing it with '?'
        query = chunk.split() # turn chunk into list
        query.pop(numOfValues) # remove this list item
        # check if chunk has slots by checking for colons (which separate slots from values)
        if ':' in slotvalue:
            slot,value = slotvalue.split(':')
            query.insert(numOfValues, slot+':?') # replace value with ?
            query = ' '.join(query) # convert query to a string
            queryVec, queryStr = self.queryWithSlots(query)
        else:
            value = slotvalue
            query.insert(numOfValues, '?') # replace value with ?
            query = ' '.join(query) # convert query to a string
            queryVec, queryStr = self.queryJustValues(query)
        numOfValues = numOfValues + 1;

        # find the match between the query vector and the value's memory vector
        match = self.memory[value].compare(queryVec)
        sumOfCosines = sumOfCosines + match
        if self.verbose:
            print 'The query is ' + queryStr
            print 'Match is ' + str(match) + ' for ' + value + ' = ' + self.memStr[value]
     coherence = sumOfCosines / numOfValues
     if self.verbose:
        print 'The coherence is ' + str(coherence)
     if coherence <= self.threshold:
        self.fail(self._request_count)
     else:
         chunkObj = Chunk(chunk)
         chunkObj.activation = coherence
         self.recall(chunkObj,matches=[],request_number=self._request_count)     
示例#4
0
文件: hdm.py 项目: MatthewAKelly/HDM
 def resonance(self,chunk):
    if '?' in chunk:
       print 'chunk is ' + chunk
       raise Exception("Use the resonance function when the chunk has no '?'. If there is a '?' use request instead")
         
    coherence = self.get_activation(chunk)
    if self.verbose:
       print 'The coherence is ' + str(coherence)
    if coherence <= self.threshold:
       self.fail(self._request_count)
    else:
        chunkObj = Chunk(chunk)
        chunkObj.activation = coherence
        self.recall(chunkObj,matches=[],request_number=self._request_count)     
示例#5
0
    def examine(self, pat):
        if isinstance(pat, str) and ':' not in pat and pat.count(' ') == 1:
            pat = 'x:%s y:%s' % tuple(pat.split(' '))

        self.lastExamine = Pattern(pat, self.sch.bound)

        pat = self.lastExamine

        for obj in self.parent.parent.get_children():
            if hasattr(obj, 'x') and hasattr(obj, 'y') and getattr(
                    obj, 'visible', True):
                if pat.match(obj) is not None:
                    #if self.isClose(obj.x,float(pat[0])) and self.isClose(obj.y,float(pat[1])):
                    self.busy = True
                    yield 0.085
                    self.busy = False
                    if obj in self.parent.parent.get_children():
                        self.tracking = obj
                        self.log._ = 'Vision sees %s' % Chunk(obj)
                        self._visual.set(obj)
                        self.finst.add(obj)
                    else:
                        self.tracking = None
                        self.log._ = 'Vision sees nothing'
                        self._visual.clear()
                    break
示例#6
0
 def chunk2str(self, chunk):
     # if the chunk is a Buffer object, extract the Chunk object from inside it, then turn the Chunk into a string
     if isinstance(chunk, Buffer):
         chunk = Chunk(chunk.chunk)
     # if the chunk is a Chunk object, turn the Chunk into a string
     if isinstance(chunk, Chunk):
         chunk = str(chunk)
     return chunk
 def add(self,chunk,record=None,**keys):
   if self.error: self.error=False
   if isinstance(chunk,Buffer):
     chunk=Chunk(chunk.chunk)
   else:
     bound=None
     if hasattr(self,'sch'):
       bound=getattr(self.sch,'bound',None)
     chunk=Chunk(chunk,bound)
   for c in self.dm:
     if chunk==c:
       for a in self.adaptors: a.merge(c,**keys)
       break
   else:
     for a in self.adaptors: a.create(chunk,**keys)
     self.dm.append(chunk)
   chunk.record=record
示例#8
0
文件: dm.py 项目: KoreyMac54/SGOMS
 def add(self,chunk,record=None,**keys):
   if self.error: self.error=False
   if isinstance(chunk,Buffer):
     chunk=Chunk(chunk.chunk)
   else:
     bound=None
     if hasattr(self,'sch'):
       bound=getattr(self.sch,'bound',None)
     chunk=Chunk(chunk,bound)
   for c in self.dm:
     if chunk==c:
       for a in self.adaptors: a.merge(c,**keys)
       break
   else:
     for a in self.adaptors: a.create(chunk,**keys)
     self.dm.append(chunk)
   chunk.record=record
示例#9
0
    def request(self, chunk):
        self.busy = True
        if self.error: self.error = False
        self._request_count += 1

        # convert chunk to string (if it isn't already a string)
        chunk = self.chunk2str(chunk)
        # assign any unassigned values in chunk string
        chunk = self.assignValues(chunk)

        # check if chunk has slots by checking for colons (which separate slots from values)
        if ':' in chunk:
            queryVec, queryStr = self.queryWithSlots(chunk)
        else:
            queryVec, queryStr = self.queryJustValues(chunk)

        if self.verbose:
            print 'The query is ' + queryStr
        highestCosine = self.threshold
        bestMatch = 'none'
        # find the best match to the query vector in memory
        for mem, memVec in self.memory.items():
            thisCosine = memVec.compare(queryVec)
            if self.verbose:
                print mem, thisCosine
            if thisCosine > highestCosine:
                highestCosine = thisCosine
                bestMatch = mem
        if self.verbose:
            print bestMatch

        if bestMatch == 'none':
            self.fail(self._request_count)
        else:
            # replace the placeholder '?' with the retrieved memory 'bestMatch'
            chunk = chunk.replace('?', bestMatch)
            if self.verbose:
                print 'Best match is ' + bestMatch + ' = ' + self.memStr[
                    bestMatch]
                print 'output chunk = ' + chunk
            chunkObj = Chunk(chunk)
            chunkObj.activation = highestCosine
            self.recall(chunkObj,
                        matches=[],
                        request_number=self._request_count)
示例#10
0
 def get_activation(self, chunk):
     if not isinstance(chunk, Chunk):
         try:
             chunk = Chunk(chunk, self.sch.bound)
         except AttributeError:
             chunk = Chunk(chunk, None)
         for c in self.dm:
             if chunk == c:
                 chunk = c
                 break
         else:
             raise Exception('No such chunk found')
     act = 0
     for a in self.adaptors:
         act += a.activation(chunk)
     if self.record_all_chunks or chunk.record is True:
         self.log[str(chunk)] = act
     return act
示例#11
0
    def resonance(self, chunk):
        if '?' in chunk:
            print('chunk is ' + chunk)
            raise Exception(
                "Use the resonance function when the chunk has no '?'. If there is a '?' use request instead"
            )

        coherence = self.get_activation(chunk)
        if self.verbose:
            print('The coherence is ' + str(coherence))
        if coherence <= self.threshold:
            self.fail(self._request_count)
        else:
            chunkObj = Chunk(chunk)
            chunkObj.activation = coherence
            self.recall(chunkObj,
                        matches=[],
                        request_number=self._request_count)
示例#12
0
    def requestValue(self, chunk, require_new=False):
        # check if chunk has slots by checking for colons (which separate slots from values)
        if ':' in chunk:
            queryVec = self.queryWithSlots(chunk)
        else:
            queryVec = self.queryJustValues(chunk)

        highestCosine = self.threshold
        bestMatch = 'none'
        if self.verbose:
            print('Query is: ' + chunk)
            print('inhibited values: ' + str(self.inhibited))
            print('Finst contains: ' + str(self.finst.obj))
        # find the best match to the query vector in memory
        for mem, memVec in self.mem.items():
            # skip inhibited values
            if mem not in self.inhibited:
                # skip previously reported values if require_new is true
                if (not require_new) or (not self.finst.contains(mem)):
                    thisCosine = memVec.compare(queryVec)
                    if self.verbose:
                        print(mem, thisCosine)
                    if thisCosine > highestCosine:
                        highestCosine = thisCosine
                        bestMatch = mem

        if bestMatch == 'none':
            if self.verbose:
                print('No matches found above threshold of cosine =',
                      self.threshold)
            self.fail(self._request_count)
        else:
            # replace the placeholder '?' with the retrieved memory 'bestMatch'
            chunk = chunk.replace('?', bestMatch)
            if self.verbose:
                print('Best match is ' + bestMatch)
                print('with a cosine of ' + str(highestCosine))
                print('output chunk = ' + chunk)
            chunkObj = Chunk(chunk)
            chunkObj.activation = highestCosine
            self.finst.add(bestMatch)
            self.recall(chunkObj,
                        matches=[],
                        request_number=self._request_count)
示例#13
0
文件: hdm.py 项目: KoreyMac54/HDM
  def request(self,chunk):
     self.busy=True
     if self.error: self.error=False
     self._request_count+=1

     
     # convert chunk to string (if it isn't already a string)
     chunk = self.chunk2str(chunk)
     # assign any unassigned values in chunk string
     chunk = self.assignValues(chunk)
     
     # check if chunk has slots by checking for colons (which separate slots from values)
     if ':' in chunk:
        queryVec, queryStr = self.queryWithSlots(chunk)
     else:
        queryVec, queryStr = self.queryJustValues(chunk)
     
     if self.verbose:
        print 'The query is ' + queryStr
     highestCosine = self.threshold
     bestMatch = 'none'
     # find the best match to the query vector in memory
     for mem,memVec in self.memory.items():
        thisCosine = memVec.compare(queryVec)
        if self.verbose:
            print mem, thisCosine
        if thisCosine > highestCosine:
            highestCosine = thisCosine 
            bestMatch = mem
     if self.verbose:
        print bestMatch

     if bestMatch == 'none':
        self.fail(self._request_count)
     else:
         # replace the placeholder '?' with the retrieved memory 'bestMatch'
         chunk = chunk.replace('?',bestMatch)
         if self.verbose:
            print 'Best match is ' + bestMatch + ' = ' + self.memStr[bestMatch]
            print 'output chunk = ' + chunk
         chunkObj = Chunk(chunk)
         chunkObj.activation = highestCosine
         self.recall(chunkObj,matches=[],request_number=self._request_count)
示例#14
0
 def examine(self, pat):
     """
 Check the visible object at a visual location.
 :param pat: specify the visual location.
 :return:
 """
     # The argument "pat" (pattern) contains the information of a visual location.
     # If pat provides only the values of x-coordinate and y-coordinate,
     # we reorganize pat into 'x: x-coordinate y: y-coordinate'.
     if isinstance(pat, str) and ':' not in pat and pat.count(' ') == 1:
         pat = 'x:%s y:%s' % tuple(pat.split(' '))
     # The x-coordinate, y-coordinate often are variables, e.g. "?x ?y". We use function Pattern() to map
     # the variables to the values stored in sch.bound.
     self.lastExamine = Pattern(pat, self.sch.bound)
     # Now we update the variable pat which has assigned valules.
     pat = self.lastExamine
     # In the following self is the vision module, self.parent is the agent which includes the vision module,
     # and self.parent.parent is the environment in which the agent is. In the for-loop, each object in the environment
     # is checked to see if they are visiable objects.
     for obj in self.parent.parent.get_children():
         # First, let us check if an object is a visible object. We do so by checking if the object contains the attributes
         # "x", "y", and if the attribute "visible=True".
         if hasattr(obj, 'x') and hasattr(obj, 'y') and getattr(
                 obj, 'visible', True):
             # Further, if the visual location pat matches the location of the visible object,
             if pat.match(obj) is not None:
                 #(obsolete) if self.isClose(obj.x,float(pat[0])) and self.isClose(obj.y,float(pat[1])):
                 # The vision module starts working; it is busy.
                 self.busy = True
                 # The default time required for a vision module request is set as 0.085s.
                 yield 0.085
                 # The vision module finishes working; it is not busy.
                 self.busy = False
                 # In the following, self is the vision module, self.parent is the agent which includes the vision module,
                 # and self.parent.parent is the environment in which the agent is.
                 # If obj is still an object in the environment,
                 if obj in self.parent.parent.get_children():
                     # The vision module is tracking this object.
                     self.tracking = obj
                     # We print the following information to the display.
                     self.log._ = 'Vision sees %s' % Chunk(obj)
                     # We put the object into the visual buffer.
                     self._visual.set(obj)
                     # We add the object into the list of finst (finger instantiation).
                     self.finst.add(obj)
                 # If obj is no longer an object in the environment,
                 else:
                     # There is nothing to track.
                     self.tracking = None
                     # We print the following information to the display.
                     self.log._ = 'Vision sees nothing'
                     # We clear the visual buffer.
                     self._visual.clear()
                 # Each time, only one object can be seen. When we find one, we break the for-loop.
                 break
示例#15
0
文件: hdm.py 项目: MatthewAKelly/HDM
  def requestValue(self,chunk,require_new=False):
     # check if chunk has slots by checking for colons (which separate slots from values)
     if ':' in chunk:
        queryVec = self.queryWithSlots(chunk)
     else:
        queryVec = self.queryJustValues(chunk)
     
     highestCosine = self.threshold
     bestMatch = 'none'
     if self.verbose:
        print 'Query is: ' + chunk
        print 'inhibited values: ' + str(self.inhibited)
        print 'Finst contains: ' + str(self.finst.obj)
     # find the best match to the query vector in memory
     for mem,memVec in self.mem.items():
        # skip inhibited values
        if mem not in self.inhibited:
            # skip previously reported values if require_new is true
            if (not require_new) or (not self.finst.contains(mem)):
                thisCosine = memVec.compare(queryVec)
                if self.verbose:
                    print mem, thisCosine
                if thisCosine > highestCosine:
                    highestCosine = thisCosine 
                    bestMatch = mem

     if bestMatch == 'none':
        if self.verbose:
            print 'No matches found above threshold of cosine =', self.threshold
        self.fail(self._request_count)
     else:
         # replace the placeholder '?' with the retrieved memory 'bestMatch'
         chunk = chunk.replace('?',bestMatch)
         if self.verbose:
            print 'Best match is ' + bestMatch
            print 'with a cosine of ' + str(highestCosine)
            print 'output chunk = ' + chunk
         chunkObj = Chunk(chunk)
         chunkObj.activation = highestCosine
         self.finst.add(bestMatch)
         self.recall(chunkObj,matches=[],request_number=self._request_count)
示例#16
0
    def recall(self, chunk, matches, request_number):
        keys = list(sorted(chunk.keys()))
        if not hasattr(chunk, '_blend_keys'):
            bk = []
            for k in keys:
                try:
                    v = float(chunk[k])
                    bk.append(k)
                except:
                    pass
            chunk._blend_keys = tuple(bk)
        bk = chunk._blend_keys
        if len(bk) > 0:
            a = chunk.activation
            chunk = Chunk(chunk)
            chunk.activation = a

            for b in bk:
                chunk[b] = 0
            total_activation = 0
            for m in matches:
                m.exp_activation = math.exp(m.activation)
                k = list(sorted(m.keys()))
                if k == keys:
                    blend = {}
                    try:
                        for b in bk:
                            blend[b] = float(m[b])
                    except ValueError:
                        continue
                    for b in bk:
                        chunk[b] += blend[b] * m.exp_activation
                    total_activation += m.exp_activation
            for b in bk:
                chunk[b] /= total_activation
        for m in Memory.recall(self, chunk, matches, request_number):
            yield m
示例#17
0
文件: dm.py 项目: KoreyMac54/SGOMS
 def recall(self,chunk,matches,request_number):
   keys=list(sorted(chunk.keys()))
   if not hasattr(chunk,'_blend_keys'):
     bk=[]
     for k in keys:
       try:
         v=float(chunk[k])
         bk.append(k)
       except:
         pass
     chunk._blend_keys=tuple(bk)
   bk=chunk._blend_keys
   if len(bk)>0:
     a=chunk.activation
     chunk=Chunk(chunk)
     chunk.activation=a
     
     for b in bk: chunk[b]=0
     total_activation=0
     for m in matches:
       m.exp_activation=math.exp(m.activation)
       k=list(sorted(m.keys()))
       if k==keys:
         blend={}
         try:            
           for b in bk:
             blend[b]=float(m[b])
         except ValueError:
           continue
         for b in bk:
           chunk[b]+=blend[b]*m.exp_activation
         total_activation+=m.exp_activation
     for b in bk:
       chunk[b]/=total_activation
   for m in Memory.recall(self,chunk,matches,request_number):
     yield m
示例#18
0
    def examine(self, pat):

        self.lastExamine = Pattern(pat, self.sch.bound)
        pat = self.lastExamine
        for obj in self.parent.parent.get_children():
            if hasattr(obj, 'x') and hasattr(obj, 'y') and getattr(
                    obj, 'visible', True):
                if True or pat.match(obj) is not None:
                    #if self.isClose(obj.x,float(pat[0])) and self.isClose(obj.y,float(pat[1])):
                    yield 0.085
                    if obj in self.parent.parent.get_children():
                        self.tracking = obj
                        self.log._ = 'Vision sees %s' % Chunk(obj)
                        self._visual.set(obj)
                        self.finst.add(obj)
                    else:
                        self.tracking = None
                        self.log._ = 'Vision sees nothing'
                        self._visual.clear()
                    break
示例#19
0
 def test_chunk_setting(self):
     from ccm.lib.actr.buffer import Chunk
     c = Chunk(dict(a=1, b=2))
     self.assertEqual(c['a'], 1)
     self.assertEqual(c['b'], 2)