-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaths.py
1234 lines (999 loc) · 34.7 KB
/
maths.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
"""
Module maths provides useful mathematic tools.
(see also https://github.com/yketa/active_particles/tree/master/maths.py)
"""
import numpy as np
from numpy.polynomial.polynomial import polyadd, polypow
import math
from collections import OrderedDict
from scipy import optimize
from active_work.scde import PDF
#####################
### MISCELLANEOUS ###
#####################
def relative_positions(positions, point, box_size):
"""
Returns relative positions to point in box of extent
(-box_size/2, box_size) in both dimensions of space.
Parameters
----------
positions : float array
Position of single point or array of positions.
point : float array
Position of the new centre.
box_size : float or array
Length of the box in one dimension or all dimensions.
Returns
-------
rel_positions : float array
Relative positions.
"""
return (np.array(positions) - np.array(point)
+ np.array(box_size)/2)%np.array(box_size) - np.array(box_size)/2
def wo_mean(arr):
"""
Returns deviation of values in array with respect to mean of array.
Parameters
----------
arr : array like
Array of values.
Returns
-------
dev_arr : array like
Deviations from mean of array.
"""
return np.array(arr) - np.mean(arr, axis=0)
class DictList(dict):
"""
Custom hash table class to give value [] to uninitialised keys.
"""
def __init__(self):
super().__init__()
def __getitem__(self, key):
try:
return super().__getitem__(key)
except KeyError:
return []
def normalise1D(*vector):
"""
Returs 1D vector of unitary norm with same direction.
Parameters
----------
vector : 1D array-like or coordinates as positional arguments
Vector to normalise.
Returns
-------
u_vector : 1D Numpy array
Unitary vector with same direction.
"""
vector = np.array(vector).flatten() # 1D vector
norm = np.linalg.norm(vector) # vector norm
if norm == 0: return vector # vector is 0
return vector/norm
def amplogwidth(arr, factor=2):
"""
Calculates the amplitudes of elements in array arr and, excluding the
zeros, returns the mean of the logarithms of these amplitudes plus and
minus factor times their standard deviation.
Parameters
----------
arr : array like
Array.
factor : float
Width factor. (default: 2)
Returns
-------
min : float
E(log(||arr||)) - factor*V(log(||arr||))
max : float
E(log(||arr||)) + factor*V(log(||arr||))
"""
log = np.ma.log10(np.sqrt(np.sum(arr**2, axis=-1))) # logarithms of amplitudes
mean = log.mean() # means of logarithms of amplitudes
std = log.std() # standard deviation of logarithms of amplitudes
return mean - factor*std, mean + factor*std
def mean_sterr(values, remove=False, max=None):
"""
Returns mean and standard error of values.
Parameters
----------
values : float array
Values.
remove : bool
Remove inf and -inf as well as nan. (default: False)
NOTE: A warning will be issued if remove == False and such objects are
encountered.
NOTE: This is not guaranteed to work non-1D arrays as the shape may
change.
max : float or None
Remove data which is strictly above max in absolute value.
(default: None)
NOTE: max != None will trigger remove = True.
Returns
-------
mean : float or float Numpy array
Mean of values.
sterr : float or float Numpy array
Standard error of values = std(...)/sqrt(len(...)).
NOTE: This is relevant if all values are independent.
"""
if max != None: remove = True
values = np.array(values)
if remove: values = (
(lambda _: _[~np.isinf(_)])( # remove inf
(lambda __: __[~np.isnan(__)])( # remove nan
values)))
if max != None: values = values[np.abs(values) <= max]
if values.size == 0: return None, None
return values.mean(axis=0), values.std(axis=0)/np.sqrt(values.shape[0])
def aggregate(array, n):
"""
Aggregate `array' by taking mean of bits of `n' consecutive values on last
axis.
Parameters
----------
array : float array-like
Array to aggregate.
n : int
Size of bits to aggregate.
Returns
-------
out : float Numpy array
Aggregated array.
"""
array = np.array(array)
return (np.array(
np.split(array, array.shape[-1]//n, axis=-1))
.transpose(
tuple(i for i in range(1, len(array.shape)))
+ (0, len(array.shape)))
.mean(axis=-1))
def cov(array1, array2):
"""
Return covariance of variables `array1' and `array2'.
Cov(`array1', `array2') = <`array1'*`array2'> - <`array1'><`array2'>
NOTE: `array1' and `array2' have to be the same size.
Parameters
----------
array1 : float array-like
First set of measurements.
array2 : float array-like
Second set of measurements.
Returns
-------
covariance : float
Cov(`array1', `array2') = <`array1'*`array2'> - <`array1'><`array2'>.
"""
return (lambda a, b: (a*b).mean() - a.mean()*b.mean())(
*(np.array(array1), np.array(array2)))
def divide_arrays(array1, array2):
"""
Divide array1 by array2, and outputs 0 values where array2 is equal to 0.
NOTE: array1, array2 and out must have the same shapes.
Parameters
----------
array1 : array-like
Numerator array.
array2 : array-like
Denominator array.
Returns
-------
array : array-like
Quotient array.
"""
if not(isinstance(array1, np.ndarray)): array1 = np.array(array1)
if not(isinstance(array2, np.ndarray)): array2 = np.array(array2)
return np.divide(array1, array2,
out=np.zeros(array1.shape, dtype=array1.dtype), where=array2!=0)
def linspace(init, fin, number, endpoint=True):
"""
Returns linearly spaced integer between `init' and `fin' with a maximum of
`number' of them.
Parameters
----------
init : int
Minimum value.
fin : int
Maximum value.
number : int
Number of values.
endpoint : bool
Include `number' in the array.
Returns
-------
values : numpy array
Array of values.
"""
return np.array(list(OrderedDict.fromkeys(np.linspace(
init, fin, number,
endpoint=endpoint, dtype=int))))
def logspace(init, fin, number, endpoint=True):
"""
Returns logarithmically spaced integer between `init' and `fin' with a
maximum of `number' of them.
Parameters
----------
init : int
Minimum value.
fin : int
Maximum value.
number : int
Number of values.
endpoint : bool
Include `number' in the array.
Returns
-------
values : numpy array
Array of values.
"""
return np.array(list(OrderedDict.fromkeys(map(lambda x: int(round(x)),
np.exp(np.linspace(
np.log(init), np.log(fin), number,
endpoint=endpoint))))))
def meanStdCut(array, cut=None):
"""
Returns mean and standard deviation of array with values farther than
`cut' * array.std() from the mean removed.
Parameters
----------
array : array-like
Array of values.
cut : float
Width in units of array.std() to consider. (default: None)
NOTE: if cut==None, then no value is excluded.
Returns
-------
mean : float
Mean of the truncated ensemble.
std : float
Standard deviation of the truncated ensemble.
"""
array = np.array(array)
if cut == None: return array.mean(), array.std()
array = array[np.abs(array - array.mean()) < cut*array.std()]
return array.mean(), array.std()
def angle(dx, dy):
"""
Returns angle from in x- and y-coordinates.
Parameters
----------
dx : float
x-coordinate or difference in x-coordinate.
dy : float
y-coordinate or difference in y-coordinate.
Returns
-------
ang : float
Corresponding angle in radians.
"""
return math.atan2(dy, dx)
class CurveFit:
"""
Fit a 1-variable scalar function to data points and evaluate with
uncertainty. (see scipy.optimize.curve_fit)
"""
def __init__(self, func, xdata, ydata, jac=None, **kwargs):
"""
Fit curve to data points. (see scipy.optimize.curve_fit)
Parameters
----------
func : callable scalar function
Model function, f(x, ...), taking the independent variable as the
first argument and the parameters to fit as separate remaining
arguments.
xdata : float array-like
x-data to fit.
ydata : float array-like
y-data to fit.
jac : callable 1D-array-like function or None
Jacobian matrix of the model function with respect to parameters.
(default: None)
NOTE: standard deviations will not be computed if jac == None.
Optional keyword arguments
--------------------------
Additional keyword arguments will be passed to scipy.optimize.curve_fit.
"""
self.func = func
self.jac = jac
self.xdata = np.array(xdata)
self.ydata = np.array(ydata)
self.curve_fit_kwargs = kwargs
self.popt, self.pcov = optimize.curve_fit(
self.func, self.xdata, self.ydata,
#jac=self.jac,
**self.curve_fit_kwargs)
def eval(self, *x):
"""
Evaluate fitted curve with standard deviation.
Parameters
----------
x : float
x-data.
Returns
-------
y : float Numpy array
Fitted y-data.
sigma : float Numpy array
Uncertainty on y-data.
"""
y = np.array(list(map(lambda _: self.func(_, *self.popt), x)))
sigma = np.array(list(map(lambda _: self._sigma(_), x)))
return y, sigma
def _sigma(self, x):
"""
Evaluate standard deviation at point `x'.
Parameters
----------
x : float
x-data.
Returns
-------
sigma : float
Standard deviation at `x'.
NOTE: returns 0 if self.jac == None.
"""
if self.jac is None: return 0
return np.sqrt(
np.dot(
self.jac(x, *self.popt),
np.dot(
self.pcov,
np.transpose(self.jac(x, *self.popt)))))
###################
### POLYNOMIALS ###
###################
def evalPol(pol, *x):
"""
Evaluate polynomial. (see numpy.polyeval)
NOTE: Returns None if x == None.
Parameters
----------
pol : (*,) float array-like
Polynomial coefficients (highest first).
x : float
Values at which to evaluate the polynomial.
Returns
-------
y : (*,) float Numpy array
Evaluated polynomial.
"""
return np.array(list(map(
lambda _x: None if _x == None else np.polyval(pol, _x),
x)))
def addPol(*pol):
"""
Wrapper around numpy.polynomial.polynomial.polyadd to sum several
polynomials at once.
Parameters
----------
pol : (*,) float array-like
Polynomial coefficients (lowest first).
Returns
-------
sum : (*,) float array-like
Sum of polynomials.
"""
sum = np.zeros((1,))
for p in pol:
sum = polyadd(sum, p)
return sum
class Polynomial:
"""
Store and evaluate polynomials with covariance matrix on their
coefficients.
"""
def __init__(self, pol, cov):
"""
Compute standard devation polynomial.
Considering we have polynomial
P(x) = \\sum_i a_i x^i,
and \\sigma_ij the covariance of the i-th and j-th coefficients, a_i and
a_j, we compute
\\sigma_f(x) = \\sqrt(\\sum_ij \\sigma_ij x^{i+j})
as the variance of the polynomial f evaluated at x.
(see https://en.wikipedia.org/wiki/Propagation_of_uncertainty)
Parameters
----------
pol : (N,) float array-like
Polynomial coefficients (highest first).
cov : (N, N) float-array like
Covariance matrix.
"""
pol, cov = np.array(pol), np.array(cov)
if cov.shape != (pol.size, pol.size): raise ValueError
self.pol = pol
self.deg = len(self.pol) - 1
self.cov = cov
self.covpol = np.zeros((2*self.deg + 1,)) # covariance polynomial for estimation of standard deviation
for i in range(self.deg + 1):
for j in range(self.deg + 1):
self.covpol[i + j] += self.cov[i, j]
def eval(self, *x, sigma=False):
"""
Evaluate polynomial and standard deviation.
Parameters
----------
x : float
x-values at which to evaluate the polynomial.
sigma : bool
Return associated standard deviation. (default: False)
Returns
-------
y : (*,) float Numpy array
Evaluated polynomial.
std : [if sigma] (*,) float Numpy array
Evaluated standard deviation.
"""
y = evalPol(self.pol, *x)
if sigma: return y, np.sqrt(evalPol(self.covpol, *x))
return y
class CompPol(Polynomial):
"""
Create polynomial from composition of two others.
"""
def __init__(self, pol1, pol2):
"""
Composes two polynomials (i.e., `pol1'(`pol2')) with distinct covariance
matrices.
Considering we have polynomials
f(x) = \\sum_i a_i x^i,
g(x) = \\sum_j b_j x^j,
with variances \\sigma_f and \\sigma_g when evaluated (see
active_work.maths.Polynomial), we compute
\\sigma_fg(x) = \\sigma_f(g(x))
+ \\sigma_g(x) \\times [ \\sum_i i a_i g(x)^{i-1} ]^2,
as the variance of the composed polynomial f(g) evaluated at x. We
stress that this considers no correlations between the coefficients of
the polynomials.
(see https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Non-linear_combinations)
Parameters
----------
pol1 : active_work.maths.Polynomial
First polynomial.
pol2 : active_work.maths.Polynomial
Second polynomial.
Returns
-------
pol : active_work.maths.Polynomial
Composed polynomial.
"""
self._pol1, self._pol2 = pol1, pol2
self.deg = self._pol1.deg*self._pol2.deg # degree of composed polynomial
# WARNING: numpy.polynomial.polynomial.polyadd and polypow considers
# arrays as polynomials with lowest coefficient first,
# contrarily to polyval and polyfit.
_pol1, _pol2 = self._pol1.pol[::-1], self._pol2.pol[::-1]
self.pol = np.zeros((1,)) # composed polynomial
for i in range(pol1.deg + 1):
self.pol = polyadd(self.pol, _pol1[i]*polypow(_pol2, i))
self.pol = self.pol[::-1]
def eval(self, *x, sigma=False):
"""
Evaluate polynomial and standard deviation.
Parameters
----------
x : float
x-values at which to evaluate the polynomial.
sigma : bool
Return associated standard deviation. (default: False)
Returns
-------
y : (*,) float Numpy array
Evaluated polynomial.
std : [if sigma] (*,) float Numpy array
Evaluated standard deviation.
"""
y = self._pol1.eval(*self._pol2.eval(*x, sigma=False), sigma=False)
if sigma:
var = np.array(list(map(
lambda _x, _gx:
evalPol(self._pol1.covpol, _gx)[0]
+ evalPol(self._pol2.covpol, _x)[0]*(np.sum(
[k*self._pol1.pol[-1-k]*(_gx**(k - 1))
for k in range(1, self._pol1.deg + 1)])**2),
*(x, self._pol2.eval(*x, sigma=False)))))
return y, np.sqrt(var)
return y
class PolyFit(Polynomial):
"""
Perform least squares polynomial fit and evaluate fit. (see numpy.polyfit)
"""
def __init__(self, x, y, deg=1):
"""
Perform fit.
Parameters
----------
x : (*,) float array-like
x-coordinates of sample points.
y : (*,) float array-like
y-coordinates of sample points.
deg : int
Degree of the fitting polynomial. (default: 1)
"""
self.x = np.array(x)
self.xmin = self.x.min()
self.xmax = self.x.max()
self.y = np.array(y)
self.ymin = self.y.min()
self.ymax = self.y.max()
pol, cov = np.polyfit(self.x, self.y, deg, cov=True)
Polynomial.__init__(self, pol, cov)
def eval(self, *x, restrict=False, sigma=False):
"""
Evaluate polynomial and standard deviation.
(see active_work.maths.Polynomial.eval)
Parameters
----------
x : float
x-values at which to evaluate the polynomial.
restrict : bool
Discard x-values which are not in the range of the original data.
(default: False)
sigma : bool
Return associated standard deviation. (default: False)
Returns
-------
y : (*,) float Numpy array
Evaluated polynomial.
std : [if sigma] (*,) float Numpy array
Evaluated standard deviation.
"""
if restrict:
x = np.array(x)
for i in range(len(x)):
if x[i] == None: continue
if x[i] < self.xmin or x[i] > self.xmax: x[i] = None
return super().eval(*x, sigma=sigma)
#####################
### DISTRIBUTIONS ###
#####################
class Distribution:
"""
Analyse distribution from array of values.
"""
def __init__(self, valuesArray):
"""
Define array of values.
Parameters
----------
valuesArray : float array-like
Array of values.
"""
self.valuesArray = np.array(valuesArray).flatten()
self.min = self.valuesArray.min()
self.max = self.valuesArray.max()
self.mean = self.valuesArray.mean()
self.std = self.valuesArray.std()
def pdf(self):
"""
Returns probability density function from array of values.
Returns
-------
axes : numpy array
Values at which the probability density function is evaluated.
pdf : float numpy array
Values of the probability density function.
"""
pdf = PDF(self.valuesArray)
return pdf.axes[0], pdf.pdf
def hist(self, nBins, vmin=None, vmax=None, log=False,
rescaled_to_max=False):
"""
Returns histogram of array of values.
Parameters
----------
nBins : int
Number of bins of the histogram.
vmin : float
Minimum value of the bins. (default: None)
NOTE: if vmin==None, then minimum of array is taken.
vmax : float
Maximum value of the bins. (default: None)
NOTE: if vmax==None, then maximum of array is taken.
log : bool
Consider the log of the occupancy of the bins. (default: False)
rescaled_to_max : bool
Rescale occupancy of the bins by its maximum over bins.
(default: False)
Returns
-------
bins : float numpy array
Values of the bins.
hist : float numpy array
Occupancy of the bins.
"""
if vmin == None: vmin = self.min
if vmax == None: vmax = self.max
histogram = Histogram(nBins, vmin, vmax, log=False)
histogram.values = self.valuesArray
bins = histogram.bins
hist = histogram.get_histogram()
if rescaled_to_max: hist /= hist.max()
if not(log): return bins, hist
else: return bins[hist > 0], np.log(hist[hist > 0])
def gauss(self, *x, cut=None, rescaled_to_max=False):
"""
Returns values of the Gaussian function corresponding to the mean and
variance of the array of values.
Parameters
----------
x : float
Values at which to evaluate the Gaussian function.
cut : float or None
Width in units of the standard deviation of the array of values to
consider when computing mean and standard deviation.
(see self._meanStdCut) (default: None)
NOTE: if cut==None, the width is taken to infinity, i.e. no value is
excluded.
rescaled_to_max : bool
Rescale function by its computed maximum. (default: False)
Returns
-------
gauss : float numpy array
Values of the Gaussian function at x.
"""
mean, std = self._meanStdCut(cut=cut)
if rescaled_to_max: norm = 1
else: norm = np.sqrt(2*np.pi*(std**2))
gauss = lambda y: (
np.exp(-((y - mean)**2)/(2*(std**2)))
/norm)
return np.array(list(map(gauss, x)))
def _meanStdCut(self, cut=None):
"""
Returns mean and standard deviation of values of array with values
farther than `cut' * self.valuesArray.std() if the mean removed.
Parameters
----------
array : array-like
Array of values.
cut : float
Width in units of self.valuesArray.std() to consider.
(default: None)
NOTE: if cut==None, then no value is excluded.
Returns
-------
mean : float
Mean of the truncated ensemble.
std : float
Standard deviation of the truncated ensemble.
"""
return meanStdCut(self.valuesArray, cut=cut)
class JointDistribution:
"""
Analyse joint distribution from 2 arrays of values.
"""
def __init__(self, valuesArray1, valuesArray2):
"""
Define array of values.
Parameters
----------
valuesArray1 : float array-like
First array of values.
valuesArray2 : float array-like
Second array of values.
"""
self.valuesArray1 = np.array(valuesArray1).flatten()
self.valuesArray2 = np.array(valuesArray2).flatten()
self.min1 = self.valuesArray1.min()
self.max1 = self.valuesArray1.max()
self.min2 = self.valuesArray2.min()
self.max2 = self.valuesArray2.max()
def pdf(self):
"""
Returns joint probability density function from arrays of values.
Returns
-------
pdf3D : (*, 3) float Numpy array
(0) Value of the first quantity at which the PDF is evaluated.
(1) Value of the second quantity at which the PDF is evaluated.
(2) PDF.
"""
pdf = PDF(self.valuesArray1, self.valuesArray2)
return np.transpose(
[*(lambda axes: [axes[:, -1], axes[:, -2]])( # invert axes order
(pdf.extended_axes.reshape(np.prod(pdf.pdf.shape), 2))),
pdf.pdf.flatten()])
def hist(self, nBins, vmin1=None, vmax1=None, vmin2=None, vmax2=None):
"""
Returns 3D histogram of arrays of values.
Parameters
----------
nBins : int or 2-uple-like of int
Number of bins of the histogram in all or each direction.
vmin1 : float
Minimum value of the bins for the first array. (default: None)
NOTE: if vmin1==None, then minimum of array is taken.
vmax1 : float
Maximum value of the bins for the first array. (default: None)
NOTE: if vmax1==None, then maximum of array is taken.
vmin2 : float
Minimum value of the bins for the second array. (default: None)
NOTE: if vmin2==None, then minimum of array is taken.
vmax2 : float
Maximum value of the bins for the second array. (default: None)
NOTE: if vmax2==None, then maximum of array is taken.
Returns
-------
hist : (nBins.prod(), 3) float Numpy array
Values of the histogram:
(0) Bin value of the first quantity.
(1) Bin value of the second quantity.
(2) Proportion.
"""
if vmin1 == None: vmin1 = self.min1
if vmax1 == None: vmax1 = self.max1
if vmin2 == None: vmin2 = self.min2
if vmax2 == None: vmax2 = self.max2
histogram = Histogram3D(nBins, (vmin1, vmin2), (vmax1, vmax2),
log=False)
histogram.values = np.array(list(
zip(self.valuesArray1, self.valuesArray2)))
return histogram.get_histogram()
##################
### HISTOGRAMS ###
##################
class Histogram:
"""
Make histogram from lists of float values.
"""
def __init__(self, Nbins, vmin, vmax, log=False):
"""
Parameters
----------
Nbins : int
Number of histogram bins.
vmin : float
Minimum included value for histogram bins.
NOTE: values lesser than vmin will be ignored.
vmax : float
Maximum excluded value for histogram bins.
NOTE: values greater or equal to vmax will be ignored.
log : bool.
Logarithmically spaced histogram values. (default: False)
"""
self.Nbins = int(Nbins)
self.vmin = vmin
self.vmax = vmax
if log:
self.bins = np.logspace(np.log10(self.vmin), np.log10(self.vmax),
self.Nbins, endpoint=False, base=10) # histogram bins
else:
self.bins = np.linspace(self.vmin, self.vmax,
self.Nbins, endpoint=False) # histogram bins
self.reset_values() # reset values from which to compute the histogram
self.hist = np.empty(self.Nbins) # values of the histogram at bins
def add_values(self, *values, replace=False):
"""
Add values from which to compute the histogram.
Parameters
----------
values : float or float array-like
Values to add.
replace : bool
Replace existing values. (default: False)
"""
if replace: self.reset_values()
for value in values: self.values = np.append(self.values, value)
def reset_values(self):
"""
Delete values from which to compute the histogram (self.values).
"""
self.values = np.array([])
def get_histogram(self):
"""
Get histogram from values in self.values.
Returns
-------
hist : Numpy array
Values of the histogram at self.bins.
"""
for bin in range(self.bins.size):
bin_inf = self.bins[bin]
try: bin_sup = self.bins[bin + 1]
except IndexError: bin_sup = self.vmax
self.hist[bin] = np.sum(
(self.values >= bin_inf)*(self.values < bin_sup))
binned_values = np.sum(self.hist)
if binned_values == 0: return self.hist # no binned value
else: self.hist /= np.sum(self.hist)
return self.hist
class Histogram3D:
"""
Make 3D histogram from lists of float 2-uples-like.
"""
def __init__(self, Nbins, vmin, vmax, log=False):