-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path_functions.py
1916 lines (1411 loc) · 55.2 KB
/
_functions.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
#import wx as _wx
import numpy as _n
import os as _os
import shutil as _shutil
import spinmob as _s
import pickle as _cPickle
class averager:
"""
This object will keep a running average of any "measured" quantity
(i.e. a single value drawn from a fluctuating source) along with a running
estimate of the standard deviation for individual measurements, and the
standard error on the mean, as estimated from the supplied measurements
themselves.
This object is particularly useful when averaging together large data sets,
such as long traces from a triggered oscilloscope or a series of power
spectral densities. The algorithm requires a fixed quantity of memory
regardless of how many averages one takes.
As with any averaging technique, make sure each added measurement can be
added to the running total without succumbing to round-off errors. This
is especially important for low bit depths. For example, 16-bit floating
point data runs into roundoff errors after only 3 decimal places (!),
meaning you can only effectively include up to 1024 data sets in a
calculation of the mean, with artifacts appearing significantly sooner
than this.
This averager also has the option to calculate an exponential moving average
(i.e., a low-pass filter) by specifying lowpass_frames > 0. This also provides
an estimate of the moving variance, which is systematically underestimated
as lowpass_frames is made smaller. At 2, for example, the variance is
underestimated by ~10%, and at 1, the variance becomes zero.
Arguments
---------
name='a'
Name of the data set.
lowpass_frames=0
If zero, averager will compute the average of all supplied data sets.
If positive, averager will perform a DSP low-pass on the supplied data
sets with lowpass_frames as the time constant (units of data sets).
Note this algorithm systematically underestimates the variance as
lowpass_frames approaches 1, and is within 10% of the true value for
lowpass_frames > 2.
precision=numpy.float64
Numpy dtype used in internal calculations. numpy.float32 is usually
sufficient, but numpy.float64 is safer if you are not strapped for
memory. Major precision issues seem to first appear as numpy.nan's
appearing in the calculation of self.variance_mean and
self.variance_sample, due to round off error on the
subtraction prior to the square root.
ignore_nan=True
If True, sets all NaN's appearing in the calculation to zero.
Internal Quantities
-------------------
self.lowpass_frames
Time constant for the DSP low-pass (see above).
self.ignore_nan
Whether to set NaN's appearing in calculations to zero.
self.mean
Running mean value of all supplied measurements.
self.mean_squared
Running mean^2 value of all supplied measurements.
self.name
Name of the data set.
self.N
Number of measurements that have been included thus far.
self.precision
Numpy dtype used in internal calculations.
self.variance_mean
Variance about the mean estimated from the supplied measurements.
Assumes all measurements are independently drawn from the same statistical
distribution.
self.variance_sample
Variance on individual measurements.
Assumes all measurements are independently drawn from the same statistical
distribution.
Methods
-------
add_measurement(y)
Add a new measurement and update the above quantities.
reset()
Reset the counter and all quantities to zero.
"""
def __init__(self, name='a', lowpass_frames=0, precision=_n.float64, ignore_nan=True):
# Don't forget to update the _copy method!
self.ignore_nan = ignore_nan
self.lowpass_frames = lowpass_frames
self.name = name
self.N = 0
self.mean = 0
self.mean_squared = 0
self.precision = precision
self.variance_mean = 0
self.variance_sample = 0
def __repr__(self):
return '<tools.averager '+repr(self.name)+' N='+str(self.N)+'>'
def _copy(self):
"""
Creates and returns a copy of this instance.
"""
# Make a new instance
a = type(self)()
a.ignore_nan = self.ignore_nan
a.lowpass_frames = self.lowpass_frames
a.name = self.name
a.N = self.N
a.mean = self.mean
a.mean_squared = self.mean_squared
a.precision = self.precision
a.variance_mean = self.variance_mean
a.variance_sample = self.variance_sample
return a
def add(self, y):
"""
Add a new measurement to the pool, updating the counter, means, and
standard deviations. Note this modifies the instance and returns it.
We use a modified Welford's online algorithm because it's more stable against
catastrophic cancellation.
Parameters
----------
y:
Number, numpy array, or other object (anything that can be summed
multiplied and divided in a meaningful way) representing a single
measurement. This will be automatically converted to the format
specified by self.precision.
"""
# Make sure the shape of y matches with the existing data, or reset
if not _n.shape(y) == _n.shape(self.mean): self.reset()
# Convert to the desired precision.
y = self.precision(y)
# Update the counter
self.N += 1
# if it is our first data set, initialize.
if self.N == 1:
self.mean = y
self.mean_squared = y*y
if _s.fun.is_iterable(y):
self.variance_mean = _n.zeros_like(y)
self.variance_sample = _n.zeros_like(y)
else:
self.variance_mean = 0
self.variance_sample = 0
# If we're doing a cumulative mean and variance N>1
elif not self.lowpass_frames:
N = self.N
# Remember the previous mean
old_mean = self.mean
old_mean_squared = self.mean_squared
# Get the new mean
self.mean += (y - self.mean ) / N
self.mean_squared += (y*y - self.mean_squared) / N
# Calculate the variances
self.variance_sample = (self.mean_squared - self.mean*self.mean)*self.N/(self.N-1)
#self.variance_sample = self.variance_sample*(N-2)/(N-1) + (y-old_mean)*(y-self.mean)/(N-1)
self.variance_mean = self.variance_sample/self.N
# Otherwise we're doing DSP low-pass N>1
else:
# Time constant shorthand (with a hack to make the initial variance more responsive)
tau = min(self.lowpass_frames, self.N)
kappa = 1.0/tau
# Remember the previous value
old_mean = self.mean
# Update the mean & variance_sample with DSP low-pass
self.mean = kappa*y + (1-kappa)*old_mean
self.mean_squared = kappa*y*y + (1-kappa)*self.mean_squared
# Get the standard error on the mean
ek = _n.exp(kappa)
emk = 1/ek
self.variance_sample = 0.5*(1+ek)*(self.mean_squared - self.mean*self.mean)
self.variance_mean = self.variance_sample * (1-_n.exp(-kappa))**2 / (1-_n.exp(-2*kappa))
# If we are ignoring the nan's, set them to zero.
if self.ignore_nan:
if type(self.variance_sample) == _n.ndarray: _n.nan_to_num(self.variance_sample, copy=False)
else: self.variance_sample = _n.nan_to_num(self.variance_sample)
if type(self.variance_mean) == _n.ndarray: _n.nan_to_num(self.variance_mean, copy=False)
else: self.variance_mean = _n.nan_to_num(self.variance_mean)
# Otherwise, print a warning but keep moving.
elif _n.isnan(self.variance_sample).any() or _n.isnan(self.variance_mean).any():
print("WARNING: "+repr(self)+" Some elements of self.variance_mean or self.variance_sample are NaN.")
return self
def __add__(self, y):
"""
Creates a copy of this instance, adds runs add(y) on the copy, and
returns the copy.
Parameters
----------
y:
To be sent to the copy's add() function.
"""
c = self._copy()
return c.add(y)
def reset(self):
"""
Resets the average values and counter to zero.
"""
self.__init__(name = self.name,
lowpass_frames = self.lowpass_frames,
precision = self.precision,
ignore_nan = self.ignore_nan)
return self
def coarsen_array(a, level=2, method='mean'):
"""
Returns a coarsened (binned) version of the data. Currently supports
any of the numpy array operations, e.g. min, max, mean, std, ...
level=2 means every two data points will be binned.
level=0 or 1 just returns a copy of the array
"""
if a is None: return None
# make sure it's a numpy array, and that we don't destroy the original.
a = _n.array(a)
# Make sure it's an integer!
level=int(level)
# quickest option
if level in [0,1,False]: return a
# otherwise assemble the python code to execute
code = 'a.reshape(-1, level).'+method+'(axis=1)'
# execute, making sure the array can be reshaped!
try: return eval(code, dict(a=a[0:int(len(a)/level)*level], level=level))
except:
print("ERROR: Could not coarsen array with method "+repr(method))
return a
def coarsen_data(x, y, ey=None, ex=None, level=2, exponential=False):
"""
Coarsens the supplied data set. Returns coarsened arrays of x, y, along with
quadrature-coarsened arrays of ey and ex if specified.
Parameters
----------
x, y
Data arrays. Can be lists (will convert to numpy arrays).
These are coarsened by taking an average.
ey=None, ex=None
y and x uncertainties. Accepts arrays, lists, or numbers.
These are coarsened by averaging in quadrature.
level=2
For linear coarsening (default, see below), every n=level points will
be averaged together (in quadrature for errors). For exponential
coarsening, bins will be spaced by the specified scaling=level factor;
for example, level=1.4 will group points within 40% of each other's x
values. This is a great option for log-x plots, as the outcome will be
evenly spaced.
exponential=False
If False, coarsen using linear spacing. If True, the bins will be
exponentially spaced by the specified level.
"""
# Normal coarsening
if not exponential:
# Coarsen the data
xc = coarsen_array(x, level, 'mean')
yc = coarsen_array(y, level, 'mean')
# Coarsen the y error in quadrature
if not ey is None:
if not is_iterable(ey): ey = [ey]*len(y)
eyc = _n.sqrt(coarsen_array(_n.power(ey,2)/level, level, 'mean'))
# Coarsen the x error in quadrature
if not ex is None:
if not is_iterable(ey): ex = [ex]*len(x)
exc = _n.sqrt(coarsen_array(_n.power(ex,2)/level, level, 'mean'))
# Exponential coarsen
else:
# Make sure the data are arrays
x = _n.array(x)
y = _n.array(y)
# Create the new arrays to fill
xc = []
yc = []
if not ey is None:
if not is_iterable(ey): ey = _n.array([ey]*len(y))
eyc = []
if not ex is None:
if not is_iterable(ex): ex = _n.array([ex]*len(x))
exc = []
# Find the first element that is greater than zero
x0 = x[x>0][0]
# Now loop over the exponential bins
n = 0
while x0*level**n < x[-1]:
# Get all the points between x[n] and x[n]*r
mask = _n.logical_and(x0*level**n <= x, x < x0*level**(n+1))
# Only do something if points exist from this range!
if len(x[mask]):
# Take the average x value
xc.append(_n.average(x[mask]))
yc.append(_n.average(y[mask]))
# do the errors in quadrature
if not ey is None: eyc.append(_n.sqrt(_n.average((ey**2)[mask])/len(ey[mask])))
if not ex is None: exc.append(_n.sqrt(_n.average((ex**2)[mask])/len(ex[mask])))
# Increment the counter
n += 1
# Done exponential loop
# Done coarsening
# Return depending on situation
if ey is None and ex is None: return _n.array(xc), _n.array(yc)
elif ex is None : return _n.array(xc), _n.array(yc), _n.array(eyc)
elif ey is None : return _n.array(xc), _n.array(yc), _n.array(exc)
else : return _n.array(xc), _n.array(yc), _n.array(eyc), _n.array(exc)
def coarsen_matrix(Z, xlevel=0, ylevel=0, method='average'):
"""
This returns a coarsened numpy matrix.
method can be 'average', 'maximum', or 'minimum'
"""
# coarsen x
if not ylevel:
Z_coarsened = Z
else:
temp = []
for z in Z: temp.append(coarsen_array(z, ylevel, method))
Z_coarsened = _n.array(temp)
# coarsen y
if xlevel:
Z_coarsened = Z_coarsened.transpose()
temp = []
for z in Z_coarsened: temp.append(coarsen_array(z, xlevel, method))
Z_coarsened = _n.array(temp).transpose()
return Z_coarsened
# first coarsen the columns (if necessary)
if ylevel:
Z_ycoarsened = []
for c in Z: Z_ycoarsened.append(coarsen_array(c, ylevel, method))
Z_ycoarsened = _n.array(Z_ycoarsened)
# now coarsen the rows
if xlevel: return coarsen_array(Z_ycoarsened, xlevel, method)
else: return _n.array(Z_ycoarsened)
def erange(start, end, steps):
"""
Returns a numpy array over the specified range taking geometric steps.
See also numpy.logspace()
"""
if start == 0:
print("Nothing you multiply zero by gives you anything but zero. Try picking something small.")
return None
if end == 0:
print("It takes an infinite number of steps to get to zero. Try a small number?")
return None
# figure out our multiplication scale
x = (1.0*end/start)**(1.0/(steps-1))
# now generate the array
ns = _n.array(list(range(0,steps)))
a = start*_n.power(x,ns)
# tidy up the last element (there's often roundoff error)
a[-1] = end
return a
def is_a_number(s, other_options=[]):
"""
This takes an object and determines whether it's a number or a string
representing a number. Handles real or complex numbers, and strings such as
'1.23', '1.23+4.5j', '1.23+4.5i', '(1.23+4.5j)', '(1.23+4.5i)', numpy.nan,
numpy.inf.
This uses a try/except to cover strings and numbers simultaneously, so it's
slower than numpy's iscomplex, isreal, isnan, isinf.
Parameters
----------
s : object, str
Object to test with float() and complex() and complex() after removing
parenthesis and replacing 'i' with 'j' (for other formats).
other_options=[] : list
List of other values to check if the default methods fail.
Returns
-------
1 if float() worked
2 if complex() worked
3 if is in other_options
False if nothing worked
"""
if _s.fun.is_iterable(s) and not type(s) == str: return False
try:
float(s)
return 1
except:
try:
complex(s)
return 2
except:
try:
complex(s.replace('(','').replace(')','').replace('i','j'))
return 2
except:
if s in other_options: return 3
else: return False
def is_iterable(a):
"""
Determine whether the object is iterable, but not a string.
This function is left over from a time when Python was 2, not 3.
"""
return hasattr(a, '__iter__') and not type(a) == str
def append_to_file(path, string):
file = open(path, 'a')
file.write(string)
file.close()
def array_shift(a, n, fill="average"):
"""
This will return an array with all the elements shifted forward in index by n.
a is the array
n is the amount by which to shift (can be positive or negative)
fill="average" fill the new empty elements with the average of the array
fill="wrap" fill the new empty elements with the lopped-off elements
fill=37.2 fill the new empty elements with the value 37.2
"""
new_a = _n.array(a)
if n==0: return new_a
fill_array = _n.array([])
fill_array.resize(_n.abs(n))
# fill up the fill array before we do the shift
if fill is "average": fill_array = 0.0*fill_array + _n.average(a)
elif fill is "wrap" and n >= 0:
for i in range(0,n): fill_array[i] = a[i-n]
elif fill is "wrap" and n < 0:
for i in range(0,-n): fill_array[i] = a[i]
else: fill_array = 0.0*fill_array + fill
# shift and fill
if n > 0:
for i in range(n, len(a)): new_a[i] = a[i-n]
for i in range(0, n): new_a[i] = fill_array[i]
else:
for i in range(0, len(a)+n): new_a[i] = a[i-n]
for i in range(0, -n): new_a[-i-1] = fill_array[-i-1]
return new_a
def assemble_covariance(error, correlation):
"""
This takes an error vector and a correlation matrix and assembles the covariance
"""
covariance = []
for n in range(0, len(error)):
covariance.append([])
for m in range(0, len(error)):
covariance[n].append(correlation[n][m]*error[n]*error[m])
return _n.array(covariance)
def chi_squared(p, f, xdata, ydata):
return(sum( (ydata - f(p,xdata))**2 ))
def combine_dictionaries(a, b):
"""
returns the combined dictionary. a's values preferentially chosen
"""
c = {}
for key in list(b.keys()): c[key]=b[key]
for key in list(a.keys()): c[key]=a[key]
return c
def data_from_file(path, delimiter=" "):
lines = read_lines(path)
x = []
y = []
for line in lines:
s=line.split(delimiter)
if len(s) > 1:
x.append(float(s[0]))
y.append(float(s[1]))
return([_n.array(x), _n.array(y)])
def data_to_file(path, xarray, yarray, delimiter=" ", mode="w"):
file = open(path, mode)
for n in range(0, len(xarray)):
file.write(str(xarray[n]) + delimiter + str(yarray[n]) + '\n')
file.close()
def decompose_covariance(c):
"""
This decomposes a covariance matrix into an error vector and a correlation matrix
"""
# make it a kickass copy of the original
c = _n.array(c)
# first get the error vector
e = []
for n in range(0, len(c[0])): e.append(_n.sqrt(c[n][n]))
# now cycle through the matrix, dividing by e[1]*e[2]
for n in range(0, len(c[0])):
for m in range(0, len(c[0])):
c[n][m] = c[n][m] / (e[n]*e[m])
return [_n.array(e), _n.array(c)]
def derivative(xdata, ydata):
"""
performs d(ydata)/d(xdata) with nearest-neighbor slopes
must be well-ordered, returns new arrays [xdata, dydx_data]
neighbors:
"""
D_ydata = []
D_xdata = []
for n in range(1, len(xdata)-1):
D_xdata.append(xdata[n])
D_ydata.append((ydata[n+1]-ydata[n-1])/(xdata[n+1]-xdata[n-1]))
return [D_xdata, D_ydata]
def derivative_fit(xdata, ydata, neighbors=1):
"""
loops over the data points, performing a least-squares linear fit of the
nearest neighbors at each point. Returns an array of x-values and slopes.
xdata should probably be well-ordered.
neighbors How many data point on the left and right to include.
"""
x = []
dydx = []
nmax = len(xdata)-1
for n in range(nmax+1):
# get the indices of the data to fit
i1 = max(0, n-neighbors)
i2 = min(nmax, n+neighbors)
# get the sub data to fit
xmini = _n.array(xdata[i1:i2+1])
ymini = _n.array(ydata[i1:i2+1])
slope, intercept = fit_linear(xmini, ymini)
# make x the average of the xmini
x.append(float(sum(xmini))/len(xmini))
dydx.append(slope)
return _n.array(x), _n.array(dydx)
def difference(ydata1, ydata2):
"""
Returns the number you should add to ydata1 to make it line up with ydata2
"""
y1 = _n.array(ydata1)
y2 = _n.array(ydata2)
return(sum(y2-y1)/len(ydata1))
def distort_matrix_X(Z, X, f, new_xmin, new_xmax, subsample=3):
"""
Applies a distortion (remapping) to the matrix Z (and x-values X) using function f.
returns new_Z, new_X
f is an INVERSE function old_x(new_x)
Z is a matrix. X is an array where X[n] is the x-value associated with the array Z[n].
new_xmin, new_xmax is the possible range of the distorted x-variable for generating Z
points is how many elements the stretched Z should have. "auto" means use the same number of bins
"""
Z = _n.array(Z)
X = _n.array(X)
points = len(Z)*subsample
# define a function for searching
def zero_me(new_x): return f(new_x)-target_old_x
# do a simple search to find the new_x that gives old_x = min(X)
target_old_x = min(X)
new_xmin = find_zero_bisect(zero_me, new_xmin, new_xmax, _n.abs(new_xmax-new_xmin)*0.0001)
target_old_x = max(X)
new_xmax = find_zero_bisect(zero_me, new_xmin, new_xmax, _n.abs(new_xmax-new_xmin)*0.0001)
# now loop over all the new x values
new_X = []
new_Z = []
bin_width = float(new_xmax-new_xmin)/(points)
for new_x in frange(new_xmin, new_xmax, bin_width):
# make sure we're in the range of X
if f(new_x) <= max(X) and f(new_x) >= min(X):
# add this guy to the array
new_X.append(new_x)
# get the interpolated column
new_Z.append( interpolate(X,Z,f(new_x)) )
return _n.array(new_Z), _n.array(new_X)
def distort_matrix_Y(Z, Y, f, new_ymin, new_ymax, subsample=3):
"""
Applies a distortion (remapping) to the matrix Z (and y-values Y) using function f.
returns new_Z, new_Y
f is a function old_y(new_y)
Z is a matrix. Y is an array where Y[n] is the y-value associated with the array Z[:,n].
new_ymin, new_ymax is the range of the distorted x-variable for generating Z
points is how many elements the stretched Z should have. "auto" means use the same number of bins
"""
# just use the same methodology as before by transposing, distorting X, then
# transposing back
new_Z, new_Y = distort_matrix_X(Z.transpose(), Y, f, new_ymin, new_ymax, subsample)
return new_Z.transpose(), new_Y
def dumbguy_minimize(f, xmin, xmax, xstep):
"""
This just steps x and looks for a peak
returns x, f(x)
"""
prev = f(xmin)
this = f(xmin+xstep)
for x in frange(xmin+xstep,xmax,xstep):
next = f(x+xstep)
# see if we're on top
if this < prev and this < next: return x, this
prev = this
this = next
return x, this
def elements_are_numbers(array):
"""
Tests whether the elements of the supplied array are numbers.
"""
# empty case
if len(array) == 0: return 0
output_value = 1
for x in array:
# test it and die if it's not a number
test = is_a_number(x)
if not test: return False
# mention if it's complex
output_value = max(output_value,test)
return output_value
def elements_are_strings(array, start_index=0, end_index=-1):
if len(array) == 0: return 0
if end_index < 0: end_index=len(array)-1
for n in range(start_index, end_index+1):
if not type(array[n]) == str: return 0
return 1
def elements_are_iterable(array):
"""
Returns True if every element is a list/array-like object (not a string).
"""
for a in array:
if not is_iterable(a):
return False
return True
def equalize_list_lengths(a,b):
"""
Modifies the length of list a to match b. Returns a.
a can also not be a list (will convert it to one).
a will not be modified.
"""
if not _s.fun.is_iterable(a): a = [a]
a = list(a)
while len(a)>len(b): a.pop(-1)
while len(a)<len(b): a.append(a[-1])
return a
def find_N_peaks(array, N=4, max_iterations=100, rec_max_iterations=3, recursion=1):
"""
This will run the find_peaks algorythm, adjusting the baseline until exactly N peaks are found.
"""
if recursion<0: return None
# get an initial guess as to the baseline
ymin = min(array)
ymax = max(array)
for n in range(max_iterations):
# bisect the range to estimate the baseline
y1 = (ymin+ymax)/2.0
# now see how many peaks this finds. p could have 40 for all we know
p, s, i = find_peaks(array, y1, True)
# now loop over the subarrays and make sure there aren't two peaks in any of them
for n in range(len(i)):
# search the subarray for two peaks, iterating 3 times (75% selectivity)
p2 = find_N_peaks(s[n], 2, rec_max_iterations, rec_max_iterations=rec_max_iterations, recursion=recursion-1)
# if we found a double-peak
if not p2 is None:
# push these non-duplicate values into the master array
for x in p2:
# if this point is not already in p, push it on
if not x in p: p.append(x+i[n]) # don't forget the offset, since subarrays start at 0
# if we nailed it, finish up
if len(p) == N: return p
# if we have too many peaks, we need to increase the baseline
if len(p) > N: ymin = y1
# too few? decrease the baseline
else: ymax = y1
return None
def find_peaks(array, baseline=0.1, return_subarrays=False):
"""
This will try to identify the indices of the peaks in array, returning a list of indices in ascending order.
Runs along the data set until it jumps above baseline. Then it considers all the subsequent data above the baseline
as part of the peak, and records the maximum of this data as one peak value.
"""
peaks = []
if return_subarrays:
subarray_values = []
subarray_indices = []
# loop over the data
n = 0
while n < len(array):
# see if we're above baseline, then start the "we're in a peak" loop
if array[n] > baseline:
# start keeping track of the subarray here
if return_subarrays:
subarray_values.append([])
subarray_indices.append(n)
# find the max
ymax=baseline
nmax = n
while n < len(array) and array[n] > baseline:
# add this value to the subarray
if return_subarrays:
subarray_values[-1].append(array[n])
if array[n] > ymax:
ymax = array[n]
nmax = n
n = n+1
# store the max
peaks.append(nmax)
else: n = n+1
if return_subarrays: return peaks, subarray_values, subarray_indices
else: return peaks
def find_two_peaks(data, remove_background=True):
"""
Returns two indicies for the two maxima
"""
y = _n.array( data )
x = _n.array( list(range(0,len(y))) )
# if we're supposed to, remove the linear background
if remove_background:
[slope, offset] = fit_linear(x,y)
y = y - slope*x
y = y - min(y)
# find the global maximum
max1 = max(y)
n1 = index(max1, y)
# now starting at n1, work yourway left and right until you find
# the left and right until the data drops below a 1/2 the max.
# the first side to do this gives us the 1/2 width.
np = n1+1
nm = n1-1
yp = max1
ym = max1
width = 0
while 0 < np < len(y) and 0 < nm < len(y):
yp = y[np]
ym = y[nm]
if yp <= 0.5*max1 or ym <= 0.5*max1:
width = np - n1
break
np += 1
nm -= 1
# if we didn't find it, we pooped out
if width == 0:
return [n1,-1]
# this means we have a valid 1/2 width. Find the other max in the
# remaining data
n2 = nm
while 1 < np < len(y)-1 and 1 < nm < len(y)-1:
if y[np] > y[n2]:
n2 = np
if y[nm] > y[n2]:
n2 = nm
np += 1
nm -= 1
return([n1,n2])
def find_zero_bisect(f, xmin, xmax, xprecision):
"""
This will bisect the range and zero in on zero.
"""
if f(xmax)*f(xmin) > 0:
print("find_zero_bisect(): no zero on the range",xmin,"to",xmax)
return None
temp = min(xmin,xmax)
xmax = max(xmin,xmax)
xmin = temp
xmid = (xmin+xmax)*0.5
while xmax-xmin > xprecision:
y = f(xmid)
# pick the direction with one guy above and one guy below zero
if y > 0:
# move left or right?
if f(xmin) < 0: xmax=xmid
else: xmin=xmid
# f(xmid) is below zero
elif y < 0:
# move left or right?
if f(xmin) > 0: xmax=xmid
else: xmin=xmid
# yeah, right
else: return xmid
# bisect again
xmid = (xmin+xmax)*0.5