Beispiel #1
0
    def transform(self, particleArray):
        '''Given an array of Particles, select one and process
        '''
        if len(particleArray) == 0:  # empty
            return None

        pIndex = random.choice(range(len(particleArray)))
        p = particleArray[pIndex]
        # only process if state matches current state of this particle
        if p.getState() != self.getState():
            return particleArray  # return unaltered reference
        # find transform
        if self.getState() not in self.transformMap.keys():
            return None

        weights = []
        options = []
        for o, w in self.transformMap[self.getState()]:
            weights.append(w)
            options.append(o)
        boundary = unit.unitBoundaryProportion(weights)
        i = unit.unitBoundaryPos(random.random(), boundary)
        result = options[i]  # index is in position

        if result == None:  # remove
            #environment.printDebug(['transform(); removing particle:', p])
            particleArray.pop(pIndex)
        # if a string value the same as the current state of the particle
        elif result == p.getState():
            pass  # do nothing
        else:  # not yet implemented: need to convert do a different state
            # for this wee need a life cycle argument
            pass
Beispiel #2
0
 def next(self, unitVal, previous, order, slide=1):
     """generate the next value of the a new chain
     unitVal is floating point number b/n 0 and 1; can be generated
     by any distribution. this value determines the selection of values
     previous is a list of values that will be analaized
     if the list is insufficiant for the order, if slide, will use 
     next available order, otherwise, will use zero order
     order may be a float; if so it will use weighting from drawer
     """
     symbols = list(self._symbols.keys())
     # get appropriate order: if a float, will be dynamically allocated
     order = drawer.floatToInt(order, 'weight')
     if order not in list(range(0, self._ordersSrc[-1]+1)):
         order = self._ordersSrc[-1] # use highest defined
     #print _MOD, 'using order', order
     # get appropriate key of given length of previous
     prevLen = len(previous)
     if prevLen <= order: # if less then specified by order
         if slide: # use length as order
             srcSeq = self._valueListToSymbolList(previous)
         else: srcSeq = () # jump to zeroth
     else: # if values are greater in length than order
         if order == 0: srcSeq = ()
         else:                 
             srcSeq = self._valueListToSymbolList(previous[-order:])      
     # determine of there is a direct match, or an expression match
     wList = self._findWeights(srcSeq) # may return None
     # if none, will create equal distribution of all symbols
     # return parallel lists of weights, symbols, both in same order
     wPost, sDeclared = self._scrubWeights(wList)
     #print _MOD, 'order, wPost, sDeclared', order, wPost, sDeclared
     boundary = unit.unitBoundaryProportion(wPost)
     i = unit.unitBoundaryPos(unitVal, boundary)
     # get symbol, then de-signify symbols into the store value
     return self._symbols[sDeclared[i]]
Beispiel #3
0
    def transform(self, particleArray):
        '''Given an array of Particles, select one and process
        '''
        if len(particleArray) == 0: # empty
            return None

        pIndex = random.choice(range(len(particleArray)))
        p = particleArray[pIndex]
        # only process if state matches current state of this particle
        if p.getState() != self.getState():
            return particleArray # return unaltered reference
        # find transform        
        if self.getState() not in self.transformMap.keys():
            return None

        weights = []
        options = []
        for o, w in self.transformMap[self.getState()]:
            weights.append(w)
            options.append(o)
        boundary = unit.unitBoundaryProportion(weights)
        i = unit.unitBoundaryPos(random.random(), boundary)
        result = options[i] # index is in position

        if result == None: # remove
            #environment.printDebug(['transform(); removing particle:', p])
            particleArray.pop(pIndex)
        # if a string value the same as the current state of the particle
        elif result == p.getState():
            pass # do nothing
        else: # not yet implemented: need to convert do a different state
            # for this wee need a life cycle argument 
            pass
Beispiel #4
0
 def next(self, unitVal, previous, order, slide=1):
     """generate the next value of the a new chain
     unitVal is floating point number b/n 0 and 1; can be generated
     by any distribution. this value determines the selection of values
     previous is a list of values that will be analaized
     if the list is insufficiant for the order, if slide, will use 
     next available order, otherwise, will use zero order
     order may be a float; if so it will use weighting from drawer
     """
     symbols = self._symbols.keys()
     # get appropriate order: if a float, will be dynamically allocated
     order = drawer.floatToInt(order, 'weight')
     if order not in range(0, self._ordersSrc[-1]+1):
         order = self._ordersSrc[-1] # use highest defined
     #print _MOD, 'using order', order
     # get appropriate key of given length of previous
     prevLen = len(previous)
     if prevLen <= order: # if less then specified by order
         if slide: # use length as order
             srcSeq = self._valueListToSymbolList(previous)
         else: srcSeq = () # jump to zeroth
     else: # if values are greater in length than order
         if order == 0: srcSeq = ()
         else:                 
             srcSeq = self._valueListToSymbolList(previous[-order:])      
     # determine of there is a direct match, or an expression match
     wList = self._findWeights(srcSeq) # may return None
     # if none, will create equal distribution of all symbols
     # return parallel lists of weights, symbols, both in same order
     wPost, sDeclared = self._scrubWeights(wList)
     #print _MOD, 'order, wPost, sDeclared', order, wPost, sDeclared
     boundary = unit.unitBoundaryProportion(wPost)
     i = unit.unitBoundaryPos(unitVal, boundary)
     # get symbol, then de-signify symbols into the store value
     return self._symbols[sDeclared[i]]
Beispiel #5
0
 def roll(self):
     valCont = random.random()  # continueous value
     if self.sideNo == 0:
         self.valueLast = valCont
     else:
         i = unit.unitBoundaryPos(valCont, self.sideBounds)
         a, m, b = self.sideBounds[i]
         self.valueLast = m
Beispiel #6
0
 def roll(self):
     valCont = random.random() # continueous value
     if self.sideNo == 0:
         self.valueLast = valCont
     else: 
         i = unit.unitBoundaryPos(valCont, self.sideBounds)
         a, m, b = self.sideBounds[i]
         self.valueLast = m
Beispiel #7
0
    def __next__(self):
        '''Apply all rules and produce a new self._state

        >>> g = Grammar()
        >>> g.load('a{3}b{4} @ a{bab}b{aab} @ abaa')
        >>> str(g)
        'a{3}b{4}@a{bab}b{aab}@abaa'
        >>> g.next()
        >>> g.getState()
        'babaabbabbab'
        >>> g.next()
        >>> g.getState()
        'aabbabaabbabbabaabaabbabaabaabbabaab'
        >>> g.getState(values=True)
        [3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0, 3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0, 3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0]

        >>> g = Grammar()
        >>> g.load('a{3}b{4}c{20}d{2} @ a{bab}b{acb}c{ac}d{cd} @ abd')
        >>> str(g)
        'a{3}b{4}c{20}d{2}@a{bab}c{ac}b{acb}d{cd}@abd'
        >>> g.next()
        >>> g.getState() 
        'babacbcd'
        >>> g.next()
        >>> g.getState() 
        'acbbabacbbabacacbaccd'


        >>> g = Grammar()
        >>> g.load('a{a}b{b} @ a{ab}b{a} @ b')
        >>> g.getState()
        'b'
        >>> g.next()
        >>> g.getState()
        'a'
        >>> g.next()
        >>> g.getState()
        'ab'
        >>> g.next()
        >>> g.getState()
        'aba'
        >>> g.next()
        >>> g.getState()
        'abaab'
        >>> g.next()
        >>> g.getState()
        'abaababa'

        '''
        if self._state == None or self._state == '':
            self._state = self._axiom  # a copy in principle

        stateNew = self._state  # copy
        matchTag = []  # matched start indices
        replacementCount = 0

        # make groups of index values, src groups to match
        # need to find largest rule in size
        indexCharPairs = []
        # self._maxRuleOutputSize

        #environment.printDebug(['next(): self._state', self._state])

        for size in range(1, self._maxRuleOutputSize + 1):
            #for size in range(1, 2):
            for i in range(0, len(self._state), size):
                pair = (i, self._state[i:i + size])
                if pair not in indexCharPairs:
                    indexCharPairs.append(pair)

        for inRule, outRule in list(self._rules.items()):

            environment.printDebug(
                ['next(): in/out rule',
                 repr(inRule), outRule])
            # grammar.py: next(): in/out rule '*' [('ab',1)]

            #environment.printDebug(['next(): index char pairs', indexCharPairs])

            # char here may be 1 or more characters, up to max rule size
            for i, char in indexCharPairs:
                #for i, char in enumerate(self._state):

                # comparison to rule
                match = False
                # test single character, exact match
                if inRule == self.EXPRESSALL or inRule == char:
                    match = True
                # if mutliple characters, and one is expressall, and lenght
                # is the same
                elif (len(inRule) > 1 and len(inRule) == len(char)
                      and self.EXPRESSALL in inRule):
                    matchChar = 0
                    for j in range(len(inRule)):
                        if inRule[j] == char[j] or inRule[j] == self.EXPRESSALL:
                            matchChar += 1
                    if matchChar == len(inRule):
                        match = True

                if not match:
                    continue

                # need to find cases of two or more char matches

                # store a string of index in the temp to mark positions
                # can find first instance of symbol; will not
                # be past symbols b/c we are replacing with the old index nums
                iNew = stateNew.find(char)
                pre = stateNew[:iNew]
                # skip location
                post = stateNew[iNew + len(char):]
                # insert marker as a random cod
                tag = self._tagIn(replacementCount)
                replacementCount += 1
                stateNew = pre + tag + post

                #environment.printDebug(['next(): stateNew', stateNew, repr(pre), repr(tag), repr(post)])
                # make a rule section

                # if only one rule, simply provide it
                if len(outRule) == 1:
                    # a list of value, weight pairSymbol
                    replacement = outRule[0][0]
                # if more than one rule, do a weighted selection
                else:
                    options = []
                    weights = []
                    for o, w in outRule:
                        options.append(o)
                        weights.append(w)
                    # create unit boundaries from ordered weights
                    boundary = unit.unitBoundaryProportion(weights)
                    i = unit.unitBoundaryPos(random.random(), boundary)
                    replacement = options[i]  # index is in position

                # a lost of all replacements to make, between the tag and the
                # replacement
                matchTag.append([tag, replacement])

        # do all replacements
        #environment.printDebug(['stateNew: prereplace', stateNew])
        for tag, replacement in matchTag:
            # these are not actual indices but tags to points in the scratch
            iNew = stateNew.find(tag)
            pre = stateNew[:iNew]
            # skip location
            post = stateNew[iNew + len(tag):]
            # insert final value
            stateNew = pre + replacement + post

        #environment.printDebug(['stateNew: post', stateNew])

        # replace old
        self._state = stateNew
Beispiel #8
0
    def next(self):
        '''Apply all rules and produce a new self._state

        >>> g = Grammar()
        >>> g.load('a{3}b{4} @ a{bab}b{aab} @ abaa')
        >>> str(g)
        'a{3}b{4}@a{bab}b{aab}@abaa'
        >>> g.next()
        >>> g.getState()
        'babaabbabbab'
        >>> g.next()
        >>> g.getState()
        'aabbabaabbabbabaabaabbabaabaabbabaab'
        >>> g.getState(values=True)
        [3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0, 3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0, 3.0, 3.0, 4.0, 4.0, 3.0, 4.0, 3.0, 3.0, 4.0]

        >>> g = Grammar()
        >>> g.load('a{3}b{4}c{20}d{2} @ a{bab}b{acb}c{ac}d{cd} @ abd')
        >>> str(g)
        'a{3}b{4}c{20}d{2}@a{bab}c{ac}b{acb}d{cd}@abd'
        >>> g.next()
        >>> g.getState() 
        'babacbcd'
        >>> g.next()
        >>> g.getState() 
        'acbbabacbbabacacbaccd'


        >>> g = Grammar()
        >>> g.load('a{a}b{b} @ a{ab}b{a} @ b')
        >>> g.getState()
        'b'
        >>> g.next()
        >>> g.getState()
        'a'
        >>> g.next()
        >>> g.getState()
        'ab'
        >>> g.next()
        >>> g.getState()
        'aba'
        >>> g.next()
        >>> g.getState()
        'abaab'
        >>> g.next()
        >>> g.getState()
        'abaababa'

        '''
        if self._state == None or self._state == '':
            self._state = self._axiom # a copy in principle

        stateNew = self._state # copy
        matchTag = [] # matched start indices
        replacementCount = 0

        # make groups of index values, src groups to match
        # need to find largest rule in size
        indexCharPairs = []
        # self._maxRuleOutputSize

        #environment.printDebug(['next(): self._state', self._state])

        for size in range(1, self._maxRuleOutputSize+1):
        #for size in range(1, 2):
            for i in range(0, len(self._state), size):      
                pair = (i, self._state[i:i+size])
                if pair not in indexCharPairs:
                    indexCharPairs.append(pair) 

        for inRule, outRule in self._rules.items():

            environment.printDebug(['next(): in/out rule', repr(inRule), outRule])
            # grammar.py: next(): in/out rule '*' [('ab',1)] 

            #environment.printDebug(['next(): index char pairs', indexCharPairs])

            # char here may be 1 or more characters, up to max rule size
            for i, char in indexCharPairs:
            #for i, char in enumerate(self._state):

                # comparison to rule
                match = False
                # test single character, exact match
                if inRule == self.EXPRESSALL or inRule == char: 
                    match = True
                # if mutliple characters, and one is expressall, and lenght
                # is the same
                elif (len(inRule) > 1 and len(inRule) == len(char) 
                and self.EXPRESSALL in inRule):
                    matchChar = 0
                    for j in range(len(inRule)):
                        if inRule[j] == char[j] or inRule[j] == self.EXPRESSALL:
                            matchChar += 1
                    if matchChar == len(inRule):
                        match = True

                if not match:
                    continue

                # need to find cases of two or more char matches

                # store a string of index in the temp to mark positions
                # can find first instance of symbol; will not 
                # be past symbols b/c we are replacing with the old index nums
                iNew = stateNew.find(char)
                pre = stateNew[:iNew]
                # skip location
                post = stateNew[iNew+len(char):] 
                # insert marker as a random cod
                tag = self._tagIn(replacementCount)
                replacementCount += 1
                stateNew = pre + tag + post

                #environment.printDebug(['next(): stateNew', stateNew, repr(pre), repr(tag), repr(post)])
                # make a rule section

                # if only one rule, simply provide it 
                if len(outRule) == 1:
                    # a list of value, weight pairSymbol
                    replacement = outRule[0][0] 
                # if more than one rule, do a weighted selection
                else:
                    options = []
                    weights = []
                    for o, w in outRule:
                        options.append(o)
                        weights.append(w)
                    # create unit boundaries from ordered weights
                    boundary = unit.unitBoundaryProportion(weights)
                    i = unit.unitBoundaryPos(random.random(), boundary)
                    replacement = options[i] # index is in position

                # a lost of all replacements to make, between the tag and the
                # replacement
                matchTag.append([tag, replacement])

        # do all replacements
        #environment.printDebug(['stateNew: prereplace', stateNew])
        for tag, replacement in matchTag:
            # these are not actual indices but tags to points in the scratch
            iNew = stateNew.find(tag)
            pre = stateNew[:iNew]
            # skip location
            post = stateNew[iNew+len(tag):]
            # insert final value
            stateNew = pre + replacement + post

        #environment.printDebug(['stateNew: post', stateNew])

        # replace old
        self._state = stateNew