-
Notifications
You must be signed in to change notification settings - Fork 134
/
powerlaw.py
2855 lines (2498 loc) · 107 KB
/
powerlaw.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
#The MIT License (MIT)
#
#Copyright (c) 2013-2021 Jeff Alstott
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
# as described in https://docs.python.org/2/library/functions.html#print
from __future__ import print_function
import sys
__version__ = "1.5"
# This needs to be a list of the keys in the supported_distributions
# attribute of the Fit class. The __getattr__ method needs the list.
# If it uses supported_distributions.keys(), then it gets into an
# infinte loop when unpickling a Fit object. Hence the need for a
# separate list outside the scope of the Fit class.
supported_distribution_list = ['power_law',
'lognormal',
'exponential',
'truncated_power_law',
'stretched_exponential',
'lognormal_positive']
class Fit(object):
"""
A fit of a data set to various probability distributions, namely power
laws. For fits to power laws, the methods of Clauset et al. 2007 are used.
These methods identify the portion of the tail of the distribution that
follows a power law, beyond a value xmin. If no xmin is
provided, the optimal one is calculated and assigned at initialization.
Parameters
----------
data : list or array
discrete : boolean, optional
Whether the data is discrete (integers).
xmin : int or float, optional
The data value beyond which distributions should be fitted. If
None an optimal one will be calculated.
xmax : int or float, optional
The maximum value of the fitted distributions.
verbose: bool, optional
Whether to print updates about where we are in the fitting process.
Default True.
estimate_discrete : bool, optional
Whether to estimate the fit of a discrete power law using fast
analytical methods, instead of calculating the fit exactly with
slow numerical methods. Very accurate with xmin>6
sigma_threshold : float, optional
Upper limit on the standard error of the power law fit. Used after
fitting, when identifying valid xmin values.
parameter_range : dict, optional
Dictionary of valid parameter ranges for fitting. Formatted as a
dictionary of parameter names ('alpha' and/or 'sigma') and tuples
of their lower and upper limits (ex. (1.5, 2.5), (None, .1)
pdf_ends_at_xmax: bool, optional
Whether to use the pdf that has an upper cutoff at xmax to fit the
powerlaw distribution.
"""
def __init__(self, data,
discrete=False,
xmin=None, xmax=None,
verbose=True,
fit_method='Likelihood',
estimate_discrete=True,
discrete_approximation='round',
sigma_threshold=None,
parameter_range=None,
fit_optimizer=None,
xmin_distance='D',
xmin_distribution='power_law',
pdf_ends_at_xmax=False,
**kwargs):
self.data_original = data
# import logging
from numpy import asarray
self.data = asarray(self.data_original, dtype='float')
if self.data.ndim != 1:
raise ValueError("Input data must be one-dimensional")
self.discrete = discrete
self.fit_method = fit_method
self.estimate_discrete = estimate_discrete
self.discrete_approximation = discrete_approximation
self.sigma_threshold = sigma_threshold
self.parameter_range = parameter_range
self.given_xmin = xmin
self.given_xmax = xmax
self.xmin = self.given_xmin
self.xmax = self.given_xmax
self.xmin_distance = xmin_distance
self.pdf_ends_at_xmax = pdf_ends_at_xmax
if 0 in self.data:
if verbose: print("Values less than or equal to 0 in data. Throwing out 0 or negative values", file=sys.stderr)
self.data = self.data[self.data>0]
if self.xmax:
self.xmax = float(self.xmax)
self.fixed_xmax = True
n_above_max = sum(self.data>self.xmax)
self.data = self.data[self.data<=self.xmax]
else:
n_above_max = 0
self.fixed_xmax = False
if not all(self.data[i] <= self.data[i+1] for i in range(len(self.data)-1)):
from numpy import sort
self.data = sort(self.data)
self.fitting_cdf_bins, self.fitting_cdf = cdf(self.data, xmin=None, xmax=self.xmax)
self.supported_distributions = {'power_law': Power_Law,
'lognormal': Lognormal,
'exponential': Exponential,
'truncated_power_law': Truncated_Power_Law,
'stretched_exponential': Stretched_Exponential,
'lognormal_positive': Lognormal_Positive,
}
#'gamma': None}
self.xmin_distribution = self.supported_distributions[xmin_distribution]
self.xmin_distribution.pdf_ends_at_xmax = self.pdf_ends_at_xmax
if xmin and type(xmin)!=tuple and type(xmin)!=list:
self.fixed_xmin = True
self.xmin = float(xmin)
self.noise_flag = None
pl = Power_Law(xmin=self.xmin,
xmax=self.xmax,
discrete=self.discrete,
fit_method=self.fit_method,
estimate_discrete=self.estimate_discrete,
data=self.data,
parameter_range=self.parameter_range,
pdf_ends_at_xmax=self.pdf_ends_at_xmax)
setattr(self,self.xmin_distance, getattr(pl, self.xmin_distance))
self.alpha = pl.alpha
self.sigma = pl.sigma
#self.power_law = pl
else:
self.fixed_xmin=False
if verbose:
print("Calculating best minimal value for {} fit".format(
xmin_distribution.replace('_',' '), file=sys.stderr))
self.find_xmin()
self.data = self.data[self.data>=self.xmin]
self.n = float(len(self.data))
self.n_tail = self.n + n_above_max
def __getattr__(self, name):
if name in supported_distribution_list:
#from string import capwords
#dist = capwords(name, '_')
#dist = globals()[dist] #Seems a hack. Might try import powerlaw; getattr(powerlaw, dist)
dist = self.supported_distributions[name]
if dist == Power_Law:
parameter_range = self.parameter_range
else:
parameter_range = None
setattr(self,
name,
dist(data=self.data,
xmin=self.xmin,
xmax=self.xmax,
discrete=self.discrete,
fit_method=self.fit_method,
estimate_discrete=self.estimate_discrete,
discrete_approximation=self.discrete_approximation,
parameter_range=parameter_range,
parent_Fit=self))
return getattr(self, name)
else:
raise AttributeError(name)
def find_xmin(self, xmin_distance=None):
"""
Returns the optimal xmin beyond which the scaling regime of the power
law fits best. The attribute self.xmin of the Fit object is also set.
The optimal xmin beyond which the scaling regime of the power law fits
best is identified by minimizing the Kolmogorov-Smirnov distance
between the data and the theoretical power law fit.
This is the method of Clauset et al. 2007.
"""
from numpy import unique, asarray, argmin, nan, repeat, arange
#Much of the rest of this function was inspired by Adam Ginsburg's plfit code,
#specifically the mapping and sigma threshold behavior:
#http://code.google.com/p/agpy/source/browse/trunk/plfit/plfit.py?spec=svn359&r=357
if not self.given_xmin:
possible_xmins = self.data
else:
possible_ind = min(self.given_xmin)<=self.data
possible_ind *= self.data<=max(self.given_xmin)
possible_xmins = self.data[possible_ind]
xmins, xmin_indices = unique(possible_xmins, return_index=True)
#Don't look at last xmin, as that's also the xmax, and we want to at least have TWO points to fit!
xmins = xmins[:-1]
xmin_indices = xmin_indices[:-1]
if xmin_distance is None:
xmin_distance = self.xmin_distance
if len(xmins)<=0:
print("Less than 2 unique data values left after xmin and xmax "
"options! Cannot fit. Returning nans.", file=sys.stderr)
from numpy import nan, array
self.xmin = nan
self.D = nan
self.V = nan
self.Asquare = nan
self.Kappa = nan
self.alpha = nan
self.sigma = nan
self.n_tail = nan
setattr(self, xmin_distance+'s', array([nan]))
self.alphas = array([nan])
self.sigmas = array([nan])
self.in_ranges = array([nan])
self.xmins = array([nan])
self.noise_flag = True
return self.xmin
def fit_function(xmin, idx, num_xmins):
print('xmin progress: {:02d}%'.format(int(idx/num_xmins * 100)), end='\r')
pl = self.xmin_distribution(xmin=xmin,
xmax=self.xmax,
discrete=self.discrete,
estimate_discrete=self.estimate_discrete,
fit_method=self.fit_method,
data=self.data,
parameter_range=self.parameter_range,
parent_Fit=self,
pdf_ends_at_xmax=self.pdf_ends_at_xmax)
if not hasattr(pl, 'sigma'):
pl.sigma = nan
if not hasattr(pl, 'alpha'):
pl.alpha = nan
return getattr(pl, xmin_distance), pl.alpha, pl.sigma, pl.in_range()
num_xmins = len(xmins)
fits = asarray(list(map(fit_function, xmins, arange(num_xmins), repeat(num_xmins, num_xmins))))
# logging.warning(fits.shape)
setattr(self, xmin_distance+'s', fits[:,0])
self.alphas = fits[:,1]
self.sigmas = fits[:,2]
self.in_ranges = fits[:,3].astype(bool)
self.xmins = xmins
good_values = self.in_ranges
if self.sigma_threshold:
good_values = good_values * (self.sigmas < self.sigma_threshold)
if good_values.all():
min_D_index = argmin(getattr(self, xmin_distance+'s'))
self.noise_flag = False
elif not good_values.any():
min_D_index = argmin(getattr(self, xmin_distance+'s'))
self.noise_flag = True
else:
from numpy.ma import masked_array
masked_Ds = masked_array(getattr(self, xmin_distance+'s'), mask=~good_values)
min_D_index = masked_Ds.argmin()
self.noise_flag = False
if self.noise_flag:
print("No valid fits found.", file=sys.stderr)
#Set the Fit's xmin to the optimal xmin
self.xmin = xmins[min_D_index]
setattr(self, xmin_distance, getattr(self, xmin_distance+'s')[min_D_index])
self.alpha = self.alphas[min_D_index]
self.sigma = self.sigmas[min_D_index]
#Update the fitting CDF given the new xmin, in case other objects, like
#Distributions, want to use it for fitting (like if they do KS fitting)
self.fitting_cdf_bins, self.fitting_cdf = self.cdf()
return self.xmin
def nested_distribution_compare(self, dist1, dist2, nested=True, **kwargs):
"""
Returns the loglikelihood ratio, and its p-value, between the two
distribution fits, assuming the candidate distributions are nested.
Parameters
----------
dist1 : string
Name of the first candidate distribution (ex. 'power_law')
dist2 : string
Name of the second candidate distribution (ex. 'exponential')
nested : bool or None, optional
Whether to assume the candidate distributions are nested versions
of each other. None assumes not unless the name of one distribution
is a substring of the other. True by default.
Returns
-------
R : float
Loglikelihood ratio of the two distributions' fit to the data. If
greater than 0, the first distribution is preferred. If less than
0, the second distribution is preferred.
p : float
Significance of R
"""
return self.distribution_compare(dist1, dist2, nested=nested, **kwargs)
def distribution_compare(self, dist1, dist2, nested=None, **kwargs):
"""
Returns the loglikelihood ratio, and its p-value, between the two
distribution fits, assuming the candidate distributions are nested.
Parameters
----------
dist1 : string
Name of the first candidate distribution (ex. 'power_law')
dist2 : string
Name of the second candidate distribution (ex. 'exponential')
nested : bool or None, optional
Whether to assume the candidate distributions are nested versions
of each other. None assumes not unless the name of one distribution
is a substring of the other.
Returns
-------
R : float
Loglikelihood ratio of the two distributions' fit to the data. If
greater than 0, the first distribution is preferred. If less than
0, the second distribution is preferred.
p : float
Significance of R
"""
if (dist1 in dist2) or (dist2 in dist1) and nested is None:
print("Assuming nested distributions", file=sys.stderr)
nested = True
dist1 = getattr(self, dist1)
dist2 = getattr(self, dist2)
loglikelihoods1 = dist1.loglikelihoods(self.data)
loglikelihoods2 = dist2.loglikelihoods(self.data)
return loglikelihood_ratio(
loglikelihoods1, loglikelihoods2,
nested=nested,
**kwargs)
def loglikelihood_ratio(self, dist1, dist2, nested=None, **kwargs):
"""
Another name for distribution_compare.
"""
return self.distribution_compare(dist1, dist2, nested=nested, **kwargs)
def cdf(self, original_data=False, survival=False, **kwargs):
"""
Returns the cumulative distribution function of the data.
Parameters
----------
original_data : bool, optional
Whether to use all of the data initially passed to the Fit object.
If False, uses only the data used for the fit (within xmin and
xmax.)
survival : bool, optional
Whether to return the complementary cumulative distribution
function, 1-CDF, also known as the survival function.
Returns
-------
X : array
The sorted, unique values in the data.
probabilities : array
The portion of the data that is less than or equal to X.
"""
if original_data:
data = self.data_original
xmin = None
xmax = None
else:
data = self.data
xmin = self.xmin
xmax = self.xmax
return cdf(data, xmin=xmin, xmax=xmax, survival=survival,
**kwargs)
def ccdf(self, original_data=False, survival=True, **kwargs):
"""
Returns the complementary cumulative distribution function of the data.
Parameters
----------
original_data : bool, optional
Whether to use all of the data initially passed to the Fit object.
If False, uses only the data used for the fit (within xmin and
xmax.)
survival : bool, optional
Whether to return the complementary cumulative distribution
function, also known as the survival function, or the cumulative
distribution function, 1-CCDF.
Returns
-------
X : array
The sorted, unique values in the data.
probabilities : array
The portion of the data that is greater than or equal to X.
"""
if original_data:
data = self.data_original
xmin = None
xmax = None
else:
data = self.data
xmin = self.xmin
xmax = self.xmax
return cdf(data, xmin=xmin, xmax=xmax, survival=survival,
**kwargs)
def pdf(self, original_data=False, **kwargs):
"""
Returns the probability density function (normalized histogram) of the
data.
Parameters
----------
original_data : bool, optional
Whether to use all of the data initially passed to the Fit object.
If False, uses only the data used for the fit (within xmin and
xmax.)
Returns
-------
bin_edges : array
The edges of the bins of the probability density function.
probabilities : array
The portion of the data that is within the bin. Length 1 less than
bin_edges, as it corresponds to the spaces between them.
"""
if original_data:
data = self.data_original
xmin = None
xmax = None
else:
data = self.data
xmin = self.xmin
xmax = self.xmax
edges, hist = pdf(data, xmin=xmin, xmax=xmax, **kwargs)
return edges, hist
def plot_cdf(self, ax=None, original_data=False, survival=False, **kwargs):
"""
Plots the CDF to a new figure or to axis ax if provided.
Parameters
----------
ax : matplotlib axis, optional
The axis to which to plot. If None, a new figure is created.
original_data : bool, optional
Whether to use all of the data initially passed to the Fit object.
If False, uses only the data used for the fit (within xmin and
xmax.)
survival : bool, optional
Whether to plot a CDF (False) or CCDF (True). False by default.
Returns
-------
ax : matplotlib axis
The axis to which the plot was made.
"""
if original_data:
data = self.data_original
else:
data = self.data
return plot_cdf(data, ax=ax, survival=survival, **kwargs)
def plot_ccdf(self, ax=None, original_data=False, survival=True, **kwargs):
"""
Plots the CCDF to a new figure or to axis ax if provided.
Parameters
----------
ax : matplotlib axis, optional
The axis to which to plot. If None, a new figure is created.
original_data : bool, optional
Whether to use all of the data initially passed to the Fit object.
If False, uses only the data used for the fit (within xmin and
xmax.)
survival : bool, optional
Whether to plot a CDF (False) or CCDF (True). True by default.
Returns
-------
ax : matplotlib axis
The axis to which the plot was made.
"""
if original_data:
data = self.data_original
else:
data = self.data
return plot_cdf(data, ax=ax, survival=survival, **kwargs)
def plot_pdf(self, ax=None, original_data=False,
linear_bins=False, **kwargs):
"""
Plots the probability density function (PDF) or the data to a new figure
or to axis ax if provided.
Parameters
----------
ax : matplotlib axis, optional
The axis to which to plot. If None, a new figure is created.
original_data : bool, optional
Whether to use all of the data initially passed to the Fit object.
If False, uses only the data used for the fit (within xmin and
xmax.)
linear_bins : bool, optional
Whether to use linearly spaced bins (True) or logarithmically
spaced bins (False). False by default.
Returns
-------
ax : matplotlib axis
The axis to which the plot was made.
"""
if original_data:
data = self.data_original
else:
data = self.data
return plot_pdf(data, ax=ax, linear_bins=linear_bins, **kwargs)
class Distribution(object):
"""
An abstract class for theoretical probability distributions. Can be created
with particular parameter values, or fitted to a dataset. Fitting is
by maximum likelihood estimation by default.
Parameters
----------
xmin : int or float, optional
The data value beyond which distributions should be fitted. If
None an optimal one will be calculated.
xmax : int or float, optional
The maximum value of the fitted distributions.
discrete : boolean, optional
Whether the distribution is discrete (integers).
data : list or array, optional
The data to which to fit the distribution. If provided, the fit will
be created at initialization.
fit_method : "Likelihood" or "KS", optional
Method for fitting the distribution. "Likelihood" is maximum Likelihood
estimation. "KS" is minimial distance estimation using The
Kolmogorov-Smirnov test.
parameters : tuple or list, optional
The parameters of the distribution. Will be overridden if data is
given or the fit method is called.
parameter_range : dict, optional
Dictionary of valid parameter ranges for fitting. Formatted as a
dictionary of parameter names ('alpha' and/or 'sigma') and tuples
of their lower and upper limits (ex. (1.5, 2.5), (None, .1)
initial_parameters : tuple or list, optional
Initial values for the parameter in the fitting search.
discrete_approximation : "round", "xmax" or int, optional
If the discrete form of the theoeretical distribution is not known,
it can be estimated. One estimation method is "round", which sums
the probability mass from x-.5 to x+.5 for each data point. The other
option is to calculate the probability for each x from 1 to N and
normalize by their sum. N can be "xmax" or an integer.
parent_Fit : Fit object, optional
A Fit object from which to use data, if it exists.
"""
def __init__(self,
xmin=1, xmax=None,
discrete=False,
fit_method='Likelihood',
data=None,
parameters=None,
parameter_range=None,
initial_parameters=None,
discrete_approximation='round',
parent_Fit=None,
**kwargs):
self.xmin = xmin
self.xmax = xmax
self.discrete = discrete
self.fit_method = fit_method
self.discrete_approximation = discrete_approximation
self.parameter1 = None
self.parameter2 = None
self.parameter3 = None
self.parameter1_name = None
self.parameter2_name = None
self.parameter3_name = None
if parent_Fit:
self.parent_Fit = parent_Fit
if parameters is not None:
self.parameters(parameters)
if parameter_range:
self.parameter_range(parameter_range)
if initial_parameters:
self._given_initial_parameters(initial_parameters)
if (data is not None) and not (parameter_range and self.parent_Fit):
self.fit(data)
def fit(self, data=None, suppress_output=False):
"""
Fits the parameters of the distribution to the data. Uses options set
at initialization.
"""
if data is None and hasattr(self, 'parent_Fit'):
data = self.parent_Fit.data
data = trim_to_range(data, xmin=self.xmin, xmax=self.xmax)
if self.fit_method=='Likelihood':
def fit_function(params):
self.parameters(params)
return -sum(self.loglikelihoods(data))
elif self.fit_method=='KS':
def fit_function(params):
self.parameters(params)
self.KS(data)
return self.D
from scipy.optimize import fmin
parameters, negative_loglikelihood, iter, funcalls, warnflag, = \
fmin(
lambda params: fit_function(params),
self.initial_parameters(data),
full_output=1,
disp=False)
self.parameters(parameters)
if not self.in_range():
self.noise_flag=True
else:
self.noise_flag=False
if self.noise_flag and not suppress_output:
print("No valid fits found.", file=sys.stderr)
self.loglikelihood =-negative_loglikelihood
self.KS(data)
def KS(self, data=None):
"""
Returns the Kolmogorov-Smirnov distance D between the distribution and
the data. Also sets the properties D+, D-, V (the Kuiper testing
statistic), and Kappa (1 + the average difference between the
theoretical and empirical distributions).
Parameters
----------
data : list or array, optional
If not provided, attempts to use the data from the Fit object in
which the Distribution object is contained.
"""
if data is None and hasattr(self, 'parent_Fit'):
data = self.parent_Fit.data
data = trim_to_range(data, xmin=self.xmin, xmax=self.xmax)
if len(data)<2:
print("Not enough data. Returning nan", file=sys.stderr)
from numpy import nan
self.D = nan
self.D_plus = nan
self.D_minus = nan
self.Kappa = nan
self.V = nan
self.Asquare = nan
return self.D
if hasattr(self, 'parent_Fit'):
bins = self.parent_Fit.fitting_cdf_bins
Actual_CDF = self.parent_Fit.fitting_cdf
ind = bins>=self.xmin
bins = bins[ind]
Actual_CDF = Actual_CDF[ind]
dropped_probability = Actual_CDF[0]
Actual_CDF -= dropped_probability
Actual_CDF /= 1-dropped_probability
else:
bins, Actual_CDF = cdf(data)
Theoretical_CDF = self.cdf(bins)
CDF_diff = Theoretical_CDF - Actual_CDF
self.D_plus = CDF_diff.max()
self.D_minus = -1.0*CDF_diff.min()
from numpy import mean
self.Kappa = 1 + mean(CDF_diff)
self.V = self.D_plus + self.D_minus
self.D = max(self.D_plus, self.D_minus)
self.Asquare = sum((
(CDF_diff**2) /
(Theoretical_CDF * (1 - Theoretical_CDF) + 1e-12)
)[1:]
)
return self.D
def ccdf(self,data=None, survival=True):
"""
The complementary cumulative distribution function (CCDF) of the
theoretical distribution. Calculated for the values given in data
within xmin and xmax, if present.
Parameters
----------
data : list or array, optional
If not provided, attempts to use the data from the Fit object in
which the Distribution object is contained.
survival : bool, optional
Whether to calculate a CDF (False) or CCDF (True).
True by default.
Returns
-------
X : array
The sorted, unique values in the data.
probabilities : array
The portion of the data that is less than or equal to X.
"""
return self.cdf(data=data, survival=survival)
def cdf(self,data=None, survival=False):
"""
The cumulative distribution function (CDF) of the theoretical
distribution. Calculated for the values given in data within xmin and
xmax, if present.
Parameters
----------
data : list or array, optional
If not provided, attempts to use the data from the Fit object in
which the Distribution object is contained.
survival : bool, optional
Whether to calculate a CDF (False) or CCDF (True).
False by default.
Returns
-------
X : array
The sorted, unique values in the data.
probabilities : array
The portion of the data that is less than or equal to X.
"""
if data is None and hasattr(self, 'parent_Fit'):
data = self.parent_Fit.data
data = trim_to_range(data, xmin=self.xmin, xmax=self.xmax)
n = len(data)
from sys import float_info
if not self.in_range():
from numpy import tile
return tile(10**float_info.min_10_exp, n)
if self._cdf_xmin==1:
#If cdf_xmin is 1, it means we don't have the numerical accuracy to
#calculate this tail. So we make everything 1, indicating
#we're at the end of the tail. Such an xmin should be thrown
#out by the KS test.
from numpy import ones
CDF = ones(n)
return CDF
CDF = self._cdf_base_function(data) - self._cdf_xmin
norm = 1 - self._cdf_xmin
if self.xmax:
norm = norm - (1 - self._cdf_base_function(self.xmax))
CDF = CDF/norm
if survival:
CDF = 1 - CDF
possible_numerical_error = False
from numpy import isnan, min
if isnan(min(CDF)):
print("'nan' in fit cumulative distribution values.", file=sys.stderr)
possible_numerical_error = True
#if 0 in CDF or 1 in CDF:
# print("0 or 1 in fit cumulative distribution values.", file=sys.stderr)
# possible_numerical_error = True
if possible_numerical_error:
print("Likely underflow or overflow error: the optimal fit for this distribution gives values that are so extreme that we lack the numerical precision to calculate them.", file=sys.stderr)
return CDF
@property
def _cdf_xmin(self):
return self._cdf_base_function(self.xmin)
def pdf(self, data=None):
"""
Returns the probability density function (normalized histogram) of the
theoretical distribution for the values in data within xmin and xmax,
if present.
Parameters
----------
data : list or array, optional
If not provided, attempts to use the data from the Fit object in
which the Distribution object is contained.
Returns
-------
probabilities : array
"""
if data is None and hasattr(self, 'parent_Fit'):
data = self.parent_Fit.data
data = trim_to_range(data, xmin=self.xmin, xmax=self.xmax)
n = len(data)
from sys import float_info
if not self.in_range():
from numpy import tile
return tile(10**float_info.min_10_exp, n)
if not self.discrete:
f = self._pdf_base_function(data)
C = self._pdf_continuous_normalizer
likelihoods = f*C
else:
if self._pdf_discrete_normalizer:
f = self._pdf_base_function(data)
C = self._pdf_discrete_normalizer
likelihoods = f*C
elif self.discrete_approximation=='round':
lower_data = data-.5
upper_data = data+.5
#Temporarily expand xmin and xmax to be able to grab the extra bit of
#probability mass beyond the (integer) values of xmin and xmax
#Note this is a design decision. One could also say this extra
#probability "off the edge" of the distribution shouldn't be included,
#and that implementation is retained below, commented out. Note, however,
#that such a cliff means values right at xmin and xmax have half the width to
#grab probability from, and thus are lower probability than they would otherwise
#be. This is particularly concerning for values at xmin, which are typically
#the most likely and greatly influence the distribution's fit.
self.xmin -= .5
if self.xmax:
self.xmax += .5
#Clean data for invalid values before handing to cdf, which will purge them
#lower_data[lower_data<self.xmin] +=.5
#if self.xmax:
# upper_data[upper_data>self.xmax] -=.5
likelihoods = self.cdf(upper_data)-self.cdf(lower_data)
self.xmin +=.5
if self.xmax:
self.xmax -= .5
else:
if self.discrete_approximation=='xmax':
upper_limit = self.xmax
else:
upper_limit = self.discrete_approximation
# from mpmath import exp
from numpy import arange
X = arange(self.xmin, upper_limit+1)
PDF = self._pdf_base_function(X)
PDF = (PDF/sum(PDF)).astype(float)
likelihoods = PDF[(data-self.xmin).astype(int)]
likelihoods[likelihoods==0] = 10**float_info.min_10_exp
return likelihoods
@property
def _pdf_continuous_normalizer(self):
C = 1 - self._cdf_xmin
if self.xmax:
C -= 1 - self._cdf_base_function(self.xmax+1)
C = 1.0/C
return C
@property
def _pdf_discrete_normalizer(self):
return False
def parameter_range(self, r, initial_parameters=None):
"""
Set the limits on the range of valid parameters to be considered while
fitting.
Parameters
----------
r : dict
A dictionary of the parameter range. Restricted parameter
names are keys, and with tuples of the form (lower_bound,
upper_bound) as values.
initial_parameters : tuple or list, optional
Initial parameter values to start the fitting search from.
"""
from types import FunctionType
if type(r)==FunctionType:
self._in_given_parameter_range = r
else:
self._range_dict = r
if initial_parameters:
self._given_initial_parameters = initial_parameters
if self.parent_Fit:
self.fit(self.parent_Fit.data)
def in_range(self):
"""
Whether the current parameters of the distribution are within the range
of valid parameters.
"""
try:
r = self._range_dict
result = True
for k in r.keys():
#For any attributes we've specificed, make sure we're above the lower bound
#and below the lower bound (if they exist). This must be true of all of them.
lower_bound, upper_bound = r[k]
if upper_bound is not None:
result *= getattr(self, k) < upper_bound
if lower_bound is not None:
result *= getattr(self, k) > lower_bound
return result
except AttributeError:
try:
in_range = self._in_given_parameter_range(self)
except AttributeError:
in_range = self._in_standard_parameter_range()
return bool(in_range)
def initial_parameters(self, data):
"""
Return previously user-provided initial parameters or, if never
provided, calculate new ones. Default initial parameter estimates are
unique to each theoretical distribution.
"""
try:
return self._given_initial_parameters
except AttributeError:
return self._initial_parameters(data)
def likelihoods(self, data):
"""
The likelihoods of the observed data from the theoretical distribution.
Another name for the probabilities or probability density function.
"""
return self.pdf(data)
def loglikelihoods(self, data):
"""
The logarithm of the likelihoods of the observed data from the
theoretical distribution.
"""
from numpy import log
return log(self.likelihoods(data))
def plot_ccdf(self, data=None, ax=None, survival=True, **kwargs):
"""
Plots the complementary cumulative distribution function (CDF) of the
theoretical distribution for the values given in data within xmin and
xmax, if present. Plots to a new figure or to axis ax if provided.
Parameters
----------
data : list or array, optional
If not provided, attempts to use the data from the Fit object in
which the Distribution object is contained.
ax : matplotlib axis, optional
The axis to which to plot. If None, a new figure is created.
survival : bool, optional
Whether to plot a CDF (False) or CCDF (True). True by default.