-
Notifications
You must be signed in to change notification settings - Fork 4
/
numpyext.py
1598 lines (1279 loc) · 47 KB
/
numpyext.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
# -*- coding: utf-8 -*-
"""Contains extensions to numpy."""
from six.moves import range
import numpy as np
def linear_least_squares_fit(model, npar, x, y, yerr=None):
"""
Fits a model that is linear in the parameters.
Parameters
----------
model: vectorized function, args=(x, par)
npar: number of parameters for model (length of par vector)
x, y, yerr: coordinates and errors of data points
Returns
-------
x: best-fit vector of parameters
cov: covariance matrix of parameters
chi2: chi2 at minimum
ndof: statistical degrees of freedom
"""
if yerr is None:
b = np.atleast_1d(y)
X = np.transpose([model(x, u) for u in np.identity(npar)])
else:
ye = np.atleast_1d(yerr)
b = np.atleast_1d(y) / ye
X = np.transpose([model(x, u) / ye for u in np.identity(npar)])
XTX_inv = np.linalg.inv(np.dot(X.T, X))
x = np.dot(np.dot(XTX_inv, X.T), b)
chi2 = np.sum((b - np.dot(X, x))**2)
ndof = len(y) - npar
return x, XTX_inv, chi2, ndof
def rebin(factor, w, edges=None, axis=0):
"""
Re-bins a N-dimensional histogram along a chosen axis.
Parameters
----------
factor: integer
Number of neighboring bins to merge. Number of original
bins must be divisible by factor.
w: array-like
Number field that represents the histogram content.
edges: array-like (optional)
Bin edges of the axis to re-bin.
axis: integer (optional)
Axis to re-bin, defaults to first axis.
Returns
-------
w: array
Number field that represents the re-binned histogram
content.
edges: array (only if edges were supplied)
Bin edges after re-binning.
"""
w = np.atleast_1d(w)
nbin = w.shape[axis]
if nbin % factor != 0:
raise ValueError("factor %i is not a divider of %i bins" % (factor, nbin))
n = nbin / factor
shape = np.array(w.shape)
shape[axis] = n
w2 = np.zeros(shape, dtype=w.dtype)
for i in range(factor):
mask = [slice(x) for x in shape]
mask[axis] = slice(i, nbin, factor)
w2 += w[mask]
if edges is not None:
edges2 = [edges[factor * i] for i in range(n)] + [edges[-1]]
return w2, edges2
else:
return w2
def bin(x, y, bins=10, range=None):
"""
Bin x and returns lists of the y-values inside each bin.
Parameters
----------
x: array-like
Variable that is binned.
y: array-like
Variable that is sorted according to the binning of x.
bins: integer or array-like
Number of bins or array of lower bin edges + last high bin edge.
range: tuple, lenght of 2 (optional)
If range is set, only (x,y) pairs are used where x is inside the range.
Ignored, if bins is an array.
Returns
-------
yBins: list of lists
List of y-values which correspond to the x-bins.
xegdes: array of floats
Lower bin edges. Has length len(yBins)+1.
"""
ys = np.atleast_1d(y)
xs = np.atleast_1d(x)
if type(bins) is int:
if range is None:
range = (min(x), max(x) + np.finfo(float).eps)
else:
mask = (range[0] <= xs) & (xs < range[1])
xs = xs[mask]
ys = ys[mask]
xedges = np.linspace(range[0], range[1], bins + 1)
else:
xedges = bins
bins = len(xedges) - 1
binnedys = []
for i in range(bins):
if i == bins - 1:
binnedys.append(ys[(xedges[i] <= xs) & (xs <= xedges[i + 1])])
else:
binnedys.append(ys[(xedges[i] <= xs) & (xs < xedges[i + 1])])
return binnedys, xedges
def profile(x, y, bins=10, range=None, sigma_cut=None):
"""
Compute the (robust) profile of a set of data points.
Parameters
----------
x,y : array-like
Input data. The (x,y) pairs are binned according to the x-array,
while the averages are computed from the y-values inside a x-bin.
bins : int or array-like, optional
Defines the number of equal width bins in the given range (10,
by default). If bins is an array, it is used for the bin edges
of the profile.
range : (float,float), optional
The lower and upper range of the bins. If not provided, range
is simply ``(a.min(), a.max())``. Values outside the range are
ignored.
sigma_cut : float, optional
If sigma_cut is set, outliers in the data are rejected before
computing the profile. Outliers are detected based on the scaled
MAD and the median of the distribution of the y's in each bin.
All data points with |y - median| > sigma_cut x MAD are ignored
in the computation.
Returns
-------
yavg : array of dtype float
Returns the averages of the y-values in each bin.
ystd : array of dtype float
Returns the standard deviation in each bin. If you want the
uncertainty of ymean, calculate: yunc = ystd/numpy.sqrt(n-1).
n : array of dtype int
Returns the number of events in each bin.
xedge : array of dtype float
Returns the bin edges. Beware: it has length(yavg)+1.
Examples
--------
>>> yavg, ystd, n, xedge = profile(np.array([0.,1.,2.,3.]), np.array([0.,1.,2.,3.]), 2)
>>> yavg
array([0.5, 2.5])
>>> ystd
array([0.5, 0.5])
>>> n
array([2, 2])
>>> xedge
array([0. , 1.5, 3. ])
"""
y = np.asfarray(np.atleast_1d(y))
n, xedge = np.histogram(x, bins=bins, range=range)
if sigma_cut is None:
ysum = np.histogram(x, bins=bins, range=range, weights=y)[0]
yysum = np.histogram(x, bins=bins, range=range, weights=y * y)[0]
else:
if sigma_cut <= 0:
raise ValueError("sigma_cut <= 0 detected, has to be positive")
# sort y into bins
ybin = bin(x, y, bins, range)[0]
if type(bins) is int:
nbins = bins
else:
nbins = len(bins) - 1
# reject outliers in calculation of avg, std
ysum = np.zeros(nbins)
yysum = np.zeros(nbins)
for i in range(nbins):
ymed = np.median(ybin[i])
ymad = mad(ybin[i])
for y in ybin[i]:
if ymad == 0 or abs(y - ymed) < sigma_cut * ymad:
ysum[i] += y
yysum[i] += y * y
else:
n[i] -= 1
mask = n == 0
n[mask] = 1
yavg = ysum / n
ystd = np.sqrt(yysum / n - yavg * yavg)
yavg[mask] = np.nan
ystd[mask] = np.nan
return yavg, ystd, n, xedge
def profile2d(x, y, z, bins=(10, 10), range=None):
"""
Compute the profile of a set of data points in 2d.
"""
if not isinstance(z, np.ndarray):
z = np.array(z)
ws, xedges, yedges = np.histogram2d(x, y, bins, range)
zsums = np.histogram2d(x, y, bins, range, weights=z)[0]
zzsums = np.histogram2d(x, y, bins, range, weights=z * z)[0]
zavgs = zsums / ws
zstds = np.sqrt(zzsums / ws - zavgs * zavgs)
return zavgs, zstds, ws, xedges, yedges
def centers(x):
"""
Compute the centers of an array of bin edges.
Parameters
----------
x: array-like
A 1-d array containing lower bin edges.
Returns
-------
c: array of dtype float
Returns the centers of the bins.
hw: array of dtype float
Returns the half-width of the bins.
Examples
--------
>>> centers([0.0, 1.0, 2.0])
(array([0.5, 1.5]), array([0.5, 0.5]))
"""
x = np.atleast_1d(x)
assert len(x) > 1, "Array should have size > 1 to make call to centers() reasonable!"
hw = 0.5 * (x[1:] - x[:-1])
return x[:-1] + hw, hw
def derivative(f, x, step=None, order=1):
"""
Numerically calculate the first or second derivative of a function.
Parameters
----------
f: function-like
Function of which to calculate the derivative.
It has to accept a single float argument and may return a vector or a float.
x: float
Where to evaluate the derivative.
step: float (optional)
By default, the step size for the numerical derivative is calculated
automatically. This may take many more evaluations of f(x) than necessary.
The calculation can be speed up by setting the step size.
order: integer (optional)
Order of the derivative. May be 1 or 2 for the first or second derivative.
Returns
-------
The first or second derivative of f(x).
Notes
-----
Numerically calculated derivatives are not exact and we do not give an error
estimate.
Examples
--------
>>> def f(x) : return 2 + x + 2*x*x + x*x*x
>>> round(derivative(f, 1.0), 3)
8
>>> round(derivative(f, 1.0, step=1e-3), 3)
8
>>> round(derivative(f, 1.0, order=2), 3)
10
>>> np.round(derivative(f, np.ones(2)), 3)
array([8., 8.])
>>> np.round(derivative(f, np.ones(2), order=2), 3)
array([10., 10.])
Notes
-----
The first derivative is calculated with the five point stencil,
see e.g. Wikipedia. The code to determine the step size was taken
from the GNU scientific library.
"""
eps = np.finfo(float).eps
# the correct power is 1/order of h in the
# error term of the numerical formula
h0 = h = eps ** 0.33 if order == 1 else eps ** 0.25
userStep = step is not None
for i in range(10):
dx = step if userStep else (h * x if np.all(x) else h)
tmp = x + dx
dx = tmp - x
fpp = f(x + 2.0 * dx)
fp = f(x + dx)
fm = f(x - dx)
fmm = f(x - 2.0 * dx)
if userStep:
break
if order == 1:
a = np.abs(fpp - fp)
b = np.abs(fpp + fp)
if np.all(a > 0.5 * b * h0):
break
else:
a = np.abs(fpp + fmm - fp - fm)
b = np.abs(fpp + fmm + fp + fm)
if np.all(a > 0.5 * b * h0):
break
h *= 10
if order == 1:
return (fmm - fpp + 8.0 * (fp - fm)) / (12.0 * dx)
else:
return (fpp + fmm - fp - fm) / (3.0 * dx * dx)
def derivativeND(f, xs, step=1e-8):
"""
Numerically calculates the first derivatives of an R^n -> R function.
The derivatives can be calculated at several points at once.
Parameters
----------
f : callable
An R^n -> R function to differentiate. Has to be callable with
f(xs), where xs is a 2-d array of shape n_points x n_variables.
xs : array-like
A 2-d array of function values of shape n_points x n_variables.
step : float
Step size for the differentiation.
Notes
-----
The derivatives are calculated using the central finite difference
method with 2nd order accuracy (i.e., a two point stencil) for each
dimension.
Returns
-------
A 2-d array of the derivatives for each point and dimension. The
shape is n_points x n_variables.
Examples
--------
>>> def f(xy):
... x, y = xy.T
... return x ** 2 + y ** 2
...
>>> derivativeND(f, ([0., 0.], [1., 0.], [0., 1.]))
array([[0., 0.],
[2., 0.],
[0., 2.]])
"""
xs = np.atleast_2d(xs)
n_rows, n_vars = xs.shape
bloated_xs = np.repeat(xs, n_vars, 0)
epsilons = np.tile(np.eye(n_vars) * step, [n_rows, 1])
return (f(bloated_xs + epsilons) -
f(bloated_xs - epsilons)).reshape(-1, n_vars) / (2 * step)
def jacobian(f, x, steps=None):
"""
Numerically calculate the matrix of first derivatives.
Parameters
----------
f: function-like
Has to be callable as f(x).
x: array-like
Vector of parameters.
steps: array-like (optional)
Vector of deltas to use in the numerical approximation,
see derivative(...). Has to have the same length as x.
Returns
-------
The Jacobi matrix of the first derivatives.
Examples
--------
>>> def f(v): return 0.5*np.dot(v,v)
>>> jacobian(f,np.ones(2))
array([[1., 1.]])
>>> def f(v): return np.dot(v,v)*v
>>> jacobian(f,np.ones(2))
array([[4., 2.],
[2., 4.]])
"""
nx = len(x)
# cheap way to determine dimension of f's output
y = f(x)
ny = len(y) if hasattr(y, "__len__") else 1
jacobi = np.zeros((ny, nx))
e = np.zeros(nx)
for ix in range(nx):
e *= 0
e[ix] = 1
der = derivative(lambda z: f(x + z * e), 0,
step=None if steps is None else steps[ix])
for iy in range(ny):
jacobi[iy, ix] = der[iy] if ny > 1 else der
return jacobi
def hessian(f, x, steps):
"""
Numerically calculate the matrix of second derivatives.
Parameters
----------
f: function-like
Has to be callable as f(x).
x: array-like
Vector of parameters.
steps: array-like
Vector of deltas to use in the numerical approximation.
Has to have the same length as x.
Returns
-------
The symmetric Hesse matrix of the second derivatives.
"""
xx = np.array(x, dtype=np.float)
n = len(x)
hesse = np.empty((n, n))
for i in range(n):
for j in range(i, n):
xpp = xx.copy()
xpp[i] += steps[i]
xpp[j] += steps[j]
xmm = xx.copy()
xmm[i] -= steps[i]
xmm[j] -= steps[j]
if i == j:
xm = xx.copy()
xm[i] -= steps[i]
xp = xx.copy()
xp[i] += steps[i]
hesse[i, i] = ((f(xmm) + f(xpp) - f(xp) - f(xm))
/ (3.0 * steps[i] * steps[i]))
else:
xpm = xx.copy()
xpm[i] += steps[i]
xpm[j] -= steps[j]
xmp = xx.copy()
xmp[i] -= steps[i]
xmp[j] += steps[j]
hesse[i, j] = hesse[j, i] = (
f(xpp) + f(xmm) - f(xpm) - f(xmp)) / (4.0 * steps[i] * steps[j])
return hesse
def propagate_covariance(f, x, cov):
"""
Compute the covariance matrix of y for the transformation y = f(x), given x with covariance matrix cov.
Parameters
----------
f: function-like
Has to be callable as f(x).
x: array-like
Vector of parameters.
cov: 2-d array of floats
Covariance matrix of x.
Returns
-------
fcov: matrix of floats
The covariance matrix of the output of f.
Examples
--------
>>> v = np.ones(2)
>>> cov = np.ones((2,2))
>>> def f(r):return np.dot(r,r)
>>> "%.3g" % propagate_covariance(f,v,cov)
'16'
>>> def f(r):return 2*r
>>> propagate_covariance(f,v,cov)
array([[4., 4.],
[4., 4.]])
"""
ncol = len(x)
dx = np.empty(ncol)
for icol in range(ncol):
dx[icol] = (np.sqrt(cov[icol][icol]) if cov[icol][icol] > 0.0 else 1.0) * 1e-3
jacobi = jacobian(f, x, dx)
return np.dot(jacobi, np.dot(cov, jacobi.T))
def uncertainty(f, x, cov):
"""
Compute the standard deviation of f(v), given v with covariance matrix cov.
This is a convenience function that wraps propagate_covariance(...).
Parameters
----------
f: function-like
Has to be callable as f(x).
x: array-like or single float
Vector of parameters.
cov: 2-d array of floats or single float
Covariance matrix of x.
Returns
-------
The standard deviation of f(x).
Examples
--------
>>> def f(r):return np.dot(r,r)
>>> v = np.ones(2)
>>> cov = np.ones((2,2))
>>> "%.3g" % uncertainty(f,v,cov)
'4'
"""
prop_cov = propagate_covariance(f, np.atleast_1d(x), np.atleast_2d(cov))
return np.sqrt(prop_cov[0, 0])
def quantiles(ds, qs, weights=None):
"""
Compute the quantiles qs of 1-d ds with possible weights.
Parameters
----------
ds : ds to calculate quantiles from
1-d array of numbers
qs : 1-d array of quantiles
weights : 1-d array of weights, optional (default: None)
Is expected to correspond point-to-point to values in ds
Returns
-------
quantiles of ds corresponding to qs
1-d array of equal length to qs
"""
if weights is None:
from scipy.stats.mstats import mquantiles
return mquantiles(ds, qs)
else:
ds = np.atleast_1d(ds)
qs = np.atleast_1d(qs)
weights = np.atleast_1d(weights)
assert len(ds) == len(
weights), "Data and weights arrays need to have equal length!"
assert np.all((qs >= 0) & (qs <= 1)
), "Quantiles need to be within 0 and 1!"
assert np.all(weights > 0), "Each weight must be > 0!"
m_sort = np.argsort(ds)
ds_sort = ds[m_sort]
ws_sort = weights[m_sort]
ps = (np.cumsum(ws_sort) - 0.5 * ws_sort) / np.sum(ws_sort)
return np.interp(qs, ps, ds_sort)
def median(a, weights=None, axis=0):
"""
Compute the median of data in a with optional weights.
Parameters
----------
a : data to calculate median from
n-d array of numbers
weights : weights of equal shape to a
n-d array of numbers
axis : axis to calculate median over (optional, default: 0)
To note, weighted calculation does currently only support 1-d arrays
Returns
-------
Median: float or 1-d array of floats
"""
a = np.atleast_1d(a)
if weights is None:
return np.median(a, axis=axis)
else:
assert a.ndim == 1, "Only 1-d calculation of weighted median is currently supported!"
return quantiles(a, 0.5, weights)[0]
def mad(a, weights=None, axis=0):
"""
Calculate the scaled median absolute deviation of a random distribution.
Parameters
----------
a : array-like
1-d or 2-d array of random numbers.
weights : array-like
Weights corresponding to data in a.
Calculation with weights is currently only supported for 1-d data.
Returns
-------
mad : float or 1-d array of floats
Scaled median absolute deviation of input sample. The scaling factor
is chosen such that the MAD estimates the standard deviation of a
normal distribution.
Notes
-----
The MAD is a robust estimate of the true standard deviation of a random
sample. It is robust in the sense that its output is not sensitive to
outliers.
The standard deviation is usually estimated by the square root of
the sample variance. Note, that just one value in the sample has to be
infinite for the sample variance to be also infinite. The MAD still
provides the desired answer in such a case.
In general, the sample variance is very sensitive to the tails of the
distribution and will give undesired results if the sample distribution
deviates even slightly from a true normal distribution. Many real world
distributions are not exactly normal, so this is a serious issue.
Fortunately, this is not the case for the MAD.
Of course there is a price to pay for these nice features. If the sample is
drawn from a normal distribution, the sample variance is the more
efficient estimate of the true width of the Gaussian, i.e. its
statistical uncertainty is smaller than that of the MAD.
Examples
--------
>>> a = [1.,0.,5.,4.,2.,3.,1e99]
>>> round(mad(a), 3)
2.965
"""
const = 1.482602218505602 # 1.0/inverse_cdf(3/4) of normal distribution
med = median(a, weights=weights, axis=axis)
if axis == 0:
absdevs = np.absolute(a - med)
elif axis == 1:
absdevs = np.absolute(a.T - med).T
return const * median(absdevs, weights=weights, axis=axis)
class ConvexHull:
"""
Calculate the (fractional) convex hull of a point cloud in 2-d.
Parameters
----------
x: 1-d array
vector of parameters
y: 1-d array
vector of parameters
frac: int
fraction of points contained in convex hull, default is 1.0
byprob: boolean
if false and frac < 1.0, will remove points contained in hull shape
if true and frac < 1.0, will remove least probable point based on kde estimate
Returns
-------
points: 2-d array of floats
remaining points to analyses hull object
hull: object generated by scipy.spatial.qhull.ConvexHull
contains information of ConvexHull
Notes
-----
A convex hull can be thought of as a rubber band put around the point cloud.
To plot a closed object, use the simplices contained in "hull".
Examples
--------
>>> m1 = [-0.9, -0.1, -0.0, 0.7, 1.3, 0.4, 0.6, -1.9, 0.2, -1.1]
>>> m2 = [ 0.1, 0.7, -0.9, -0.1, -0.5, -0.7, -0.9, -0.2, -0.2, -0.5]
>>> hull = ConvexHull(m1, m2)
>>> points, hull = hull()
Plot the hull:
for simplex in hull.simplices:
plt.plot(points[simplex, 0], points[simplex, 1], 'k--')
"""
def __init__(self, x, y, frac=1.0, byprob=True):
from scipy.stats import gaussian_kde
self.x = np.atleast_1d(x)
self.y = np.atleast_1d(y)
self.frac = frac
self.remove = byprob
data = np.vstack([self.x, self.y])
self.kernel = gaussian_kde(data)
def __call__(self):
return self.fractionalHull()
def convexHull(self, pos):
from scipy.spatial import ConvexHull
return ConvexHull(pos)
def removal(self, pos, bound):
x = np.array([p[0] for p in pos])
y = np.array([p[1] for p in pos])
for b in range(len(bound)):
px = np.where(x == bound[b][0])
py = np.where(y == bound[b][1])
if px == py:
x = np.delete(x, px)
y = np.delete(y, px)
return x, y
def removeByProb(self, pos, bound):
boundary = np.vstack([bound[:, 0], bound[:, 1]])
prob = self.kernel(boundary)
index = prob.argsort()
prob = prob[index]
boundary = bound[index]
return self.removal(pos, [boundary[0]])
def removePoints(self, pos):
hull = self.convexHull(pos)
boundary = np.dstack((pos[hull.vertices, 0], pos[hull.vertices, 1]))[0]
if not self.remove:
x, y = self.removal(pos, boundary)
if self.remove:
x, y = self.removeByProb(pos, boundary)
points = np.dstack((x, y))[0]
hull = self.convexHull(points)
return points, hull
def fractionalHull(self):
points = np.dstack((self.x.copy(), self.y.copy()))[0]
n = self.frac * len(points)
if self.frac == 1:
hull = self.convexHull(points)
else:
while len(points) > n:
points, hull = self.removePoints(points)
# boundary = np.dstack((points[hull.vertices,0], points[hull.vertices,1]))[0]
return points, hull
def bootstrap(function, x, r=1000):
"""
Generate r balanced bootstrap replicas of x and returns the results of a statistical function on them.
Notes
-----
The bootstrap is a non-parametric method to obtain the statistical bias
and variance of a statistical estimate. In general, the result is
approximate. You should only use this if you have no idea of the
theoretical form of the underlying p.d.f. from which the data are drawn.
Otherwise you should draw samples from that p.d.f., which may be fitted to
the data.
To obtain good results, r has to be in the range of 200 to 1000. As with
every simulation technique, the precision of the result is proportional to
r^(-1/2).
Parameters
----------
function: callable
The statistical function. It has to accept an array of the type of x and may
return a float or another array.
x: array-like
The original input data for the statistical function.
r: int
Number of bootstrap replicas.
Returns
-------
Array of results of statFunc.
"""
n = np.alen(x)
xx = np.array(x)
iB = np.array(np.random.permutation(n * r) % n)
xbGen = (xx[iB[ir * n:(ir + 1) * n]] for ir in range(r))
ybs = map(function, xbGen)
return np.array(ybs)
def bootstrap_confidence_interval(statfunc, x, coverage=0.68, replicas=1000):
"""
Calculate the bootstrap confidence interval of the result of a statistical function.
Notes
-----
See remarks of BootstrapReplicas.
Parameters
----------
statfunc: callable
The statistical function. It has to accept an array of the type of x and may
return a float or another array.
x: array-like
The original input data for the statistical function.
coverage: float
Fraction of bootstrap replicas inside the interval.
replicas: integer
Number of bootstrap replicas (defines accuracy of interval)
Returns
-------
v,dv-,dv+ : floats or arrays of floats
statfunc(x), downward uncertainty interval, upward uncertainty interval
"""
if len(x) == 0:
return 0, 0, 0
r = int(round(replicas / 200.0)) * 200 # has to be multiple of 200
q = int(round(r * coverage))
qA = (r - q) / 2
qB = r - qA
t = statfunc(x)
tB = np.sort(bootstrap(statfunc, x, r), axis=0)
return t, t - tB[qA], tB[qB] - t
def bootstrap_covariance(statfunc, x, r=1000):
"""
Calculate the uncertainty of statfunc over data set x with a balanced bootstrap.
Notes
-----
See remarks of BootstrapReplicas.
Parameters
----------
statfunc: callable
The statistical function. It has to be callable as statfunc(x)
and may return a float or another array.
x: array-like
The original input data for the statistical function.
Returns
-------
The covariance matrix of the result of statfunc.
"""
return np.cov(bootstrap(statfunc, x, r))
def binomial_proportion(nsel, ntot, coverage=0.68):
"""
Calculate a binomial proportion (e.g. efficiency of a selection) and its confidence interval.
Parameters
----------
nsel: array-like
Number of selected events.
ntot: array-like
Total number of events.
coverage: float (optional)
Requested fractional coverage of interval (default: 0.68).
Returns
-------
p: array of dtype float
Binomial fraction.
dpl: array of dtype float
Lower uncertainty delta (p - pLow).
dpu: array of dtype float
Upper uncertainty delta (pUp - p).
Examples
--------
>>> p, dpl, dpu = binomial_proportion(50,100,0.68)
>>> round(p, 3)
0.5
>>> round(dpl, 3)
0.049
>>> round(dpu, 3)
0.049
>>> abs(np.sqrt(0.5*(1.0-0.5)/100.0)-0.5*(dpl+dpu)) < 1e-3
True
Notes
-----
The confidence interval is approximate and uses the score method
of Wilson. It is based on the log-likelihood profile and can
undercover the true interval, but the coverage is on average
closer to the nominal coverage than the exact Clopper-Pearson
interval. It is impossible to achieve perfect nominal coverage
as a consequence of the discreteness of the data.
"""
from scipy.stats import norm
z = norm().ppf(0.5 + 0.5 * coverage)
z2 = z * z
p = np.asarray(nsel, dtype=np.float) / ntot
div = 1.0 + z2 / ntot
pm = (p + z2 / (2 * ntot))
dp = z * np.sqrt(p * (1.0 - p) / ntot + z2 / (4 * ntot * ntot))
pl = (pm - dp) / div
pu = (pm + dp) / div
return p, p - pl, pu - p
def poisson_uncertainty(x):
"""
Return "exact" confidence intervals, assuming a Poisson distribution for k.
Notes
-----
Exact confidence intervals from the Neyman construction tend to overcover
discrete distributions like the Poisson and Binomial distributions. This
is due to the discreteness of the observable and cannot be avoided.