PythonUtil.py 57 KB

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