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
statsinference/_fit.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
"""Single maximum-likelihood fit (internal engine behind StatsInference)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import warnings
|
|
7
|
+
from typing import Callable, Mapping, Sequence
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
from scipy import optimize, stats
|
|
11
|
+
|
|
12
|
+
from . import _plots
|
|
13
|
+
from ._distributions import (
|
|
14
|
+
_ALIASES,
|
|
15
|
+
_DISTS,
|
|
16
|
+
_INF,
|
|
17
|
+
_TINY,
|
|
18
|
+
SUPPORTED,
|
|
19
|
+
_CallableDist,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _SingleFit:
|
|
24
|
+
"""One maximum-likelihood fit (internal; use StatsInference).
|
|
25
|
+
|
|
26
|
+
Parameters
|
|
27
|
+
----------
|
|
28
|
+
x : array-like
|
|
29
|
+
Non-empty numeric vector with no NaN or infinite values.
|
|
30
|
+
densfun : str, scipy distribution, or callable
|
|
31
|
+
* a name from ``SUPPORTED`` (case-insensitive; aliases such as
|
|
32
|
+
"lognormal"/"log-normal", "nbinom" are accepted). Parameter names
|
|
33
|
+
follow R, e.g. gamma(shape, rate), weibull(shape, scale);
|
|
34
|
+
* a scipy distribution such as ``scipy.stats.gamma``; parameters are
|
|
35
|
+
its shape names plus ``loc`` and ``scale`` (``loc`` only for
|
|
36
|
+
discrete ones);
|
|
37
|
+
* a density function ``f(x, **params)``, optionally with a ``log``
|
|
38
|
+
keyword (used for numerical stability when present). ``start``
|
|
39
|
+
is then required.
|
|
40
|
+
start : dict, optional
|
|
41
|
+
Starting values, by name. Defaults are computed for named and scipy
|
|
42
|
+
distributions. Not allowed for "normal" (closed-form fit), as in R.
|
|
43
|
+
fixed : dict, optional
|
|
44
|
+
Parameters held fixed (the R version's ``...``). Removed from the
|
|
45
|
+
default ``start``.
|
|
46
|
+
lower, upper : dict, optional
|
|
47
|
+
Bounds on parameters, by name. Named distributions already bound
|
|
48
|
+
positive parameters away from zero.
|
|
49
|
+
method : str, default "L-BFGS-B"
|
|
50
|
+
Any ``scipy.optimize.minimize`` method.
|
|
51
|
+
cdf : callable, optional
|
|
52
|
+
Only for a density function: ``cdf(q, **params)``. Without it the
|
|
53
|
+
CDF is integrated numerically (slower) for the CDF/Q-Q/P-P plots.
|
|
54
|
+
discrete : bool, optional
|
|
55
|
+
Only for a density function: treat the data as counts.
|
|
56
|
+
|
|
57
|
+
Attributes
|
|
58
|
+
----------
|
|
59
|
+
estimate, sd : dict
|
|
60
|
+
Estimates and their standard errors.
|
|
61
|
+
vcov : ndarray
|
|
62
|
+
Variance-covariance matrix (order of ``param_names``).
|
|
63
|
+
loglik, aic, bic, n, converged, message
|
|
64
|
+
"""
|
|
65
|
+
|
|
66
|
+
def __init__(
|
|
67
|
+
self,
|
|
68
|
+
x,
|
|
69
|
+
densfun,
|
|
70
|
+
start: Mapping | None = None,
|
|
71
|
+
fixed: Mapping | None = None,
|
|
72
|
+
lower: Mapping | None = None,
|
|
73
|
+
upper: Mapping | None = None,
|
|
74
|
+
method: str = "L-BFGS-B",
|
|
75
|
+
cdf: Callable | None = None,
|
|
76
|
+
discrete: bool | None = None,
|
|
77
|
+
):
|
|
78
|
+
x = np.asarray(x)
|
|
79
|
+
if x.size == 0 or not np.issubdtype(x.dtype, np.number):
|
|
80
|
+
raise ValueError("'x' must be a non-empty numeric vector")
|
|
81
|
+
x = x.astype(float).ravel()
|
|
82
|
+
if not np.all(np.isfinite(x)):
|
|
83
|
+
raise ValueError("'x' contains missing or infinite values")
|
|
84
|
+
self.x, self.n = x, x.size
|
|
85
|
+
self.fixed = dict(fixed or {})
|
|
86
|
+
self.method = method
|
|
87
|
+
self._user_cdf = cdf
|
|
88
|
+
start = None if start is None else dict(start)
|
|
89
|
+
|
|
90
|
+
# ---- resolve densfun -------------------------------------------
|
|
91
|
+
if isinstance(densfun, str):
|
|
92
|
+
key = densfun.strip().lower()
|
|
93
|
+
key = _ALIASES.get(key, key)
|
|
94
|
+
if key not in _DISTS:
|
|
95
|
+
raise ValueError(
|
|
96
|
+
f"unsupported distribution '{densfun}'. "
|
|
97
|
+
f"Choose from: {', '.join(SUPPORTED)}"
|
|
98
|
+
)
|
|
99
|
+
spec = _DISTS[key]
|
|
100
|
+
self.kind, self.name = "named", key
|
|
101
|
+
self.discrete = spec.get("discrete", False)
|
|
102
|
+
self._make = spec["make"]
|
|
103
|
+
all_names = spec["params"]
|
|
104
|
+
bnd_lo = dict(zip(all_names, spec["lower"]))
|
|
105
|
+
bnd_hi = dict(
|
|
106
|
+
zip(all_names, spec.get("upper", (_INF,) * len(all_names)))
|
|
107
|
+
)
|
|
108
|
+
if key == "normal":
|
|
109
|
+
if start is not None:
|
|
110
|
+
raise ValueError(
|
|
111
|
+
"supplying pars for the Normal "
|
|
112
|
+
"distribution is not supported"
|
|
113
|
+
)
|
|
114
|
+
self._fit_normal()
|
|
115
|
+
return
|
|
116
|
+
if start is None:
|
|
117
|
+
start = {k: float(v) for k, v in spec["start"](x).items()}
|
|
118
|
+
start = {k: v for k, v in start.items() if k not in self.fixed}
|
|
119
|
+
|
|
120
|
+
elif isinstance(densfun, (stats.rv_continuous, stats.rv_discrete)):
|
|
121
|
+
self.kind, self.name = "scipy", densfun.name
|
|
122
|
+
self.discrete = isinstance(densfun, stats.rv_discrete)
|
|
123
|
+
shapes = [
|
|
124
|
+
s.strip()
|
|
125
|
+
for s in (densfun.shapes or "").split(",")
|
|
126
|
+
if s.strip()
|
|
127
|
+
]
|
|
128
|
+
all_names = tuple(
|
|
129
|
+
shapes + (["loc"] if self.discrete else ["loc", "scale"])
|
|
130
|
+
)
|
|
131
|
+
self._make = lambda **p: densfun(**p)
|
|
132
|
+
bnd_lo = {"scale": _TINY} if not self.discrete else {}
|
|
133
|
+
bnd_hi = {}
|
|
134
|
+
if start is None:
|
|
135
|
+
if self.discrete:
|
|
136
|
+
raise ValueError(
|
|
137
|
+
"'start' must be supplied for discrete "
|
|
138
|
+
"scipy distributions"
|
|
139
|
+
)
|
|
140
|
+
f_kw = {
|
|
141
|
+
("f" + k if k in ("loc", "scale") else "f" + k): v
|
|
142
|
+
for k, v in self.fixed.items()
|
|
143
|
+
}
|
|
144
|
+
guess = densfun.fit(x, **f_kw)
|
|
145
|
+
start = {
|
|
146
|
+
k: float(v)
|
|
147
|
+
for k, v in zip(all_names, guess)
|
|
148
|
+
if k not in self.fixed
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
elif callable(densfun):
|
|
152
|
+
if start is None or not isinstance(start, Mapping):
|
|
153
|
+
raise ValueError(
|
|
154
|
+
"'start' must be a named dict for a density function"
|
|
155
|
+
)
|
|
156
|
+
self.kind = "callable"
|
|
157
|
+
self.name = getattr(densfun, "__name__", "custom")
|
|
158
|
+
self.discrete = bool(discrete)
|
|
159
|
+
try:
|
|
160
|
+
has_log = "log" in inspect.signature(densfun).parameters
|
|
161
|
+
except (TypeError, ValueError):
|
|
162
|
+
has_log = False
|
|
163
|
+
fixed_ = self.fixed
|
|
164
|
+
is_discrete = self.discrete
|
|
165
|
+
self._make = lambda **p: _CallableDist(
|
|
166
|
+
densfun, {**p}, has_log, cdf, is_discrete
|
|
167
|
+
)
|
|
168
|
+
all_names = tuple(start) + tuple(fixed_)
|
|
169
|
+
bnd_lo, bnd_hi = {}, {}
|
|
170
|
+
else:
|
|
171
|
+
raise TypeError(
|
|
172
|
+
"'densfun' must be a name, a scipy distribution "
|
|
173
|
+
"or a function"
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if not start:
|
|
177
|
+
raise ValueError("'start' must be a non-empty named dict")
|
|
178
|
+
unknown = set(start) - set(all_names)
|
|
179
|
+
if unknown:
|
|
180
|
+
raise ValueError(
|
|
181
|
+
f"unknown parameter(s) in start: {sorted(unknown)}; "
|
|
182
|
+
f"expected {list(all_names)}"
|
|
183
|
+
)
|
|
184
|
+
bnd_lo.update(lower or {})
|
|
185
|
+
bnd_hi.update(upper or {})
|
|
186
|
+
self.param_names = list(start)
|
|
187
|
+
self.start = start
|
|
188
|
+
self._bounds = [
|
|
189
|
+
(
|
|
190
|
+
None if not np.isfinite(bnd_lo.get(k, -_INF)) else bnd_lo[k],
|
|
191
|
+
None if not np.isfinite(bnd_hi.get(k, _INF)) else bnd_hi[k],
|
|
192
|
+
)
|
|
193
|
+
for k in self.param_names
|
|
194
|
+
]
|
|
195
|
+
self._fit_mle()
|
|
196
|
+
|
|
197
|
+
# ---------------------------------------------------------------- core
|
|
198
|
+
def _frozen(self, theta=None):
|
|
199
|
+
"""Frozen distribution at parameter vector theta (default: estimate)."""
|
|
200
|
+
if theta is None:
|
|
201
|
+
p = dict(self.estimate)
|
|
202
|
+
else:
|
|
203
|
+
p = dict(zip(self.param_names, theta))
|
|
204
|
+
return self._make(**p, **self.fixed)
|
|
205
|
+
|
|
206
|
+
def _logdens(self, dist, x):
|
|
207
|
+
return (
|
|
208
|
+
dist.logpmf(x)
|
|
209
|
+
if (self.discrete and self.kind != "callable")
|
|
210
|
+
else dist.logpdf(x)
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
def _nll(self, theta):
|
|
214
|
+
try:
|
|
215
|
+
with np.errstate(all="ignore"), warnings.catch_warnings():
|
|
216
|
+
warnings.simplefilter("ignore")
|
|
217
|
+
ll = np.sum(self._logdens(self._frozen(theta), self.x))
|
|
218
|
+
except (ValueError, ZeroDivisionError, OverflowError):
|
|
219
|
+
return 1e300
|
|
220
|
+
return -ll if np.isfinite(ll) else 1e300
|
|
221
|
+
|
|
222
|
+
def _fit_mle(self):
|
|
223
|
+
theta0 = np.array([self.start[k] for k in self.param_names], float)
|
|
224
|
+
bounds = (
|
|
225
|
+
self._bounds
|
|
226
|
+
if self.method
|
|
227
|
+
in (
|
|
228
|
+
"L-BFGS-B",
|
|
229
|
+
"TNC",
|
|
230
|
+
"SLSQP",
|
|
231
|
+
"Powell",
|
|
232
|
+
"Nelder-Mead",
|
|
233
|
+
"trust-constr",
|
|
234
|
+
)
|
|
235
|
+
else None
|
|
236
|
+
)
|
|
237
|
+
res = optimize.minimize(
|
|
238
|
+
self._nll, theta0, method=self.method, bounds=bounds
|
|
239
|
+
)
|
|
240
|
+
# Gradient methods can stop early ("converged") after stepping into a
|
|
241
|
+
# region where the density is invalid. Always check with a
|
|
242
|
+
# derivative-free Nelder-Mead pass; if it finds a better point,
|
|
243
|
+
# polish that point with the main method again. Keep the best.
|
|
244
|
+
nm_opts = {"maxiter": 5000, "xatol": 1e-8, "fatol": 1e-10}
|
|
245
|
+
tried = [res]
|
|
246
|
+
if self.method != "Nelder-Mead":
|
|
247
|
+
x_nm = res.x if res.fun < 1e299 else theta0
|
|
248
|
+
res_nm = optimize.minimize(
|
|
249
|
+
self._nll,
|
|
250
|
+
x_nm,
|
|
251
|
+
method="Nelder-Mead",
|
|
252
|
+
bounds=bounds,
|
|
253
|
+
options=nm_opts,
|
|
254
|
+
)
|
|
255
|
+
tried.append(res_nm)
|
|
256
|
+
if res_nm.fun < res.fun - 1e-8 * (1 + abs(res.fun)):
|
|
257
|
+
tried.append(
|
|
258
|
+
optimize.minimize(
|
|
259
|
+
self._nll, res_nm.x, method=self.method, bounds=bounds
|
|
260
|
+
)
|
|
261
|
+
)
|
|
262
|
+
res = min(tried, key=lambda r: r.fun)
|
|
263
|
+
# Converged if some run reported success at (numerically) this optimum.
|
|
264
|
+
tol = 1e-6 * (1 + abs(res.fun))
|
|
265
|
+
ok = [r for r in tried if r.success and r.fun <= res.fun + tol]
|
|
266
|
+
self._opt = res
|
|
267
|
+
self.converged = bool(ok) and res.fun < 1e299
|
|
268
|
+
if ok and not res.success:
|
|
269
|
+
res = ok[0] if ok[0].fun <= res.fun + tol else res
|
|
270
|
+
self.message = str(res.message)
|
|
271
|
+
self.estimate = dict(zip(self.param_names, map(float, res.x)))
|
|
272
|
+
self.loglik = -float(res.fun)
|
|
273
|
+
self.vcov = self._vcov(res.x)
|
|
274
|
+
se = (
|
|
275
|
+
np.sqrt(np.diag(self.vcov))
|
|
276
|
+
if self.vcov is not None
|
|
277
|
+
else np.full(len(res.x), np.nan)
|
|
278
|
+
)
|
|
279
|
+
self.sd = dict(zip(self.param_names, map(float, se)))
|
|
280
|
+
if not self.converged:
|
|
281
|
+
warnings.warn(
|
|
282
|
+
f"optimizer did not report convergence: {self.message}"
|
|
283
|
+
)
|
|
284
|
+
|
|
285
|
+
def _vcov(self, theta):
|
|
286
|
+
"""Inverse of the numerical Hessian of the negative log-likelihood."""
|
|
287
|
+
k = len(theta)
|
|
288
|
+
h = 1e-4 * np.maximum(np.abs(theta), 1e-2)
|
|
289
|
+
H = np.empty((k, k))
|
|
290
|
+
f0 = self._nll(theta)
|
|
291
|
+
for i in range(k):
|
|
292
|
+
for j in range(i, k):
|
|
293
|
+
ei, ej = np.eye(k)[i] * h[i], np.eye(k)[j] * h[j]
|
|
294
|
+
if i == j:
|
|
295
|
+
H[i, i] = (
|
|
296
|
+
self._nll(theta + ei) - 2 * f0 + self._nll(theta - ei)
|
|
297
|
+
) / h[i] ** 2
|
|
298
|
+
else:
|
|
299
|
+
H[i, j] = H[j, i] = (
|
|
300
|
+
self._nll(theta + ei + ej)
|
|
301
|
+
- self._nll(theta + ei - ej)
|
|
302
|
+
- self._nll(theta - ei + ej)
|
|
303
|
+
+ self._nll(theta - ei - ej)
|
|
304
|
+
) / (4 * h[i] * h[j])
|
|
305
|
+
try:
|
|
306
|
+
V = np.linalg.inv(H)
|
|
307
|
+
if np.any(np.diag(V) < 0) or not np.all(np.isfinite(V)):
|
|
308
|
+
raise np.linalg.LinAlgError
|
|
309
|
+
return V
|
|
310
|
+
except np.linalg.LinAlgError:
|
|
311
|
+
warnings.warn("Hessian not invertible: standard errors unavailable")
|
|
312
|
+
return np.full((k, k), np.nan)
|
|
313
|
+
|
|
314
|
+
def _fit_normal(self):
|
|
315
|
+
"""Closed-form MLE, exactly as the R version."""
|
|
316
|
+
n, x = self.n, self.x
|
|
317
|
+
mx, sd0 = float(np.mean(x)), float(
|
|
318
|
+
np.std(x)
|
|
319
|
+
) # ddof=0 = sqrt((n-1)/n)*sd
|
|
320
|
+
self.param_names = ["mean", "sd"]
|
|
321
|
+
self.start = None
|
|
322
|
+
self.estimate = {"mean": mx, "sd": sd0}
|
|
323
|
+
self.sd = {"mean": sd0 / np.sqrt(n), "sd": sd0 / np.sqrt(2 * n)}
|
|
324
|
+
self.vcov = np.diag([self.sd["mean"] ** 2, self.sd["sd"] ** 2])
|
|
325
|
+
self.loglik = float(np.sum(stats.norm.logpdf(x, mx, sd0)))
|
|
326
|
+
self.converged, self.message = True, "closed form"
|
|
327
|
+
self._opt = None
|
|
328
|
+
|
|
329
|
+
# ------------------------------------------------------------- results
|
|
330
|
+
@property
|
|
331
|
+
def dist(self):
|
|
332
|
+
"""The fitted distribution (frozen scipy object or adapter)."""
|
|
333
|
+
return self._frozen()
|
|
334
|
+
|
|
335
|
+
@property
|
|
336
|
+
def k(self):
|
|
337
|
+
return len(self.param_names)
|
|
338
|
+
|
|
339
|
+
@property
|
|
340
|
+
def aic(self):
|
|
341
|
+
return 2 * self.k - 2 * self.loglik
|
|
342
|
+
|
|
343
|
+
@property
|
|
344
|
+
def bic(self):
|
|
345
|
+
return np.log(self.n) * self.k - 2 * self.loglik
|
|
346
|
+
|
|
347
|
+
def _cdf(self, q):
|
|
348
|
+
return np.asarray(self.dist.cdf(q), float)
|
|
349
|
+
|
|
350
|
+
def _ppf(self, p):
|
|
351
|
+
return np.asarray(self.dist.ppf(p), float)
|
|
352
|
+
|
|
353
|
+
def gof(self) -> dict:
|
|
354
|
+
"""Goodness-of-fit statistics (continuous fits only), plus AIC/BIC.
|
|
355
|
+
|
|
356
|
+
KS p-values assume the parameters were known in advance, so they are
|
|
357
|
+
optimistic when the parameters were estimated from the same data.
|
|
358
|
+
"""
|
|
359
|
+
out = {"aic": self.aic, "bic": self.bic}
|
|
360
|
+
if self.discrete:
|
|
361
|
+
return out
|
|
362
|
+
xs = np.sort(self.x)
|
|
363
|
+
n = self.n
|
|
364
|
+
F = np.clip(self._cdf(xs), 1e-300, 1 - 1e-16)
|
|
365
|
+
i = np.arange(1, n + 1)
|
|
366
|
+
ks = max(np.max(i / n - F), np.max(F - (i - 1) / n))
|
|
367
|
+
out["ks"] = float(ks)
|
|
368
|
+
out["ks_pvalue"] = float(stats.kstwo.sf(ks, n))
|
|
369
|
+
out["cvm"] = float(
|
|
370
|
+
1 / (12 * n) + np.sum((F - (2 * i - 1) / (2 * n)) ** 2)
|
|
371
|
+
)
|
|
372
|
+
out["ad"] = float(
|
|
373
|
+
-n - np.mean((2 * i - 1) * (np.log(F) + np.log1p(-F[::-1])))
|
|
374
|
+
)
|
|
375
|
+
return out
|
|
376
|
+
|
|
377
|
+
def summary(self, digits: int = 4) -> str:
|
|
378
|
+
lines = [
|
|
379
|
+
f"Fitting of the distribution '{self.name}' by maximum likelihood",
|
|
380
|
+
"Parameters:",
|
|
381
|
+
f" {'':<10}{'estimate':>14}{'Std. Error':>14}",
|
|
382
|
+
]
|
|
383
|
+
for k in self.param_names:
|
|
384
|
+
lines.append(
|
|
385
|
+
f" {k:<10}{self.estimate[k]:>14.{digits}g}"
|
|
386
|
+
f"{self.sd[k]:>14.{digits}g}"
|
|
387
|
+
)
|
|
388
|
+
if self.fixed:
|
|
389
|
+
lines.append(
|
|
390
|
+
"Fixed parameters: "
|
|
391
|
+
+ ", ".join(f"{k} = {v:g}" for k, v in self.fixed.items())
|
|
392
|
+
)
|
|
393
|
+
lines += [
|
|
394
|
+
f"Loglikelihood: {self.loglik:.{digits}g} "
|
|
395
|
+
f"AIC: {self.aic:.{digits}g} BIC: {self.bic:.{digits}g}",
|
|
396
|
+
f"n = {self.n} converged: {self.converged}",
|
|
397
|
+
]
|
|
398
|
+
g = self.gof()
|
|
399
|
+
if "ks" in g:
|
|
400
|
+
lines.append(
|
|
401
|
+
f"KS: {g['ks']:.{digits}g} (p = {g['ks_pvalue']:.3g}) "
|
|
402
|
+
f"CvM: {g['cvm']:.{digits}g} AD: {g['ad']:.{digits}g}"
|
|
403
|
+
)
|
|
404
|
+
text = "\n".join(lines)
|
|
405
|
+
print(text)
|
|
406
|
+
return text
|
|
407
|
+
|
|
408
|
+
def simulate(self, size=None, seed=None):
|
|
409
|
+
"""Random draws from the fitted distribution.
|
|
410
|
+
|
|
411
|
+
``seed`` may be an int, a ``numpy.random.Generator`` or None.
|
|
412
|
+
"""
|
|
413
|
+
rng = np.random.default_rng(seed)
|
|
414
|
+
return self.dist.rvs(size=size, random_state=rng)
|
|
415
|
+
|
|
416
|
+
def to_dict(self) -> dict:
|
|
417
|
+
"""Same fields the R function returns, plus the extras."""
|
|
418
|
+
return {
|
|
419
|
+
"estimate": self.estimate,
|
|
420
|
+
"sd": self.sd,
|
|
421
|
+
"vcov": self.vcov,
|
|
422
|
+
"n": self.n,
|
|
423
|
+
"loglik": self.loglik,
|
|
424
|
+
"aic": self.aic,
|
|
425
|
+
"bic": self.bic,
|
|
426
|
+
"convergence": 0 if self.converged else 1,
|
|
427
|
+
"objective": -self.loglik,
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
def __repr__(self):
|
|
431
|
+
est = ", ".join(
|
|
432
|
+
f"{k}={v:.4g} ({self.sd[k]:.2g})" for k, v in self.estimate.items()
|
|
433
|
+
)
|
|
434
|
+
return f"<fit {self.name}: {est}; loglik={self.loglik:.4g}>"
|
|
435
|
+
|
|
436
|
+
# --------------------------------------------------------------- plots
|
|
437
|
+
def plot(self, **kwargs):
|
|
438
|
+
"""2x2 panel: density, CDF, Q-Q, P-P (as plot.fitdist in R)."""
|
|
439
|
+
return _plots._plot_fits([self], **kwargs)
|
|
440
|
+
|
|
441
|
+
def denscomp(self, ax=None, **kw):
|
|
442
|
+
return _plots._panel("density", [self], ax, **kw)
|
|
443
|
+
|
|
444
|
+
def cdfcomp(self, ax=None, **kw):
|
|
445
|
+
return _plots._panel("cdf", [self], ax, **kw)
|
|
446
|
+
|
|
447
|
+
def qqcomp(self, ax=None, **kw):
|
|
448
|
+
return _plots._panel("qq", [self], ax, **kw)
|
|
449
|
+
|
|
450
|
+
def ppcomp(self, ax=None, **kw):
|
|
451
|
+
return _plots._panel("pp", [self], ax, **kw)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _compare_table(
|
|
455
|
+
fits: Sequence[_SingleFit],
|
|
456
|
+
labels: Sequence[str] | None = None,
|
|
457
|
+
sort_by: str = "aic",
|
|
458
|
+
):
|
|
459
|
+
"""Table of loglik, AIC, BIC and GOF statistics (like gofstat()).
|
|
460
|
+
|
|
461
|
+
Returns a pandas DataFrame if pandas is installed, else a list of dicts.
|
|
462
|
+
"""
|
|
463
|
+
labels = labels or [f.name for f in fits]
|
|
464
|
+
rows = []
|
|
465
|
+
for lab, f in zip(labels, fits):
|
|
466
|
+
g = f.gof()
|
|
467
|
+
rows.append(
|
|
468
|
+
{
|
|
469
|
+
"distribution": lab,
|
|
470
|
+
"k": f.k,
|
|
471
|
+
"loglik": f.loglik,
|
|
472
|
+
"aic": g["aic"],
|
|
473
|
+
"bic": g["bic"],
|
|
474
|
+
"ks": g.get("ks"),
|
|
475
|
+
"cvm": g.get("cvm"),
|
|
476
|
+
"ad": g.get("ad"),
|
|
477
|
+
}
|
|
478
|
+
)
|
|
479
|
+
rows.sort(key=lambda r: r[sort_by])
|
|
480
|
+
try:
|
|
481
|
+
import pandas as pd
|
|
482
|
+
|
|
483
|
+
return pd.DataFrame(rows).set_index("distribution")
|
|
484
|
+
except ImportError:
|
|
485
|
+
return rows
|
statsinference/_plots.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""fitdistrplus-style diagnostic panels: density, CDF, Q-Q, P-P."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
from typing import Sequence
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
# Colors for fitted curves, assigned in fixed order (blue, orange, aqua, ...).
|
|
11
|
+
_SERIES = [
|
|
12
|
+
"#257de0",
|
|
13
|
+
"#f47230",
|
|
14
|
+
"#00b894",
|
|
15
|
+
"#f2a600",
|
|
16
|
+
"#ee7fac",
|
|
17
|
+
"#008a17",
|
|
18
|
+
"#6a4ce2",
|
|
19
|
+
"#ec4647",
|
|
20
|
+
]
|
|
21
|
+
_DATA_FILL = "#c9c9c9" # neutral gray for the empirical data
|
|
22
|
+
_DATA_EDGE = "#8a8a8a"
|
|
23
|
+
_REF_LINE = "#6b6b6b"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# --------------------------------------------------------------------------
|
|
27
|
+
# Named distributions. Parameter names follow R, so code ports 1:1.
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _plot_fits(
|
|
31
|
+
fits: Sequence,
|
|
32
|
+
labels: Sequence[str] | None = None,
|
|
33
|
+
bins="auto",
|
|
34
|
+
figsize=(10, 8),
|
|
35
|
+
):
|
|
36
|
+
"""The four fitdistrplus panels with all fits overlaid."""
|
|
37
|
+
import matplotlib.pyplot as plt
|
|
38
|
+
|
|
39
|
+
fig, axes = plt.subplots(2, 2, figsize=figsize)
|
|
40
|
+
for ax, kind in zip(axes.flat, ("density", "cdf", "qq", "pp")):
|
|
41
|
+
_panel(
|
|
42
|
+
kind, fits, ax, labels=labels, bins=bins, legend=(kind == "density")
|
|
43
|
+
)
|
|
44
|
+
fig.tight_layout()
|
|
45
|
+
return fig
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _style(ax, title, xlabel, ylabel):
|
|
49
|
+
ax.set_title(title, loc="left", fontsize=11)
|
|
50
|
+
ax.set_xlabel(xlabel)
|
|
51
|
+
ax.set_ylabel(ylabel)
|
|
52
|
+
for s in ("top", "right"):
|
|
53
|
+
ax.spines[s].set_visible(False)
|
|
54
|
+
for s in ("left", "bottom"):
|
|
55
|
+
ax.spines[s].set_color("#bdbdbd")
|
|
56
|
+
ax.tick_params(colors="#5c5c5c")
|
|
57
|
+
ax.grid(True, color="#ececec", linewidth=0.8)
|
|
58
|
+
ax.set_axisbelow(True)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _panel(kind, fits, ax=None, labels=None, bins="auto", legend=True):
|
|
62
|
+
import matplotlib.pyplot as plt
|
|
63
|
+
|
|
64
|
+
if ax is None:
|
|
65
|
+
_, ax = plt.subplots(figsize=(6, 4.5))
|
|
66
|
+
if len(fits) > len(_SERIES):
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"at most {len(_SERIES)} fits can be overlaid; "
|
|
69
|
+
"fold the rest into another figure"
|
|
70
|
+
)
|
|
71
|
+
labels = list(labels or [f.name for f in fits])
|
|
72
|
+
x = fits[0].x
|
|
73
|
+
xs = np.sort(x)
|
|
74
|
+
n = x.size
|
|
75
|
+
discrete = fits[0].discrete
|
|
76
|
+
pp = (np.arange(1, n + 1) - 0.5) / n
|
|
77
|
+
lw = 2
|
|
78
|
+
|
|
79
|
+
with np.errstate(all="ignore"), warnings.catch_warnings():
|
|
80
|
+
warnings.simplefilter("ignore")
|
|
81
|
+
if kind == "density":
|
|
82
|
+
if discrete:
|
|
83
|
+
vals, counts = np.unique(x.astype(int), return_counts=True)
|
|
84
|
+
ax.bar(
|
|
85
|
+
vals,
|
|
86
|
+
counts / n,
|
|
87
|
+
width=0.8,
|
|
88
|
+
color=_DATA_FILL,
|
|
89
|
+
edgecolor="white",
|
|
90
|
+
linewidth=2,
|
|
91
|
+
label="data",
|
|
92
|
+
)
|
|
93
|
+
grid = np.arange(vals.min(), vals.max() + 1)
|
|
94
|
+
for f, lab, c in zip(fits, labels, _SERIES):
|
|
95
|
+
d = f.dist
|
|
96
|
+
y = d.pmf(grid) if hasattr(d, "pmf") else d.pdf(grid)
|
|
97
|
+
ax.plot(grid, y, "-o", color=c, lw=lw, ms=5, label=lab)
|
|
98
|
+
ylabel = "probability"
|
|
99
|
+
else:
|
|
100
|
+
ax.hist(
|
|
101
|
+
x,
|
|
102
|
+
bins=bins,
|
|
103
|
+
density=True,
|
|
104
|
+
color=_DATA_FILL,
|
|
105
|
+
edgecolor="white",
|
|
106
|
+
linewidth=1,
|
|
107
|
+
label="data",
|
|
108
|
+
)
|
|
109
|
+
pad = 0.05 * (xs[-1] - xs[0])
|
|
110
|
+
grid = np.linspace(xs[0] - pad, xs[-1] + pad, 400)
|
|
111
|
+
for f, lab, c in zip(fits, labels, _SERIES):
|
|
112
|
+
ax.plot(grid, f.dist.pdf(grid), color=c, lw=lw, label=lab)
|
|
113
|
+
ylabel = "density"
|
|
114
|
+
_style(ax, "Empirical and theoretical densities", "data", ylabel)
|
|
115
|
+
|
|
116
|
+
elif kind == "cdf":
|
|
117
|
+
ax.step(
|
|
118
|
+
xs,
|
|
119
|
+
np.arange(1, n + 1) / n,
|
|
120
|
+
where="post",
|
|
121
|
+
color=_DATA_EDGE,
|
|
122
|
+
lw=1.5,
|
|
123
|
+
label="empirical",
|
|
124
|
+
)
|
|
125
|
+
if discrete:
|
|
126
|
+
grid = np.arange(xs[0], xs[-1] + 1)
|
|
127
|
+
for f, lab, c in zip(fits, labels, _SERIES):
|
|
128
|
+
ax.step(
|
|
129
|
+
grid,
|
|
130
|
+
f._cdf(grid),
|
|
131
|
+
where="post",
|
|
132
|
+
color=c,
|
|
133
|
+
lw=lw,
|
|
134
|
+
label=lab,
|
|
135
|
+
)
|
|
136
|
+
else:
|
|
137
|
+
pad = 0.05 * (xs[-1] - xs[0])
|
|
138
|
+
grid = np.linspace(xs[0] - pad, xs[-1] + pad, 400)
|
|
139
|
+
for f, lab, c in zip(fits, labels, _SERIES):
|
|
140
|
+
ax.plot(grid, f._cdf(grid), color=c, lw=lw, label=lab)
|
|
141
|
+
_style(ax, "Empirical and theoretical CDFs", "data", "CDF")
|
|
142
|
+
|
|
143
|
+
elif kind == "qq":
|
|
144
|
+
lo, hi = xs[0], xs[-1]
|
|
145
|
+
for f, lab, c in zip(fits, labels, _SERIES):
|
|
146
|
+
q = f._ppf(pp)
|
|
147
|
+
ax.scatter(
|
|
148
|
+
q,
|
|
149
|
+
xs,
|
|
150
|
+
s=16,
|
|
151
|
+
color=c,
|
|
152
|
+
alpha=0.75,
|
|
153
|
+
edgecolor="white",
|
|
154
|
+
linewidth=0.5,
|
|
155
|
+
label=lab,
|
|
156
|
+
)
|
|
157
|
+
fin = q[np.isfinite(q)]
|
|
158
|
+
if fin.size:
|
|
159
|
+
lo, hi = min(lo, fin.min()), max(hi, fin.max())
|
|
160
|
+
ax.plot([lo, hi], [lo, hi], color=_REF_LINE, lw=1, ls="--")
|
|
161
|
+
_style(
|
|
162
|
+
ax, "Q-Q plot", "theoretical quantiles", "empirical quantiles"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
elif kind == "pp":
|
|
166
|
+
emp = np.arange(1, n + 1) / (n + 1)
|
|
167
|
+
for f, lab, c in zip(fits, labels, _SERIES):
|
|
168
|
+
ax.scatter(
|
|
169
|
+
f._cdf(xs),
|
|
170
|
+
emp,
|
|
171
|
+
s=16,
|
|
172
|
+
color=c,
|
|
173
|
+
alpha=0.75,
|
|
174
|
+
edgecolor="white",
|
|
175
|
+
linewidth=0.5,
|
|
176
|
+
label=lab,
|
|
177
|
+
)
|
|
178
|
+
ax.plot([0, 1], [0, 1], color=_REF_LINE, lw=1, ls="--")
|
|
179
|
+
_style(
|
|
180
|
+
ax,
|
|
181
|
+
"P-P plot",
|
|
182
|
+
"theoretical probabilities",
|
|
183
|
+
"empirical probabilities",
|
|
184
|
+
)
|
|
185
|
+
else:
|
|
186
|
+
raise ValueError(kind)
|
|
187
|
+
|
|
188
|
+
if legend and (len(fits) > 1 or kind in ("density", "cdf")):
|
|
189
|
+
ax.legend(frameon=False, fontsize=9)
|
|
190
|
+
return ax
|