def _loadMinMax(self, min, max): ''' >>> a = Parameter([]) >>> post = a._loadMinMax(45, 34) >>> post[0].type, post[1].type ('constant', 'constant') >>> post = a._loadMinMax(45, ['ru', 0, 1]) >>> post[0].type, post[1].type ('constant', 'randomUniform') >>> post = a._loadMinMax(['ru', 0, 1], ['ru', 0, 1]) >>> post[0].type, post[1].type ('randomUniform', 'randomUniform') ''' if drawer.isNum(min): minArgs = ('c', min) elif drawer.isList(min): minArgs = min # check max if drawer.isNum(max): maxArgs = ('c', max) elif drawer.isList(max): maxArgs = max # create a parameter object from athenaCL.libATH.libPmtr import parameter try: minObj = parameter.factory(minArgs) except error.ParameterObjectSyntaxError, msg: raise error.ParameterObjectSyntaxError, 'failed sub-parameter: %s' % msg
def _formatMsg(self, msg): if not drawer.isList(msg): msg = [msg] post = [] post.append('%s:' % self.modName) for part in msg: partMsg = str(part) if drawer.isList(part): partMsg = partMsg.replace(' ', '') post.append(partMsg) post.append('\n') return ' '.join(post)
def factory(rawArgs, libName=None, refDict=None): """this is used only for loading and returning an object can return obj or parsed args first thing in list must be a string, type def libName can be a list or a string rawArgs is a list of python data types, starting with the po name exceptions that may be raised: error.ParameterObjectSyntaxError """ reload(basePmtr) # reload base class if not drawer.isList(rawArgs): rawArgs = eval(drawer.restringulator(rawArgs)) # if only string, we have only one argument, no commas if drawer.isStr(rawArgs): rawArgs = [rawArgs] # old method simply put rawArgs, if a string, as a first argument # rawArgs = [rawArgs,] # add to a list, could be a single str # first arg is always a string, naming the parameter type # obj args could be empty if requires no arguments objType, objArgs = rawArgs[0], list(rawArgs[1:]) libOpt = [] # option libs if not drawer.isList(libName): libOpt.append(libName) else: libOpt = libName for i in range(0, len(libOpt)): name = libOpt[i] if name != None: # None is all name = pmtrLibParser(name) # name of possible library try: # will raise exception on error mod, modStr = locator(objType, name) #check type string except error.ParameterObjectSyntaxError as e: modStr = None if modStr == None: if i != len(libOpt) - 1: continue # if not the last one to try else: raise error.ParameterObjectSyntaxError( 'parameter lib error (%s: %s, %s, %s)' % (name, objType, modStr, rawArgs)) else: # got a good object break # failure pmtrObjAttr = getattr(mod, modStr) #print _MOD, 'factory loading object', mod, objType pmtrObj = pmtrObjAttr(objArgs, refDict) return pmtrObj
def factory(rawArgs, libName=None, refDict=None): """this is used only for loading and returning an object can return obj or parsed args first thing in list must be a string, type def libName can be a list or a string rawArgs is a list of python data types, starting with the po name exceptions that may be raised: error.ParameterObjectSyntaxError """ reload(basePmtr) # reload base class if not drawer.isList(rawArgs): rawArgs = eval(drawer.restringulator(rawArgs)) # if only string, we have only one argument, no commas if drawer.isStr(rawArgs): rawArgs = [rawArgs] # old method simply put rawArgs, if a string, as a first argument # rawArgs = [rawArgs,] # add to a list, could be a single str # first arg is always a string, naming the parameter type # obj args could be empty if requires no arguments objType, objArgs = rawArgs[0], list(rawArgs[1:]) libOpt = [] # option libs if not drawer.isList(libName): libOpt.append(libName) else: libOpt = libName for i in range(0, len(libOpt)): name = libOpt[i] if name != None: # None is all name = pmtrLibParser(name) # name of possible library try: # will raise exception on error mod, modStr = locator(objType, name) #check type string except error.ParameterObjectSyntaxError, e: modStr = None if modStr == None: if i != len(libOpt) - 1: continue # if not the last one to try else: raise error.ParameterObjectSyntaxError, 'parameter lib error (%s: %s, %s, %s)' % (name, objType, modStr, rawArgs) else: # got a good object break # failure pmtrObjAttr = getattr(mod, modStr) #print _MOD, 'factory loading object', mod, objType pmtrObj = pmtrObjAttr(objArgs, refDict) return pmtrObj
def getAllScTriples(cardRange='all', tniTog=0): """gets all scTriples within a variety of ranges card range can be specified as string 'all', as an int (getting just the values of that int or as a range from 1 to 12; if range, last values is inclusif""" if cardRange == 'all': gatherCards = list(range(1, 13)) elif drawer.isInt(cardRange): gatherCards = [ cardRange, ] # only get one card elif drawer.isList(cardRange): if cardRange[1] < cardRange[0]: raise ValueError('bad cardinality range given') elif cardRange[0] == cardRange[1]: gatherCards = [ cardRange[0], ] # only get one card else: gatherCards = list(range(cardRange[0], cardRange[1] + 1)) found = [] for scTriple in list(TNREF.keys()): card = scTriple[0] inv = scTriple[2] if card in gatherCards: if tniTog and inv == -1: pass # leave out inversions else: found.append(scTriple) found.sort() return found
def _guessType(self): """try to determine what kind of duration/dynamic data is given can be string or integer tuple/list: (2,1,1) or (3,1) can be string char like q, e, t, s, th? can be string acc list .5 1 .3 1 """ data = copy.copy(self.srcData) if drawer.isStr(data): data = data.strip() # temp data data = data.lower() if len(data) == 0: return None # no data found if data[0].islower(): # if has chars if data in REFdurStr.keys(): return 'str' elif data in REFdynStr.keys(): # maybe its a dynmaic return 'acc' # acc string value alone else: raise error.PulseSyntaxError elif data[0] == '[' or data[0] == '(': # its a list or tuple return 'triple' elif data.find(',') >= 0: # if there are commas in string return 'triple' else: # assume its an acc string return 'acc' if drawer.isNum(data): # acc list return 'acc' if drawer.isList(data): return 'triple'
def __init__(self, args, refDict): """searches a list of directories recursively and finds all files files named in args are found within these directories dirs are onlys serached if list of dirs has changed""" basePmtr.Parameter.__init__(self, args, refDict) # call base init self.type = None # in subclass self.outputFmt = 'str' # declare outputFmt as string self.argTypes = [['list', 'str'], 'str'] self.argNames = ['fileNameList', 'selectionString'] self.argDefaults = [[], 'rc'] # check raw arguments for number, type ok, msg = self._checkRawArgs() if ok == 0: raise error.ParameterObjectSyntaxError(msg) # report error self.dirList = [] # used to look for changes self.filePathList = [] # updated on __call__ self.timer = rhythm.Timer() # sets start time self.updatePathList = 1 # forces update of paths # not sure this is functioning #self.tLastUpdate = 0.0 # time of last file dir update if drawer.isList(self.args[0]): self.nameList = self.args[0] elif drawer.isStr(self.args[0]): tempList = [] tempList.append(self.args[0]) self.nameList = tuple(tempList) self.control = self._selectorParser(self.args[1]) # raises exception # choose names from name list self.selector = basePmtr.Selector(self.nameList, self.control)
def _getProductionCount(self, span): '''Given a number representing range to threshold, provide the number of particles produced. >>> pcr = {(-10,-1):8, (0,10):1, (11, 20):2, None: [3, 5]} >>> pairs = [('a', 1), ('b', 2)] >>> a = SensorProducer() >>> a.setThreshold(30) >>> a.setParticle(pairs, 'b') >>> a.setProductionCountRange(pcr) >>> a._getProductionCount(3) 1 >>> a._getProductionCount(12) 2 >>> a._getProductionCount(34) in [3,4,5] True >>> a._getProductionCount(-4) 8 ''' countRaw = None for key in self.productionCountRange.keys(): # a None key provides a default value range if key == None: continue # key is inclusive min max: if span >= key[0] and span <= key[1]: countRaw = self.productionCountRange[key] # if no match, get None, for all spans out of defined ranges if countRaw == None: countRaw = self.productionCountRange[None] if not drawer.isList(countRaw): # create an inclusive range countRaw = [countRaw, countRaw] count = random.choice(range(countRaw[0], countRaw[1] + 1)) return count
def __init__(self, lifeCycle): """A model of a multi-state particle that is defined by an ordered series of states, and a number of frames at that state. `lifeCycle` is a list of pairs; each pair gives a state (as a string letter) followed by a number of frames at which that state exists after all states have passed, the particle is dead. >>> pairs = [('a', 30), ('b',30)] >>> a = Particle(pairs) >>> a.lifeSpan 60 >>> a.lifeBounds {'a': (1, 30), 'b': (31, 60)} >>> pairs = [('a', 10)] >>> a = Particle(pairs) >>> a.lifeSpan 10 >>> a.lifeBounds {'a': (1, 10)} """ if not drawer.isList(lifeCycle): raise error.ParticleSyntaxError('life cycle must be a list') self.lifeCycle = lifeCycle self.lifeBounds = {} self.lifeSpan = 0 # number of frames in life self._updateLifeSpan() # update lifeSpan and lifeBounds self.age = 0 # number of cycles passed self.state = self.lifeCycle[0][0] # get first state
def _findWeights(self, srcSeq): """given a src sequence, find a weight label that matches if not match is available, then return None (will result in and qual distribution when srubbed)""" # for expression compat, need a method here to search weights # and determine of there is a direct match, or an expression match if self._weightSrc.has_key(srcSeq): # direct match return self._weightSrc[srcSeq] # if no key defined, search for matching expressions srcLen = len(srcSeq) for label in self._weightSrc.keys(): if len(label) != srcLen: continue # a def for a different order matchCount = 0 for i in range(srcLen): # if both are symbol strings, will match if label[i] == srcSeq[i]: matchCount = matchCount + 1 elif drawer.isList(label[i]): # its an expression if label[i][0] == self.EXPRESSALL: # match anything matchCount = matchCount + 1 elif label[i][0] == self.EXPRESSNOT: if label[i][1] != srcSeq[i]: # not supplied operand matchCount = matchCount + 1 elif label[i][0] == self.EXPRESSOR: if srcSeq[i] in label[i][1:]: # match any operands matchCount = matchCount + 1 if matchCount == srcLen: environment.printDebug(['exp match; label:', label, 'src:', srcSeq]) return self._weightSrc[label] # return None if nothing found return None
def getAllScTriples(cardRange='all', tniTog=0): """gets all scTriples within a variety of ranges card range can be specified as string 'all', as an int (getting just the values of that int or as a range from 1 to 12; if range, last values is inclusif""" if cardRange == 'all': gatherCards = range(1,13) elif drawer.isInt(cardRange): gatherCards = [cardRange,] # only get one card elif drawer.isList(cardRange): if cardRange[1] < cardRange[0]: raise ValueError, 'bad cardinality range given' elif cardRange[0] == cardRange[1]: gatherCards = [cardRange[0],] # only get one card else: gatherCards = range(cardRange[0], cardRange[1]+1) found = [] for scTriple in TNREF.keys(): card = scTriple[0] inv = scTriple[2] if card in gatherCards: if tniTog and inv == -1: pass # leave out inversions else: found.append(scTriple) found.sort() return found
def _getProductionCount(self, span): '''Given a number representing range to threshold, provide the number of particles produced. >>> pcr = {(-10,-1):8, (0,10):1, (11, 20):2, None: [3, 5]} >>> pairs = [('a', 1), ('b', 2)] >>> a = SensorProducer() >>> a.setThreshold(30) >>> a.setParticle(pairs, 'b') >>> a.setProductionCountRange(pcr) >>> a._getProductionCount(3) 1 >>> a._getProductionCount(12) 2 >>> a._getProductionCount(34) in [3,4,5] True >>> a._getProductionCount(-4) 8 ''' countRaw = None for key in self.productionCountRange.keys(): # a None key provides a default value range if key == None: continue # key is inclusive min max: if span >= key[0] and span <= key[1]: countRaw = self.productionCountRange[key] # if no match, get None, for all spans out of defined ranges if countRaw == None: countRaw = self.productionCountRange[None] if not drawer.isList(countRaw): # create an inclusive range countRaw = [countRaw, countRaw] count = random.choice(range(countRaw[0], countRaw[1]+1)) return count
def _findWeights(self, srcSeq): """given a src sequence, find a weight label that matches if not match is available, then return None (will result in and qual distribution when srubbed)""" # for expression compat, need a method here to search weights # and determine of there is a direct match, or an expression match if srcSeq in self._weightSrc: # direct match return self._weightSrc[srcSeq] # if no key defined, search for matching expressions srcLen = len(srcSeq) for label in list(self._weightSrc.keys()): if len(label) != srcLen: continue # a def for a different order matchCount = 0 for i in range(srcLen): # if both are symbol strings, will match if label[i] == srcSeq[i]: matchCount = matchCount + 1 elif drawer.isList(label[i]): # its an expression if label[i][0] == self.EXPRESSALL: # match anything matchCount = matchCount + 1 elif label[i][0] == self.EXPRESSNOT: if label[i][1] != srcSeq[i]: # not supplied operand matchCount = matchCount + 1 elif label[i][0] == self.EXPRESSOR: if srcSeq[i] in label[i][1:]: # match any operands matchCount = matchCount + 1 if matchCount == srcLen: environment.printDebug(['exp match; label:', label, 'src:', srcSeq]) return self._weightSrc[label] # return None if nothing found return None
def printDebug(self, msg, *arguments): if self.debug <= 0: return # do nothing else: if not drawer.isList(msg): msg = [msg] if len(arguments) > 0: msg += arguments sys.stderr.write(self._formatMsg(msg))
def iMod(self, axis=0): """axis transposition, but retaining octave positon like tMod """ # find desired index if drawer.isNum(axis): index = _InvAxisToIndex(axis) if drawer.isList(axis): index = _InvPcPairToIndex(axis[0], axis[1]) self._real = pcoInverter(self._real, index) self.data = self._convert(self.format, 'psReal', self._real)
def clear(self): """processes init value and replaces history with first generation""" stepInit = self._getTemplate() if drawer.isNum(self.init): for y in range(self.size[1]): for x in range(self.size[0]): self.stepTemplate[y][x] = self.init elif drawer.isList(self.init): # assume list is same size from for row in self.init: for col in row: self.stepTemplate[y][x] = col self.stepHistory = [stepInit] # a list of arrays
def _recursiveUpdate(self, argSrc): # args are already evaluated data and strings # argSrc must at a lost of values insertFix = self._waveReplace(argSrc) # returns a list # check for embedded for i in range(len(insertFix)): arg = insertFix[i] # look for an arg that is a list if drawer.isList(arg) and len(arg) > 0: argPost = self._recursiveUpdate(arg) # returns a tuple insertFix[i] = argPost # assign over old postiion return insertFix
def repr(self, format=''): # why not use baesParameter representation methods here? msg = [] for name in self.argNames: if drawer.isList(self.switch(name)): msg.append('%s' % self._scrubList(self.switch(name))) else: msg.append('%s' % typeset.anyDataToStr(self.switch(name))) if format in ['argsOnly', '']: msg = [self.type,] + msg return ', '.join(msg) elif format in ['noType']: return ', '.join(msg)
def clear(self): """processes init value and replaces history with first generation will always add an init to the history, meaning that there will always be one more generation than expected in most cases """ stepInit = self._getTemplate() if drawer.isStr(self.init): numStr, junk = drawer.strExtractNum(self.init) if self.init == 'center': centerIndex = self._getCenter() if self.dstValues == None: # continuous case if self.DECIMAL: val = decimal.Decimal(1) else: val = 1.0 # should add one here, but need -1 for list position shift stepInit[self._getCenter()] = val else: # center value is dependent; must provude as variable stepInit[self._getCenter()] = self.dstValues[ self.dstIndexCenter] elif self.init == 'random': for x in range(self.size): if self.dstValues == None: # continuous case if self.DECIMAL: val = decimal.Decimal(str(random.random())) else: val = random.random() stepInit[x] = val else: # discrete stepInit[x] = random.choice(self.dstValues) # may be number as a string; treat as a list elif len(numStr) == len(self.init): for x in range(self.size): # must be integers, use force to limit at min / max if self.dstValues != None: min = self.dstValues[0] max = self.dstValues[-1] else: # continuous, unit interval min = 0 max = 1 val = drawer.strToNum(self.init[(x % len(self.init))], 'int', min, max, 1) stepInit[x] = val elif drawer.isNum(self.init): for x in range(self.size): stepInit[x] = self.init elif drawer.isList(self.init): for x in range(self.size): stepInit[x] = self.init[(x % len(self.init))] self.stepHistory = [stepInit] # a list of arrays
def __init__(self, args, refDict): """ >>> a = StaticParameterTexture([], {}) """ # note: look for first arg as type and remove if not drawer.isList(args): # single tuple not evaluated as list args = [args,] # add to list if args != []: # if not empty if args[0] == self.type: args = args[1:] Parameter.__init__(self, args, refDict) # call base init self.argCountOffset = 0 # dif b/n kept and shown args self.parent = 'textureStatic' # mark as a special type self.outputFmt = None # output values from dictionary self._switches = {} # dictionary that stores switch valuess
def _scrubEntryLines(entryLines): """run over entry lines and make sure each sub list is a list and not a tuple; return None if empty""" entryLines = list(entryLines) # make sure its alist i = 0 empty = 0 for line in entryLines: if drawer.isList(line): entryLines[i] = list(line) if len(entryLines[i]) == 0: empty = empty + 1 # maybe do other conversions here too i = i + 1 if empty == i: # if all lines are empty return None return entryLines
def clear(self): """processes init value and replaces history with first generation will always add an init to the history, meaning that there will always be one more generation than expected in most cases """ stepInit = self._getTemplate() if drawer.isStr(self.init): numStr, junk = drawer.strExtractNum(self.init) if self.init == 'center': centerIndex = self._getCenter() if self.dstValues == None: # continuous case if self.DECIMAL: val = decimal.Decimal(1) else: val = 1.0 # should add one here, but need -1 for list position shift stepInit[self._getCenter()] = val else: # center value is dependent; must provude as variable stepInit[self._getCenter()] = self.dstValues[self.dstIndexCenter] elif self.init == 'random': for x in range(self.size): if self.dstValues == None: # continuous case if self.DECIMAL: val = decimal.Decimal(str(random.random())) else: val = random.random() stepInit[x] = val else: # discrete stepInit[x] = random.choice(self.dstValues) # may be number as a string; treat as a list elif len(numStr) == len(self.init): for x in range(self.size): # must be integers, use force to limit at min / max if self.dstValues != None: min = self.dstValues[0] max = self.dstValues[-1] else: # continuous, unit interval min = 0 max = 1 val = drawer.strToNum(self.init[(x % len(self.init))], 'int', min, max, 1) stepInit[x] = val elif drawer.isNum(self.init): for x in range(self.size): stepInit[x] = self.init elif drawer.isList(self.init): for x in range(self.size): stepInit[x] = self.init[(x % len(self.init))] self.stepHistory = [stepInit] # a list of arrays
def caInitParser(usrStr): """ >>> caInitParser('center') 'center' >>> caInitParser('junk') == None True """ usrNum, junk = drawer.strExtractNum(usrStr) if drawer.isNum(usrStr) or (len(usrNum) == len(usrStr) or drawer.isList(usrStr)): return usrStr # not a string, a data obj # only parse if a string ref = { 'center': ['c', 'center'], 'random': ['r', 'random'], } usrStr = drawer.selectionParse(usrStr, ref) return usrStr # may be Non
def caInitParser(usrStr): """ >>> caInitParser('center') 'center' >>> caInitParser('junk') == None True """ usrNum, junk = drawer.strExtractNum(usrStr) if drawer.isNum(usrStr) or (len(usrNum) == len(usrStr) or drawer.isList(usrStr)): return usrStr # not a string, a data obj # only parse if a string ref = { 'center' : ['c', 'center'], 'random' : ['r', 'random'], } usrStr = drawer.selectionParse(usrStr, ref) return usrStr # may be Non
def pyToXml(parentName, name, dict, indent=1, levelManifest=[]): """convert nested python dictionary into an xml data structure indent is current indent level dictionaries found at node, that consist of all str keys, will be recursed levelManifest is a list of labels for each dictionary level None will use the dictionary name as is pairs match TagName, DisplayName""" if levelManifest == [] or levelManifest[0] == None: levelMatch = {} else: if not drawer.isList(levelManifest[0]): # match all levelMatch = {'all':levelManifest[0]} # match all parents #levelName = levelManifest[0] else: levelMatch = {} # embeded pairs of possible matches for i in range(0, len(levelManifest[0]) - 1): # stores pairs in dictionary levelMatch[levelManifest[0][i]] = levelManifest[0][i+1] #print _MOD, parentName, name, levelMatch # if a level match is given, only name for that object msg = [] tab = '\t' * indent msg.append(_resolveOuterName('open', tab, levelMatch, parentName, name)) keyList = dict.keys() keyList.sort() for key in keyList: tab = '\t' * (indent + 1) val = dict[key] # only recurse into dictionary if dict keys are strings if _dictionaryStrKey(val): # remove this levelName form the list # enter name as parent name msg = msg + pyToXml(name, key, val, indent+1, levelManifest[1:]) else: valStr = xmlScrub(str(val)) msg.append('\n%s<attr key="%s" value="%s"/>' % (tab, key, valStr)) tab = '\t' * indent msg.append(_resolveOuterName('close', tab, levelMatch, parentName, name)) return msg # do not join
def _reprWeightLabelKey(self, raw): """provide a string representation of a weight label expressionis may be used and must be handled separately""" msg = [] for element in raw: if drawer.isList(element): # its an expression if element[0] == self.EXPRESSOR: elementStr = self.EXPRESSOR.join(element[1:]) elif element[0] == self.EXPRESSNOT: elementStr = '%s%s' % (self.EXPRESSNOT, element[1]) else: # must be self.EXPRESSALL elementStr = self.EXPRESSALL msg.append(elementStr) else: msg.append(element) # join w/ step symbol msg = self.STEP.join(msg) # always add one at end return '%s%s' % (msg, self.STEP)
def _keyParser(self, usrStr): if drawer.isNum(usrStr) or drawer.isList(usrStr): return usrStr # not a string, a data obj # only parse if a string # may need to add: 'd' for dimension # 'z' for z axis? ref = { 'f': ['f', 'format', 'form', 'type'], 'k': ['k', 'colors'], 'r': ['r', 'radius'], 'i': ['i', 'init', 'initial'], 'x': ['x', 'size'], 'y': ['y', 'steps', 'gen'], 'w': ['w', 'width'], 'c': ['c', 'center'], 's': ['s', 'skip'], } usrStr = drawer.selectionParse(usrStr, ref) return usrStr # may be None
def _keyParser(self, usrStr): if drawer.isNum(usrStr) or drawer.isList(usrStr): return usrStr # not a string, a data obj # only parse if a string # may need to add: 'd' for dimension # 'z' for z axis? ref = { 'f' : ['f', 'format', 'form', 'type'], 'k' : ['k', 'colors'], 'r' : ['r', 'radius'], 'i' : ['i', 'init', 'initial'], 'x' : ['x', 'size'], 'y' : ['y', 'steps', 'gen'], 'w' : ['w', 'width'], 'c' : ['c', 'center'], 's' : ['s', 'skip'], } usrStr = drawer.selectionParse(usrStr, ref) return usrStr # may be None
def __init__(self, argStr, stripComma=False): """Note: `argStr` can be either a string or a list of pre-partitioned objects. >>> a = ArgOps('test 1 2 3') >>> a.get(2) '2' >>> a.get(2, evaluate=True) 2 >>> b = ArgOps(['test', 1, 2, 3]) >>> b.get(2) 2 >>> b.get(2, evaluate=True) 2 >>> b.get(1, sumRange=True) # will realize values as strings '123' >>> b = ArgOps('test, stip, comma', stripComma=True) >>> b.get(0) 'test' >>> b = ArgOps('test, stip, comma', stripComma=False) >>> b.get(0) 'test,' """ if drawer.isList(argStr): # accept already partitioned lists self.argList = argStr else: argStr = argStr.strip() # clear trailing white space self.argList = argStr.split() # will split b/n or more spaces # strip trailing comma #if stripComma != 'noStrip': if stripComma: counter = 0 for entry in self.argList: # only remove comma of last line if len(entry) > 1 and entry[-1] == ',': self.argList[counter] = entry[:-1] counter += 1
def anyDataToStr(usrData, sigDig=None, seqBrace='tuple'): """convert any data to a proper string, taking type into account lists are recursive examined with the same function note: this will convert a list [] into a tuple representation depending on optional arg will automatically remove space between comma-separated lists >>> anyDataToStr('test') 'test' >>> anyDataToStr([3, 'mixed', [3,4,5]]) '(3,mixed,(3,4,5))' >>> anyDataToStr([2.35, ('a', (234, 34))]) '(2.35,(a,(234,34)))' """ if drawer.isStr(usrData): return usrData elif drawer.isInt(usrData): return '%i' % usrData elif drawer.isFloat(usrData): if sigDig != None: # force a certain length return '%s' % str(round(usrData, sigDig)) else: # adaptive by size: sigDig = sigDigMeasure(usrData) return '%s' % str(round(usrData, sigDig)) elif drawer.isBool(usrData): # does not work, evaluates as string? return boolAsStr(usrData) elif usrData == None: return 'none' elif drawer.isList(usrData): newData = [] for q in usrData: # recursively apply to each element in list newData.append(anyDataToStr(q, sigDig, seqBrace)) if seqBrace == 'tuple': return '(%s)' % ','.join(newData) elif seqBrace == 'list': return '[%s]' % ','.join(newData) else: return repr(usrData)
def _loadPulse(self): objList = [] if drawer.isStr(self.srcData): # if whole argument is a string; not yet implemented # this is not going to work, cannot devide a compelete string w/ , strList = self.srcData.split(',') # split for element in strList: obj = Pulse(element) # will raise exception on load error objList.append(obj) elif drawer.isNum(self.srcData): obj = Pulse(self.srcData) # will raise exception on load error objList.append(obj) elif drawer.isList(self.srcData): if self._tripleMonadTest(self.srcData): # a single triple obj = Pulse(self.srcData) objList.append(obj) else: # get individual chunks; a pulse list for element in self.srcData: obj = Pulse(element) # will raise exception on load error objList.append(obj) else: raise error.PulseSyntaxError return objList
def _expandRawTriple(self, data): """take an int, 2, or three element tuple and provide defaults returns None if nothing expandable if third element in list exists and is a string will be converted does checks on div and mult, divide by zero error and all raise exception """ defD = 1 # default values defM = 1 defA = 1 if drawer.isNum(data): # assum its an acc return (defD, defM, self. _normAcc(data)) elif drawer.isStr(data): # assum its an acc as string return (defD, defM, self. _normAcc(self._dynStrToVal(data))) elif drawer.isList(data): data = list(data) # convert to list for assignment if len(data) == 0: return None elif len(data) == 1: # its an acc return (defD, defM, self. _normAcc(data)) elif len(data) == 2: try: data[0], data[1] = self._normDivMult(data[0], data[1]) except error.PulseSyntaxError: return None # error return (data[0], data[1], defA) else: # other info in a list will be removed try: data[0], data[1] = self._normDivMult(data[0], data[1]) except error.PulseSyntaxError: return None # error if drawer.isStr(data[2]): acc = self._dynStrToVal(data[2]) else: # its a number acc = data[2] return (data[0], data[1], self. _normAcc(acc)) else: return None # error
def _expandRawTriple(self, data): """take an int, 2, or three element tuple and provide defaults returns None if nothing expandable if third element in list exists and is a string will be converted does checks on div and mult, divide by zero error and all raise exception """ defD = 1 # default values defM = 1 defA = 1 if drawer.isNum(data): # assum its an acc return (defD, defM, self._normAcc(data)) elif drawer.isStr(data): # assum its an acc as string return (defD, defM, self._normAcc(self._dynStrToVal(data))) elif drawer.isList(data): data = list(data) # convert to list for assignment if len(data) == 0: return None elif len(data) == 1: # its an acc return (defD, defM, self._normAcc(data)) elif len(data) == 2: try: data[0], data[1] = self._normDivMult(data[0], data[1]) except error.PulseSyntaxError: return None # error return (data[0], data[1], defA) else: # other info in a list will be removed try: data[0], data[1] = self._normDivMult(data[0], data[1]) except error.PulseSyntaxError: return None # error if drawer.isStr(data[2]): acc = self._dynStrToVal(data[2]) else: # its a number acc = data[2] return (data[0], data[1], self._normAcc(acc)) else: return None # error
def strongType(usrArgs, argTypes, defaultArgs=[], argCountOffset=0): """Argument checking tool. checks raw arg type and number, one level deep (does not recurse into list) will supply defaults if missing args after last given and self.defaultArgs defined two arguments required, both lists: args = a list of arguments, of proper python data types argTypes = list of one-level deap types, specified w/ strings 'list', 'num', 'float', 'int', 'str'; see drawer.py one optional args defaultArgs = list of default args to substitute returns: newArgs, ok, msg >>> strongType([[1,2,3]], ['list']) ([[1, 2, 3]], 1, '') >>> strongType([.5, 3, 'three'], ['float', 'int', 'str']) ([0.5, 3, 'three'], 1, '') >>> strongType([3.2], ['num', 'num']) ([3.2000...], 0, 'incorrect number of arguments; enter 2 arguments.') >>> strongType([3.2, 5, 6], ['num', 'num']) ([3.2000..., 5, 6], 0, 'too many arguments; enter 2 arguments.') """ argCount = len(argTypes) if len(usrArgs) < argCount: # try to get from defaults if len(defaultArgs) == argCount: # defaults exits (default is 0) for retrieve in defaultArgs[len(usrArgs):]: usrArgs.append(retrieve) # add missing to end #print 'argTools.py: adding default', retrieve, defaultArgs else: # nothing we can do: failure msg = ('incorrect number of arguments; enter %i arguments.' % (argCount + argCountOffset)) # add incase if name offset return usrArgs, 0, msg elif len(usrArgs) > argCount: #print _MOD, len(usrArgs), argCount msg = 'too many arguments; enter %i arguments.' % (argCount + argCountOffset) return usrArgs, 0, msg for pos in range(0, argCount): argTest = usrArgs[pos] # can be [list, num, float, int, str] typeCandidates = argTypes[pos] if not drawer.isList(typeCandidates): typeCandidates = [ typeCandidates, ] # add to list for type in typeCandidates: if type == 'list' and drawer.isList(argTest): match = 1 break elif type == 'num' and drawer.isNum(argTest): match = 1 break elif type == 'float' and drawer.isFloat(argTest): match = 1 break elif type == 'int' and drawer.isInt(argTest): match = 1 break elif type == 'str' and drawer.isStr(argTest): match = 1 break else: # dont break; need to through other possbilities match = 0 # should covnert types to better strings if match == 0: msg = ( 'wrong type of data used as an argument. replace %s with a %s argument type.' % ( repr(typeset.anyDataToStr(argTest)), # provide 'or' to show that any type in candidate is good drawer.typeListAsStr(typeCandidates, 'or'))) return usrArgs, 0, msg # all good return usrArgs, 1, ''
def findNormalT(pcSet, setMatrix=None): """finds normal form of any pc set and returns forte number as a scTriple data structure, and transposition from normal form pcSet may contain psReals, and as such, need to be converted to ints >>> findNormalT([3,4,5]) ((3, 1, 0), 3) """ if setMatrix == None: # use forte as default setMatrix = FORTE MONADscTuple = (1,1,0) # check for bad data if drawer.isStr(pcSet): return None # error, no strings supported here if drawer.isList(pcSet): for psReal in pcSet:# make sure all values are numbers; no strings allowed if drawer.isStr(psReal): return None # break, return None as error # check for unusual data if drawer.isNum(pcSet): # its a single number pcVal = pitchTools.roundMicro(pcSet) # second number is transposition from 0 return MONADscTuple, (pcVal % 12) if len(pcSet) == 1: #filter out monad! pcVal = pitchTools.roundMicro(pcSet[0]) return MONADscTuple, (pcVal % 12) # scrub and go pcSetClone = [] for psReal in pcSet: # pcSet may contian psReal, w/ floating values pcSetClone.append(pitchTools.roundMicro(psReal)) #check fr non base 12 numbers, negative numbers, redundancies pcSetClone = list(pcSetTransposer(pcSetClone, 0)) pcSetClone.sort() i = 0 chord = [] for i in range(0,12): # remove redundancies if i in pcSetClone: chord.append(i) card = len(chord) if card < 1: # monad has already been filtered out return None # 2nd no is transposition from 0 if card == 1: # this is a set like (3,3,3,3) return MONADscTuple, (pcSet[0] % 12) elif card > 12: return None # 'irrational cardinality error' rotIndices = range(0, card) foundIndex = None #control variable for rot in rotIndices: r = rot # dont need to add 1? + 1 rotSet = chord[r:card] + chord[0:r] dif = rotSet[0] pSet = pcSetTransposer(rotSet, -dif) iSet = tuple(pcInverter(pSet)) maxRange = len(setMatrix[card]) # check all sets of given card for match for index in range(1, maxRange): # start with 1, not zero # this is a default; may be a symmetrical set and have no inversion foundInv = 'A' # test each set in this cardinality; "0" gets pitches testSet = tuple(setMatrix[card][index][0]) if iSet == testSet: foundIndex = index foundInv = 'B' #nt sure yet if 1 or 0 break elif pSet == testSet: foundIndex = index foundInv = 'A' #nt sure yet if 1 or 0 break if foundIndex != None: break if foundIndex == None: ## no set found return None #'failed!!!' if foundInv == 'B': # has inversion that is non-redundant (variant) if setMatrix[card][foundIndex][2][1] == 0 : scInv = -1 else: scInv = 0 elif foundInv == 'A': # has inversion that is non-redundant (variant) if setMatrix[card][foundIndex][2][1] == 0 : scInv = 1 else: scInv = 0 return (card, foundIndex, scInv), dif
def strongType(usrArgs, argTypes, defaultArgs=[], argCountOffset=0): """Argument checking tool. checks raw arg type and number, one level deep (does not recurse into list) will supply defaults if missing args after last given and self.defaultArgs defined two arguments required, both lists: args = a list of arguments, of proper python data types argTypes = list of one-level deap types, specified w/ strings 'list', 'num', 'float', 'int', 'str'; see drawer.py one optional args defaultArgs = list of default args to substitute returns: newArgs, ok, msg >>> strongType([[1,2,3]], ['list']) ([[1, 2, 3]], 1, '') >>> strongType([.5, 3, 'three'], ['float', 'int', 'str']) ([0.5, 3, 'three'], 1, '') >>> strongType([3.2], ['num', 'num']) ([3.2000...], 0, 'incorrect number of arguments; enter 2 arguments.') >>> strongType([3.2, 5, 6], ['num', 'num']) ([3.2000..., 5, 6], 0, 'too many arguments; enter 2 arguments.') """ argCount = len(argTypes) if len(usrArgs) < argCount: # try to get from defaults if len(defaultArgs) == argCount: # defaults exits (default is 0) for retrieve in defaultArgs[len(usrArgs):]: usrArgs.append(retrieve) # add missing to end #print 'argTools.py: adding default', retrieve, defaultArgs else: # nothing we can do: failure msg = ('incorrect number of arguments; enter %i arguments.' % (argCount + argCountOffset)) # add incase if name offset return usrArgs, 0, msg elif len(usrArgs) > argCount: #print _MOD, len(usrArgs), argCount msg = 'too many arguments; enter %i arguments.' % (argCount + argCountOffset) return usrArgs, 0, msg for pos in range(0, argCount): argTest = usrArgs[pos] # can be [list, num, float, int, str] typeCandidates = argTypes[pos] if not drawer.isList(typeCandidates): typeCandidates = [typeCandidates,] # add to list for type in typeCandidates: if type == 'list' and drawer.isList(argTest): match = 1 break elif type == 'num' and drawer.isNum(argTest): match = 1 break elif type == 'float' and drawer.isFloat(argTest): match = 1 break elif type == 'int' and drawer.isInt(argTest): match = 1 break elif type == 'str' and drawer.isStr(argTest): match = 1 break else: # dont break; need to through other possbilities match = 0 # should covnert types to better strings if match == 0: msg = ('wrong type of data used as an argument. replace %s with a %s argument type.' % (repr(typeset.anyDataToStr(argTest)), # provide 'or' to show that any type in candidate is good drawer.typeListAsStr(typeCandidates, 'or'))) return usrArgs, 0, msg # all good return usrArgs, 1, ''
def __init__(self, ao=None, barHEIGHT=10, winWIDTH=None, fmt='pil', master=None): # bar height is the height of texture in pixels. the total height of a # of a window is determined by the number of textures if ao == None: from athenaCL.libATH import athenaObj # update need for color prefs update = athenaObj.External() update.updateAll('noMessages') pcsPath = [(4,3,10),(1,5,4,3),(2,11,4),(7,5,3)] scPath = [(3,2,1),(4,14,0),(3,2,-1),(3,5,1)] mapDict = None activePath = 'testPath' else: update = ao.external # rename update from AO pathLib = ao.pathLib activePath = ao.activePath pcsPath = pathLib[activePath].get('pcsPath') scPath = pathLib[activePath].get('scPath') # gets a dict of (sourcePosition, destinationPosition) : map entries if pathLib[activePath].voiceType == 'none': mapDict = None else: mapDict = pathLib[activePath].voiceLib[ pathLib[activePath].activeVoice]['maps'] fontTitle = 'micro' fontText = 'micro' COLORfgMain = update.getPref('gui', 'COLORfgMain') COLORbgMargin = update.getPref('gui', 'COLORbgMargin') COLORbgGrid = update.getPref('gui', 'COLORbgGrid') COLORbgAbs = update.getPref('gui', 'COLORbgAbs') COLORfgAlt = update.getPref('gui', 'COLORfgAlt') COLORtxTitle = update.getPref('gui', 'COLORtxTitle') COLORtxLabel = update.getPref('gui', 'COLORtxLabel') COLORtxUnit = update.getPref('gui', 'COLORtxUnit') self.totalSets = len(pcsPath) self.vertEntries = 0 # max number of vertical cells for set in pcsPath: if len(set) >= self.vertEntries: self.vertEntries = len(set) # add ont vertical entry for the set-class key accross the top self.vertEntries = self.vertEntries + 1 self.noGutters = self.vertEntries + 1 self.mapGUTTER = 3 # in pixels, space between cells self.rMarginSize = 4 self.tMarginSize = 4 self.lMarginSize = 96 # same as imagePmtr; was 100 self.bMarginSize = 4 # half of imagePmtr # this calculate the height of the entire window self.winHEIGHT = (self.vertEntries * barHEIGHT) + (self.noGutters * self.mapGUTTER) + self.tMarginSize + self.bMarginSize if winWIDTH == None: self.winWIDTH = (self.lMarginSize + self.rMarginSize) + (66 * self.totalSets) elif winWIDTH < 200: self.winWIDTH = 200 elif winWIDTH > 3000: self.winWIDTH = 3000 else: self.winWIDTH = winWIDTH #600 # # get size of just the data region self.mapHEIGHT = self.winHEIGHT - (self.tMarginSize + self.bMarginSize) self.mapWIDTH = self.winWIDTH - (self.lMarginSize + self.rMarginSize) # map height includes all gutters; dont need to add belwo5 self.heightAllGutters = self.mapGUTTER * self.noGutters self.heightAllEntries = self.mapHEIGHT - self.heightAllGutters if self.vertEntries > 0: #round to nearest pix self.cellHeight = round(self.heightAllEntries/(self.vertEntries+0.0)) else: self.cellHeight = 0 self.cellWidth = round(self.mapWIDTH / (self.totalSets + 0.0)) self.cellEntryWidth = 18 # pixels for each pc entry # offset of lines above cell bottom self.vertCellOffset = round(self.cellHeight * .5) # create canvas self.c = imageTools.Canvas(fmt, self.winWIDTH, self.winHEIGHT, COLORbgAbs, 'PVview: %s' % activePath, master) # draw margin rectangles self.c.rectangle(0, 0, self.winWIDTH, self.tMarginSize, COLORbgMargin, None, 0) self.c.rectangle(0, 0, self.lMarginSize, self.winHEIGHT, COLORbgMargin, None, 0) self.c.rectangle(0, self.tMarginSize + self.mapHEIGHT, self.winWIDTH, self.winHEIGHT, COLORbgMargin, None, 0) self.c.rectangle(self.mapWIDTH + self.lMarginSize, 0, self.winWIDTH, self.winHEIGHT, COLORbgMargin, None, 0) # set name in upper left self.c.gridText(self.mapGUTTER, self.mapGUTTER + self.tMarginSize, 'nw', activePath, fontTitle, COLORtxUnit) # draw key for sets xCurrentPos = self.lMarginSize for keyPartition in range(self.totalSets): xStart = xCurrentPos xEnd = xCurrentPos + self.cellWidth yStart = self.tMarginSize yEnd = self.winHEIGHT # commented out portions create filled rectangles if keyPartition == 0: # first needs to be bkg color # removing first grid to remove ob1 error w/ vector graphics #self.c.line(xStart,yStart,xStart,yEnd, COLORbgAbs, width=1) scName = multiset.scToStr(scPath[keyPartition]) # this adds numbers to key self.c.gridText((xCurrentPos+self.mapGUTTER), self.mapGUTTER + self.tMarginSize, 'nw', scName, fontTitle, COLORtxUnit) elif (keyPartition % 1) == 0: self.c.line(xStart,yStart,xStart,yEnd, COLORbgMargin, .5) scName = multiset.scToStr(scPath[keyPartition]) # this adds numbers to key self.c.gridText((xCurrentPos+self.mapGUTTER), self.mapGUTTER + self.tMarginSize, 'nw', scName, fontTitle, COLORtxUnit) else: # this are the lines that divide verticalities self.c.line(xStart,yStart,xStart,yEnd, COLORbgGrid, .5) xCurrentPos = xCurrentPos + self.cellWidth # sets xPosition = self.lMarginSize axisDict = {} columnCount = 0 for chord in pcsPath: xPosition = xPosition + self.mapGUTTER yPosition = self.tMarginSize + (self.mapGUTTER*2) + self.cellHeight rowCount = 0 for note in chord: #yPosition = yPosition #+ self.mapGUTTER #+ self.cellHeight yLineStart = yPosition + 8 # needs to be shifted down xLineStart = xPosition - self.mapGUTTER - 1 # shift left 1 # axis dict used for drawing lines axisDict[(columnCount, rowCount)] = (xLineStart, yLineStart) pcString = '%i' % note self.c.gridText(xPosition, yPosition, 'nw', pcString, fontText, COLORtxTitle) rowCount = rowCount + 1 yPosition = yPosition + self.cellHeight + self.mapGUTTER xPosition = xPosition + (self.cellWidth - self.mapGUTTER) columnCount = columnCount + 1 # draw even if voices are not possible if mapDict != None: for i in range(self.totalSets-1): thisSetIndex = i nextSetIndex = i + 1 # this has been a source of error, but not clear why # some keys have produced a key error mapDictkey = (thisSetIndex, nextSetIndex) map = mcObj.fetchMap(mapDict[mapDictkey]) for j in range(len(map)): # go down vertically startCord = axisDict[(i,j)] nextRowPosition = map[j] if drawer.isList(nextRowPosition): for subRowPosition in nextRowPosition: # get next position endCord = axisDict[((i+1),subRowPosition)] self.c.line((startCord[0]+self.cellEntryWidth), (startCord[1]-self.vertCellOffset), (endCord[0]), (endCord[1]-self.vertCellOffset), COLORfgMain, 1) else: # get next position endCord = axisDict[((i+1),nextRowPosition)] self.c.line((startCord[0]+self.cellEntryWidth), (startCord[1]-self.vertCellOffset), (endCord[0]), (endCord[1]-self.vertCellOffset), COLORfgMain, 1)
def findNormalT(pcSet, setMatrix=None): """finds normal form of any pc set and returns forte number as a scTriple data structure, and transposition from normal form pcSet may contain psReals, and as such, need to be converted to ints >>> findNormalT([3,4,5]) ((3, 1, 0), 3) """ if setMatrix == None: # use forte as default setMatrix = FORTE MONADscTuple = (1, 1, 0) # check for bad data if drawer.isStr(pcSet): return None # error, no strings supported here if drawer.isList(pcSet): for psReal in pcSet: # make sure all values are numbers; no strings allowed if drawer.isStr(psReal): return None # break, return None as error # check for unusual data if drawer.isNum(pcSet): # its a single number pcVal = pitchTools.roundMicro(pcSet) # second number is transposition from 0 return MONADscTuple, (pcVal % 12) if len(pcSet) == 1: #filter out monad! pcVal = pitchTools.roundMicro(pcSet[0]) return MONADscTuple, (pcVal % 12) # scrub and go pcSetClone = [] for psReal in pcSet: # pcSet may contian psReal, w/ floating values pcSetClone.append(pitchTools.roundMicro(psReal)) #check fr non base 12 numbers, negative numbers, redundancies pcSetClone = list(pcSetTransposer(pcSetClone, 0)) pcSetClone.sort() i = 0 chord = [] for i in range(0, 12): # remove redundancies if i in pcSetClone: chord.append(i) card = len(chord) if card < 1: # monad has already been filtered out return None # 2nd no is transposition from 0 if card == 1: # this is a set like (3,3,3,3) return MONADscTuple, (pcSet[0] % 12) elif card > 12: return None # 'irrational cardinality error' rotIndices = list(range(0, card)) foundIndex = None #control variable for rot in rotIndices: r = rot # dont need to add 1? + 1 rotSet = chord[r:card] + chord[0:r] dif = rotSet[0] pSet = pcSetTransposer(rotSet, -dif) iSet = tuple(pcInverter(pSet)) maxRange = len(setMatrix[card]) # check all sets of given card for match for index in range(1, maxRange): # start with 1, not zero # this is a default; may be a symmetrical set and have no inversion foundInv = 'A' # test each set in this cardinality; "0" gets pitches testSet = tuple(setMatrix[card][index][0]) if iSet == testSet: foundIndex = index foundInv = 'B' #nt sure yet if 1 or 0 break elif pSet == testSet: foundIndex = index foundInv = 'A' #nt sure yet if 1 or 0 break if foundIndex != None: break if foundIndex == None: ## no set found return None #'failed!!!' if foundInv == 'B': # has inversion that is non-redundant (variant) if setMatrix[card][foundIndex][2][1] == 0: scInv = -1 else: scInv = 0 elif foundInv == 'A': # has inversion that is non-redundant (variant) if setMatrix[card][foundIndex][2][1] == 0: scInv = 1 else: scInv = 0 return (card, foundIndex, scInv), dif