-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
executable file
·4669 lines (3615 loc) · 142 KB
/
tools.py
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
"""A collection of tools, tips, and tricks.
2009-07-20 22:36 IJC: Created
2010-10-28 11:53 IJMC: Updated documentation for Sphinx.
2011-06-15 09:34 IJMC: More functions have been added; cleaned documentation.
"""
import pdb
import numpy as np
def getfigs():
"""Return a list of all open matplotlib figures.
No inputs or options."""
from matplotlib._pylab_helpers import Gcf
figs = [manager.canvas.figure for manager in Gcf.get_all_fig_managers()]
figlist = [fig.number for fig in figs]
return figlist
def nextfig():
"""Return one greater than the largest-numbered figure currently
open. If no figures are open, return unity.
No inputs or options."""
# 2010-03-01 14:28 IJC: Created
figlist = getfigs()
if len(figlist)==0:
return 1
else:
return max(figlist)+1
return figlist
def printfigs(filename, figs=None, format=None, pdfmode='texexec', verbose=False, closefigs=False):
"""Print desired figures using designated 'format'. Concatenate PDFs.
:Inputs:
filename -- string. prepended to all open figures
figs -- int or list.
figures to access, then apply savefig to. If None, print
all open figures; if -1, print current figure.
format -- string or list of strings.
if 'pdf', all images are concatenated into one file (use
"pdfs" for individual pdf figure files)
pdfmode -- string;
method of concatenating PDFs. Either 'texexec' or 'gs'
(for GhostScript) or 'tar' to wrap individual
figures in a Tarball.
closefigs -- bool
If True, close each figure after printing it to disk.
:NOTES:
If no explicit path is passed and a subdirectory 'figures'
exists in the current directory, the figures will be printed in
'figures' instead.
:EXAMPLE:
::
from pylab import *
figure(1); plot(arange(10), randn(10), 'ob')
figure(2); plot(arange(15), randn(15), '-xr')
printfigs('testing')
!open testing.pdf
"""
# 2009-07-20 23:10 IJC: Created; inspired by FGD.
# 2009-09-08 13:54 IJC: Made it work with single-figure, non-list input.
# 2010-02-02 11:50 IJC: Now it kills the 'logfile' detritus.
# 2010-10-27 17:05 IJC: New texexec syntax is "result=...", not "result ..."
# 2011-03-01 18:14 IJC: Added capability for multiple formats (in
# a list). Also, figure numbers are not
# catted to the filename when saving a
# single figure.
# 2011-08-29 10:23 IJMC: Now don't try to concatenate single PDF figures.
# 2012-11-01 11:41 IJMC: Slightly changed if-block for 'figs'.
# 2014-05-03 15:04 IJMC: Added 'closefigs' flag.
# 2014-09-02 08:50 IJMC: Added 'tar' PDFMODE
# 2015-12-08 09:03 IJMC: Now 'None' is also valid PDF mode
from pylab import savefig, figure, gcf, close
from matplotlib._pylab_helpers import Gcf
import os
import pdb
figlist = getfigs()
if verbose: print "Available figure numbers>>" ,figlist
if figs is None:
figs = figlist
elif figs is -1:
figs = [gcf().number]
else:
if hasattr(figs, '__iter__'):
figs = list(figs)
else:
figs = [figs]
figlist = [val for val in figs if val in figlist]
nfig = len(figlist)
print "Figures to print>>",figlist
if format==None:
format = filename[-3::]
filename = filename[0:len(filename)-4]
if hasattr(format, 'capitalize'):
format = [format]
nformat = 1
elif hasattr(format, '__iter__'):
nformat = len(format)
else:
format = [str(format)]
nformat = 1
if len(figlist)==0:
print "No open figures found; exiting."
return
for thisformat in format:
fnamelist = []
for ii in range(nfig):
if nfig>1:
fname = filename + str(figlist[ii])
else:
fname = filename
if thisformat=='pdf' and nfig>1:
fname = fname + '_temp'
if thisformat=='pdfs':
fname = fname + '.pdf'
else:
fname = fname + '.' + thisformat
figure(figlist[ii])
savefig(fname )
fnamelist.append(fname)
if closefigs and thisformat==format[-1]: # last time at this figure
close(figlist[ii])
if thisformat=='pdf':
if nfig==1:
savefig(fnamelist[0])
else: # we have to concatenate multiple PDF figures:
bigfilename = filename + '.' + thisformat
if os.path.isfile(bigfilename):
os.remove(bigfilename)
if pdfmode is None:
execstr, rmstr = '', ''
elif pdfmode=='gs':
execstr = 'gs -q -sPAPERSIZE=letter -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=' + bigfilename
rmstr = ''
elif pdfmode=='texexec':
execstr = 'texexec --pdfcopy --result=' + bigfilename
rmstr = 'rm %s' % bigfilename.replace('pdf','log')
elif pdfmode[0:3]=='tar':
execstr = 'tar -cvf %s ' % bigfilename.replace('pdf','tar')
fnamelist_local = [os.path.split(fn)[1] for fn in fnamelist]
[os.rename(fn, fn2) for fn,fn2 in zip(fnamelist, fnamelist_local)]
rmstr = 'rm ' + ' '.join(fnamelist_local)
fnamelist = fnamelist_local
else:
execstr = ''
rmstr = ''
for fn in fnamelist:
execstr += ' ' + fn
#pdb.set_trace()
if verbose: print "PDFMODE exec call>>", execstr
os.system(execstr)
#pdb.set_trace()
if len(rmstr)>0:
os.system(rmstr)
if pdfmode is not None:
for fn in fnamelist:
try:
os.remove(fn)
except:
pass
return
def plotstyle(i, c=['b', 'g', 'r', 'c', 'm', 'y', 'k'], \
s=['.', 'x', 's', '^', '*', 'o', '+', 'v', 'p', 'D'], \
l=['-', '--', '-.', ':']):
"""Return plot properties to help distinguish many types of plot symbols.
:INPUT:
i -- int.
:OPTIONAL INPUT:
c -- color, or list of colors accepted by pylab.plot
s -- symbol, or list of symbols accepted by pylab.plot
l -- linestyle, or list of linestyles accepted by pylab.plot
:OUTPUT:
tuple of (color, symbol, linestyle)
:REQUIREMENTS: :doc:`numpy`
"""
# 2009-09-10 16:42 IJC: Created
from numpy import tile, array
if not c.__class__==list:
c = list(c)
if not s.__class__==list:
s = list(s)
if not l.__class__==list:
l = list(l)
nc = len(c)
ns = len(s)
nl = len(l)
if not hasattr(i,'__iter__'):
i = array([i])
i = abs(array(i))
nrepc = (max(i)/nc+1.).astype(int)
nreps = (max(i)/ns+1.).astype(int)
nrepl = (max(i)/nl+1.).astype(int)
c = tile(c, nrepc)
s = tile(s, nreps)
l = tile(l, nrepl)
if len(i)==1:
ret = c[i][0], s[i][0], l[i][0]
else:
ret = list(c[i]),list(s[i]),list(l[i])
return ret
def flatten(L, maxdepth=100):
"""Flatten a list.
Stolen from http://mail.python.org/pipermail/tutor/2001-January/002914.html"""
# 2009-09-10 16:54 IJC: Input.
if type(L) != type([]): return [L]
if L == []:
return L
else:
maxdepth -= 1
return flatten(L[0]) + flatten(L[1:], maxdepth=maxdepth)
def replaceall(seq, obj, rep):
"""Replace all instances of 'obj' with 'rep' in list 'seq'
:INPUT:
seq -- (list) list within which to find-and-replace elements
obj -- target object to replace
rep -- replacement object
:EXAMPLE:
::
import tools
b = [2, ['spam', ['eggs', 5, dict(spam=3)]]]
tools.replaceall(b, 'spam', 'bacon')
print b
:NOTES:
-- Will fail if 'obj' is itself a list.
-- Edits list in-place, so make a copy first if you want to
retain the old version of your list.
-- Has not been tested for extremely deep lists
:SEE ALSO:
:func:`popall`
"""
#2009-09-11 10:22 IJC: Created
n = len(seq)
for ii in range(n):
if seq[ii].__class__==list:
replaceall(seq[ii], obj, rep)
else:
if seq[ii]==obj:
seq[ii]=rep
return
def popall(seq, obj):
"""Remove all instances of 'obj' from list 'seq'
:INPUT:
seq -- (list) list from which to pop elements
obj -- target object to remove
:EXAMPLE:
::
import tools
b = [3, 'spam', range(5)]
tools.popall(b, 4)
print b
:NOTES:
-- Will fail if 'obj' is itself a list.
-- Edits list in-place, so make a copy first if you want to
retain the old version of your list.
-- Has not been tested for extremely deep lists
:SEE ALSO:
:func:`replaceall`
"""
#2009-09-11 10:22 IJC: Created
n = len(seq)
for ii in range(n):
print ii,seq[ii]
if seq[ii].__class__==list:
popall(seq[ii], obj)
doneYet = False
while not doneYet:
try:
seq.remove(obj)
except:
doneYet = True
return
def drawRectangle(x,y,width,height,**kw):
"""Draw a rectangle patch on the current, or specified, axes.
:INPUT:
x, y -- lower-left corner of rectangle
width, height -- dimensions of rectangle
:OPTIONAL INPUT:
ax -- Axis to draw upon. if None, defaults to current axes.
dodraw -- if True, call 'draw()' function to immediately re-draw axes.
**kw -- options passable to :func:`matplotlib.patches.Rectangle`
:NOTE: Axes will NOT auto-rescale after this is called.
"""
# 2009-09-17 01:33 IJC: Created
# 2014-03-01 13:51 IJMC: Added 'dodraw' option.
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
if kw.has_key('ax'):
ax = kw.pop('ax')
else:
ax = plt.gca()
p = mpatches.Rectangle((x,y), width, height, **kw)
ax.add_patch(p)
if kw.has_key('dodraw') and kw['dodraw']: plt.draw()
return ax, p
def drawPolygon(xy,**kw):
"""Draw a rectangle patch on the current, or specified, axes.
:INPUT:
xy -- numpy array of coordinates, with shape Nx2.
:OPTIONAL INPUT:
ax -- Axis to draw upon. if None, defaults to current axes.
dodraw -- if True, call 'draw()' function to immediately re-draw axes.
**kw -- options passable to :func:`matplotlib.patches.Polygon`
:SEE ALSO:
:func:`drawRectangle`
:NOTE: Axes will NOT auto-rescale after this is called.
"""
# 2010-12-02 19:58 IJC: Created from drawRectangle
# 2014-03-01 13:51 IJMC: Added 'dodraw' option.
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
if kw.has_key('ax'):
ax = kw.pop('ax')
else:
ax = plt.gca()
p = mpatches.Polygon(xy, **kw)
ax.add_patch(p)
if kw.has_key('dodraw') and kw['dodraw']: plt.draw()
return ax, p
def drawCircle(x,y,radius,**kw):
"""Draw a circular patch on the current, or specified, axes.
:INPUT:
x, y -- center of circle
radius -- radius of circle
:OPTIONAL INPUT:
ax -- Axis to draw upon. if None, defaults to current axes.
dodraw -- if True, call 'draw()' function to immediately re-draw axes.
**kw -- options passable to :func:`matplotlib.patches.Circle`
:NOTE: Axes will NOT auto-rescale after this is called.
"""
# 2011-01-28 16:03 IJC: Created
# 2014-03-01 13:51 IJMC: Added 'dodraw' option.
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
if kw.has_key('ax'):
ax = kw.pop('ax')
else:
ax = plt.gca()
p = mpatches.Circle((x,y), radius, **kw)
ax.add_patch(p)
if kw.has_key('dodraw') and kw['dodraw']: plt.draw()
return ax, p
def drawEllipse(x,y,width, height,**kw):
"""Draw an elliptical patch on the current, or specified, axes.
:INPUT:
x, y -- center of ellipse
width -- width of ellipse
height -- width of ellipse
:OPTIONAL INPUT:
ax -- Axis to draw upon. if None, defaults to current axes.
dodraw -- if True, call 'draw()' function to immediately re-draw axes.
**kw -- options passable to :func:`matplotlib.patches.Ellipse`
(angle, linewidth, fill, ...)
:NOTE: Axes will NOT auto-rescale after this is called.
:SEE_ALSO:
:func:`drawCircle`, :func:`drawRectangle`
"""
# 2011-10-20 11:32 IJMC: Created
# 2014-03-01 13:51 IJMC: Added 'dodraw' option.
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
if kw.has_key('ax'):
ax = kw.pop('ax')
else:
ax = plt.gca()
p = mpatches.Ellipse((x,y), width, height, **kw)
ax.add_patch(p)
if kw.has_key('dodraw') and kw['dodraw']: plt.draw()
return ax, p
def errxy(x,y,xbins, xmode='mean', ymode='mean', xerr='minmax', yerr='sdom', clean=None, binfactor=None, verbose=False,returnstats=False, timing=False):
"""Bin down datasets in X and Y for errorbar plotting
:INPUTS:
x -- (array) independent variable data
y -- (array) dependent variable data
xbins -- (array) edges of bins, in x-space. Only x-data
between two bin edges will be used. Thus if M bin
edges are entered, (M-1) datapoints will be returned.
If xbins==None, then no binning is done.
:OPTIONAL INPUT:
xmode/ymode -- (str) method to aggregate x/y data into datapoints:
'mean' -- use numpy.mean
'median' -- use numpy.median
'sum' -- use numpy.sum
None -- don't compute; return the empty list []
xerr/yerr -- (str) method to aggregate x/y data into errorbars
'std' -- sample standard deviation (numpy.std)
'sdom' -- standard deviation on the mean; i.e., std/sqrt(N)
'minmax' -- use full range of data in the bin
None -- don't compute; return the empty list []
binfactor -- (int) If not None, average over this many
consecutive values instead of binning explicitly by
time-based bins. Can also be a sequence, telling the
number of values over which to average. E.g.,
binfactor=[10,10,20] will bin over the first 10 points,
the second 10 points, and the next 20 points.
clean -- (dict) keyword options to clean y-data ONLY, via
analysis.removeoutliers, with an additional "nsigma"
keyword. See removeoutliers for more information.
E.g.: clean=dict(nsigma=5,remove='both',niter=1)
:OUTPUTS: a tuple of four arrays to be passed to matplotlib.pyplot.errorbar:
xx -- locations of the aggregated x-datapoint in each bin
yy -- locations of the aggregated y-datapoint in each bin
xerr -- x-errorbars
yerr -- y-errorbars
:EXAMPLE:
::
x = hstack((arange(10), arange(20)+40))
y = randn(len(x))
xbins = [-1,15,70]
xx,yy,xerr,yerr = errxy(x,y,xbins)
plot(x,y, '.b')
errorbar(xx,yy,xerr=xerr,yerr=yerr, fmt='or')
:NOTES:
To just bin down uncleaned data (i.e., no 'error' terms
returned), set clean, xerr, yerr to None. However, when
computing all values (xerr and yerr not None) it is faster
to set clean to some rediculous value, i.e.,
clean=dict(niter=0, nsigma=9e99). This probably means more
optimization could be done.
Be sure you call the errorbar function using the keywords xerr
and yerr, since otherwise the default order of inputs to the
function is (x,y,yerr,xerr).
Data 'x' are determined to be in a bin with sides (L, R) when
satisfying the condition (x>L) and (x<=R)
:SEE ALSO: matplotlib.pyplot.errorbar, :func:`analysis.removeoutliers`
:REQUIREMENTS: :doc:`numpy`, :doc:`analysis`
"""
# 2009-09-29 20:07 IJC: Created w/mean-median and std-sdom-minmax.
# 2009-12-14 16:01 IJC: xbins can be 'None' for no binning.
# 2009-12-15 10:09 IJC: Added "binfactor" option.
# 2009-12-22 09:56 IJC: "binfactor" can now be a sequence.
# 2009-12-29 01:16 IJC: Fixed a bug with binfactor sequences.
# 2010-04-29 09:59 IJC: Added 'returnstats' feature
# 2010-10-19 16:25 IJC: Added 'sum' option for x-data
# 2011-03-22 12:57 IJC: Added 'none' option for data and errors
# 2012-03-20 16:33 IJMC: Fixed bug; xmode=='none' now works.
# 2012-03-27 14:00 IJMC: Now using np.digitize -- speed boost.
# Rewrote code to optimize (somewhat),
# cleaned up 'import' statements.
# 2012-04-08 15:57 IJMC: New speed boost from adopting
# numpy.histogram-like implementation:
# numpy.searchsorted, etc.
import numpy as np
from analysis import removeoutliers
if timing:
import time
tic = time.time()
def sdom(data):
"""Return standard deviation of the mean."""
return np.std(data)/np.sqrt(data.size)
def getcenter(data, cmode):
"""Get data center based on mode. Helper function."""
if cmode is None:
ret = 0
elif cmode=='mean':
ret = np.mean(data)
elif cmode=='median':
ret = np.median(data)
elif cmode=='sum':
ret = np.sum(data)
return ret
def geterr(data, emode, cmode):
"""Get errorbar. Helper function."""
if emode is None:
ret = []
elif emode=='std':
ret = np.std(data)
elif emode=='sdom':
ret = sdom(data)
elif emode=='minmax':
if len(data)==0:
ret = [np.nan, np.nan]
else:
center = getcenter(data,cmode)
ret = [center-min(data), max(data)-center]
return ret
def cleandata(data, clean, returnstats=False):
"""Clean data using removeoutliers. Helper function."""
init_count = np.array(data).size
if clean==None: # Don't clean at all!
#clean = dict(nsigma=1000, niter=0)
if returnstats:
ret = data, (init_count, init_count)
else:
ret = data
else: # Clean the data somehow ('clean' must be a dict)
if not clean.has_key('nsigma'):
clean.update(dict(nsigma=99999))
data = removeoutliers(data, **clean)
if returnstats:
ret = data, (init_count, np.array(data).size)
else:
ret = data
return ret
if timing:
print "%1.3f sec since starting function; helpers defined" % (time.time() - tic)
####### Begin main function ##########
sorted_index = np.argsort(x)
x = np.array(x, copy=False)[sorted_index]
y = np.array(y, copy=False)[sorted_index]
#x = np.array(x,copy=True).ravel()
#y = np.array(y,copy=True).ravel()
xbins = np.array(xbins,copy=True).ravel()
if xbins[0]==None and binfactor==None:
if returnstats ==False:
ret = x, y, np.ones(x.shape)*np.nan, np.ones(y.shape)*np.nan
else:
ret = x, y, np.ones(x.shape)*np.nan, np.ones(y.shape)*np.nan, (x.size, x.size)
return ret
if binfactor==None: # used passed-in 'xbins'
xbins = np.sort(xbins)
elif hasattr(binfactor,'__iter__'): # use variable-sized bins
binfactor = np.array(binfactor).copy()
sortedx = np.sort(x)
betweens = np.hstack((x.min()-1, 0.5*(sortedx[1::]+sortedx[0:len(x)-1]), x.max()+1))
xbins = []
counter = 0
for ii in range(len(binfactor)):
thisbin = betweens[counter]
xbins.append(thisbin)
counter += binfactor[ii]
xbins.append(x.max() + 1)
else: # bin down by the same factor throughout
binfactor = int(binfactor)
sortedx = np.sort(x)
betweens = np.hstack((x.min()-1, 0.5*(sortedx[1::]+sortedx[0:len(x)-1]), x.max()+1))
xbins = betweens[::binfactor]
if timing:
print "%1.3f sec since starting function; bins defined" % (time.time() - tic)
nbins = len(xbins)-1
arraynan = np.array([np.nan])
exx = []
eyy = []
xx = np.zeros(nbins)
yy = np.zeros(nbins)
yy2 = np.zeros(nbins)
init_count, final_count = y.size, 0
if timing:
setuptime = 0
xdatatime = 0
ydatatime = 0
statstime = 0
#import pylab as py
#xxx = np.sort(x)
if timing: tic1 = time.time()
#inds = np.digitize(x, xbins)
inds2 = [[x.searchsorted(xbins[ii], side='left'), \
x.searchsorted(xbins[ii+1], side='left')] for ii in range(nbins)]
if timing: setuptime += (time.time() - tic1)
#pdb.set_trace()
#bin_means = [data[digitized == i].mean() for i in range(1, len(bins))]
dox = xmode is not None
doy = ymode is not None
doex = xerr is not None
doey = yerr is not None
if clean is None:
if timing: tic3 = time.time()
if dox: exec ('xfunc = np.%s' % xmode) in locals()
if doy: exec ('yfunc = np.%s' % ymode) in locals()
for ii in range(nbins):
#index = inds==(ii+1)
if dox:
#xx[ii] = xfunc(x[index])
xx[ii] = xfunc(x[inds2[ii][0]:inds2[ii][1]])
if doy:
#yy[ii] = yfunc(y[index])
yy[ii] = yfunc(y[inds2[ii][0]:inds2[ii][1]])
if doex:
#exx.append(geterr(x[index], xerr, xmode))
exx.append(geterr(x[inds2[ii][0]:inds2[ii][1]], xerr, xmode))
if doey:
#eyy.append(geterr(y[index], yerr, ymode))
eyy.append(geterr(y[inds2[ii][0]:inds2[ii][1]], yerr, ymode))
if timing: statstime += (time.time() - tic3)
#pdb.set_trace()
else:
for ii in range(nbins):
if timing: tic1 = time.time()
#index = inds==(ii+1)
if timing: setuptime += (time.time() - tic1)
if timing: tic2 = time.time()
xdata = x[inds2[ii][0]:inds2[ii][1]]
if timing: xdatatime += (time.time() - tic2)
if timing: tic25 = time.time()
if ymode is None and yerr is None: # We're free to ignore the y-data:
ydata = arraynan
else: # We have to compute something with the y-data:
if clean is not None:
ydata, retstats = cleandata(y[inds2[ii][0]:inds2[ii][1]], clean, returnstats=True)
if returnstats:
final_count += retstats[1]
else: # We don't have to clean the data
ydata = y[inds2[ii][0]:inds2[ii][1]]
if returnstats:
final_count += ydata.size
if timing: ydatatime += (time.time() - tic25)
if timing: tic3 = time.time()
xx[ii] = getcenter(xdata,xmode)
if timing: tic4 = time.time()
yy[ii] = getcenter(ydata,ymode)
if timing: tic5 = time.time()
exx.append(geterr( xdata,xerr,xmode))
if timing: tic6 = time.time()
eyy.append(geterr( ydata,yerr,ymode))
if timing: tic7 = time.time()
if timing: statstime += (time.time() - tic3)
#exx[ii] = geterr( xdata,xerr,xmode)
#eyy[ii] = geterr( ydata,yerr,ymode)
if timing:
print "%1.3f sec for setting up bins & indices..." % setuptime
print "%1.3f sec for getting x data clean and ready." % xdatatime
print "%1.3f sec for getting y data clean and ready." % ydatatime
#print "%1.3f sec for computing x-data statistics." % (tic4-tic3)
#print "%1.3f sec for computing y-data statistics." % (tic5-tic4)
#print "%1.3f sec for computing x-error statistics." % (tic6-tic5)
#print "%1.3f sec for computing y-error statistics." % (tic7-tic6)
print "%1.3f sec for computing statistics........." % statstime
if timing:
print "%1.3f sec since starting function; uncertainties defined" % (time.time() - tic)
#xx = array(xx)
#yy = array(yy)
exx = np.array(exx).transpose() # b/c 2D if minmax option used
eyy = np.array(eyy).transpose() # b/c 2D if minmax option used
#pdb.set_trace()
if returnstats:
ret= xx,yy,exx,eyy,(init_count, final_count)
else:
ret = xx,yy,exx,eyy
#print 'tools: returnstats, len(ret)>>', returnstats, len(ret)
if timing:
print "%1.3f sec since starting function; returning" % (time.time() - tic)
return ret
def ploth(*args, **kw):
"""Plot 1D data in a histogram-like format. If x-coordinates are
specified, they refer to the centers of the histogram bars.
Uses same format as matplotlib.pyplot.plot. For example:
::
ploth(x, y) # plot x and y using solid linestyle (default)
ploth(x, y, 'bo') # plot x and y using blue circle markers w/no line
ploth(y) # plot y using x as index array 0..N-1
ploth(y, 'r*--') # ditto, but with red star corners and dashed line
:OPTIONS:
rot90 : bool
If True, data will be plotted histogram-style vertically,
rather than the standard horizontal plotting.
:REQUIREMENTS: :doc:`numpy`, :doc:`analysis`
"""
# 2009-09-17 09:26 IJC: Created
# 2012-09-27 19:19 IJMC: Added 'rot90' keyword
from numpy import arange, concatenate, vstack
from pylab import plot
if len(args)==1:
y=args[0]
ny = len(y)
x = arange(ny)
plotstr = '-'
elif len(args)==2 and args[1].__class__==str:
y=args[0]
ny = len(y)
x = arange(ny)
plotstr = args[1]
elif len(args)==2 and args[1].__class__<>str:
x = args[0]
y=args[1]
ny = len(y)
plotstr = '-'
elif len(args)>=3:
x = args[0]
y=args[1]
ny = len(y)
plotstr = args[1]
if kw.has_key('rot90') and kw['rot90']:
temp = x
x = y
y = temp
ny = len(y)
nx = len(x)
rot90 = kw.pop('rot90')
else:
rot90 = False
x1= 0.5*(x[1::]+x[0:ny-1])
xx = concatenate(([x[0]], vstack((x1,x1)).transpose().ravel(), [x[-1]]))
yy = vstack((y,y)).transpose().ravel()
if rot90:
phandle = plot(xx,yy,plotstr,**kw)
else:
phandle = plot(xx,yy,plotstr,**kw)
return phandle
def flatten(x, maxdepth=100):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
:OPTIONAL INPUTS:
maxdepth -- scalar
number of layers deep to dig. Seting to zero causes no flattening to occur.
:Examples:
::
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
# 2009-09-26 14:05 IJC: Taken from
# http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
# 2011-06-24 15:40 IJMC: Added maxdepth keyword
result = []
for el in x:
#if isinstance(el, (list, tuple)):
if hasattr(el, "__iter__") and not isinstance(el, basestring) and maxdepth>0:
maxdepth -= 1
result.extend(flatten(el, maxdepth=maxdepth))
else:
result.append(el)
return result
def fconvolve(a, v, oversamp=2):
"""Returns the discrete, linear convolution of 1-D sequences a and v,
using Fast Fourier Transforms. Restrictions are: a and v must
both be real-valued, and len(a)>len(v).
:REQUIREMENTS: :doc:`analysis`, :doc:`numpy`
"""
# 2009-10-29 11:00 IJC: Created
from analysis import pad
from numpy.fft import fft, ifft, fftshift
from numpy import real, array
a = array(a,copy=True).ravel()
v = array(v,copy=True).ravel()
na = len(a)
nv = len(v)
nfft = oversamp*na
a2 = pad(a, 1, nfft)[0,:]
v2 = pad(v, 1, nfft)[0,:]
fa2 = fft(a2)
fv2 = fft(v2)
ret = real(fftshift(ifft(fa2 * fv2)))
return pad(ret, 1, na).ravel()
def cplim(a1,a2):
"""Copy axis limits from one axes to another.
:INPUTS:
a1, a2 -- either (1) handles to axes objects, or (2) figure
numbers. If figures have subplots, you can refer to a
particular subplot using decimal notation. So, 1.3
would refer to subplot 3 of figure 1.
:REQUIREMENTS: :doc:`matplotlib` (when this is written...)
"""
# 2009-12-08 16:30 IJC: Had the idea...
print "To be written -- and what a great day it will be."
return
def legc(leg,col='color'):
"""Color legend text to match linecolor.
:Inputs:
'leg' is a legend object.
'col' sets the field of the leg.get_lines() objects to use to find
the color.
You may need to refresh the figure to see the changes."""
# 2009-12-14 09:50 IJC: Created
texts = leg.get_texts()
lines = leg.get_lines()
for label,line in zip(texts,lines):
label.set_color(line.get_color())
return leg
def keylist(filelist, keys):
"""Create an object based on FITS header keys extracted from a filelist.
:Inputs:
filelist -- sequence of strings representing filenames (for PyFITS)
keys -- sequence of strings representing header keys
#Keys not found in a file will result in the string value
:REQUIREMENTS: :doc:`pyfits`, :doc:`spitzer`
"""
try:
from astropy.io import fits as pyfits
except:
import pyfits
from spitzer import baseObject
# 2010-01-24 15:23 IJC: Created
# 2010-01-26 10:27 IJC: Solved a pernicious little problem: always
# call object creation w/parentheses!
obj = baseObject()
for k in keys:
exec('obj.%s=[]'%k)
for f in filelist:
h = pyfits.getheader(f)
for k in keys:
exec("obj.%s.append(h['%s'])" %(k,k) )
return obj