def _waveReplace(self, argSrc): """always returns a list, not a tuple""" arg = list(argSrc[:]) if not drawer.isStr(arg[0]): return arg # dont alter # try to find pmtr Type pmtrType = None for lib in ["genPmtrObjs", "rthmPmtrObjs"]: try: pmtrType = parameter.pmtrTypeParser(arg[0], lib) except error.ParameterObjectSyntaxError: continue if pmtrType == None: # no match found return arg # insert step string as second argument elif pmtrType in [ "waveSine", "waveCosine", "waveSawDown", "waveSawUp", "wavePulse", "waveTriangle", "wavePowerDown", "wavePowerUp", ]: # make sure that this is not alreayd fixed: if drawer.isStr(arg[1]): # can assume that this is a t/e string return arg newArgs = [arg[0], "t"] + list(arg[1:]) environment.printDebug(["changed args:", arg, "to:", newArgs]) return newArgs else: return arg
def _waveReplace(self, argSrc): """always returns a list, not a tuple""" arg = list(argSrc[:]) if not drawer.isStr(arg[0]): return arg # dont alter # try to find pmtr Type pmtrType = None for lib in [ 'genPmtrObjs', 'rthmPmtrObjs', ]: try: pmtrType = parameter.pmtrTypeParser(arg[0], lib) except error.ParameterObjectSyntaxError: continue if pmtrType == None: # no match found return arg # insert step string as second argument elif pmtrType in [ 'waveSine', 'waveCosine', 'waveSawDown', 'waveSawUp', 'wavePulse', 'waveTriangle', 'wavePowerDown', 'wavePowerUp' ]: # make sure that this is not alreayd fixed: if drawer.isStr(arg[1]): # can assume that this is a t/e string return arg newArgs = [arg[0], 't'] + list(arg[1:]) environment.printDebug(['changed args:', arg, 'to:', newArgs]) return newArgs else: return arg
def _processType(self): """process raw data into appropriate primative format""" data = copy.copy(self.srcData) if self.format == 'psName': if drawer.isStr(data): return data else: return None elif self.format == 'psReal': # psReal values should not be rounded if drawer.isStr(data): try: return float(data) except ValueError: return None else: return data elif self.format == 'midi': #midi values should always be rounded if drawer.isStr(data): data = drawer.strStripAlpha(data) try: return float(data) # dont convert to int except ValueError: return None elif drawer.isInt(data): return data else: # its a float, round return data elif self.format == 'pch': # floating point values if drawer.isStr(data): data = drawer.strStripAlpha(data) try: return _normalizePch(float(data)) except ValueError: return None if drawer.isFloat(data): return _normalizePch(data) else: # something is wrong return None elif self.format == 'fq': # floating point values if drawer.isStr(data): data = drawer.strStripAlpha(data) try: return float(data) except ValueError: return None if drawer.isNum(data): return float(data) # convert to float else: # something is wrong return None else: # error return None
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 factory(request): # all will get all ouput formats if drawer.isStr(request): request = drawer.strScrub(request, 'L') if request == 'all': request = outputFormatNames.values() # if other string given, add to a list else: request = [request] # load objects reqArray = [] for name in request: name = outputFormatParser(name) if name == None: continue # user strings have lower case first char w/ format prefix className = 'Format' + name[0].upper() + name[1:] # get module attribute for class modAttr = globals()[className] reqArray.append(modAttr()) if len(reqArray) == 1: return reqArray[0] else: return reqArray
def _guessType(self): """try to determine what kind of pitch data is being provided psReal is default for any integer midi values must be marked some other way (w/ an m?) """ data = copy.copy(self.srcData) if drawer.isStr(data): data = drawer.strScrub(data, 'L') if len(data) == 0: return None # no data found if data[0] in REFdiaNameToPc: return 'psName' elif data.find('m') >= 0 or data.find('midi') >= 0: # an m designates a midi note number return 'midi' elif data.find('pch') >= 0: # a pch designates a pch value return 'pch' elif data.find('hz') >= 0 or data.find('fq') >= 0: return 'fq' else: # assume other strings are psInts return 'psReal' if drawer.isInt(data): # midi int, or ps int return 'psReal' if drawer.isFloat(data): # assume it is a psReal value return 'psReal'
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 factory(request): # all will get all ouput formats if drawer.isStr(request): request = drawer.strScrub(request, 'L') if request == 'all': request = list(outputFormatNames.values()) # if other string given, add to a list else: request = [request] # load objects reqArray = [] for name in request: name = outputFormatParser(name) if name == None: continue # user strings have lower case first char w/ format prefix className = 'Format' + name[0].upper() + name[1:] # get module attribute for class modAttr = globals()[className] reqArray.append(modAttr()) if len(reqArray) == 1: return reqArray[0] else: return reqArray
def _dictionaryStrKey(data): """check to see this is a dictionary, and all keys are strings""" if drawer.isDict(data):# recurse into dictionary, use key as name for key in data.keys(): if not drawer.isStr(key): return 0 # dictionary, but a key is not a string return 1 # all keys are strings, a dictionary return 0 # not a dictionary
def pdfMerge(fileDst, fileList): """uses ghostscript to merge pdf files into a new file""" if drawer.isStr(fileList): fileList = [fileList,] cmd = 'gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=%s ' % fileDst for file in fileList: cmd = cmd + '%s ' % file os.system(cmd)
def chmod( value, path, ): if os.name == 'posix': if not drawer.isStr(value): value = str(value) os.system("chmod %s '%s'" % (value, path))
def pdfMerge(fileDst, fileList): """uses ghostscript to merge pdf files into a new file""" if drawer.isStr(fileList): fileList = [ fileList, ] cmd = 'gs -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=%s ' % fileDst for file in fileList: cmd = cmd + '%s ' % file os.system(cmd)
def _reprListData(self, listData, outer=1): msgList = [] for data in listData: if not drawer.isStr(data): msgList.append(str(data)) else: msgList.append(data) msg = ','.join(msgList) # should be a list of strings if outer: return '(%s)' % msg else: return msg
def _reprListData(self, listData, outer=0): msgList = [] for data in listData: if not drawer.isStr(data): msgList.append(str(data)) else: msgList.append(data) msg = ','.join(msgList) # should be a list of strings if outer: return '(%s)' % msg else: return msg
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 chmodSudo(value, path, sudoFound=None): """sudo is not avail on all plats, so su root on other nixes""" if os.name == 'posix': if not drawer.isStr(value): value = str(value) if sudoFound == None: # test sudoFound = drawer.isSudo() # 1 if exists if drawer.isDarwin() or sudoFound: print PROMPTdarwin % ('changing permissions', path) os.system('sudo chmod %s "%s"' % (value, path)) else: # other *nixes print PROMPTposix % ('changing permissions', path) os.system('su root -c "chmod %s %s"' % (value, path))
def _processFormat(self): """process raw data into a rhythm triples stored as a rhythm triple in self.triple return None on error """ data = copy.copy(self.srcData) if self.format == 'str': if drawer.isStr(data) and data in REFdurStr.keys(): data = data.strip() data = data.lower() return self._expandRawTriple( REFdurStr[data]) # return None on error else: return None elif self.format == 'triple': if drawer.isStr(data): data = self._scrubDynStr( data) # may raise error.PulseSyntaxError try: data = list(eval(data)) # convert to list except (ValueError, SyntaxError): return None return self._expandRawTriple(data) # return None on error else: # its a real tuple/list return self._expandRawTriple(data) # return None on error elif self.format == 'acc': # a list of amps if drawer.isStr(data): if data in REFdynStr.keys(): # its a string data = self._dynStrToVal(data) # convert to number else: # its a string number like '3' try: data = eval(data) # an int/float except (ValueError, SyntaxError): return None return self._expandRawTriple(data) # return None on error else: # its a real int/float return self._expandRawTriple(data) # return None on error else: # error return None
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 _processFormat(self): """process raw data into a rhythm triples stored as a rhythm triple in self.triple return None on error """ data = copy.copy(self.srcData) if self.format == 'str': if drawer.isStr(data) and data in REFdurStr.keys(): data = data.strip() data = data.lower() return self._expandRawTriple(REFdurStr[data]) # return None on error else: return None elif self.format == 'triple': if drawer.isStr(data): data = self._scrubDynStr(data) # may raise error.PulseSyntaxError try: data = list(eval(data)) # convert to list except (ValueError, SyntaxError): return None return self._expandRawTriple(data) # return None on error else: # its a real tuple/list return self._expandRawTriple(data) # return None on error elif self.format == 'acc': # a list of amps if drawer.isStr(data): if data in REFdynStr.keys(): # its a string data = self._dynStrToVal(data) # convert to number else: # its a string number like '3' try: data = eval(data) # an int/float except (ValueError, SyntaxError): return None return self._expandRawTriple(data) # return None on error else: # its a real int/float return self._expandRawTriple(data) # return None on error else: # error return None
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 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, data): # ds is decimal seconds, or values less than 1, as a decimal # ds is not converted to ms or any other unit self.time = {'f':0, 's':0, 'm':0, 'h':0, 'd':0} self.sec = 0 self.srcData = data self.timeLabels = ['d', 'h', 'm', 's', 'f'] # must be in order if drawer.isStr(data): self._humanToSec(data) # load to self.time elif drawer.isNum(data): # assume seconds self.time['s'] = data # keep floating point values else: raise ValueError, 'unsupported data type' self._updateTime() # update and shifts all values
def __init__(self, data): # ds is decimal seconds, or values less than 1, as a decimal # ds is not converted to ms or any other unit self.time = {'f': 0, 's': 0, 'm': 0, 'h': 0, 'd': 0} self.sec = 0 self.srcData = data self.timeLabels = ['d', 'h', 'm', 's', 'f'] # must be in order if drawer.isStr(data): self._humanToSec(data) # load to self.time elif drawer.isNum(data): # assume seconds self.time['s'] = data # keep floating point values else: raise ValueError, 'unsupported data type' self._updateTime() # update and shifts all values
def wrapText(msg, charW=40, indentW=0, wrapType='line'): """convert line breaks into a list indent: if pos, applied to all lines except the first if neg, applied only to first line wrap type 'line' wraps each line wrapType 'bundle' wraps all lines as a single unit reads actual line breaks and groups all lines as whole not repeating next line until all lines have been shown usefill when presenting a long line of data that is broken into columns returns a string, not a list of strings """ strIndex = 0 startPosition = 0 if msg == None: return None # find natural line breaks and separate into lines # do not remove any white space or any adjustments entryLines = msg.split('\n') if entryLines[-1] == '': entryLines = entryLines[:-1] # bundle lines into a list bundledLines = [] bundledMaps = [] for line in entryLines: wrapLines = _singleLineWrap(line, charW, indentW, wrapType) bundledLines.append(wrapLines) #bundledMaps.append(lineMap) # add list lines to string if wrapType == 'line': pass elif wrapType == 'bundle': #print parallel info bundledLines = _bundleLines(charW, indentW, bundledLines) # make the new string newMsg = [] for bundle in bundledLines: for line in bundle: if not drawer.isStr(line): pass # case where it is a 0, as appended in bundleLines else: newMsg.append(line) # compare source to new string for last return newMsg = _lastReturnCheck(msg, '\n'.join(newMsg)) # check last \n return newMsg
def _pmtrNumberToUsr(self, pmtr, shift, style='str'): """convert a parameter number string into data numbers are returned as numbers, strings as strings str, and cmd produce un-altered numbers usr wil shift by appropriate values""" if drawer.isNum(pmtr): if style in ['str', 'cmd']: return pmtr elif style == 'usr': return pmtr + shift if drawer.isStr(pmtr): if style in ['str', 'cmd']: return pmtr elif style == 'usr': pmtr = drawer.strScrub(pmtr, 'lower') pmtr = pmtr.replace('q', '') return str(int(pmtr) + shift)
def _updateDefault(self, src): """make a ca dictionary rule and mutation are left out, as dynamic""" xMAX = 1000 yMAX = 10000 ref = { # these are the limits 'f' : ('s',), # must be first element of a list 'k' : (2, 0, 36), # def, min, max 'r' : (1, .5, 10), 'i' : ('center',), 'x' : (91, 1, xMAX), # should be odd value 'y' : (135, 1, yMAX), 'w' : (0, 0, yMAX), # will get value of 'c' : (0, -xMAX, xMAX), # center 's' : (0, 0, yMAX), # skip } # src keys have already been formated to single character refs for key in ref.keys(): if key not in src.keys(): src[key] = ref[key][0] else: # keu exists, eval numbers if necessary if drawer.isNum(ref[key][0]): # check numbers min = ref[key][1] max = ref[key][2] # permit r values w/ decimal .5 if key =='r' and '.' in src[key]: # double, round, and divide; will be either 0 or .5 value = drawer.strToNum(src[key], 'float', min, max) value = round(value*2) / 2 else: value = drawer.strToNum(src[key], 'int', min, max) if value != None: src[key] = value else: # cant resolve value, provide default src[key] = ref[key][0] if drawer.isStr(ref[key][0]): # check strings if key == 'f': value = caFormatParser(src[key]) elif key == 'i': value = caInitParser(src[key]) if value != None: src[key] = value else: src[key] = ref[key][0] return src
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 _updateDefault(self, src): """make a ca dictionary rule and mutation are left out, as dynamic""" xMAX = 1000 yMAX = 10000 ref = { # these are the limits 'f': ('s', ), # must be first element of a list 'k': (2, 0, 36), # def, min, max 'r': (1, .5, 10), 'i': ('center', ), 'x': (91, 1, xMAX), # should be odd value 'y': (135, 1, yMAX), 'w': (0, 0, yMAX), # will get value of 'c': (0, -xMAX, xMAX), # center 's': (0, 0, yMAX), # skip } # src keys have already been formated to single character refs for key in ref.keys(): if key not in src.keys(): src[key] = ref[key][0] else: # keu exists, eval numbers if necessary if drawer.isNum(ref[key][0]): # check numbers min = ref[key][1] max = ref[key][2] # permit r values w/ decimal .5 if key == 'r' and '.' in src[key]: # double, round, and divide; will be either 0 or .5 value = drawer.strToNum(src[key], 'float', min, max) value = round(value * 2) / 2 else: value = drawer.strToNum(src[key], 'int', min, max) if value != None: src[key] = value else: # cant resolve value, provide default src[key] = ref[key][0] if drawer.isStr(ref[key][0]): # check strings if key == 'f': value = caFormatParser(src[key]) elif key == 'i': value = caInitParser(src[key]) if value != None: src[key] = value else: src[key] = ref[key][0] return src
def getPercNameFromNoteName(usrStr): """get perc name from midi note number nameStr can be a string (psName) or number (midiNote number) """ if drawer.isStr(usrStr): psInt = pitchTools.psNameToPs(usrStr) midiInt = pitchTools.psToMidi(psInt) else: midiInt = int(usrStr) # normalize bad values if midiInt < 35: midiInt = 35 if midiInt > 81: midiInt = 81 else: for name, num in gmPercussionNames.items(): if num == midiInt: percName = name break return percName
def graphNumber(min, max, value, charWidth=50, emptyChar='.', fullChar='+'): """produces a graph of an object in a field values can be ints or floats """ if min > max: high = min low = max rev = 1 # reverse string at end else: high = max low = min rev = 0 if value == None or drawer.isStr(value): value = low - 1 # off range distance = high - low pcentValue = float((value-low)) / distance pcentInc = 1.0 / charWidth litInc = float(distance) / charWidth str = [] pcentPosition = 0.0 literalPosition = low for counter in range(0, charWidth): if (pcentValue >= pcentPosition and pcentValue < (pcentPosition + pcentInc)): str.append(fullChar) elif counter == (charWidth-1): # last register if pcentValue >= (1.0 - pcentInc) and pcentValue <= 1.0: #print pcentValue, pcentPosition str.append(fullChar) else: str.append(emptyChar) else: str.append(emptyChar) pcentPosition = pcentPosition + pcentInc if rev == 1: l = list(str) l.reverse() str = [] for letter in l: str.append(letter) return ''.join(str)
def _loadAutoConstantStr(self, arg, ref, lib='genPmtrObjs'): """accept a number, a list parameter object, or a string from within a dfeind string group""" # ref = {'0' : ['tn', 't', 't n' '0'], # } if drawer.isNum(arg): pmtrArgs = ('c', arg) elif drawer.isStr(arg): post = drawer.selectionParse(arg, ref, 0) # autosearch off if post == None: raise error.ParameterObjectSyntaxError, 'no such preset name known.' pmtrArgs = ('c', post) # a constant pmtr obj else: # its a list to create a ParameterObject pmtrArgs = arg # create a ParameterObject from athenaCL.libATH.libPmtr import parameter try: obj = parameter.factory(pmtrArgs, lib) except error.ParameterObjectSyntaxError, msg: raise error.ParameterObjectSyntaxError, 'failed sub-parameter: %s' % msg
def reprUsage(self, searchStr, errorStr=None): """just return a formatted usage string, or error message if none exists; this is used as an error message from command.py when bad command line args are given""" name, usageStr = self.searchCmdUsage(searchStr) if usageStr == None: if errorStr == None: return 'incorrect usage; no additional help available.\n' else: return 'incorrect usage; %s.\n' % errorStr elif errorStr == None: return '%s %s\n' % (self.__msgUsage, usageStr) else: if not drawer.isStr(errorStr): # case of an built-in exception obj errorStr = str(errorStr) # must be converted into string errorStr = errorStr.strip() # this used to replace colons w/ periods, # but this is not always desirable # errorStr = errorStr.replace(':', '.') return '%s %s (%s)\n' % (self.__msgUsage, usageStr, errorStr)
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 promptGetFile(prompt='select a file', defaultDir='', mode='file', dlgVisualMethod=None, termObj=None): """multi platform/gui methods for selecting file to open text version allowes user to browse file system mode can be either filr or app, to allow application selection this is only explicitly necessary in text-based file selection """ if dlgVisualMethod == None: # test for vis method if not provided dlgVisualMethod = autoDlgMethod() if defaultDir != '': pass # used as default dir selection elif drawer.getcwd() != None: defaultDir = drawer.getcwd() elif drawer.getud() != None: defaultDir = drawer.getud() else: defaultDir = '' defaultDir = drawer.pathScrub(defaultDir) path = None # empty until defined # platform specific file dialogs. if dlgVisualMethod == 'mac': try: path, stat = _macGetFile(prompt, defaultDir) return path, stat except: print(lang.msgDlgMacError) # platform specific file dialogs. if dlgVisualMethod[:2] == 'tk': try: import tkinter import tkinter.filedialog TK = 1 except ImportError: TK = 0 print(lang.msgDlgTkError) if dlgVisualMethod[:2] == 'tk' and TK: tkTemp = tkinter.Tk() tkTemp.withdraw() options = { 'filetypes': [("all files", "*")], 'title': prompt, 'parent': tkTemp } # need to check if defaultDir still exists if os.path.isdir(defaultDir): options['initialdir'] = defaultDir guiTemp = tkinter.filedialog.Open() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( try: path = guiTemp.show() # clean up gui mess del guiTemp tkTemp.destroy() except: pass # tk broke somehow if path not in ['', None] and drawer.isStr(path): path = drawer.pathScrub(path) return path, 1 # may be problem here with a keyboard interupt exception #elif path == None: # if not set yet, something went wrong # pass # fall below to text based else: return '', 0 # failure # for all other platforms, dlgVisualMethod == text try: msg, ok = _textGetFile(prompt, defaultDir, mode, dlgVisualMethod, termObj) except (OSError, IOError): # catch file errors, or dirs called tt dont exist msg = '' # this is usually the path itself ok = 0 return msg, ok
def promptPutFile(prompt='name this file:', defaultName='name', defaultDir='', extension='*', dlgVisualMethod=None, termObj=None): """multi platform/gui methods for selecting a file to write to text version allows user to browse file system """ if dlgVisualMethod == None: # test for vis method if not provided dlgVisualMethod = autoDlgMethod() path = None # empty until defined # platform specific file dialogs. if dlgVisualMethod == 'mac': stat = 0 try: path, stat = _macPutFile(prompt, defaultName, defaultDir) return path, stat except: # will be MacOS.Error but must import MacOS to select? print(lang.msgDlgMacError) # platform specific file dialogs. if dlgVisualMethod[:2] == 'tk': try: import tkinter import tkinter.filedialog TK = 1 except ImportError: TK = 0 print(lang.msgDlgTkError) if dlgVisualMethod[:2] == 'tk' and TK == 1: tkTemp = tkinter.Tk() tkTemp.withdraw() # put extension here, but dont know if i need period or not options = { 'filetypes': [("all files", "*")], 'title': prompt, 'parent': tkTemp } # need to check if directory still exists if os.path.isdir(defaultDir): options['initialdir'] = defaultDir guiTemp = tkinter.filedialog.SaveAs() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( try: path = guiTemp.show() del guiTemp # clean up gui mess tkTemp.destroy() # return path except: pass # tk broke somehow if path not in ['', None] and drawer.isStr(path): path = drawer.pathScrub(path) return path, 1 # may be problem here with a keyboard interupt exception #elif path == None: # if not set yet, something went wrong # pass # fall below to text based else: return '', 0 # for all other platforms try: msg, ok = _textPutFile(prompt, defaultName, defaultDir, extension, dlgVisualMethod, termObj) except (OSError, IOError): # catch file errors, or dirs called tt dont exist msg = '' # this is usually the path itself ok = 0 return msg, ok
def promptGetDir(prompt='select a directory:', sampleDir='', dlgVisualMethod=None, termObj=None): """multi platform/gui methods for optaining a directory text based version displays dir listings """ if dlgVisualMethod == None: # test for vis method if not provided dlgVisualMethod = autoDlgMethod() # check for bad directories if sampleDir != '': pass # used as default dir selection elif drawer.getcwd() != None: sampleDir = drawer.getcwd() elif drawer.getud() != None: sampleDir = drawer.getud() else: sampleDir = '' sampleDir = drawer.pathScrub(sampleDir) pathToFile = None # empty until defined # platform specific file dialogs. if dlgVisualMethod == 'mac': try: path, stat = _macGetDirectory(prompt) return path, stat except: print(lang.msgDlgMacError) # platform specific file dialogs. if dlgVisualMethod[:2] == 'tk': try: import tkinter import tkinter.filedialog TK = 1 except ImportError: TK = 0 print(lang.msgDlgTkError) if dlgVisualMethod[:2] == 'tk' and TK == 1: tkTemp = tkinter.Tk() tkTemp.withdraw() ## "dir" only shows directories, but are unable to select options = { 'filetypes': [("directory", "*")], 'title': prompt, 'parent': tkTemp } # need to check if defaultDir still exists if os.path.isdir(sampleDir): options['initialdir'] = sampleDir guiTemp = tkinter.filedialog.Open() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( try: pathToFile = guiTemp.show() del guiTemp # clean up gui mess tkTemp.destroy() except: # tk broke somehow pass # return path if pathToFile not in ['', None] and drawer.isStr(pathToFile): pathToFile = os.path.dirname(pathToFile) # remove file name pathToFile = drawer.pathScrub(pathToFile) return pathToFile, 1 elif pathToFile == None: # if not set yet, something went wrong pass # fall below to text based else: return '', 0 # for all other platforms, dlgVisualMethod == text try: msg, ok = _textGetDirectory(prompt, sampleDir, termObj) except (OSError, IOError): # catch file errors, or dirs called tt dont exist msg = '' # this is usually the path itself ok = 0 return msg, ok
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 promptGetDir(prompt='select a directory:', sampleDir='', dlgVisualMethod=None, termObj=None): """multi platform/gui methods for optaining a directory text based version displays dir listings """ if dlgVisualMethod == None: # test for vis method if not provided dlgVisualMethod = autoDlgMethod() # check for bad directories if sampleDir != '': pass # used as default dir selection elif drawer.getcwd() != None: sampleDir = drawer.getcwd() elif drawer.getud() != None: sampleDir = drawer.getud() else: sampleDir = '' sampleDir = drawer.pathScrub(sampleDir) pathToFile = None # empty until defined # platform specific file dialogs. if dlgVisualMethod == 'mac': try: path, stat = _macGetDirectory(prompt) return path, stat except: print lang.msgDlgMacError # platform specific file dialogs. if dlgVisualMethod[:2] == 'tk': try: import Tkinter import tkFileDialog TK = 1 except ImportError: TK = 0 print lang.msgDlgTkError if dlgVisualMethod[:2] == 'tk' and TK == 1: tkTemp = Tkinter.Tk() tkTemp.withdraw() ## "dir" only shows directories, but are unable to select options = {'filetypes':[("directory", "*")], 'title' : prompt, 'parent' : tkTemp} # need to check if defaultDir still exists if os.path.isdir(sampleDir): options['initialdir'] = sampleDir guiTemp = tkFileDialog.Open() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( try: pathToFile = guiTemp.show() del guiTemp # clean up gui mess tkTemp.destroy() except: # tk broke somehow pass # return path if pathToFile not in ['', None] and drawer.isStr(pathToFile): pathToFile = os.path.dirname(pathToFile) # remove file name pathToFile = drawer.pathScrub(pathToFile) return pathToFile, 1 elif pathToFile == None: # if not set yet, something went wrong pass # fall below to text based else: return '', 0 # for all other platforms, dlgVisualMethod == text try: msg, ok = _textGetDirectory(prompt, sampleDir, termObj) except (OSError, IOError): # catch file errors, or dirs called tt dont exist msg = '' # this is usually the path itself ok = 0 return msg, ok
def promptPutFile(prompt='name this file:', defaultName='name', defaultDir='', extension='*', dlgVisualMethod=None, termObj=None): """multi platform/gui methods for selecting a file to write to text version allows user to browse file system """ if dlgVisualMethod == None: # test for vis method if not provided dlgVisualMethod = autoDlgMethod() path = None # empty until defined # platform specific file dialogs. if dlgVisualMethod == 'mac': stat = 0 try: path, stat = _macPutFile(prompt, defaultName, defaultDir) return path, stat except: # will be MacOS.Error but must import MacOS to select? print lang.msgDlgMacError # platform specific file dialogs. if dlgVisualMethod[:2] == 'tk': try: import Tkinter import tkFileDialog TK = 1 except ImportError: TK = 0 print lang.msgDlgTkError if dlgVisualMethod[:2] == 'tk' and TK == 1: tkTemp = Tkinter.Tk() tkTemp.withdraw() # put extension here, but dont know if i need period or not options = {'filetypes':[("all files", "*")], 'title' : prompt, 'parent' : tkTemp} # need to check if directory still exists if os.path.isdir(defaultDir): options['initialdir'] = defaultDir guiTemp = tkFileDialog.SaveAs() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( try: path = guiTemp.show() del guiTemp # clean up gui mess tkTemp.destroy() # return path except: pass # tk broke somehow if path not in ['', None] and drawer.isStr(path): path = drawer.pathScrub(path) return path, 1 # may be problem here with a keyboard interupt exception #elif path == None: # if not set yet, something went wrong # pass # fall below to text based else: return '', 0 # for all other platforms try: msg, ok = _textPutFile(prompt, defaultName, defaultDir, extension, dlgVisualMethod, termObj) except (OSError, IOError): # catch file errors, or dirs called tt dont exist msg = '' # this is usually the path itself ok = 0 return msg, ok
def insertMix(self, pos, insertData, method=None): """insert the data at specifiec location data can be in the form of a unitList (b/n 0 and 1) or string data (assuming its in the same channel it may be good to allow for a negative position: insert the necessary frames before x and y """ # zero position measured form x xData = self.getData() xSize = copy.copy(self.frames) if drawer.isStr(insertData): # divide channel number * byte ySize = arrayLenToFrameLen(len(insertData), self.bytes, self.ch) yData = insertData else: #must be a unit list ySize = len(insertData) # channel does not matter in unit list yData = self.sampleGenObj.unitSynthesizer(insertData, method) #print _MOD, 'x, y size', xSize, ySize if pos == 0: # just pad end of shorter if ySize == xSize: _caseStr = 'a' # this is just for debugging xFinal = xData yFinal = yData elif ySize > xSize : # x needs pad after _caseStr = 'b' dif = ySize - xSize xFinal = xData + self.sampleGenObj.silence(dif) yFinal = yData elif ySize < xSize : # y needs pad after _caseStr = 'c' dif = xSize - ySize xFinal = xData yFinal = yData + self.sampleGenObj.silence(dif) else: if ySize >= xSize: _caseStr = 'd' posRemain = (pos + ySize) - xSize xFinal = xData + self.sampleGenObj.silence(posRemain) yFinal = self.sampleGenObj.silence(pos) + yData elif ySize < xSize: # x needs pad after if pos + ySize == xSize: _caseStr = 'e' xRemain = pos # postpend to x yRemain = 0 elif pos + ySize < xSize: # need yRemain _caseStr = 'f' xRemain = 0 yRemain = xSize - (pos + ySize) elif pos + ySize > xSize: # need yRemain _caseStr = 'g' xRemain = (pos + ySize) - xSize yRemain = 0 xFinal = xData + self.sampleGenObj.silence(xRemain) yFinal = (self.sampleGenObj.silence(pos) + yData + self.sampleGenObj.silence(yRemain)) #print _MOD, 'resize case:', _caseStr data = self.sampleGenObj.mix(xFinal, yFinal) self._open('w') # over-write existing data self.aObj.writeframesraw(data) self._close()
def chmod(value, path,): if os.name == 'posix': if not drawer.isStr(value): value = str(value) os.system("chmod %s '%s'" % (value, path))
def formatVariCol(headerKey, entryLines, minWidthList, bufList=[], justList=[], termObj=None, wrapMode='none', wrapType='line', minBufferW=1, ): """takes a list of entries and creates parallel widths for each line takes a list of listed entries, a list of minWidths, a list of justifications. if, after analysis, a col width needs to be expanded, it is headerKey is a list of keys as a header entryLines is a list of a list of things to be printed minWidhtList is a list of minimum widths, without buffering justList is justifications, l, r, c bufList is boolean for wether a the buffer should be added or not """ # check for lists entryLines = _scrubEntryLines(entryLines) if entryLines == None: return "no data to format (dialog.py)." minWidthList = list(minWidthList) bufList = list(bufList) justList = list(justList) # get width if termObj == None: charWidth = 72 else: h, charWidth = termObj.size() # convert all entries to strings noColumns = 0 lineCount = 0 for line in entryLines: colCount = 0 for entry in line: if not drawer.isStr(entry): # not a string entry = str(entry) entry = entry.strip() # removie outer white space entry = entry.replace(' ','') # remove spaces entryLines[lineCount][colCount] = entry colCount = colCount + 1 if colCount >= noColumns: noColumns = colCount lineCount = lineCount + 1 #find min width for each column based on entry size fitColWidths = [] for col in range(0,noColumns): fitColWidths.append(0) try: a = minWidthList[col] except IndexError: minWidthList.append(0) try: a = justList[col] except IndexError: justList.append('l') # default try: a = bufList[col] except IndexError: bufList.append(1) # use default for line in entryLines: colCount = 0 for entry in line: if len(entry) >= fitColWidths[colCount]: fitColWidths[colCount] = len(entry) colCount = colCount + 1 # create lines finalColWidths = [] msgBody = [] lineCount = 0 for line in entryLines: colCount = 0 lineStr = [] for entry in line: if fitColWidths[colCount] > minWidthList[colCount]: finalW = fitColWidths[colCount] else: finalW = minWidthList[colCount] if (bufList[colCount] != 0 and fitColWidths[colCount] >= minWidthList[colCount]): # add a bufer if found width is greater or equal to fit finalW = minBufferW + finalW finalColWidths.append(finalW) if justList[colCount].lower() == 'l': lineStr.append(entry.ljust(finalColWidths[colCount])) elif justList[colCount].lower() == 'r': lineStr.append(entry.rjust(finalColWidths[colCount])) elif justList[colCount].lower() == 'c': lineStr.append(entry.center(finalColWidths[colCount])) colCount = colCount + 1 if ''.join(lineStr).strip() == '': # draw a line lineStr.append(charWidth * lang.DIVIDER) if lineCount < (len(entryLines) - 1): # addreturn lineStr.append('\n') else: # last one, no \n pass msgBody = msgBody + lineStr # add lists lineCount = lineCount + 1 msgBody = ''.join(msgBody) # convert to string if wrapMode == 'none': pass elif wrapMode == 'normal': msgBody = wrapText(msgBody, charWidth, 0, wrapType) elif wrapMode == 'tab': msgBody = wrapText(msgBody, charWidth, lang.TABW, wrapType) elif wrapMode == 'lmargin': msgBody = wrapText(msgBody, charWidth, lang.LMARGINW, wrapType) elif wrapMode == 'oneColumn': indentWidth = finalColWidths[0] msgBody = wrapText(msgBody, charWidth, indentWidth, wrapType) elif wrapMode == 'twoColumn': indentWidth = finalColWidths[0]+finalColWidths[1] msgBody = wrapText(msgBody, charWidth, indentWidth, wrapType) elif wrapMode == 'threeColumn': indentWidth = finalColWidths[0]+finalColWidths[1]+finalColWidths[2] msgBody = wrapText(msgBody, charWidth, indentWidth, wrapType) elif wrapMode == 'fourColumn': indentWidth = (finalColWidths[0]+finalColWidths[1]+ finalColWidths[2]+finalColWidths[3]) msgBody = wrapText(msgBody, charWidth, indentWidth, wrapType) # create header keys colCount = 0 totW = 0 headStr = [] headStr.append('{') for head in headerKey: if colCount < (len(headerKey) - 1): if head != '': headStr.append(head + ',') # key divider else: headStr.append(head) colCount = colCount + 1 headStr.append('}') headStr.append('\n') # + (lang.DIVIDER * totW) + '\n' if len(headerKey) != 0: # skip header if empty list headStr.append(msgBody) msgFinal = ''.join(headStr) else: msgFinal = msgBody return msgFinal
def promptGetFile(prompt='select a file', defaultDir='', mode='file', dlgVisualMethod=None, termObj=None): """multi platform/gui methods for selecting file to open text version allowes user to browse file system mode can be either filr or app, to allow application selection this is only explicitly necessary in text-based file selection """ if dlgVisualMethod == None: # test for vis method if not provided dlgVisualMethod = autoDlgMethod() if defaultDir != '': pass # used as default dir selection elif drawer.getcwd() != None: defaultDir = drawer.getcwd() elif drawer.getud() != None: defaultDir = drawer.getud() else: defaultDir = '' defaultDir = drawer.pathScrub(defaultDir) path = None # empty until defined # platform specific file dialogs. if dlgVisualMethod == 'mac': try: path, stat = _macGetFile(prompt, defaultDir) return path, stat except: print lang.msgDlgMacError # platform specific file dialogs. if dlgVisualMethod[:2] == 'tk': try: import Tkinter import tkFileDialog TK = 1 except ImportError: TK = 0 print lang.msgDlgTkError if dlgVisualMethod[:2] == 'tk' and TK: tkTemp = Tkinter.Tk() tkTemp.withdraw() options = {'filetypes':[("all files", "*")], 'title' : prompt, 'parent' : tkTemp} # need to check if defaultDir still exists if os.path.isdir(defaultDir): options['initialdir'] = defaultDir guiTemp = tkFileDialog.Open() guiTemp.options = options # filename = apply(tkFileDialog.Open, (), options).show( try: path = guiTemp.show() # clean up gui mess del guiTemp tkTemp.destroy() except: pass # tk broke somehow if path not in ['', None] and drawer.isStr(path): path = drawer.pathScrub(path) return path, 1 # may be problem here with a keyboard interupt exception #elif path == None: # if not set yet, something went wrong # pass # fall below to text based else: return '', 0 # failure # for all other platforms, dlgVisualMethod == text try: msg, ok = _textGetFile(prompt, defaultDir, mode, dlgVisualMethod, termObj) except (OSError, IOError): # catch file errors, or dirs called tt dont exist msg = '' # this is usually the path itself ok = 0 return msg, ok
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