statsinference 0.1.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- statsinference/__init__.py +18 -0
- statsinference/_distributions.py +214 -0
- statsinference/_fit.py +485 -0
- statsinference/_plots.py +190 -0
- statsinference/inference.py +413 -0
- statsinference-0.1.4.dist-info/METADATA +129 -0
- statsinference-0.1.4.dist-info/RECORD +9 -0
- statsinference-0.1.4.dist-info/WHEEL +4 -0
- statsinference-0.1.4.dist-info/licenses/LICENSE +32 -0
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""The public StatsInference class."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from ._distributions import _ALIASES, _DISTS, SUPPORTED
|
|
10
|
+
from ._fit import _SingleFit, _compare_table
|
|
11
|
+
from ._plots import _plot_fits
|
|
12
|
+
|
|
13
|
+
# Which named distributions make sense for which data.
|
|
14
|
+
_POSITIVE = {"lognormal", "gamma", "weibull", "exponential", "chi-squared", "f"}
|
|
15
|
+
_UNIT = {"beta"}
|
|
16
|
+
_REAL = {"normal", "cauchy", "logistic", "t"}
|
|
17
|
+
_COUNT = {"poisson", "geometric", "negative binomial"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _is_count_data(x):
|
|
21
|
+
return bool(np.all(x >= 0) and np.all(x == np.round(x)))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _supports(name, x):
|
|
25
|
+
"""True if a named distribution's support contains all of the data."""
|
|
26
|
+
if name in _COUNT:
|
|
27
|
+
return _is_count_data(x)
|
|
28
|
+
if name in _POSITIVE:
|
|
29
|
+
return bool(np.all(x > 0))
|
|
30
|
+
if name in _UNIT:
|
|
31
|
+
return bool(np.all((x > 0) & (x < 1)))
|
|
32
|
+
return True
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class _Progress:
|
|
36
|
+
"""tqdm if installed, else a plain one-line counter (or nothing)."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, total, enabled):
|
|
39
|
+
self.bar, self.total, self.i, self.enabled = None, total, 0, enabled
|
|
40
|
+
if enabled:
|
|
41
|
+
try:
|
|
42
|
+
from tqdm.auto import tqdm
|
|
43
|
+
|
|
44
|
+
self.bar = tqdm(total=total, desc="Fitting", unit="dist")
|
|
45
|
+
except ImportError:
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
def update(self, label):
|
|
49
|
+
self.i += 1
|
|
50
|
+
if not self.enabled:
|
|
51
|
+
return
|
|
52
|
+
if self.bar is not None:
|
|
53
|
+
self.bar.set_postfix_str(label)
|
|
54
|
+
self.bar.update(1)
|
|
55
|
+
else:
|
|
56
|
+
print(f"\r[{self.i}/{self.total}] {label:<20}", end="", flush=True)
|
|
57
|
+
|
|
58
|
+
def close(self):
|
|
59
|
+
if self.bar is not None:
|
|
60
|
+
self.bar.close()
|
|
61
|
+
elif self.enabled:
|
|
62
|
+
print()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class StatsInference:
|
|
66
|
+
"""Fit univariate distributions to data by maximum likelihood.
|
|
67
|
+
|
|
68
|
+
Parameters
|
|
69
|
+
----------
|
|
70
|
+
x : array-like
|
|
71
|
+
Non-empty numeric vector with no NaN or infinite values.
|
|
72
|
+
densfun : optional
|
|
73
|
+
If given, fit it straight away
|
|
74
|
+
(same as ``StatsInference(x).fit(densfun)``).
|
|
75
|
+
**fit_kwargs
|
|
76
|
+
Passed on to :meth:`fit`.
|
|
77
|
+
|
|
78
|
+
After :meth:`fit` or :meth:`select`, the chosen fit's results are
|
|
79
|
+
available directly on the object: ``estimate``, ``sd``, ``vcov``,
|
|
80
|
+
``loglik``, ``aic``, ``bic``, ``n``, ``converged``, ``dist`` (the fitted
|
|
81
|
+
scipy distribution), and the methods ``summary()``, ``gof()``,
|
|
82
|
+
``plot()``, ``denscomp()``, ``cdfcomp()``, ``qqcomp()``, ``ppcomp()``.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, x, densfun=None, **fit_kwargs):
|
|
86
|
+
x = np.asarray(x)
|
|
87
|
+
if x.size == 0 or not np.issubdtype(x.dtype, np.number):
|
|
88
|
+
raise ValueError("'x' must be a non-empty numeric vector")
|
|
89
|
+
x = x.astype(float).ravel()
|
|
90
|
+
if not np.all(np.isfinite(x)):
|
|
91
|
+
raise ValueError("'x' contains missing or infinite values")
|
|
92
|
+
self.x = x
|
|
93
|
+
self.result = None # the chosen fit
|
|
94
|
+
self.fits = {} # label -> fit, for every successful fit
|
|
95
|
+
self.failures = {} # label -> error message
|
|
96
|
+
self.table = None # ranking from select()
|
|
97
|
+
self.criterion = None
|
|
98
|
+
if densfun is not None:
|
|
99
|
+
self.fit(densfun, **fit_kwargs)
|
|
100
|
+
|
|
101
|
+
# -------------------------------------------------------------- fitting
|
|
102
|
+
def fit(
|
|
103
|
+
self,
|
|
104
|
+
densfun,
|
|
105
|
+
start=None,
|
|
106
|
+
fixed=None,
|
|
107
|
+
lower=None,
|
|
108
|
+
upper=None,
|
|
109
|
+
method="L-BFGS-B",
|
|
110
|
+
cdf=None,
|
|
111
|
+
discrete=None,
|
|
112
|
+
label=None,
|
|
113
|
+
):
|
|
114
|
+
"""Fit one distribution; it becomes the current result.
|
|
115
|
+
|
|
116
|
+
``densfun`` is a supported name (see ``SUPPORTED``), a scipy
|
|
117
|
+
distribution such as ``scipy.stats.gamma``, or a density function
|
|
118
|
+
``f(x, **params[, log=])`` (then ``start`` is required).
|
|
119
|
+
|
|
120
|
+
start, fixed, lower, upper : dict, optional
|
|
121
|
+
Keyed by parameter name. ``fixed`` holds parameters that are not
|
|
122
|
+
estimated (R's ``...``). Not allowed: ``start`` for "normal",
|
|
123
|
+
which is fitted in closed form.
|
|
124
|
+
method : any ``scipy.optimize.minimize`` method.
|
|
125
|
+
cdf, discrete : only for a density function (numeric CDF otherwise).
|
|
126
|
+
label : name under which the fit is stored in ``self.fits``.
|
|
127
|
+
"""
|
|
128
|
+
f = _SingleFit(
|
|
129
|
+
self.x,
|
|
130
|
+
densfun,
|
|
131
|
+
start=start,
|
|
132
|
+
fixed=fixed,
|
|
133
|
+
lower=lower,
|
|
134
|
+
upper=upper,
|
|
135
|
+
method=method,
|
|
136
|
+
cdf=cdf,
|
|
137
|
+
discrete=discrete,
|
|
138
|
+
)
|
|
139
|
+
self.fits[label or f.name] = f
|
|
140
|
+
self.result = f
|
|
141
|
+
return self
|
|
142
|
+
|
|
143
|
+
def select(
|
|
144
|
+
self,
|
|
145
|
+
distributions=None,
|
|
146
|
+
criterion="aic",
|
|
147
|
+
verbose=1,
|
|
148
|
+
progress=True,
|
|
149
|
+
options=None,
|
|
150
|
+
):
|
|
151
|
+
"""Fit several distributions and keep the best by AIC or BIC.
|
|
152
|
+
|
|
153
|
+
Parameters
|
|
154
|
+
----------
|
|
155
|
+
distributions : list, optional
|
|
156
|
+
Names from ``SUPPORTED`` and/or scipy distribution objects.
|
|
157
|
+
Default: every named distribution whose support fits the data
|
|
158
|
+
(count distributions for non-negative integers, otherwise the
|
|
159
|
+
continuous ones; positive-only and (0, 1) ones only when the
|
|
160
|
+
data allow them).
|
|
161
|
+
criterion : {"aic", "bic"}
|
|
162
|
+
verbose : int
|
|
163
|
+
0 = silent, 1 = print the ranking at the end,
|
|
164
|
+
2 = also print each fit (or failure) as it happens.
|
|
165
|
+
progress : bool
|
|
166
|
+
Show a progress bar (tqdm if installed, else a counter).
|
|
167
|
+
options : dict, optional
|
|
168
|
+
Per-distribution keyword arguments for :meth:`fit`, keyed by
|
|
169
|
+
label, e.g. ``{"t": {"fixed": {"df": 5}}}``.
|
|
170
|
+
|
|
171
|
+
Returns
|
|
172
|
+
-------
|
|
173
|
+
self, with ``result`` set to the best fit, ``table`` holding the
|
|
174
|
+
ranking (criterion, delta, Akaike/Schwarz weights) and ``fits``
|
|
175
|
+
holding every successful fit.
|
|
176
|
+
"""
|
|
177
|
+
criterion = criterion.lower()
|
|
178
|
+
if criterion not in ("aic", "bic"):
|
|
179
|
+
raise ValueError("criterion must be 'aic' or 'bic'")
|
|
180
|
+
options = options or {}
|
|
181
|
+
|
|
182
|
+
if distributions is None:
|
|
183
|
+
# Never mix count and continuous models: their likelihoods
|
|
184
|
+
# (probabilities vs densities) are not comparable by AIC/BIC.
|
|
185
|
+
pool = (
|
|
186
|
+
sorted(_COUNT)
|
|
187
|
+
if _is_count_data(self.x)
|
|
188
|
+
else [d for d in SUPPORTED if d not in _COUNT]
|
|
189
|
+
)
|
|
190
|
+
candidates = [d for d in pool if _supports(d, self.x)]
|
|
191
|
+
else:
|
|
192
|
+
candidates = list(distributions)
|
|
193
|
+
if not candidates:
|
|
194
|
+
raise ValueError("no candidate distributions to fit")
|
|
195
|
+
|
|
196
|
+
labels = []
|
|
197
|
+
for d in candidates:
|
|
198
|
+
if isinstance(d, str):
|
|
199
|
+
key = _ALIASES.get(d.strip().lower(), d.strip().lower())
|
|
200
|
+
labels.append(key)
|
|
201
|
+
else:
|
|
202
|
+
labels.append(getattr(d, "name", str(d)))
|
|
203
|
+
|
|
204
|
+
bar = _Progress(len(candidates), progress)
|
|
205
|
+
self.failures = {}
|
|
206
|
+
fitted = {}
|
|
207
|
+
try:
|
|
208
|
+
for d, lab in zip(candidates, labels):
|
|
209
|
+
if (
|
|
210
|
+
isinstance(d, str)
|
|
211
|
+
and lab in _DISTS
|
|
212
|
+
and not _supports(lab, self.x)
|
|
213
|
+
):
|
|
214
|
+
self.failures[lab] = (
|
|
215
|
+
"data outside the distribution's support"
|
|
216
|
+
)
|
|
217
|
+
else:
|
|
218
|
+
try:
|
|
219
|
+
with warnings.catch_warnings():
|
|
220
|
+
warnings.simplefilter("ignore")
|
|
221
|
+
f = _SingleFit(self.x, d, **options.get(lab, {}))
|
|
222
|
+
if not np.isfinite(f.loglik):
|
|
223
|
+
raise RuntimeError("non-finite log-likelihood")
|
|
224
|
+
fitted[lab] = f
|
|
225
|
+
if verbose >= 2:
|
|
226
|
+
crit = getattr(f, criterion)
|
|
227
|
+
flag = "" if f.converged else " (not converged)"
|
|
228
|
+
self._say(
|
|
229
|
+
f" {lab:<20} loglik = {f.loglik:12.4f} "
|
|
230
|
+
f"{criterion.upper()} = {crit:12.4f}{flag}",
|
|
231
|
+
bar,
|
|
232
|
+
)
|
|
233
|
+
except Exception as e: # keep going, record why
|
|
234
|
+
self.failures[lab] = f"{type(e).__name__}: {e}"
|
|
235
|
+
if verbose >= 2:
|
|
236
|
+
self._say(
|
|
237
|
+
f" {lab:<20} failed: {self.failures[lab]}", bar
|
|
238
|
+
)
|
|
239
|
+
bar.update(lab)
|
|
240
|
+
finally:
|
|
241
|
+
bar.close()
|
|
242
|
+
|
|
243
|
+
if not fitted:
|
|
244
|
+
raise RuntimeError(f"every fit failed: {self.failures}")
|
|
245
|
+
|
|
246
|
+
self.fits.update(fitted)
|
|
247
|
+
self.criterion = criterion
|
|
248
|
+
self.table = self._rank(fitted, criterion)
|
|
249
|
+
best = min(fitted, key=lambda k: getattr(fitted[k], criterion))
|
|
250
|
+
self.result = fitted[best]
|
|
251
|
+
|
|
252
|
+
if verbose >= 1:
|
|
253
|
+
print(self._format_table())
|
|
254
|
+
if self.failures:
|
|
255
|
+
print(
|
|
256
|
+
"Skipped / failed: "
|
|
257
|
+
+ "; ".join(f"{k} ({v})" for k, v in self.failures.items())
|
|
258
|
+
)
|
|
259
|
+
print(f"Best by {criterion.upper()}: {best}")
|
|
260
|
+
return self
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def _say(msg, bar):
|
|
264
|
+
if bar.bar is not None:
|
|
265
|
+
bar.bar.write(msg)
|
|
266
|
+
else:
|
|
267
|
+
print("\r" + msg if bar.enabled else msg)
|
|
268
|
+
|
|
269
|
+
@staticmethod
|
|
270
|
+
def _rank(fitted, criterion):
|
|
271
|
+
rows = []
|
|
272
|
+
for lab, f in fitted.items():
|
|
273
|
+
g = f.gof()
|
|
274
|
+
rows.append(
|
|
275
|
+
{
|
|
276
|
+
"distribution": lab,
|
|
277
|
+
"k": f.k,
|
|
278
|
+
"loglik": f.loglik,
|
|
279
|
+
"aic": f.aic,
|
|
280
|
+
"bic": f.bic,
|
|
281
|
+
"ks": g.get("ks"),
|
|
282
|
+
"converged": f.converged,
|
|
283
|
+
}
|
|
284
|
+
)
|
|
285
|
+
rows.sort(key=lambda r: r[criterion])
|
|
286
|
+
best = rows[0][criterion]
|
|
287
|
+
w = np.array([np.exp(-0.5 * (r[criterion] - best)) for r in rows])
|
|
288
|
+
w /= w.sum()
|
|
289
|
+
for r, wi in zip(rows, w):
|
|
290
|
+
r["delta"] = r[criterion] - best
|
|
291
|
+
r["weight"] = float(wi)
|
|
292
|
+
cols = [
|
|
293
|
+
"distribution",
|
|
294
|
+
"k",
|
|
295
|
+
"loglik",
|
|
296
|
+
"aic",
|
|
297
|
+
"bic",
|
|
298
|
+
"delta",
|
|
299
|
+
"weight",
|
|
300
|
+
"ks",
|
|
301
|
+
"converged",
|
|
302
|
+
]
|
|
303
|
+
rows = [{c: r[c] for c in cols} for r in rows]
|
|
304
|
+
try:
|
|
305
|
+
import pandas as pd
|
|
306
|
+
|
|
307
|
+
return pd.DataFrame(rows).set_index("distribution")
|
|
308
|
+
except ImportError:
|
|
309
|
+
return rows
|
|
310
|
+
|
|
311
|
+
def _format_table(self):
|
|
312
|
+
rows = (
|
|
313
|
+
self.table.reset_index().to_dict("records")
|
|
314
|
+
if hasattr(self.table, "reset_index")
|
|
315
|
+
else self.table
|
|
316
|
+
)
|
|
317
|
+
head = (
|
|
318
|
+
f"{'distribution':<20}{'k':>3}{'loglik':>12}{'AIC':>12}{'BIC':>12}"
|
|
319
|
+
f"{'delta':>10}{'weight':>9}"
|
|
320
|
+
)
|
|
321
|
+
out = [head, "-" * len(head)]
|
|
322
|
+
for r in rows:
|
|
323
|
+
out.append(
|
|
324
|
+
f"{r['distribution']:<20}{r['k']:>3}{r['loglik']:>12.3f}"
|
|
325
|
+
f"{r['aic']:>12.3f}{r['bic']:>12.3f}{r['delta']:>10.3f}"
|
|
326
|
+
f"{r['weight']:>9.3f}{'' if r['converged'] else ' *'}"
|
|
327
|
+
)
|
|
328
|
+
if any(not r["converged"] for r in rows):
|
|
329
|
+
out.append("* optimizer did not report convergence")
|
|
330
|
+
return "\n".join(out)
|
|
331
|
+
|
|
332
|
+
# ------------------------------------------------------------- results
|
|
333
|
+
@property
|
|
334
|
+
def best_dist(self):
|
|
335
|
+
"""Name of the chosen distribution (None before fitting)."""
|
|
336
|
+
return None if self.result is None else self.result.name
|
|
337
|
+
|
|
338
|
+
def simulate(self, size=None, seed=None, dist=None):
|
|
339
|
+
"""Simulate from the fitted distribution.
|
|
340
|
+
|
|
341
|
+
Parameters
|
|
342
|
+
----------
|
|
343
|
+
size : int or tuple of ints, optional
|
|
344
|
+
Output shape; None returns a single draw.
|
|
345
|
+
seed : int, numpy.random.Generator or None
|
|
346
|
+
For reproducible draws.
|
|
347
|
+
dist : str, optional
|
|
348
|
+
Label of another stored fit (see ``self.fits``); default is the
|
|
349
|
+
chosen one (``best_dist``).
|
|
350
|
+
|
|
351
|
+
Example
|
|
352
|
+
-------
|
|
353
|
+
>>> si = StatsInference(x).select(verbose=0)
|
|
354
|
+
>>> sims = si.simulate(1000, seed=123)
|
|
355
|
+
"""
|
|
356
|
+
if dist is None:
|
|
357
|
+
if self.result is None:
|
|
358
|
+
raise AttributeError("call fit() or select() before simulate()")
|
|
359
|
+
f = self.result
|
|
360
|
+
else:
|
|
361
|
+
key = (
|
|
362
|
+
_ALIASES.get(dist.strip().lower(), dist.strip().lower())
|
|
363
|
+
if dist not in self.fits
|
|
364
|
+
else dist
|
|
365
|
+
)
|
|
366
|
+
if key not in self.fits:
|
|
367
|
+
raise KeyError(
|
|
368
|
+
f"no fit named '{dist}'; available: {list(self.fits)}"
|
|
369
|
+
)
|
|
370
|
+
f = self.fits[key]
|
|
371
|
+
return f.simulate(size=size, seed=seed)
|
|
372
|
+
|
|
373
|
+
def __getattr__(self, name):
|
|
374
|
+
# Delegate estimate, sd, aic, summary(), plot(), ... to the chosen fit.
|
|
375
|
+
result = self.__dict__.get("result")
|
|
376
|
+
if result is None:
|
|
377
|
+
raise AttributeError(
|
|
378
|
+
f"'{name}' is not available yet: call fit() or select() first"
|
|
379
|
+
)
|
|
380
|
+
return getattr(result, name)
|
|
381
|
+
|
|
382
|
+
def compare(self, labels=None, sort_by=None):
|
|
383
|
+
"""GOF table (loglik, AIC, BIC, KS, CvM, AD) for the given fits."""
|
|
384
|
+
labels = labels or list(self.fits)
|
|
385
|
+
return _compare_table(
|
|
386
|
+
[self.fits[k] for k in labels],
|
|
387
|
+
labels,
|
|
388
|
+
sort_by=sort_by or self.criterion or "aic",
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
def plot_compare(self, labels=None, top=None, **kwargs):
|
|
392
|
+
"""Overlay several fits on the four diagnostic panels.
|
|
393
|
+
|
|
394
|
+
By default the ``top`` best (3 if ``select()`` was run) are shown.
|
|
395
|
+
"""
|
|
396
|
+
if labels is None:
|
|
397
|
+
if self.table is not None:
|
|
398
|
+
order = (
|
|
399
|
+
list(self.table.index)
|
|
400
|
+
if hasattr(self.table, "index")
|
|
401
|
+
else [r["distribution"] for r in self.table]
|
|
402
|
+
)
|
|
403
|
+
labels = order[: top or 3]
|
|
404
|
+
else:
|
|
405
|
+
labels = list(self.fits)[:top] if top else list(self.fits)
|
|
406
|
+
return _plot_fits(
|
|
407
|
+
[self.fits[k] for k in labels], labels=labels, **kwargs
|
|
408
|
+
)
|
|
409
|
+
|
|
410
|
+
def __repr__(self):
|
|
411
|
+
if self.result is None:
|
|
412
|
+
return f"<StatsInference n={self.x.size}, not fitted>"
|
|
413
|
+
return f"<StatsInference n={self.x.size}, {self.result!r}>"
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: statsinference
|
|
3
|
+
Version: 0.1.4
|
|
4
|
+
Summary: Maximum-likelihood fitting of univariate distributions, AIC/BIC model selection, diagnostic plots and simulation.
|
|
5
|
+
Author: Your Name
|
|
6
|
+
License-Expression: BSD-3-Clause-Clear
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: AIC,BIC,distribution fitting,maximum likelihood,statistics
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Requires-Dist: matplotlib>=3.5
|
|
14
|
+
Requires-Dist: numpy>=1.22
|
|
15
|
+
Requires-Dist: scipy>=1.9
|
|
16
|
+
Provides-Extra: all
|
|
17
|
+
Requires-Dist: pandas; extra == 'all'
|
|
18
|
+
Requires-Dist: tqdm; extra == 'all'
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: autopep8; extra == 'dev'
|
|
21
|
+
Requires-Dist: black; extra == 'dev'
|
|
22
|
+
Requires-Dist: build; extra == 'dev'
|
|
23
|
+
Requires-Dist: coverage; extra == 'dev'
|
|
24
|
+
Requires-Dist: flake8; extra == 'dev'
|
|
25
|
+
Requires-Dist: pdoc; extra == 'dev'
|
|
26
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
27
|
+
Requires-Dist: twine; extra == 'dev'
|
|
28
|
+
Provides-Extra: pandas
|
|
29
|
+
Requires-Dist: pandas; extra == 'pandas'
|
|
30
|
+
Provides-Extra: progress
|
|
31
|
+
Requires-Dist: tqdm; extra == 'progress'
|
|
32
|
+
Provides-Extra: test
|
|
33
|
+
Requires-Dist: coverage; extra == 'test'
|
|
34
|
+
Requires-Dist: pytest; extra == 'test'
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# statsinference
|
|
38
|
+
|
|
39
|
+
Fit univariate distributions to data by maximum likelihood, pick the best one
|
|
40
|
+
by AIC or BIC, check the fit with fitdistrplus-style plots, and simulate from it.
|
|
41
|
+
|
|
42
|
+
## Install
|
|
43
|
+
|
|
44
|
+
### From GitHub
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install git+https
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
### From PyPI
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install . # from this folder
|
|
54
|
+
pip install ".[all]" # with progress bar (tqdm) and DataFrame tables (pandas)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import numpy as np
|
|
61
|
+
from statsinference import StatsInference
|
|
62
|
+
|
|
63
|
+
x = np.random.default_rng(1).gamma(2, 1.5, size=300)
|
|
64
|
+
|
|
65
|
+
# Let it choose among every distribution whose support fits the data
|
|
66
|
+
si = StatsInference(x).select(criterion="aic", verbose=1, progress=True)
|
|
67
|
+
si.best_dist # 'gamma'
|
|
68
|
+
si.estimate, si.sd # estimates and standard errors
|
|
69
|
+
si.table # ranking: loglik, AIC, BIC, delta, weight, KS
|
|
70
|
+
si.summary() # estimates, loglik, AIC/BIC, KS / CvM / AD
|
|
71
|
+
si.plot() # density, CDF, Q-Q and P-P panels
|
|
72
|
+
si.plot_compare(top=3) # the three best overlaid
|
|
73
|
+
|
|
74
|
+
sims = si.simulate(1000, seed=123) # draws from the best fit
|
|
75
|
+
alt = si.simulate(1000, seed=123, dist="weibull") # or from another candidate
|
|
76
|
+
|
|
77
|
+
# Or fit one distribution directly
|
|
78
|
+
StatsInference(x).fit("weibull").summary()
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Supported distributions
|
|
82
|
+
|
|
83
|
+
Named (case-insensitive, parameter names as in R): `beta`, `cauchy`,
|
|
84
|
+
`chi-squared`, `exponential`, `f`, `gamma` (shape, rate), `geometric`,
|
|
85
|
+
`logistic`, `lognormal` / `log-normal`, `negative binomial` (size, mu),
|
|
86
|
+
`normal` (closed form), `poisson`, `t` (location-scale: m, s, df), `weibull`.
|
|
87
|
+
|
|
88
|
+
Also accepted by `fit()` and `select()`:
|
|
89
|
+
|
|
90
|
+
- any SciPy distribution, e.g. `scipy.stats.genextreme`;
|
|
91
|
+
- your own density `f(x, **params)`, optionally with a `log` argument
|
|
92
|
+
(pass `start=`).
|
|
93
|
+
|
|
94
|
+
## Main options
|
|
95
|
+
|
|
96
|
+
| Method | Arguments |
|
|
97
|
+
|---|---|
|
|
98
|
+
| `fit(densfun, start, fixed, lower, upper, method)` | `fixed` holds parameters not estimated, e.g. `fixed={"df": 5}` |
|
|
99
|
+
| `select(distributions, criterion, verbose, progress, options)` | `verbose`: 0 silent, 1 ranking, 2 each fit; `options={"t": {"fixed": {"df": 5}}}` |
|
|
100
|
+
| `simulate(size, seed, dist)` | `dist` picks another stored fit |
|
|
101
|
+
| `compare()`, `gof()`, `plot()`, `denscomp()`, `cdfcomp()`, `qqcomp()`, `ppcomp()` | |
|
|
102
|
+
|
|
103
|
+
Notes:
|
|
104
|
+
|
|
105
|
+
- With non-negative whole numbers, `select()` compares only count
|
|
106
|
+
distributions (Poisson, geometric, negative binomial); count and
|
|
107
|
+
continuous likelihoods cannot be compared by AIC. Pass `distributions=`
|
|
108
|
+
to override.
|
|
109
|
+
- KS p-values treat the parameters as known, so they are optimistic when the
|
|
110
|
+
parameters were estimated from the same data.
|
|
111
|
+
|
|
112
|
+
## Development
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
make help # list every target
|
|
116
|
+
make install # editable install with extras (uses uv if present, needs an active venv)
|
|
117
|
+
make test # run the tests
|
|
118
|
+
make run-tests # install, then tests with coverage
|
|
119
|
+
make lint # flake8
|
|
120
|
+
make format # black + autopep8, line length 80
|
|
121
|
+
make run-examples # run everything in examples/
|
|
122
|
+
make docs # API docs with pdoc, in statsinference-docs/
|
|
123
|
+
make check-dist # build sdist + wheel and check them with twine
|
|
124
|
+
make release # upload to PyPI
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
BSD 3-Clause Clear License; see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
statsinference/__init__.py,sha256=JAqPqquasErdHntEdpkyyGhH-42HT71C7tbsbm-w-4s,599
|
|
2
|
+
statsinference/_distributions.py,sha256=3GXC14o5LiojG35SD4F8nh-nYBBZIyWI9wyyZwr2jo4,6675
|
|
3
|
+
statsinference/_fit.py,sha256=VEYSqIfb8-ZYMO2uMDU7BCDhuKM_B_qxUFI2yYa5kss,17500
|
|
4
|
+
statsinference/_plots.py,sha256=-uakaIUUbhk2z9YQr9gNnDxyW6FUv8iFG1zTFl1UTmA,6158
|
|
5
|
+
statsinference/inference.py,sha256=BeT1kux2eBe6JYavac70jjPtDdRFV7An6QDzB_JHQjI,14476
|
|
6
|
+
statsinference-0.1.4.dist-info/METADATA,sha256=ADDNDXWe_Ypwlg1gNNRcNTPt8b3e3FzSLwOQ2WSk_UQ,4495
|
|
7
|
+
statsinference-0.1.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
statsinference-0.1.4.dist-info/licenses/LICENSE,sha256=Pk1V45WjH8Hye9TyOdIJxW4C11r_IDLWhKpv5A3i-Qs,1690
|
|
9
|
+
statsinference-0.1.4.dist-info/RECORD,,
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
The Clear BSD License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026, [Thierry Moudiki]
|
|
4
|
+
All rights reserved.
|
|
5
|
+
|
|
6
|
+
Redistribution and use in source and binary forms, with or without
|
|
7
|
+
modification, are permitted (subject to the limitations in the disclaimer
|
|
8
|
+
below) provided that the following conditions are met:
|
|
9
|
+
|
|
10
|
+
* Redistributions of source code must retain the above copyright notice,
|
|
11
|
+
this list of conditions and the following disclaimer.
|
|
12
|
+
|
|
13
|
+
* Redistributions in binary form must reproduce the above copyright
|
|
14
|
+
notice, this list of conditions and the following disclaimer in the
|
|
15
|
+
documentation and/or other materials provided with the distribution.
|
|
16
|
+
|
|
17
|
+
* Neither the name of the copyright holder nor the names of its
|
|
18
|
+
contributors may be used to endorse or promote products derived from this
|
|
19
|
+
software without specific prior written permission.
|
|
20
|
+
|
|
21
|
+
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
|
|
22
|
+
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
|
|
23
|
+
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
24
|
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
|
25
|
+
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
|
|
26
|
+
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
|
27
|
+
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
|
28
|
+
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
|
29
|
+
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
|
|
30
|
+
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
31
|
+
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
32
|
+
POSSIBILITY OF SUCH DAMAGE.
|