PythonUtil.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. import types
  2. import string
  3. import re
  4. import math
  5. import operator
  6. import inspect
  7. import os
  8. import sys
  9. import random
  10. if __debug__:
  11. import traceback
  12. from direct.directutil import Verify
  13. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  14. # NOTE: ifAbsentPut has been replaced with Python's dictionary's builtin setdefault
  15. # before:
  16. # ifAbsentPut(dict, key, defaultValue)
  17. # after:
  18. # dict.setdefault(key, defaultValue)
  19. # Please use setdefault instead -- Joe
  20. def enumerate(L):
  21. """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax:
  22. for i, item in enumerate(L):
  23. ...
  24. enumerate is a built-in feature in Python 2.3, which implements it
  25. using an iterator. For now, we can use this quick & dirty
  26. implementation that returns a list of tuples that is completely
  27. constructed every time enumerate() is called.
  28. """
  29. return zip(xrange(len(L)), L)
  30. import __builtin__
  31. if not hasattr(__builtin__, 'enumerate'):
  32. __builtin__.enumerate = enumerate
  33. def unique(L1, L2):
  34. """Return a list containing all items in 'L1' that are not in 'L2'"""
  35. L2 = dict([(k,None) for k in L2])
  36. return [item for item in L1 if item not in L2]
  37. def indent(stream, numIndents, str):
  38. """
  39. Write str to stream with numIndents in front of it
  40. """
  41. # To match emacs, instead of a tab character we will use 4 spaces
  42. stream.write(' ' * numIndents + str)
  43. def writeFsmTree(instance, indent = 0):
  44. if hasattr(instance, 'parentFSM'):
  45. writeFsmTree(instance.parentFSM, indent-2)
  46. elif hasattr(instance, 'fsm'):
  47. name = ''
  48. if hasattr(instance.fsm, 'state'):
  49. name = instance.fsm.state.name
  50. print "%s: %s"%(instance.fsm.name, name)
  51. if __debug__:
  52. class StackTrace:
  53. def __init__(self, label="", start=0, limit=None):
  54. """
  55. label is a string (or anything that be be a string)
  56. that is printed as part of the trace back.
  57. This is just to make it easier to tell what the
  58. stack trace is referring to.
  59. start is an integer number of stack frames back
  60. from the most recent. (This is automatically
  61. bumped up by one to skip the __init__ call
  62. to the StackTrace).
  63. limit is an integer number of stack frames
  64. to record (or None for unlimited).
  65. """
  66. self.label = label
  67. if limit is not None:
  68. self.trace = traceback.extract_stack(sys._getframe(1+start),
  69. limit=limit)
  70. else:
  71. self.trace = traceback.extract_stack(sys._getframe(1+start))
  72. def __str__(self):
  73. r = "Debug stack trace of %s (back %s frames):\n"%(
  74. self.label, len(self.trace),)
  75. for i in traceback.format_list(self.trace):
  76. r+=i
  77. return r
  78. #-----------------------------------------------------------------------------
  79. def traceFunctionCall(frame):
  80. """
  81. return a string that shows the call frame with calling arguments.
  82. e.g.
  83. foo(x=234, y=135)
  84. """
  85. f = frame
  86. co = f.f_code
  87. dict = f.f_locals
  88. n = co.co_argcount
  89. if co.co_flags & 4: n = n+1
  90. if co.co_flags & 8: n = n+1
  91. r=''
  92. if dict.has_key('self'):
  93. r = '%s.'%(dict['self'].__class__.__name__, )
  94. r+="%s("%(f.f_code.co_name, )
  95. comma=0 # formatting, whether we should type a comma.
  96. for i in range(n):
  97. name = co.co_varnames[i]
  98. if name=='self':
  99. continue
  100. if comma:
  101. r+=', '
  102. else:
  103. # ok, we skipped the first one, the rest get commas:
  104. comma=1
  105. r+=name
  106. r+='='
  107. if dict.has_key(name):
  108. v=str(dict[name])
  109. if len(v)>200:
  110. r+="<too big for debug>"
  111. else:
  112. r+=str(dict[name])
  113. else: r+="*** undefined ***"
  114. return r+')'
  115. def traceParentCall():
  116. return traceFunctionCall(sys._getframe(2))
  117. def printThisCall():
  118. print traceFunctionCall(sys._getframe(1))
  119. return 1 # to allow "assert printThisCall()"
  120. if __debug__:
  121. def lineage(obj, verbose=0, indent=0):
  122. """
  123. return instance or class name in as a multiline string.
  124. Usage: print lineage(foo)
  125. (Based on getClassLineage())
  126. """
  127. r=""
  128. if type(obj) == types.ListType:
  129. r+=(" "*indent)+"python list\n"
  130. elif type(obj) == types.DictionaryType:
  131. r+=(" "*indent)+"python dictionary\n"
  132. elif type(obj) == types.ModuleType:
  133. r+=(" "*indent)+str(obj)+"\n"
  134. elif type(obj) == types.InstanceType:
  135. r+=lineage(obj.__class__, verbose, indent)
  136. elif type(obj) == types.ClassType:
  137. r+=(" "*indent)
  138. if verbose:
  139. r+=obj.__module__+"."
  140. r+=obj.__name__+"\n"
  141. for c in obj.__bases__:
  142. r+=lineage(c, verbose, indent+2)
  143. return r
  144. def tron():
  145. sys.settrace(trace)
  146. def trace(frame, event, arg):
  147. if event == 'line':
  148. pass
  149. elif event == 'call':
  150. print traceFunctionCall(sys._getframe(1))
  151. elif event == 'return':
  152. print "returning"
  153. elif event == 'exception':
  154. print "exception"
  155. return trace
  156. def troff():
  157. sys.settrace(None)
  158. #-----------------------------------------------------------------------------
  159. def apropos(obj, *args):
  160. """
  161. Obsolete, use pdir
  162. """
  163. print 'Use pdir instead'
  164. def getClassLineage(obj):
  165. """
  166. print object inheritance list
  167. """
  168. if type(obj) == types.DictionaryType:
  169. # Just a dictionary, return dictionary
  170. return [obj]
  171. elif type(obj) == types.InstanceType:
  172. # Instance, make a list with the instance and its class interitance
  173. return [obj] + getClassLineage(obj.__class__)
  174. elif type(obj) == types.ClassType:
  175. # Class, see what it derives from
  176. lineage = [obj]
  177. for c in obj.__bases__:
  178. lineage = lineage + getClassLineage(c)
  179. return lineage
  180. else:
  181. # Not what I'm looking for
  182. return []
  183. def pdir(obj, str = None, fOverloaded = 0, width = None,
  184. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  185. # Remove redundant class entries
  186. uniqueLineage = []
  187. for l in getClassLineage(obj):
  188. if type(l) == types.ClassType:
  189. if l in uniqueLineage:
  190. break
  191. uniqueLineage.append(l)
  192. # Pretty print out directory info
  193. uniqueLineage.reverse()
  194. for obj in uniqueLineage:
  195. _pdir(obj, str, fOverloaded, width, fTruncate, lineWidth, wantPrivate)
  196. print
  197. def _pdir(obj, str = None, fOverloaded = 0, width = None,
  198. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  199. """
  200. Print out a formatted list of members and methods of an instance or class
  201. """
  202. def printHeader(name):
  203. name = ' ' + name + ' '
  204. length = len(name)
  205. if length < 70:
  206. padBefore = int((70 - length)/2.0)
  207. padAfter = max(0,70 - length - padBefore)
  208. header = '*' * padBefore + name + '*' * padAfter
  209. print header
  210. print
  211. def printInstanceHeader(i, printHeader = printHeader):
  212. printHeader(i.__class__.__name__ + ' INSTANCE INFO')
  213. def printClassHeader(c, printHeader = printHeader):
  214. printHeader(c.__name__ + ' CLASS INFO')
  215. def printDictionaryHeader(d, printHeader = printHeader):
  216. printHeader('DICTIONARY INFO')
  217. # Print Header
  218. if type(obj) == types.InstanceType:
  219. printInstanceHeader(obj)
  220. elif type(obj) == types.ClassType:
  221. printClassHeader(obj)
  222. elif type (obj) == types.DictionaryType:
  223. printDictionaryHeader(obj)
  224. # Get dict
  225. if type(obj) == types.DictionaryType:
  226. dict = obj
  227. else:
  228. dict = obj.__dict__
  229. # Adjust width
  230. if width:
  231. maxWidth = width
  232. else:
  233. maxWidth = 10
  234. keyWidth = 0
  235. aproposKeys = []
  236. privateKeys = []
  237. remainingKeys = []
  238. for key in dict.keys():
  239. if not width:
  240. keyWidth = len(key)
  241. if str:
  242. if re.search(str, key, re.I):
  243. aproposKeys.append(key)
  244. if (not width) and (keyWidth > maxWidth):
  245. maxWidth = keyWidth
  246. else:
  247. if key[:1] == '_':
  248. if wantPrivate:
  249. privateKeys.append(key)
  250. if (not width) and (keyWidth > maxWidth):
  251. maxWidth = keyWidth
  252. else:
  253. remainingKeys.append(key)
  254. if (not width) and (keyWidth > maxWidth):
  255. maxWidth = keyWidth
  256. # Sort appropriate keys
  257. if str:
  258. aproposKeys.sort()
  259. else:
  260. privateKeys.sort()
  261. remainingKeys.sort()
  262. # Print out results
  263. if wantPrivate:
  264. keys = aproposKeys + privateKeys + remainingKeys
  265. else:
  266. keys = aproposKeys + remainingKeys
  267. format = '%-' + `maxWidth` + 's'
  268. for key in keys:
  269. value = dict[key]
  270. if callable(value):
  271. strvalue = `Signature(value)`
  272. else:
  273. strvalue = `value`
  274. if fTruncate:
  275. # Cut off line (keeping at least 1 char)
  276. strvalue = strvalue[:max(1,lineWidth - maxWidth)]
  277. print (format % key)[:maxWidth] + '\t' + strvalue
  278. # Magic numbers: These are the bit masks in func_code.co_flags that
  279. # reveal whether or not the function has a *arg or **kw argument.
  280. _POS_LIST = 4
  281. _KEY_DICT = 8
  282. def _is_variadic(function):
  283. return function.func_code.co_flags & _POS_LIST
  284. def _has_keywordargs(function):
  285. return function.func_code.co_flags & _KEY_DICT
  286. def _varnames(function):
  287. return function.func_code.co_varnames
  288. def _getcode(f):
  289. """
  290. _getcode(f)
  291. This function returns the name and function object of a callable
  292. object.
  293. """
  294. def method_get(f):
  295. return f.__name__, f.im_func
  296. def function_get(f):
  297. return f.__name__, f
  298. def instance_get(f):
  299. if hasattr(f, '__call__'):
  300. method = f.__call__
  301. if (type(method) == types.MethodType):
  302. func = method.im_func
  303. else:
  304. func = method
  305. return ("%s%s" % (f.__class__.__name__, '__call__'), func)
  306. else:
  307. s = ("Instance %s of class %s does not have a __call__ method" %
  308. (f, f.__class__.__name__))
  309. raise TypeError, s
  310. def class_get(f):
  311. if hasattr(f, '__init__'):
  312. return f.__name__, f.__init__.im_func
  313. else:
  314. return f.__name__, lambda: None
  315. codedict = { types.UnboundMethodType: method_get,
  316. types.MethodType : method_get,
  317. types.FunctionType : function_get,
  318. types.InstanceType : instance_get,
  319. types.ClassType : class_get,
  320. }
  321. try:
  322. return codedict[type(f)](f)
  323. except KeyError:
  324. if callable(f): # eg, built-in functions and methods
  325. # raise ValueError, "type %s not supported yet." % type(f)
  326. return f.__name__, None
  327. else:
  328. raise TypeError, ("object %s of type %s is not callable." %
  329. (f, type(f)))
  330. class Signature:
  331. def __init__(self, func):
  332. self.type = type(func)
  333. self.name, self.func = _getcode(func)
  334. def ordinary_args(self):
  335. n = self.func.func_code.co_argcount
  336. return _varnames(self.func)[0:n]
  337. def special_args(self):
  338. n = self.func.func_code.co_argcount
  339. x = {}
  340. #
  341. if _is_variadic(self.func):
  342. x['positional'] = _varnames(self.func)[n]
  343. if _has_keywordargs(self.func):
  344. x['keyword'] = _varnames(self.func)[n+1]
  345. elif _has_keywordargs(self.func):
  346. x['keyword'] = _varnames(self.func)[n]
  347. else:
  348. pass
  349. return x
  350. def full_arglist(self):
  351. base = list(self.ordinary_args())
  352. x = self.special_args()
  353. if x.has_key('positional'):
  354. base.append(x['positional'])
  355. if x.has_key('keyword'):
  356. base.append(x['keyword'])
  357. return base
  358. def defaults(self):
  359. defargs = self.func.func_defaults
  360. args = self.ordinary_args()
  361. mapping = {}
  362. if defargs is not None:
  363. for i in range(-1, -(len(defargs)+1), -1):
  364. mapping[args[i]] = defargs[i]
  365. else:
  366. pass
  367. return mapping
  368. def __repr__(self):
  369. if self.func:
  370. defaults = self.defaults()
  371. specials = self.special_args()
  372. l = []
  373. for arg in self.ordinary_args():
  374. if defaults.has_key(arg):
  375. l.append( arg + '=' + str(defaults[arg]) )
  376. else:
  377. l.append( arg )
  378. if specials.has_key('positional'):
  379. l.append( '*' + specials['positional'] )
  380. if specials.has_key('keyword'):
  381. l.append( '**' + specials['keyword'] )
  382. return "%s(%s)" % (self.name, string.join(l, ', '))
  383. else:
  384. return "%s(?)" % self.name
  385. def aproposAll(obj):
  386. """
  387. Print out a list of all members and methods (including overloaded methods)
  388. of an instance or class
  389. """
  390. apropos(obj, fOverloaded = 1, fTruncate = 0)
  391. def doc(obj):
  392. if (isinstance(obj, types.MethodType)) or \
  393. (isinstance(obj, types.FunctionType)):
  394. print obj.__doc__
  395. def adjust(command = None, dim = 1, parent = None, **kw):
  396. """
  397. adjust(command = None, parent = None, **kw)
  398. Popup and entry scale to adjust a parameter
  399. Accepts any Slider keyword argument. Typical arguments include:
  400. command: The one argument command to execute
  401. min: The min value of the slider
  402. max: The max value of the slider
  403. resolution: The resolution of the slider
  404. text: The label on the slider
  405. These values can be accessed and/or changed after the fact
  406. >>> vg = adjust()
  407. >>> vg['min']
  408. 0.0
  409. >>> vg['min'] = 10.0
  410. >>> vg['min']
  411. 10.0
  412. """
  413. # Make sure we enable Tk
  414. from direct.tkwidgets import Valuator
  415. # Set command if specified
  416. if command:
  417. kw['command'] = lambda x: apply(command, x)
  418. if parent is None:
  419. kw['title'] = command.__name__
  420. kw['dim'] = dim
  421. # Create toplevel if needed
  422. if not parent:
  423. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  424. else:
  425. vg = apply(Valuator.ValuatorGroup,(parent,), kw)
  426. vg.pack(expand = 1, fill = 'x')
  427. return vg
  428. def difference(a, b):
  429. """
  430. difference(list, list):
  431. """
  432. if not a: return b
  433. if not b: return a
  434. d = []
  435. for i in a:
  436. if (i not in b) and (i not in d):
  437. d.append(i)
  438. for i in b:
  439. if (i not in a) and (i not in d):
  440. d.append(i)
  441. return d
  442. def intersection(a, b):
  443. """
  444. intersection(list, list):
  445. """
  446. if not a: return []
  447. if not b: return []
  448. d = []
  449. for i in a:
  450. if (i in b) and (i not in d):
  451. d.append(i)
  452. for i in b:
  453. if (i in a) and (i not in d):
  454. d.append(i)
  455. return d
  456. def union(a, b):
  457. """
  458. union(list, list):
  459. """
  460. # Copy a
  461. c = a[:]
  462. for i in b:
  463. if (i not in c):
  464. c.append(i)
  465. return c
  466. def sameElements(a, b):
  467. if len(a) != len(b):
  468. return 0
  469. for elem in a:
  470. if elem not in b:
  471. return 0
  472. for elem in b:
  473. if elem not in a:
  474. return 0
  475. return 1
  476. def makeList(x):
  477. """returns x, converted to a list"""
  478. if type(x) is types.ListType:
  479. return x
  480. elif type(x) is types.TupleType:
  481. return list(x)
  482. else:
  483. return [x,]
  484. def makeTuple(x):
  485. """returns x, converted to a tuple"""
  486. if type(x) is types.ListType:
  487. return tuple(x)
  488. elif type(x) is types.TupleType:
  489. return x
  490. else:
  491. return (x,)
  492. def list2dict(L, value=None):
  493. """creates dict using elements of list, all assigned to same value"""
  494. return dict([(k,value) for k in L])
  495. def invertDict(D):
  496. """creates a dictionary by 'inverting' D; keys are placed in the new
  497. dictionary under their corresponding value in the old dictionary.
  498. Data will be lost if D contains any duplicate values.
  499. >>> old = {'key1':1, 'key2':2}
  500. >>> invertDict(old)
  501. {1: 'key1', 2: 'key2'}
  502. """
  503. n = {}
  504. for key, value in D.items():
  505. n[value] = key
  506. return n
  507. def invertDictLossless(D):
  508. """similar to invertDict, but values of new dict are lists of keys from
  509. old dict. No information is lost.
  510. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  511. >>> invertDictLossless(old)
  512. {1: ['key1'], 2: ['key2', 'keyA']}
  513. """
  514. n = {}
  515. for key, value in D.items():
  516. n.setdefault(value, [])
  517. n[value].append(key)
  518. return n
  519. def uniqueElements(L):
  520. """are all elements of list unique?"""
  521. return len(L) == len(list2dict(L))
  522. def disjoint(L1, L2):
  523. """returns non-zero if L1 and L2 have no common elements"""
  524. used = dict([(k,None) for k in L1])
  525. for k in L2:
  526. if k in used:
  527. return 0
  528. return 1
  529. def contains(whole, sub):
  530. """
  531. Return 1 if whole contains sub, 0 otherwise
  532. """
  533. if (whole == sub):
  534. return 1
  535. for elem in sub:
  536. # The first item you find not in whole, return 0
  537. if elem not in whole:
  538. return 0
  539. # If you got here, whole must contain sub
  540. return 1
  541. def replace(list, old, new, all=0):
  542. """
  543. replace 'old' with 'new' in 'list'
  544. if all == 0, replace first occurrence
  545. otherwise replace all occurrences
  546. returns the number of items replaced
  547. """
  548. if old not in list:
  549. return 0
  550. if not all:
  551. i = list.index(old)
  552. list[i] = new
  553. return 1
  554. else:
  555. numReplaced = 0
  556. for i in xrange(len(list)):
  557. if list[i] == old:
  558. numReplaced += 1
  559. list[i] = new
  560. return numReplaced
  561. def reduceAngle(deg):
  562. """
  563. Reduces an angle (in degrees) to a value in [-180..180)
  564. """
  565. return (((deg + 180.) % 360.) - 180.)
  566. def fitSrcAngle2Dest(src, dest):
  567. """
  568. given a src and destination angle, returns an equivalent src angle
  569. that is within [-180..180) of dest
  570. examples:
  571. fitSrcAngle2Dest(30,60) == 30
  572. fitSrcAngle2Dest(60,30) == 60
  573. fitSrcAngle2Dest(0,180) == 0
  574. fitSrcAngle2Dest(-1,180) == 359
  575. fitSrcAngle2Dest(-180,180) == 180
  576. """
  577. return dest + reduceAngle(src - dest)
  578. def fitDestAngle2Src(src, dest):
  579. """
  580. given a src and destination angle, returns an equivalent dest angle
  581. that is within [-180..180) of src
  582. examples:
  583. fitDestAngle2Src(30,60) == 60
  584. fitDestAngle2Src(60,30) == 30
  585. fitDestAngle2Src(0,180) == -180
  586. fitDestAngle2Src(1,180) == 180
  587. """
  588. return src + (reduceAngle(dest - src))
  589. def closestDestAngle2(src, dest):
  590. # The function above didn't seem to do what I wanted. So I hacked
  591. # this one together. I can't really say I understand it. It's more
  592. # from impirical observation... GRW
  593. diff = src - dest
  594. if diff > 180:
  595. # if the difference is greater that 180 it's shorter to go the other way
  596. return dest - 360
  597. elif diff < -180:
  598. # or perhaps the OTHER other way...
  599. return dest + 360
  600. else:
  601. # otherwise just go to the original destination
  602. return dest
  603. def closestDestAngle(src, dest):
  604. # The function above didn't seem to do what I wanted. So I hacked
  605. # this one together. I can't really say I understand it. It's more
  606. # from impirical observation... GRW
  607. diff = src - dest
  608. if diff > 180:
  609. # if the difference is greater that 180 it's shorter to go the other way
  610. return src - (diff - 360)
  611. elif diff < -180:
  612. # or perhaps the OTHER other way...
  613. return src - (360 + diff)
  614. else:
  615. # otherwise just go to the original destination
  616. return dest
  617. def binaryRepr(number, max_length = 32):
  618. # This will only work reliably for relatively small numbers.
  619. # Increase the value of max_length if you think you're going
  620. # to use long integers
  621. assert number < 2L << max_length
  622. shifts = map (operator.rshift, max_length * [number], \
  623. range (max_length - 1, -1, -1))
  624. digits = map (operator.mod, shifts, max_length * [2])
  625. if not digits.count (1): return 0
  626. digits = digits [digits.index (1):]
  627. return string.join (map (repr, digits), '')
  628. # constant profile defaults
  629. PyUtilProfileDefaultFilename = 'profiledata'
  630. PyUtilProfileDefaultLines = 80
  631. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  632. # call this from the prompt, and break back out to the prompt
  633. # to stop profiling
  634. #
  635. # OR to do inline profiling, you must make a globally-visible
  636. # function to be profiled, i.e. to profile 'self.load()', do
  637. # something like this:
  638. #
  639. # def func(self=self):
  640. # self.load()
  641. # import __builtin__
  642. # __builtin__.func = func
  643. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  644. # del __builtin__.func
  645. #
  646. def startProfile(filename=PyUtilProfileDefaultFilename,
  647. lines=PyUtilProfileDefaultLines,
  648. sorts=PyUtilProfileDefaultSorts,
  649. silent=0,
  650. callInfo=1,
  651. cmd='run()'):
  652. import profile
  653. profile.run(cmd, filename)
  654. if not silent:
  655. printProfile(filename, lines, sorts, callInfo)
  656. # call this to see the results again
  657. def printProfile(filename=PyUtilProfileDefaultFilename,
  658. lines=PyUtilProfileDefaultLines,
  659. sorts=PyUtilProfileDefaultSorts,
  660. callInfo=1):
  661. import pstats
  662. s = pstats.Stats(filename)
  663. s.strip_dirs()
  664. for sort in sorts:
  665. s.sort_stats(sort)
  666. s.print_stats(lines)
  667. if callInfo:
  668. s.print_callees(lines)
  669. s.print_callers(lines)
  670. def capitalizeFirst(str):
  671. return '%s%s' % (string.upper(str[0]), str[1:])
  672. def getSetterName(valueName, prefix='set'):
  673. # getSetterName('color') -> 'setColor'
  674. # getSetterName('color', 'get') -> 'getColor'
  675. return '%s%s%s' % (prefix, string.upper(valueName[0]), valueName[1:])
  676. def getSetter(targetObj, valueName, prefix='set'):
  677. # getSetter(smiley, 'pos') -> smiley.setPos
  678. return getattr(targetObj, getSetterName(valueName, prefix))
  679. class Functor:
  680. def __init__(self, function, *args, **kargs):
  681. assert callable(function), "function should be a callable obj"
  682. self._function = function
  683. self._args = args
  684. self._kargs = kargs
  685. self.__name__ = 'Functor: %s' % self._function.__name__
  686. self.__doc__ = self._function.__doc__
  687. def __call__(self, *args, **kargs):
  688. """call function"""
  689. _args = list(self._args)
  690. _args.extend(args)
  691. _kargs = self._kargs.copy()
  692. _kargs.update(kargs)
  693. return apply(self._function,_args,_kargs)
  694. class Stack:
  695. def __init__(self):
  696. self.__list = []
  697. def push(self, item):
  698. self.__list.append(item)
  699. def top(self):
  700. # return the item on the top of the stack without popping it off
  701. return self.__list[-1]
  702. def pop(self):
  703. return self.__list.pop()
  704. def clear(self):
  705. self.__list = []
  706. def __len__(self):
  707. return len(self.__list)
  708. """
  709. ParamObj/ParamSet
  710. =================
  711. These two classes support you in the definition of a formal set of
  712. parameters for an object type. The parameters may be safely queried/set on
  713. an object instance at any time, and the object will react to newly-set
  714. values immediately.
  715. ParamSet & ParamObj also provide a mechanism for atomically setting
  716. multiple parameter values before allowing the object to react to any of the
  717. new values--useful when two or more parameters are interdependent and there
  718. is risk of setting an illegal combination in the process of applying a new
  719. set of values.
  720. To make use of these classes, derive your object from ParamObj. Then define
  721. a 'ParamSet' subclass that derives from the parent class' 'ParamSet' class,
  722. and define the object's parameters within its ParamSet class. (see examples
  723. below)
  724. The ParamObj base class provides 'get' and 'set' functions for each
  725. parameter if they are not defined. These default implementations
  726. respectively set the parameter value directly on the object, and expect the
  727. value to be available in that location for retrieval.
  728. Classes that derive from ParamObj can optionally declare a 'get' and 'set'
  729. function for each parameter. The setter should simply store the value in a
  730. location where the getter can find it; it should not do any further
  731. processing based on the new parameter value. Further processing should be
  732. implemented in an 'apply' function. The applier function is optional, and
  733. there is no default implementation.
  734. NOTE: the previous value of a parameter is available inside an apply
  735. function as 'self.getPriorValue()'
  736. The ParamSet class declaration lists the parameters and defines a default
  737. value for each. ParamSet instances represent a complete set of parameter
  738. values. A ParamSet instance created with no constructor arguments will
  739. contain the default values for each parameter. The defaults may be
  740. overriden by passing keyword arguments to the ParamSet's constructor. If a
  741. ParamObj instance is passed to the constructor, the ParamSet will extract
  742. the object's current parameter values.
  743. ParamSet.applyTo(obj) sets all of its parameter values on 'obj'.
  744. SETTERS AND APPLIERS
  745. ====================
  746. Under normal conditions, a call to a setter function, i.e.
  747. cam.setFov(90)
  748. will actually result in the following calls being made:
  749. cam.setFov(90)
  750. cam.applyFov()
  751. Calls to several setter functions, i.e.
  752. cam.setFov(90)
  753. cam.setViewType('cutscene')
  754. will result in this call sequence:
  755. cam.setFov(90)
  756. cam.applyFov()
  757. cam.setViewType('cutscene')
  758. cam.applyViewType()
  759. Suppose that you desire the view type to already be set to 'cutscene' at
  760. the time when applyFov() is called. You could reverse the order of the set
  761. calls, but suppose that you also want the fov to be set properly at the
  762. time when applyViewType() is called.
  763. In this case, you can 'lock' the params, i.e.
  764. cam.lockParams()
  765. cam.setFov(90)
  766. cam.setViewType('cutscene')
  767. cam.unlockParams()
  768. This will result in the following call sequence:
  769. cam.setFov(90)
  770. cam.setViewType('cutscene')
  771. cam.applyFov()
  772. cam.applyViewType()
  773. NOTE: Currently the order of the apply calls following an unlock is not
  774. guaranteed.
  775. EXAMPLE CLASSES
  776. ===============
  777. Here is an example of a class that uses ParamSet/ParamObj to manage its
  778. parameters:
  779. class Camera(ParamObj):
  780. class ParamSet(ParamObj.ParamSet):
  781. Params = {
  782. 'viewType': 'normal',
  783. 'fov': 60,
  784. }
  785. ...
  786. def getViewType(self):
  787. return self.viewType
  788. def setViewType(self, viewType):
  789. self.viewType = viewType
  790. def applyViewType(self):
  791. if self.viewType == 'normal':
  792. ...
  793. def getFov(self):
  794. return self.fov
  795. def setFov(self, fov):
  796. self.fov = fov
  797. def applyFov(self):
  798. base.camera.setFov(self.fov)
  799. ...
  800. EXAMPLE USAGE
  801. =============
  802. cam = Camera()
  803. ...
  804. # set up for the cutscene
  805. savedSettings = cam.ParamSet(cam)
  806. cam.setViewType('closeup')
  807. cam.setFov(90)
  808. ...
  809. # cutscene is over, set the camera back
  810. savedSettings.applyTo(cam)
  811. del savedSettings
  812. """
  813. class ParamObj:
  814. # abstract base for classes that want to support a formal parameter
  815. # set whose values may be queried, changed, 'bulk' changed, and
  816. # extracted/stored/applied all at once (see documentation above)
  817. # ParamSet subclass: container of parameter values. Derived class must
  818. # derive a new ParamSet class if they wish to define new params. See
  819. # documentation above.
  820. class ParamSet:
  821. Params = {
  822. # base class does not define any parameters, but they would
  823. # appear here as 'name': value,
  824. }
  825. def __init__(self, *args, **kwArgs):
  826. self.__class__._compileDefaultParams()
  827. if len(args) == 1 and len(kwArgs) == 0:
  828. # extract our params from an existing ParamObj instance
  829. obj = args[0]
  830. self.paramVals = {}
  831. for param in self.getParams():
  832. self.paramVals[param] = getSetter(obj, param, 'get')()
  833. else:
  834. assert len(args) == 0
  835. if __debug__:
  836. for arg in kwArgs.keys():
  837. assert arg in self.getParams()
  838. self.paramVals = dict(kwArgs)
  839. def getValue(self, param):
  840. if param in self.paramVals:
  841. return self.paramVals[param]
  842. return self._Params[param]
  843. def applyTo(self, obj):
  844. # Apply our entire set of params to a ParamObj
  845. obj.lockParams()
  846. for param in self.getParams():
  847. getSetter(obj, param)(self.getValue(param))
  848. obj.unlockParams()
  849. # CLASS METHODS
  850. def getParams(cls):
  851. # returns safely-mutable list of param names
  852. cls._compileDefaultParams()
  853. return cls._Params.keys()
  854. getParams = classmethod(getParams)
  855. def getDefaultValue(cls, param):
  856. cls._compileDefaultParams()
  857. return cls._Params[param]
  858. getDefaultValue = classmethod(getDefaultValue)
  859. def _compileDefaultParams(cls):
  860. if cls.__dict__.has_key('_Params'):
  861. # we've already compiled the defaults for this class
  862. return
  863. bases = list(cls.__bases__)
  864. # bring less-derived classes to the front
  865. mostDerivedLast(bases)
  866. cls._Params = {}
  867. for c in (bases + [cls]):
  868. # make sure this base has its dict of param defaults
  869. c._compileDefaultParams()
  870. if c.__dict__.has_key('Params'):
  871. # apply this class' default param values to our dict
  872. cls._Params.update(c.Params)
  873. _compileDefaultParams = classmethod(_compileDefaultParams)
  874. # END PARAMSET SUBCLASS
  875. def __init__(self, *args, **kwArgs):
  876. assert(issubclass(self.ParamSet, ParamObj.ParamSet))
  877. # If you pass in a ParamSet obj, its values will be applied to this
  878. # object in the constructor.
  879. params = None
  880. if len(args) == 1 and len(kwArgs) == 0:
  881. # if there's one argument, assume that it's a ParamSet
  882. params = args[0]
  883. elif len(kwArgs) > 0:
  884. assert len(args) == 0
  885. # if we've got keyword arguments, make a ParamSet out of them
  886. params = self.ParamSet(**kwArgs)
  887. self._paramLockRefCount = 0
  888. # this holds dictionaries of parameter values prior to the set that we
  889. # are performing
  890. self._priorValuesStack = Stack()
  891. # this holds the name of the parameter that we are currently modifying
  892. # at the top of the stack
  893. self._curParamStack = Stack()
  894. def setterStub(param, setterFunc, self,
  895. value):
  896. # should we apply the value now or should we wait?
  897. # if this obj's params are locked, we track which values have
  898. # been set, and on unlock, we'll call the applyers for those
  899. # values
  900. if self._paramLockRefCount > 0:
  901. setterFunc(value)
  902. priorValues = self._priorValuesStack.top()
  903. if param not in priorValues:
  904. try:
  905. priorValue = getSetter(self, param, 'get')()
  906. except:
  907. priorValue = None
  908. priorValues[param] = priorValue
  909. self._paramsSet[param] = None
  910. else:
  911. # prepare for call to getPriorValue
  912. self._priorValuesStack.push({
  913. param: getSetter(self, param, 'get')()
  914. })
  915. setterFunc(value)
  916. # call the applier, if there is one
  917. applier = getattr(self, getSetterName(param, 'apply'), None)
  918. if applier is not None:
  919. self._curParamStack.push(param)
  920. applier()
  921. self._curParamStack.pop()
  922. self._priorValuesStack.pop()
  923. if hasattr(self, 'handleParamChange'):
  924. self.handleParamChange((param,))
  925. # insert stub funcs for param setters
  926. for param in self.ParamSet.getParams():
  927. setterName = getSetterName(param)
  928. getterName = getSetterName(param, 'get')
  929. # is there a setter defined?
  930. if not hasattr(self, setterName):
  931. # no; provide the default
  932. def defaultSetter(self, value, param=param):
  933. setattr(self, param, value)
  934. self.__class__.__dict__[setterName] = defaultSetter
  935. # is there a getter defined?
  936. if not hasattr(self, getterName):
  937. # no; provide the default. If there is no value set, return
  938. # the default
  939. def defaultGetter(self, param=param,
  940. default=self.ParamSet.getDefaultValue(param)):
  941. return getattr(self, param, default)
  942. self.__class__.__dict__[getterName] = defaultGetter
  943. # grab a reference to the setter
  944. setterFunc = getattr(self, setterName)
  945. # if the setter is a direct member of this instance, move the setter
  946. # aside
  947. if setterName in self.__dict__:
  948. self.__dict__[setterName + '_MOVED'] = self.__dict__[setterName]
  949. setterFunc = self.__dict__[setterName]
  950. # install a setter stub that will a) call the real setter and
  951. # then the applier, or b) call the setter and queue the
  952. # applier, depending on whether our params are locked
  953. self.__dict__[setterName] = Functor(setterStub, param,
  954. setterFunc, self)
  955. if params is not None:
  956. params.applyTo(self)
  957. def setDefaultParams(self):
  958. # set all the default parameters on ourself
  959. self.ParamSet().applyTo(self)
  960. def lockParams(self):
  961. self._paramLockRefCount += 1
  962. if self._paramLockRefCount == 1:
  963. self._handleLockParams()
  964. def unlockParams(self):
  965. if self._paramLockRefCount > 0:
  966. self._paramLockRefCount -= 1
  967. if self._paramLockRefCount == 0:
  968. self._handleUnlockParams()
  969. def _handleLockParams(self):
  970. # this will store the names of the parameters that are modified
  971. self._paramsSet = {}
  972. # this will store the values of modified params (from prior to
  973. # the lock).
  974. self._priorValuesStack.push({})
  975. def _handleUnlockParams(self):
  976. for param in self._paramsSet:
  977. # call the applier, if there is one
  978. applier = getattr(self, getSetterName(param, 'apply'), None)
  979. if applier is not None:
  980. self._curParamStack.push(param)
  981. applier()
  982. self._curParamStack.pop()
  983. self._priorValuesStack.pop()
  984. if hasattr(self, 'handleParamChange'):
  985. self.handleParamChange(tuple(self._paramsSet.keys()))
  986. del self._paramsSet
  987. def paramsLocked(self):
  988. return self._paramLockRefCount > 0
  989. def getPriorValue(self):
  990. # call this within an apply function to find out what the prior value
  991. # of the param was
  992. return self._priorValuesStack.top()[self._curParamStack.top()]
  993. def __repr__(self):
  994. argStr = ''
  995. for param in self.ParamSet.getParams():
  996. argStr += '%s=%s,' % (param,
  997. repr(getSetter(self, param, 'get')()))
  998. return '%s(%s)' % (self.__class__.__name__, argStr)
  999. """
  1000. POD (Plain Ol' Data)
  1001. Like ParamObj/ParamSet, but without lock/unlock/getPriorValue and without
  1002. appliers. Similar to a C++ struct, but with auto-generated setters and
  1003. getters.
  1004. Use POD when you want the generated getters and setters of ParamObj, but
  1005. efficiency is a concern and you don't need the bells and whistles provided
  1006. by ParamObj.
  1007. POD.__init__ *MUST* be called. You should NOT define your own data getters
  1008. and setters. Data values may be read, set, and modified directly. You will
  1009. see no errors if you define your own getters/setters, but there is no
  1010. guarantee that they will be called--and they will certainly be bypassed by
  1011. POD internally.
  1012. EXAMPLE CLASSES
  1013. ===============
  1014. Here is an example of a class heirarchy that uses POD to manage its data:
  1015. class Enemy(POD):
  1016. DataSet = {
  1017. 'faction': 'navy',
  1018. }
  1019. class Sailor(Enemy):
  1020. DataSet = {
  1021. 'build': HUSKY,
  1022. 'weapon': Cutlass(scale=.9),
  1023. }
  1024. EXAMPLE USAGE
  1025. =============
  1026. s = Sailor(faction='undead', build=SKINNY)
  1027. # make two copies of s
  1028. s2 = s.makeCopy()
  1029. s3 = Sailor(s)
  1030. # example sets
  1031. s2.setWeapon(Musket())
  1032. s3.build = TALL
  1033. # example gets
  1034. faction2 = s2.getFaction()
  1035. faction3 = s3.faction
  1036. """
  1037. class POD:
  1038. DataSet = {
  1039. # base class does not define any data items, but they would
  1040. # appear here as 'name': value,
  1041. }
  1042. def __init__(self, *args, **kwArgs):
  1043. self.__class__._compileDefaultDataSet()
  1044. if len(args) == 1 and len(kwArgs) == 0:
  1045. # extract our dataset from an existing POD instance
  1046. obj = args[0]
  1047. for name in self.getDataNames():
  1048. # if the other obj doesn't have this data item, stick to the
  1049. # default
  1050. if hasattr(obj, name):
  1051. setattr(self, name, getattr(obj, name))
  1052. else:
  1053. setattr(self, name, self.getDefaultValue(name))
  1054. else:
  1055. assert len(args) == 0
  1056. if __debug__:
  1057. for arg in kwArgs.keys():
  1058. assert arg in self.getDataNames(), (
  1059. "unknown argument for %s: '%s'" % (
  1060. self.__class__, arg))
  1061. for name in self.getDataNames():
  1062. if name in kwArgs:
  1063. setattr(self, name, kwArgs[name])
  1064. else:
  1065. setattr(self, name, self.getDefaultValue(name))
  1066. def setDefaultValues(self):
  1067. # set all the default data values on ourself
  1068. for name in self.getDataNames():
  1069. setattr(self, name, self.getDefaultValue(name))
  1070. def makeCopy(self):
  1071. # returns a duplicate of this object
  1072. return self.__class__(self)
  1073. def applyTo(self, obj):
  1074. # Apply our entire set of data to another POD
  1075. for name in self.getDataNames():
  1076. setattr(obj, name, getattr(self, name))
  1077. def getValue(self, name):
  1078. return getattr(self, name)
  1079. # CLASS METHODS
  1080. def getDataNames(cls):
  1081. # returns safely-mutable list of datum names
  1082. cls._compileDefaultDataSet()
  1083. return cls._DataSet.keys()
  1084. getDataNames = classmethod(getDataNames)
  1085. def getDefaultValue(cls, name):
  1086. cls._compileDefaultDataSet()
  1087. return cls._DataSet[name]
  1088. getDefaultValue = classmethod(getDefaultValue)
  1089. def _compileDefaultDataSet(cls):
  1090. if cls.__dict__.has_key('_DataSet'):
  1091. # we've already compiled the defaults for this class
  1092. return
  1093. # create setters & getters for this class
  1094. if cls.__dict__.has_key('DataSet'):
  1095. for name in cls.DataSet:
  1096. def defaultSetter(self, value, name=name):
  1097. setattr(self, name, value)
  1098. cls.__dict__[getSetterName(name)] = defaultSetter
  1099. def defaultGetter(self, name=name,
  1100. default=cls.DataSet[name]):
  1101. return getattr(self, name, default)
  1102. cls.__dict__[getSetterName(name, 'get')] = defaultGetter
  1103. # this dict will hold all of the aggregated default data values for
  1104. # this particular class, including values from its base classes
  1105. cls._DataSet = {}
  1106. bases = list(cls.__bases__)
  1107. # bring less-derived classes to the front
  1108. mostDerivedLast(bases)
  1109. for c in (bases + [cls]):
  1110. # make sure this base has its dict of data defaults
  1111. c._compileDefaultDataSet()
  1112. if c.__dict__.has_key('DataSet'):
  1113. # apply this class' default data values to our dict
  1114. cls._DataSet.update(c.DataSet)
  1115. _compileDefaultDataSet = classmethod(_compileDefaultDataSet)
  1116. # END CLASS METHODS
  1117. def __repr__(self):
  1118. argStr = ''
  1119. for name in self.getDataNames():
  1120. argStr += '%s=%s,' % (name, repr(getattr(self, name)))
  1121. return '%s(%s)' % (self.__class__.__name__, argStr)
  1122. def bound(value, bound1, bound2):
  1123. """
  1124. returns value if value is between bound1 and bound2
  1125. otherwise returns bound that is closer to value
  1126. """
  1127. if bound1 > bound2:
  1128. return min(max(value, bound2), bound1)
  1129. else:
  1130. return min(max(value, bound1), bound2)
  1131. def lerp(v0, v1, t):
  1132. """
  1133. returns a value lerped between v0 and v1, according to t
  1134. t == 0 maps to v0, t == 1 maps to v1
  1135. """
  1136. return v0 + (t * (v1 - v0))
  1137. def average(*args):
  1138. """ returns simple average of list of values """
  1139. val = 0.
  1140. for arg in args:
  1141. val += arg
  1142. return val / len(args)
  1143. def addListsByValue(a, b):
  1144. """
  1145. returns a new array containing the sums of the two array arguments
  1146. (c[0] = a[0 + b[0], etc.)
  1147. """
  1148. c = []
  1149. for x, y in zip(a, b):
  1150. c.append(x + y)
  1151. return c
  1152. def boolEqual(a, b):
  1153. """
  1154. returns true if a and b are both true or both false.
  1155. returns false otherwise
  1156. (a.k.a. xnor -- eXclusive Not OR).
  1157. """
  1158. return (a and b) or not (a or b)
  1159. def lineupPos(i, num, spacing):
  1160. """
  1161. use to line up a series of 'num' objects, in one dimension,
  1162. centered around zero
  1163. 'i' is the index of the object in the lineup
  1164. 'spacing' is the amount of space between objects in the lineup
  1165. """
  1166. assert num >= 1
  1167. assert i >= 0 and i < num
  1168. pos = float(i) * spacing
  1169. return pos - ((float(spacing) * (num-1))/2.)
  1170. def formatElapsedSeconds(seconds):
  1171. """
  1172. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  1173. representing the indicated elapsed time in seconds.
  1174. """
  1175. sign = ''
  1176. if seconds < 0:
  1177. seconds = -seconds
  1178. sign = '-'
  1179. # We use math.floor() instead of casting to an int, so we avoid
  1180. # problems with numbers that are too large to represent as
  1181. # type int.
  1182. seconds = math.floor(seconds)
  1183. hours = math.floor(seconds / (60 * 60))
  1184. if hours > 36:
  1185. days = math.floor((hours + 12) / 24)
  1186. return "%s%d days" % (sign, days)
  1187. seconds -= hours * (60 * 60)
  1188. minutes = (int)(seconds / 60)
  1189. seconds -= minutes * 60
  1190. if hours != 0:
  1191. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  1192. else:
  1193. return "%s%d:%02d" % (sign, minutes, seconds)
  1194. def solveQuadratic(a, b, c):
  1195. # quadratic equation: ax^2 + bx + c = 0
  1196. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  1197. # returns None, root, or [root1, root2]
  1198. # a cannot be zero.
  1199. if a == 0.:
  1200. return None
  1201. # calculate the determinant (b^2 - 4ac)
  1202. D = (b * b) - (4. * a * c)
  1203. if D < 0:
  1204. # there are no solutions (sqrt(negative number) is undefined)
  1205. return None
  1206. elif D == 0:
  1207. # only one root
  1208. return (-b) / (2. * a)
  1209. else:
  1210. # OK, there are two roots
  1211. sqrtD = math.sqrt(D)
  1212. twoA = 2. * a
  1213. root1 = ((-b) - sqrtD) / twoA
  1214. root2 = ((-b) + sqrtD) / twoA
  1215. return [root1, root2]
  1216. def stackEntryInfo(depth=0, baseFileName=1):
  1217. """
  1218. returns the sourcefilename, line number, and function name of
  1219. an entry in the stack.
  1220. 'depth' is how far back to go in the stack; 0 is the caller of this
  1221. function, 1 is the function that called the caller of this function, etc.
  1222. by default, strips off the path of the filename; override with baseFileName
  1223. returns (fileName, lineNum, funcName) --> (string, int, string)
  1224. returns (None, None, None) on error
  1225. """
  1226. try:
  1227. stack = None
  1228. frame = None
  1229. try:
  1230. stack = inspect.stack()
  1231. # add one to skip the frame associated with this function
  1232. frame = stack[depth+1]
  1233. filename = frame[1]
  1234. if baseFileName:
  1235. filename = os.path.basename(filename)
  1236. lineNum = frame[2]
  1237. funcName = frame[3]
  1238. result = (filename, lineNum, funcName)
  1239. finally:
  1240. del stack
  1241. del frame
  1242. except:
  1243. result = (None, None, None)
  1244. return result
  1245. def lineInfo(baseFileName=1):
  1246. """
  1247. returns the sourcefilename, line number, and function name of the
  1248. code that called this function
  1249. (answers the question: 'hey lineInfo, where am I in the codebase?')
  1250. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1251. """
  1252. return stackEntryInfo(1)
  1253. def callerInfo(baseFileName=1):
  1254. """
  1255. returns the sourcefilename, line number, and function name of the
  1256. caller of the function that called this function
  1257. (answers the question: 'hey callerInfo, who called me?')
  1258. see stackEntryInfo, above, for info on 'baseFileName' and return types
  1259. """
  1260. return stackEntryInfo(2)
  1261. def lineTag(baseFileName=1, verbose=0, separator=':'):
  1262. """
  1263. returns a string containing the sourcefilename and line number
  1264. of the code that called this function
  1265. (equivalent to lineInfo, above, with different return type)
  1266. see stackEntryInfo, above, for info on 'baseFileName'
  1267. if 'verbose' is false, returns a compact string of the form
  1268. 'fileName:lineNum:funcName'
  1269. if 'verbose' is true, returns a longer string that matches the
  1270. format of Python stack trace dumps
  1271. returns empty string on error
  1272. """
  1273. fileName, lineNum, funcName = callerInfo()
  1274. if fileName is None:
  1275. return ''
  1276. if verbose:
  1277. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  1278. else:
  1279. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  1280. funcName)
  1281. def findPythonModule(module):
  1282. # Look along the python load path for the indicated filename.
  1283. # Returns the located pathname, or None if the filename is not
  1284. # found.
  1285. filename = module + '.py'
  1286. for dir in sys.path:
  1287. pathname = os.path.join(dir, filename)
  1288. if os.path.exists(pathname):
  1289. return pathname
  1290. return None
  1291. def describeException(backTrace = 4):
  1292. # When called in an exception handler, returns a string describing
  1293. # the current exception.
  1294. def byteOffsetToLineno(code, byte):
  1295. # Returns the source line number corresponding to the given byte
  1296. # offset into the indicated Python code module.
  1297. import array
  1298. lnotab = array.array('B', code.co_lnotab)
  1299. line = code.co_firstlineno
  1300. for i in range(0, len(lnotab),2):
  1301. byte -= lnotab[i]
  1302. if byte <= 0:
  1303. return line
  1304. line += lnotab[i+1]
  1305. return line
  1306. infoArr = sys.exc_info()
  1307. exception = infoArr[0]
  1308. exceptionName = getattr(exception, '__name__', None)
  1309. extraInfo = infoArr[1]
  1310. trace = infoArr[2]
  1311. stack = []
  1312. while trace.tb_next:
  1313. # We need to call byteOffsetToLineno to determine the true
  1314. # line number at which the exception occurred, even though we
  1315. # have both trace.tb_lineno and frame.f_lineno, which return
  1316. # the correct line number only in non-optimized mode.
  1317. frame = trace.tb_frame
  1318. module = frame.f_globals.get('__name__', None)
  1319. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1320. stack.append("%s:%s, " % (module, lineno))
  1321. trace = trace.tb_next
  1322. frame = trace.tb_frame
  1323. module = frame.f_globals.get('__name__', None)
  1324. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1325. stack.append("%s:%s, " % (module, lineno))
  1326. description = ""
  1327. for i in range(len(stack) - 1, max(len(stack) - backTrace, 0) - 1, -1):
  1328. description += stack[i]
  1329. description += "%s: %s" % (exceptionName, extraInfo)
  1330. return description
  1331. def mostDerivedLast(classList):
  1332. """pass in list of classes. sorts list in-place, with derived classes
  1333. appearing after their bases"""
  1334. def compare(a,b):
  1335. if issubclass(a,b):
  1336. result=1
  1337. elif issubclass(b,a):
  1338. result=-1
  1339. else:
  1340. result=0
  1341. #print a,b,result
  1342. return result
  1343. classList.sort(compare)
  1344. def clampScalar(value, a, b):
  1345. # calling this ought to be faster than calling both min and max
  1346. if a < b:
  1347. if value < a:
  1348. return a
  1349. elif value > b:
  1350. return b
  1351. else:
  1352. return value
  1353. else:
  1354. if value < b:
  1355. return b
  1356. elif value > a:
  1357. return a
  1358. else:
  1359. return value
  1360. def weightedChoice(choiceList, rng=random.random, sum=None):
  1361. """given a list of (weight,item) pairs, chooses an item based on the
  1362. weights. rng must return 0..1. if you happen to have the sum of the
  1363. weights, pass it in 'sum'."""
  1364. # TODO: add support for dicts
  1365. if sum is None:
  1366. sum = 0.
  1367. for weight, item in choiceList:
  1368. sum += weight
  1369. rand = rng()
  1370. accum = rand * sum
  1371. for weight, item in choiceList:
  1372. accum -= weight
  1373. if accum <= 0.:
  1374. return item
  1375. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1376. # Or you passed in a 'sum' that was was too large.
  1377. # Return the last item.
  1378. return item
  1379. def randFloat(a, b=0., rng=random.random):
  1380. """returns a random float in [a,b]
  1381. call with single argument to generate random float between arg and zero
  1382. """
  1383. return lerp(a,b,rng())
  1384. def normalDistrib(a, b, gauss=random.gauss):
  1385. """
  1386. NOTE: assumes a < b
  1387. Returns random number between a and b, using gaussian distribution, with
  1388. mean=avg(a,b), and a standard deviation that fits ~99.7% of the curve
  1389. between a and b. Outlying results are clipped to a and b.
  1390. ------------------------------------------------------------------------
  1391. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1392. The 68-95-99.7% Rule
  1393. ====================
  1394. All normal density curves satisfy the following property which is often
  1395. referred to as the Empirical Rule:
  1396. 68% of the observations fall within 1 standard deviation of the mean.
  1397. 95% of the observations fall within 2 standard deviations of the mean.
  1398. 99.7% of the observations fall within 3 standard deviations of the mean.
  1399. Thus, for a normal distribution, almost all values lie within 3 standard
  1400. deviations of the mean.
  1401. ------------------------------------------------------------------------
  1402. In calculating our standard deviation, we divide (b-a) by 6, since the
  1403. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1404. """
  1405. return max(a, min(b, gauss((a+b)*.5, (b-a)/6.)))
  1406. def weightedRand(valDict, rng=random.random):
  1407. """
  1408. pass in a dictionary with a selection -> weight mapping. Eg.
  1409. {"Choice 1" : 10,
  1410. "Choice 2" : 30,
  1411. "bear" : 100}
  1412. -Weights need not add up to any particular value.
  1413. -The actual selection will be returned.
  1414. """
  1415. selections = valDict.keys()
  1416. weights = valDict.values()
  1417. totalWeight = 0
  1418. for weight in weights:
  1419. totalWeight += weight
  1420. # get a random value between 0 and the total of the weights
  1421. randomWeight = rng() * totalWeight
  1422. # find the index that corresponds with this weight
  1423. for i in range(len(weights)):
  1424. totalWeight -= weights[i]
  1425. if totalWeight <= randomWeight:
  1426. return selections[i]
  1427. assert(True, "Should never get here")
  1428. return selections[-1]
  1429. def randUint31(rng=random.random):
  1430. """returns a random integer in [0..2^31).
  1431. rng must return float in [0..1]"""
  1432. return int(rng() * 0x7FFFFFFF)
  1433. def randInt32(rng=random.random):
  1434. """returns a random integer in [-2147483648..2147483647].
  1435. rng must return float in [0..1]
  1436. """
  1437. i = int(rng() * 0x7FFFFFFF)
  1438. if rng() < .5:
  1439. i *= -1
  1440. return i
  1441. def randUint32(rng=random.random):
  1442. """returns a random integer in [0..2^32).
  1443. rng must return float in [0..1]"""
  1444. return long(rng() * 0xFFFFFFFFL)
  1445. class Enum:
  1446. """Pass in list of strings or string of comma-separated strings.
  1447. Items are accessible as instance.item, and are assigned unique,
  1448. increasing integer values. Pass in integer for 'start' to override
  1449. starting value.
  1450. Example:
  1451. >>> colors = Enum('red, green, blue')
  1452. >>> colors.red
  1453. 0
  1454. >>> colors.green
  1455. 1
  1456. >>> colors.blue
  1457. 2
  1458. >>> colors.getString(colors.red)
  1459. 'red'
  1460. """
  1461. if __debug__:
  1462. # chars that cannot appear within an item string.
  1463. InvalidChars = string.whitespace
  1464. def _checkValidIdentifier(item):
  1465. invalidChars = string.whitespace+string.punctuation
  1466. invalidChars = invalidChars.replace('_','')
  1467. invalidFirstChars = invalidChars+string.digits
  1468. if item[0] in invalidFirstChars:
  1469. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  1470. item)
  1471. if not disjoint(item, invalidChars):
  1472. for char in item:
  1473. if char in invalidChars:
  1474. raise SyntaxError, (
  1475. "Enum\n'%s'\ncontains illegal char '%s'" %
  1476. (item, char))
  1477. return 1
  1478. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  1479. def __init__(self, items, start=0):
  1480. if type(items) == types.StringType:
  1481. items = items.split(',')
  1482. self._stringTable = {}
  1483. # make sure we don't overwrite an existing element of the class
  1484. assert(self._checkExistingMembers(items))
  1485. assert(uniqueElements(items))
  1486. i = start
  1487. for item in items:
  1488. # remove leading/trailing whitespace
  1489. item = string.strip(item)
  1490. # is there anything left?
  1491. if len(item) == 0:
  1492. continue
  1493. # make sure there are no invalid characters
  1494. assert(Enum._checkValidIdentifier(item))
  1495. self.__dict__[item] = i
  1496. self._stringTable[i] = item
  1497. i += 1
  1498. def getString(self, value):
  1499. return self._stringTable[value]
  1500. def __contains__(self, value):
  1501. return value in self._stringTable
  1502. def __len__(self):
  1503. return len(self._stringTable)
  1504. if __debug__:
  1505. def _checkExistingMembers(self, items):
  1506. for item in items:
  1507. if hasattr(self, item):
  1508. return 0
  1509. return 1
  1510. ############################################################
  1511. # class: Singleton
  1512. # Purpose: This provides a base metaclass for all classes
  1513. # that require one and only one instance.
  1514. #
  1515. # Example: class mySingleton:
  1516. # __metaclass__ = PythonUtil.Singleton
  1517. # def __init__(self,...):
  1518. # ...
  1519. #
  1520. # Note: This class is based on Python's New-Style Class
  1521. # design. An error will occur if a defined class
  1522. # attemps to inherit from a Classic-Style Class only,
  1523. # ie: class myClassX:
  1524. # def __init__(self, ...):
  1525. # ...
  1526. #
  1527. # class myNewClassX(myClassX):
  1528. # __metaclass__ = PythonUtil.Singleton
  1529. # def __init__(self, ...):
  1530. # myClassX.__init__(self, ...)
  1531. # ...
  1532. #
  1533. # This causes problems because myNewClassX is a
  1534. # New-Style class that inherits from only a
  1535. # Classic-Style base class. There are two ways
  1536. # simple ways to resolve this issue.
  1537. #
  1538. # First, if possible, make myClassX a
  1539. # New-Style class by inheriting from object
  1540. # object. IE: class myClassX(object):
  1541. #
  1542. # If for some reason that is not an option, make
  1543. # myNewClassX inherit from object and myClassX.
  1544. # IE: class myNewClassX(object, myClassX):
  1545. ############################################################
  1546. class Singleton(type):
  1547. def __init__(cls,name,bases,dic):
  1548. super(Singleton,cls).__init__(name,bases,dic)
  1549. cls.instance=None
  1550. def __call__(cls,*args,**kw):
  1551. if cls.instance is None:
  1552. cls.instance=super(Singleton,cls).__call__(*args,**kw)
  1553. return cls.instance
  1554. class SingletonError(ValueError):
  1555. """ Used to indicate an inappropriate value for a Singleton."""