forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonUtil.py
More file actions
2699 lines (2375 loc) · 83.6 KB
/
PythonUtil.py
File metadata and controls
2699 lines (2375 loc) · 83.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Contains miscellaneous utility functions and classes."""
__all__ = [
'indent', 'doc', 'adjust', 'difference', 'intersection', 'union',
'sameElements', 'makeList', 'makeTuple', 'list2dict', 'invertDict',
'invertDictLossless', 'uniqueElements', 'disjoint', 'contains', 'replace',
'reduceAngle', 'fitSrcAngle2Dest', 'fitDestAngle2Src', 'closestDestAngle2',
'closestDestAngle', 'getSetterName', 'getSetter', 'Functor', 'Stack',
'Queue', 'bound', 'clamp', 'lerp', 'average', 'addListsByValue',
'boolEqual', 'lineupPos', 'formatElapsedSeconds', 'solveQuadratic',
'findPythonModule', 'mostDerivedLast', 'clampScalar', 'weightedChoice',
'randFloat', 'normalDistrib', 'weightedRand', 'randUint31', 'randInt32',
'SerialNumGen', 'serialNum', 'uniqueName', 'Enum', 'Singleton',
'SingletonError', 'printListEnum', 'safeRepr', 'fastRepr',
'isDefaultValue', 'ScratchPad', 'Sync', 'itype', 'getNumberedTypedString',
'getNumberedTypedSortedString', 'printNumberedTyped', 'DelayedCall',
'DelayedFunctor', 'FrameDelayedCall', 'SubframeCall', 'getBase',
'GoldenRatio', 'GoldenRectangle', 'rad90', 'rad180', 'rad270', 'rad360',
'nullGen', 'loopGen', 'makeFlywheelGen', 'flywheel', 'listToIndex2item',
'listToItem2index', 'formatTimeCompact', 'deeptype', 'StdoutCapture',
'StdoutPassthrough', 'Averager', 'getRepository', 'formatTimeExact',
'startSuperLog', 'endSuperLog', 'typeName', 'safeTypeName',
'histogramDict', 'unescapeHtmlString',
]
if __debug__:
__all__ += ['StackTrace', 'traceFunctionCall', 'traceParentCall',
'printThisCall', 'stackEntryInfo', 'lineInfo', 'callerInfo',
'lineTag', 'profileFunc', 'profiled', 'startProfile',
'printProfile', 'getProfileResultString', 'printStack',
'printReverseStack']
import types
import math
import os
import sys
import random
import time
import builtins
import importlib
__report_indent = 3
from panda3d.core import ConfigVariableBool
"""
# with one integer positional arg, this uses about 4/5 of the memory of the Functor class below
def Functor(function, *args, **kArgs):
argsCopy = args[:]
def functor(*cArgs, **ckArgs):
kArgs.update(ckArgs)
return function(*(argsCopy + cArgs), **kArgs)
return functor
"""
class Functor:
def __init__(self, function, *args, **kargs):
assert callable(function), "function should be a callable obj"
self._function = function
self._args = args
self._kargs = kargs
if hasattr(self._function, '__name__'):
self.__name__ = self._function.__name__
else:
self.__name__ = str(itype(self._function))
if hasattr(self._function, '__doc__'):
self.__doc__ = self._function.__doc__
else:
self.__doc__ = self.__name__
def destroy(self):
del self._function
del self._args
del self._kargs
del self.__name__
del self.__doc__
def _do__call__(self, *args, **kargs):
_kargs = self._kargs.copy()
_kargs.update(kargs)
return self._function(*(self._args + args), **_kargs)
__call__ = _do__call__
def __repr__(self):
s = 'Functor(%s' % self._function.__name__
for arg in self._args:
try:
argStr = repr(arg)
except:
argStr = 'bad repr: %s' % arg.__class__
s += ', %s' % argStr
for karg, value in list(self._kargs.items()):
s += ', %s=%s' % (karg, repr(value))
s += ')'
return s
class Stack:
def __init__(self):
self.__list = []
def push(self, item):
self.__list.append(item)
def top(self):
# return the item on the top of the stack without popping it off
return self.__list[-1]
def pop(self):
return self.__list.pop()
def clear(self):
self.__list = []
def isEmpty(self):
return len(self.__list) == 0
def __len__(self):
return len(self.__list)
class Queue:
# FIFO queue
# interface is intentionally identical to Stack (LIFO)
def __init__(self):
self.__list = []
def push(self, item):
self.__list.append(item)
def top(self):
# return the next item at the front of the queue without popping it off
return self.__list[0]
def front(self):
return self.__list[0]
def back(self):
return self.__list[-1]
def pop(self):
return self.__list.pop(0)
def clear(self):
self.__list = []
def isEmpty(self):
return len(self.__list) == 0
def __len__(self):
return len(self.__list)
def indent(stream, numIndents, str):
"""
Write str to stream with numIndents in front of it
"""
# To match emacs, instead of a tab character we will use 4 spaces
stream.write(' ' * numIndents + str)
if __debug__:
import traceback
import marshal
class StackTrace:
def __init__(self, label="", start=0, limit=None):
"""
label is a string (or anything that be be a string)
that is printed as part of the trace back.
This is just to make it easier to tell what the
stack trace is referring to.
start is an integer number of stack frames back
from the most recent. (This is automatically
bumped up by one to skip the __init__ call
to the StackTrace).
limit is an integer number of stack frames
to record (or None for unlimited).
"""
self.label = label
if limit is not None:
self.trace = traceback.extract_stack(sys._getframe(1+start),
limit=limit)
else:
self.trace = traceback.extract_stack(sys._getframe(1+start))
def compact(self):
r = ''
comma = ','
for filename, lineNum, funcName, text in self.trace:
r += '%s.%s:%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma)
if len(r):
r = r[:-len(comma)]
return r
def reverseCompact(self):
r = ''
comma = ','
for filename, lineNum, funcName, text in self.trace:
r = '%s.%s:%s%s%s' % (filename[:filename.rfind('.py')][filename.rfind('\\')+1:], funcName, lineNum, comma, r)
if len(r):
r = r[:-len(comma)]
return r
def __str__(self):
r = "Debug stack trace of %s (back %s frames):\n"%(
self.label, len(self.trace),)
for i in traceback.format_list(self.trace):
r+=i
r+="***** NOTE: This is not a crash. This is a debug stack trace. *****"
return r
def printStack():
print(StackTrace(start=1).compact())
return True
def printReverseStack():
print(StackTrace(start=1).reverseCompact())
return True
def printVerboseStack():
print(StackTrace(start=1))
return True
#-----------------------------------------------------------------------------
def traceFunctionCall(frame):
"""
return a string that shows the call frame with calling arguments.
e.g.
foo(x=234, y=135)
"""
f = frame
co = f.f_code
dict = f.f_locals
n = co.co_argcount
if co.co_flags & 4: n = n+1
if co.co_flags & 8: n = n+1
r=''
if 'self' in dict:
r = '%s.'%(dict['self'].__class__.__name__,)
r+="%s("%(f.f_code.co_name,)
comma=0 # formatting, whether we should type a comma.
for i in range(n):
name = co.co_varnames[i]
if name=='self':
continue
if comma:
r+=', '
else:
# ok, we skipped the first one, the rest get commas:
comma=1
r+=name
r+='='
if name in dict:
v=safeRepr(dict[name])
if len(v)>2000:
# r+="<too big for debug>"
r += (v[:2000] + "...")
else:
r+=v
else: r+="*** undefined ***"
return r+')'
def traceParentCall():
return traceFunctionCall(sys._getframe(2))
def printThisCall():
print(traceFunctionCall(sys._getframe(1)))
return 1 # to allow "assert printThisCall()"
# Magic numbers: These are the bit masks in func_code.co_flags that
# reveal whether or not the function has a *arg or **kw argument.
_POS_LIST = 4
_KEY_DICT = 8
def doc(obj):
if (isinstance(obj, types.MethodType)) or \
(isinstance(obj, types.FunctionType)):
print(obj.__doc__)
def adjust(command = None, dim = 1, parent = None, **kw):
"""
adjust(command = None, parent = None, **kw)
Popup and entry scale to adjust a parameter
Accepts any Slider keyword argument. Typical arguments include:
command: The one argument command to execute
min: The min value of the slider
max: The max value of the slider
resolution: The resolution of the slider
text: The label on the slider
These values can be accessed and/or changed after the fact
>>> vg = adjust()
>>> vg['min']
0.0
>>> vg['min'] = 10.0
>>> vg['min']
10.0
"""
# Make sure we enable Tk
# Don't use a regular import, to prevent ModuleFinder from picking
# it up as a dependency when building a .p3d package.
Valuator = importlib.import_module('direct.tkwidgets.Valuator')
# Set command if specified
if command:
kw['command'] = lambda x: command(*x)
if parent is None:
kw['title'] = command.__name__
kw['dim'] = dim
# Create toplevel if needed
if not parent:
vg = Valuator.ValuatorGroupPanel(parent, **kw)
else:
vg = Valuator.ValuatorGroup(parent, **kw)
vg.pack(expand = 1, fill = 'x')
return vg
def difference(a, b):
"""
difference(list, list):
"""
if not a: return b
if not b: return a
d = []
for i in a:
if (i not in b) and (i not in d):
d.append(i)
for i in b:
if (i not in a) and (i not in d):
d.append(i)
return d
def intersection(a, b):
"""
intersection(list, list):
"""
if not a: return []
if not b: return []
d = []
for i in a:
if (i in b) and (i not in d):
d.append(i)
for i in b:
if (i in a) and (i not in d):
d.append(i)
return d
def union(a, b):
"""
union(list, list):
"""
# Copy a
c = a[:]
for i in b:
if (i not in c):
c.append(i)
return c
def sameElements(a, b):
if len(a) != len(b):
return 0
for elem in a:
if elem not in b:
return 0
for elem in b:
if elem not in a:
return 0
return 1
def makeList(x):
"""returns x, converted to a list"""
if type(x) is list:
return x
elif type(x) is tuple:
return list(x)
else:
return [x,]
def makeTuple(x):
"""returns x, converted to a tuple"""
if type(x) is list:
return tuple(x)
elif type(x) is tuple:
return x
else:
return (x,)
def list2dict(L, value=None):
"""creates dict using elements of list, all assigned to same value"""
return dict([(k, value) for k in L])
def listToIndex2item(L):
"""converts list to dict of list index->list item"""
d = {}
for i, item in enumerate(L):
d[i] = item
return d
assert listToIndex2item(['a','b']) == {0: 'a', 1: 'b',}
def listToItem2index(L):
"""converts list to dict of list item->list index
This is lossy if there are duplicate list items"""
d = {}
for i, item in enumerate(L):
d[item] = i
return d
assert listToItem2index(['a','b']) == {'a': 0, 'b': 1,}
def invertDict(D, lossy=False):
"""creates a dictionary by 'inverting' D; keys are placed in the new
dictionary under their corresponding value in the old dictionary.
It is an error if D contains any duplicate values.
>>> old = {'key1':1, 'key2':2}
>>> invertDict(old)
{1: 'key1', 2: 'key2'}
"""
n = {}
for key, value in D.items():
if not lossy and value in n:
raise Exception('duplicate key in invertDict: %s' % value)
n[value] = key
return n
def invertDictLossless(D):
"""similar to invertDict, but values of new dict are lists of keys from
old dict. No information is lost.
>>> old = {'key1':1, 'key2':2, 'keyA':2}
>>> invertDictLossless(old)
{1: ['key1'], 2: ['key2', 'keyA']}
"""
n = {}
for key, value in D.items():
n.setdefault(value, [])
n[value].append(key)
return n
def uniqueElements(L):
"""are all elements of list unique?"""
return len(L) == len(list2dict(L))
def disjoint(L1, L2):
"""returns non-zero if L1 and L2 have no common elements"""
used = dict([(k, None) for k in L1])
for k in L2:
if k in used:
return 0
return 1
def contains(whole, sub):
"""
Return 1 if whole contains sub, 0 otherwise
"""
if (whole == sub):
return 1
for elem in sub:
# The first item you find not in whole, return 0
if elem not in whole:
return 0
# If you got here, whole must contain sub
return 1
def replace(list, old, new, all=0):
"""
replace 'old' with 'new' in 'list'
if all == 0, replace first occurrence
otherwise replace all occurrences
returns the number of items replaced
"""
if old not in list:
return 0
if not all:
i = list.index(old)
list[i] = new
return 1
else:
numReplaced = 0
for i in range(len(list)):
if list[i] == old:
numReplaced += 1
list[i] = new
return numReplaced
rad90 = math.pi / 2.
rad180 = math.pi
rad270 = 1.5 * math.pi
rad360 = 2. * math.pi
def reduceAngle(deg):
"""
Reduces an angle (in degrees) to a value in [-180..180)
"""
return (((deg + 180.) % 360.) - 180.)
def fitSrcAngle2Dest(src, dest):
"""
given a src and destination angle, returns an equivalent src angle
that is within [-180..180) of dest
examples:
fitSrcAngle2Dest(30, 60) == 30
fitSrcAngle2Dest(60, 30) == 60
fitSrcAngle2Dest(0, 180) == 0
fitSrcAngle2Dest(-1, 180) == 359
fitSrcAngle2Dest(-180, 180) == 180
"""
return dest + reduceAngle(src - dest)
def fitDestAngle2Src(src, dest):
"""
given a src and destination angle, returns an equivalent dest angle
that is within [-180..180) of src
examples:
fitDestAngle2Src(30, 60) == 60
fitDestAngle2Src(60, 30) == 30
fitDestAngle2Src(0, 180) == -180
fitDestAngle2Src(1, 180) == 180
"""
return src + (reduceAngle(dest - src))
def closestDestAngle2(src, dest):
# The function above didn't seem to do what I wanted. So I hacked
# this one together. I can't really say I understand it. It's more
# from impirical observation... GRW
diff = src - dest
if diff > 180:
# if the difference is greater that 180 it's shorter to go the other way
return dest - 360
elif diff < -180:
# or perhaps the OTHER other way...
return dest + 360
else:
# otherwise just go to the original destination
return dest
def closestDestAngle(src, dest):
# The function above didn't seem to do what I wanted. So I hacked
# this one together. I can't really say I understand it. It's more
# from impirical observation... GRW
diff = src - dest
if diff > 180:
# if the difference is greater that 180 it's shorter to go the other way
return src - (diff - 360)
elif diff < -180:
# or perhaps the OTHER other way...
return src - (360 + diff)
else:
# otherwise just go to the original destination
return dest
class StdoutCapture:
# redirects stdout to a string
def __init__(self):
self._oldStdout = sys.stdout
sys.stdout = self
self._string = ''
def destroy(self):
sys.stdout = self._oldStdout
del self._oldStdout
def getString(self):
return self._string
# internal
def write(self, string):
self._string = ''.join([self._string, string])
class StdoutPassthrough(StdoutCapture):
# like StdoutCapture but also allows output to go through to the OS as normal
# internal
def write(self, string):
self._string = ''.join([self._string, string])
self._oldStdout.write(string)
# constant profile defaults
if __debug__:
from io import StringIO
PyUtilProfileDefaultFilename = 'profiledata'
PyUtilProfileDefaultLines = 80
PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
_ProfileResultStr = ''
def getProfileResultString():
# if you called profile with 'log' not set to True,
# you can call this function to get the results as
# a string
global _ProfileResultStr
return _ProfileResultStr
def profileFunc(callback, name, terse, log=True):
global _ProfileResultStr
if 'globalProfileFunc' in builtins.__dict__:
# rats. Python profiler is not re-entrant...
base.notify.warning(
'PythonUtil.profileStart(%s): aborted, already profiling %s'
#'\nStack Trace:\n%s'
% (name, builtins.globalProfileFunc,
#StackTrace()
))
return
builtins.globalProfileFunc = callback
builtins.globalProfileResult = [None]
prefix = '***** START PROFILE: %s *****' % name
if log:
print(prefix)
startProfile(cmd='globalProfileResult[0]=globalProfileFunc()', callInfo=(not terse), silent=not log)
suffix = '***** END PROFILE: %s *****' % name
if log:
print(suffix)
else:
_ProfileResultStr = '%s\n%s\n%s' % (prefix, _ProfileResultStr, suffix)
result = globalProfileResult[0]
del builtins.__dict__['globalProfileFunc']
del builtins.__dict__['globalProfileResult']
return result
def profiled(category=None, terse=False):
""" decorator for profiling functions
turn categories on and off via "want-profile-categoryName 1"
e.g.::
@profiled('particles')
def loadParticles():
...
::
want-profile-particles 1
"""
assert type(category) in (str, type(None)), "must provide a category name for @profiled"
# allow profiling in published versions
"""
try:
null = not __dev__
except:
null = not __debug__
if null:
# if we're not in __dev__, just return the function itself. This
# results in zero runtime overhead, since decorators are evaluated
# at module-load.
def nullDecorator(f):
return f
return nullDecorator
"""
def profileDecorator(f):
def _profiled(*args, **kArgs):
name = '(%s) %s from %s' % (category, f.__name__, f.__module__)
# showbase might not be loaded yet, so don't use
# base.config. Instead, query the ConfigVariableBool.
if (category is None) or ConfigVariableBool('want-profile-%s' % category, 0).getValue():
return profileFunc(Functor(f, *args, **kArgs), name, terse)
else:
return f(*args, **kArgs)
_profiled.__doc__ = f.__doc__
return _profiled
return profileDecorator
# intercept profile-related file operations to avoid disk access
movedOpenFuncs = []
movedDumpFuncs = []
movedLoadFuncs = []
profileFilenames = set()
profileFilenameList = Stack()
profileFilename2file = {}
profileFilename2marshalData = {}
def _profileOpen(filename, *args, **kArgs):
# this is a replacement for the file open() builtin function
# for use during profiling, to intercept the file open
# operation used by the Python profiler and profile stats
# systems
if filename in profileFilenames:
# if this is a file related to profiling, create an
# in-RAM file object
if filename not in profileFilename2file:
file = StringIO()
file._profFilename = filename
profileFilename2file[filename] = file
else:
file = profileFilename2file[filename]
else:
file = movedOpenFuncs[-1](filename, *args, **kArgs)
return file
def _profileMarshalDump(data, file):
# marshal.dump doesn't work with StringIO objects
# simulate it
if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
if file._profFilename in profileFilenames:
profileFilename2marshalData[file._profFilename] = data
return None
return movedDumpFuncs[-1](data, file)
def _profileMarshalLoad(file):
# marshal.load doesn't work with StringIO objects
# simulate it
if isinstance(file, StringIO) and hasattr(file, '_profFilename'):
if file._profFilename in profileFilenames:
return profileFilename2marshalData[file._profFilename]
return movedLoadFuncs[-1](file)
def _installProfileCustomFuncs(filename):
assert filename not in profileFilenames
profileFilenames.add(filename)
profileFilenameList.push(filename)
movedOpenFuncs.append(builtins.open)
builtins.open = _profileOpen
movedDumpFuncs.append(marshal.dump)
marshal.dump = _profileMarshalDump
movedLoadFuncs.append(marshal.load)
marshal.load = _profileMarshalLoad
def _getProfileResultFileInfo(filename):
return (profileFilename2file.get(filename, None),
profileFilename2marshalData.get(filename, None))
def _setProfileResultsFileInfo(filename, info):
f, m = info
if f:
profileFilename2file[filename] = f
if m:
profileFilename2marshalData[filename] = m
def _clearProfileResultFileInfo(filename):
profileFilename2file.pop(filename, None)
profileFilename2marshalData.pop(filename, None)
def _removeProfileCustomFuncs(filename):
assert profileFilenameList.top() == filename
marshal.load = movedLoadFuncs.pop()
marshal.dump = movedDumpFuncs.pop()
builtins.open = movedOpenFuncs.pop()
profileFilenames.remove(filename)
profileFilenameList.pop()
profileFilename2file.pop(filename, None)
# don't let marshalled data pile up
profileFilename2marshalData.pop(filename, None)
# call this from the prompt, and break back out to the prompt
# to stop profiling
#
# OR to do inline profiling, you must make a globally-visible
# function to be profiled, i.e. to profile 'self.load()', do
# something like this:
#
# def func(self=self):
# self.load()
# import builtins
# builtins.func = func
# PythonUtil.startProfile(cmd='func()', filename='profileData')
# del builtins.func
#
def _profileWithoutGarbageLeak(cmd, filename):
# The profile module isn't necessarily installed on every Python
# installation, so we import it here, instead of in the module
# scope.
import profile
# this is necessary because the profile module creates a memory leak
Profile = profile.Profile
statement = cmd
sort = -1
retVal = None
#### COPIED FROM profile.run ####
prof = Profile()
try:
prof = prof.run(statement)
except SystemExit:
pass
if filename is not None:
prof.dump_stats(filename)
else:
#return prof.print_stats(sort) #DCR
retVal = prof.print_stats(sort) #DCR
#################################
# eliminate the garbage leak
del prof.dispatcher
return retVal
def startProfile(filename=PyUtilProfileDefaultFilename,
lines=PyUtilProfileDefaultLines,
sorts=PyUtilProfileDefaultSorts,
silent=0,
callInfo=1,
useDisk=False,
cmd='run()'):
# uniquify the filename to allow multiple processes to profile simultaneously
filename = '%s.%s%s' % (filename, randUint31(), randUint31())
if not useDisk:
# use a RAM file
_installProfileCustomFuncs(filename)
_profileWithoutGarbageLeak(cmd, filename)
if silent:
extractProfile(filename, lines, sorts, callInfo)
else:
printProfile(filename, lines, sorts, callInfo)
if not useDisk:
# discard the RAM file
_removeProfileCustomFuncs(filename)
else:
os.remove(filename)
# call these to see the results again, as a string or in the log
def printProfile(filename=PyUtilProfileDefaultFilename,
lines=PyUtilProfileDefaultLines,
sorts=PyUtilProfileDefaultSorts,
callInfo=1):
import pstats
s = pstats.Stats(filename)
s.strip_dirs()
for sort in sorts:
s.sort_stats(sort)
s.print_stats(lines)
if callInfo:
s.print_callees(lines)
s.print_callers(lines)
# same args as printProfile
def extractProfile(*args, **kArgs):
global _ProfileResultStr
# capture print output
sc = StdoutCapture()
# print the profile output, redirected to the result string
printProfile(*args, **kArgs)
# make a copy of the print output
_ProfileResultStr = sc.getString()
# restore stdout to what it was before
sc.destroy()
def getSetterName(valueName, prefix='set'):
# getSetterName('color') -> 'setColor'
# getSetterName('color', 'get') -> 'getColor'
return '%s%s%s' % (prefix, valueName[0].upper(), valueName[1:])
def getSetter(targetObj, valueName, prefix='set'):
# getSetter(smiley, 'pos') -> smiley.setPos
return getattr(targetObj, getSetterName(valueName, prefix))
def mostDerivedLast(classList):
"""pass in list of classes. sorts list in-place, with derived classes
appearing after their bases"""
class ClassSortKey(object):
__slots__ = 'classobj',
def __init__(self, classobj):
self.classobj = classobj
def __lt__(self, other):
return issubclass(other.classobj, self.classobj)
classList.sort(key=ClassSortKey)
def bound(value, bound1, bound2):
"""
returns value if value is between bound1 and bound2
otherwise returns bound that is closer to value
"""
if bound1 > bound2:
return min(max(value, bound2), bound1)
else:
return min(max(value, bound1), bound2)
clamp = bound
def lerp(v0, v1, t):
"""
returns a value lerped between v0 and v1, according to t
t == 0 maps to v0, t == 1 maps to v1
"""
return v0 + ((v1 - v0) * t)
def getShortestRotation(start, end):
"""
Given two heading values, return a tuple describing
the shortest interval from 'start' to 'end'. This tuple
can be used to lerp a camera between two rotations
while avoiding the 'spin' problem.
"""
start, end = start % 360, end % 360
if abs(end - start) > 180:
if end < start:
end += 360
else:
start += 360
return (start, end)
def average(*args):
""" returns simple average of list of values """
val = 0.
for arg in args:
val += arg
return val / len(args)
class Averager:
def __init__(self, name):
self._name = name
self.reset()
def reset(self):
self._total = 0.
self._count = 0
def addValue(self, value):
self._total += value
self._count += 1
def getAverage(self):
return self._total / self._count
def getCount(self):
return self._count
def addListsByValue(a, b):
"""
returns a new array containing the sums of the two array arguments
(c[0] = a[0 + b[0], etc.)
"""
c = []
for x, y in zip(a, b):
c.append(x + y)
return c
def boolEqual(a, b):
"""
returns true if a and b are both true or both false.
returns false otherwise
(a.k.a. xnor -- eXclusive Not OR).
"""
return (a and b) or not (a or b)
def lineupPos(i, num, spacing):
"""
use to line up a series of 'num' objects, in one dimension,
centered around zero
'i' is the index of the object in the lineup
'spacing' is the amount of space between objects in the lineup
"""
assert num >= 1
assert i >= 0 and i < num
pos = float(i) * spacing
return pos - ((float(spacing) * (num-1))/2.)
def formatElapsedSeconds(seconds):
"""
Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
representing the indicated elapsed time in seconds.
"""
sign = ''
if seconds < 0:
seconds = -seconds
sign = '-'
# We use math.floor() instead of casting to an int, so we avoid
# problems with numbers that are too large to represent as
# type int.
seconds = math.floor(seconds)
hours = math.floor(seconds / (60 * 60))
if hours > 36:
days = math.floor((hours + 12) / 24)
return "%s%d days" % (sign, days)
seconds -= hours * (60 * 60)
minutes = (int)(seconds / 60)
seconds -= minutes * 60
if hours != 0:
return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
else:
return "%s%d:%02d" % (sign, minutes, seconds)
def solveQuadratic(a, b, c):
# quadratic equation: ax^2 + bx + c = 0
# quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
# returns None, root, or [root1, root2]
# a cannot be zero.
if a == 0.:
return None
# calculate the determinant (b^2 - 4ac)
D = (b * b) - (4. * a * c)
if D < 0:
# there are no solutions (sqrt(negative number) is undefined)
return None
elif D == 0:
# only one root
return (-b) / (2. * a)
else:
# OK, there are two roots
sqrtD = math.sqrt(D)
twoA = 2. * a
root1 = ((-b) - sqrtD) / twoA
root2 = ((-b) + sqrtD) / twoA
return [root1, root2]
if __debug__:
def stackEntryInfo(depth=0, baseFileName=1):
"""
returns the sourcefilename, line number, and function name of
an entry in the stack.
'depth' is how far back to go in the stack; 0 is the caller of this
function, 1 is the function that called the caller of this function, etc.
by default, strips off the path of the filename; override with baseFileName
returns (fileName, lineNum, funcName) --> (string, int, string)
returns (None, None, None) on error
"""
import inspect
try: