mcmaster-epg 1.0.1__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.
@@ -0,0 +1,34 @@
1
+ """EPG calculation for the McMaster method with Raynaud's modification."""
2
+
3
+ from .core import (detection_limit, detection_probability, epg, epg_ci, expected_cv,
4
+ multiplier, poisson_ci, recovery, replicates_for_cv)
5
+ from .counts import fitted_counts
6
+ from .data import EMPIRICAL_MULTIPLIER, LIMIT_OF_DETECTION, RAYNAUD_MULTIPLIER
7
+ from .detection import (fit_curve, fit_recovery, fitted, fitted_limits, fitted_recovery,
8
+ lod, pod, pod_curve)
9
+ from .epg import (EpgResult, dispersion_test, estimate_epg, negative_binomial_interval,
10
+ poisson_interval)
11
+ from .factors import (EMPIRICAL_WHOLE_CHAMBER_FACTORS, RAYNAUD_FACTORS, VARIANTS,
12
+ empirical_factor, geometric_factor, raynaud_factor)
13
+ from .report import corrected_factor, interpret, interpret_profile
14
+ from .profile import (MethodProfile, builtin_profile, load_profile, manual_profile,
15
+ nominal_profile, save_profile)
16
+ from .calibrate import calibrate, read_spiked
17
+
18
+ __version__ = "1.0.1"
19
+
20
+ __all__ = [
21
+ # simple calculator
22
+ "detection_limit", "detection_probability", "epg", "epg_ci", "expected_cv",
23
+ "multiplier", "poisson_ci", "recovery", "replicates_for_cv",
24
+ "EMPIRICAL_MULTIPLIER", "LIMIT_OF_DETECTION", "RAYNAUD_MULTIPLIER",
25
+ # validated models
26
+ "EMPIRICAL_WHOLE_CHAMBER_FACTORS", "RAYNAUD_FACTORS", "VARIANTS", "EpgResult",
27
+ "corrected_factor", "dispersion_test", "empirical_factor", "estimate_epg", "fit_curve",
28
+ "fit_recovery", "fitted", "fitted_counts", "fitted_limits", "fitted_recovery",
29
+ "geometric_factor", "interpret", "lod", "negative_binomial_interval", "pod",
30
+ "pod_curve", "poisson_interval", "raynaud_factor",
31
+ # method profiles
32
+ "MethodProfile", "builtin_profile", "calibrate", "interpret_profile", "load_profile",
33
+ "manual_profile", "nominal_profile", "read_spiked", "save_profile",
34
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,372 @@
1
+ """Calibration of a McMaster procedure from one's own spiked samples.
2
+
3
+ Input: one row per independently prepared spiked sample, with the spiking
4
+ level (eggs per gram) and the number of eggs counted in one reading. The
5
+ counts are modelled as negative binomial with mean recovery * level /
6
+ factor and dispersion k (Poisson when k = inf), fitted by maximum
7
+ likelihood. The result is a method profile (`profile.MethodProfile`) that
8
+ every other calculation of the package accepts, and a report.
9
+
10
+ Checks reported with the estimates:
11
+
12
+ * linearity: log mean count = a + b log level, likelihood-ratio test of
13
+ b = 1 (the proportional model that a single recovery assumes);
14
+ * overdispersion: likelihood-ratio test of Poisson against negative
15
+ binomial (boundary-corrected: half the chi-square tail);
16
+ * detection: LOD50 and LOD95 of the count model, and as a check the
17
+ two-parameter detection curve fitted to the share of positive samples,
18
+ with its parametric-bootstrap goodness of fit;
19
+ * predicted against observed mean counts and shares of positive samples
20
+ at every level.
21
+
22
+ Uncertainty: profile-likelihood intervals for recovery, k and the limits
23
+ of detection under the count model. The ranges of recovery and k that the
24
+ herd calculations use are profile-likelihood intervals at the matching
25
+ levels (stored in the profile as percentiles), and the calibration data are
26
+ stored in the profile, so that every result can be reproduced.
27
+ """
28
+
29
+ import csv
30
+ from dataclasses import dataclass
31
+ from functools import lru_cache
32
+ import io
33
+ import math
34
+
35
+ import numpy as np
36
+ from scipy.optimize import brentq, minimize, minimize_scalar
37
+ from scipy.special import gammaln
38
+ from scipy.stats import chi2
39
+
40
+ from .counts import K_POISSON
41
+ from .detection import fit_curve, goodness_of_fit
42
+ from .profile import PERCENTILES, MethodProfile
43
+
44
+ _LOG_K = (math.log(1e-3), math.log(K_POISSON))
45
+
46
+
47
+ def read_spiked(path):
48
+ """Levels and counts from a CSV file with the columns `level` and
49
+ `count`; comma, semicolon or tab separated, decimal comma accepted.
50
+ Other columns are ignored."""
51
+ with open(path, newline="", encoding="utf-8-sig") as fh:
52
+ return parse_spiked(fh.read())
53
+
54
+
55
+ def parse_spiked(text):
56
+ """As read_spiked, from the text of the file."""
57
+ if not text.strip():
58
+ raise ValueError("empty file")
59
+ first = text.splitlines()[0]
60
+ delim = max((";", "\t", ","), key=first.count)
61
+ rows = list(csv.DictReader(io.StringIO(text), delimiter=delim))
62
+ if not rows:
63
+ raise ValueError("no rows")
64
+ names = {name.strip().lower(): name for name in rows[0]}
65
+ if "level" not in names or "count" not in names:
66
+ raise ValueError("the file needs the columns 'level' and 'count'")
67
+ levels, counts = [], []
68
+ for row in rows:
69
+ lv, ct = row[names["level"]].strip(), row[names["count"]].strip()
70
+ if not lv and not ct:
71
+ continue
72
+ levels.append(float(lv.replace(",", ".")))
73
+ counts.append(int(ct))
74
+ return np.array(levels), np.array(counts)
75
+
76
+
77
+ def _check(levels, counts):
78
+ levels = np.asarray(levels, dtype=float)
79
+ counts = np.asarray(counts)
80
+ if levels.shape != counts.shape or levels.ndim != 1:
81
+ raise ValueError("levels and counts must be two lists of the same length")
82
+ if np.any(levels <= 0):
83
+ raise ValueError("spiking levels must be positive (unspiked samples are not used)")
84
+ if np.any(counts < 0) or np.any(counts != np.round(counts)):
85
+ raise ValueError("counts must be non-negative integers")
86
+ if np.unique(levels).size < 2:
87
+ raise ValueError("at least two spiking levels are needed")
88
+ if counts.sum() == 0:
89
+ raise ValueError("no eggs were counted at any level")
90
+ return levels, counts.astype(int)
91
+
92
+
93
+ def _nb_ll(y, mu, k):
94
+ if math.isinf(k):
95
+ return float((y * np.log(mu) - mu - gammaln(y + 1)).sum())
96
+ return float((gammaln(y + k) - gammaln(k) - gammaln(y + 1)
97
+ + k * np.log(k / (k + mu)) + y * np.log(mu / (k + mu))).sum())
98
+
99
+
100
+ def _fit(levels, y, factor, start=None, slope=False):
101
+ """Maximum-likelihood fit. Returns (recovery or intercept, k, b, loglik).
102
+ With slope=True the mean is exp(a) * (level / factor) ** b."""
103
+ x = levels / factor
104
+
105
+ def mean(par):
106
+ return np.exp(par[0]) * (x ** par[2] if slope else x)
107
+
108
+ def nll(par):
109
+ if not _LOG_K[0] <= par[1] <= _LOG_K[1]:
110
+ return 1e300
111
+ return -_nb_ll(y, mean(par), math.exp(par[1]))
112
+
113
+ r0 = math.log(y.sum() / x.sum())
114
+ starts = [start] if start is not None else [(r0, 0.0), (r0, 3.0), (r0, -1.5)]
115
+ if slope:
116
+ starts = [tuple(s[:2]) + (1.0,) for s in starts]
117
+ best = None
118
+ for st in starts:
119
+ res = minimize(nll, st, method="Nelder-Mead",
120
+ options={"xatol": 1e-8, "fatol": 1e-10, "maxiter": 4000})
121
+ if best is None or res.fun < best.fun:
122
+ best = res
123
+ # Poisson limit
124
+ if slope:
125
+ pois = minimize(lambda p: -_nb_ll(y, np.exp(p[0]) * x ** p[1], math.inf),
126
+ (best.x[0], best.x[2]), method="Nelder-Mead",
127
+ options={"xatol": 1e-8, "fatol": 1e-10})
128
+ ll_p, par_p = -pois.fun, (pois.x[0], math.inf, pois.x[1])
129
+ else:
130
+ r_p = y.sum() / x.sum()
131
+ ll_p, par_p = _nb_ll(y, r_p * x, math.inf), (math.log(r_p), math.inf, 1.0)
132
+ k = math.exp(best.x[1])
133
+ if ll_p >= -best.fun - 1e-9 or k >= 0.999 * K_POISSON:
134
+ return math.exp(par_p[0]), math.inf, par_p[2], ll_p
135
+ return math.exp(best.x[0]), k, (best.x[2] if slope else 1.0), -best.fun
136
+
137
+
138
+ def _mean_lod(p, k):
139
+ """Mean count at which P(count >= 1) = p."""
140
+ return -math.log1p(-p) if math.isinf(k) else k * ((1 - p) ** (-1 / k) - 1)
141
+
142
+
143
+ def _profile_recovery(levels, y, factor, r):
144
+ x = levels / factor
145
+ res = minimize_scalar(lambda t: -_nb_ll(y, r * x, math.exp(t)), bounds=_LOG_K,
146
+ method="bounded", options={"xatol": 1e-8})
147
+ return max(-res.fun, _nb_ll(y, r * x, math.inf))
148
+
149
+
150
+ def _profile_k(levels, y, factor, k):
151
+ x = levels / factor
152
+ if math.isinf(k):
153
+ return _nb_ll(y, (y.sum() / x.sum()) * x, math.inf)
154
+ c = math.log(y.sum() / x.sum())
155
+ res = minimize_scalar(lambda t: -_nb_ll(y, math.exp(t) * x, k), bounds=(c - 5, c + 5),
156
+ method="bounded", options={"xatol": 1e-9})
157
+ return -res.fun
158
+
159
+
160
+ def _profile_lod(levels, y, factor, p, lod):
161
+ """Log-likelihood maximised over k with recovery set so that the limit
162
+ of detection at probability p equals `lod`."""
163
+ x = levels / factor
164
+
165
+ def ll(k):
166
+ return _nb_ll(y, factor * _mean_lod(p, k) / lod * x, k)
167
+
168
+ res = minimize_scalar(lambda t: -ll(math.exp(t)), bounds=_LOG_K, method="bounded",
169
+ options={"xatol": 1e-8})
170
+ return max(-res.fun, ll(math.inf))
171
+
172
+
173
+ def _interval(profile, centre, loglik, conf, span=10.0):
174
+ """Profile-likelihood interval on the log scale around log(centre);
175
+ 0 or inf when the profile does not fall below the cut within span."""
176
+ cut = chi2.ppf(conf, 1) / 2
177
+
178
+ def g(t):
179
+ return profile(math.exp(t)) - (loglik - cut)
180
+
181
+ c = math.log(centre)
182
+ lo = math.exp(brentq(g, c - span, c, xtol=1e-9)) if g(c - span) < 0 else 0.0
183
+ hi = math.exp(brentq(g, c, c + span, xtol=1e-9)) if g(c + span) < 0 else math.inf
184
+ return lo, hi
185
+
186
+
187
+ def recovery_interval(levels, y, factor, recovery, loglik, conf=0.95):
188
+ """Profile-likelihood interval for recovery (k profiled out)."""
189
+ return _interval(lambda r: _profile_recovery(levels, y, factor, r), recovery, loglik, conf)
190
+
191
+
192
+ def k_interval(levels, y, factor, k, loglik, conf=0.95):
193
+ """Profile-likelihood interval for k (recovery profiled out); the upper
194
+ limit is inf when Poisson counts are not rejected, the lower limit at
195
+ most the search bound 0.001."""
196
+ cut = chi2.ppf(conf, 1) / 2
197
+ lo_b, hi_b = math.exp(_LOG_K[0]), math.exp(_LOG_K[1])
198
+
199
+ def g(kk):
200
+ return _profile_k(levels, y, factor, kk) - (loglik - cut)
201
+
202
+ centre = hi_b if math.isinf(k) else k
203
+ lo = (math.exp(brentq(lambda t: g(math.exp(t)), _LOG_K[0], math.log(centre), xtol=1e-9))
204
+ if g(lo_b) < 0 else lo_b)
205
+ if math.isinf(k) or g(math.inf) >= 0:
206
+ return lo, math.inf
207
+ hi = (math.exp(brentq(lambda t: g(math.exp(t)), math.log(k), _LOG_K[1], xtol=1e-9))
208
+ if g(hi_b) < 0 else math.inf)
209
+ return lo, hi
210
+
211
+
212
+ def lod_interval(levels, y, factor, p, conf=0.95):
213
+ """Limit of detection at probability p under the fitted count model,
214
+ with a profile-likelihood interval: (estimate, low, high)."""
215
+ levels, y = _check(levels, y)
216
+ r, k, _, ll = _fit(levels, y, factor)
217
+ est = factor * _mean_lod(p, k) / r
218
+ lo, hi = _interval(lambda v: _profile_lod(levels, y, factor, p, v), est, ll, conf)
219
+ return est, lo, hi
220
+
221
+
222
+ @lru_cache(maxsize=None)
223
+ def count_model_lod(counts_data, factor, p, conf):
224
+ """lod_interval for data stored in a profile (cached)."""
225
+ levels, counts = counts_data
226
+ return lod_interval(np.array(levels), np.array(counts), factor, p, conf)
227
+
228
+
229
+ @dataclass(frozen=True)
230
+ class Calibration:
231
+ profile: MethodProfile
232
+ recovery_ci: tuple
233
+ k_ci: tuple
234
+ linearity_slope: float
235
+ linearity_p: float
236
+ overdispersion_p: float
237
+ curve_limits: dict # LOD50 / LOD95 of the detection curve, or None
238
+ detection_gof_p: float
239
+ table: tuple # per level: (level, n, mean, sd, positive share, predicted mean, predicted positive share)
240
+ n_gof: int
241
+ notes: tuple
242
+
243
+
244
+ def calibrate(levels, counts, factor, name="", n_gof=1000, seed=2013, conf=0.95):
245
+ """Fit a profile to spiked samples (one count per independently prepared
246
+ sample). `factor` is the nominal multiplication factor of the reading.
247
+ n_gof: replicates of the goodness-of-fit bootstrap of the detection
248
+ curve (0 skips it)."""
249
+ levels, y = _check(levels, counts)
250
+ factor = float(factor)
251
+ r, k, _, ll = _fit(levels, y, factor)
252
+ r_ci = recovery_interval(levels, y, factor, r, ll, conf)
253
+ k_ci = k_interval(levels, y, factor, k, ll, conf)
254
+ _, _, b, ll_slope = _fit(levels, y, factor, slope=True)
255
+ lin_p = float(chi2.sf(max(0.0, 2 * (ll_slope - ll)), 1))
256
+ ll_pois = _profile_k(levels, y, factor, math.inf)
257
+ over_p = 1.0 if math.isinf(k) else float(0.5 * chi2.sf(max(0.0, 2 * (ll - ll_pois)), 1))
258
+
259
+ # parameter ranges at every stored percentile, from profile-likelihood
260
+ # intervals of the matching two-sided level
261
+ r_iv, k_iv = {}, {}
262
+ for q in PERCENTILES:
263
+ level = round(1 - 2 * min(q, 100 - q) / 100, 6)
264
+ if level not in r_iv:
265
+ r_iv[level] = recovery_interval(levels, y, factor, r, ll, level)
266
+ k_iv[level] = k_interval(levels, y, factor, k, ll, level)
267
+ pick = (lambda iv, q: iv[round(1 - 2 * min(q, 100 - q) / 100, 6)][0 if q < 50 else 1])
268
+ r_q = tuple(pick(r_iv, q) for q in PERCENTILES)
269
+ k_q = tuple(pick(k_iv, q) for q in PERCENTILES)
270
+
271
+ # per-level summary and detection curve (as a check)
272
+ rows, lv_u, pos_u, n_u = [], [], [], []
273
+ for lv in np.unique(levels):
274
+ ys = y[levels == lv]
275
+ m_pred = r * lv / factor
276
+ p_pred = -math.expm1(-m_pred) if math.isinf(k) else 1 - (1 + m_pred / k) ** (-k)
277
+ rows.append((float(lv), int(ys.size), float(ys.mean()),
278
+ float(ys.std(ddof=1)) if ys.size > 1 else float("nan"),
279
+ float((ys > 0).mean()), m_pred, p_pred))
280
+ lv_u.append(float(lv))
281
+ pos_u.append(int((ys > 0).sum()))
282
+ n_u.append(int(ys.size))
283
+ n_det = n_u[0] if len(set(n_u)) == 1 else tuple(n_u)
284
+ detection = (tuple(lv_u), tuple(pos_u), n_det)
285
+ notes = []
286
+ try:
287
+ curve = fit_curve(*detection)
288
+ curve_limits = {name_: (curve.lod(pp),) + curve.lod_ci(pp, conf)
289
+ for name_, pp in (("lod50", 0.5), ("lod95", 0.95))}
290
+ gof_p = goodness_of_fit(curve, n_boot=n_gof, seed=seed) if n_gof else float("nan")
291
+ except ValueError:
292
+ detection, curve_limits, gof_p = None, None, float("nan")
293
+ notes.append("Every sample at every level was positive (or every one negative), "
294
+ "so no detection curve can be fitted as a check.")
295
+ if lin_p < 0.05:
296
+ notes.append(f"Mean counts are not proportional to the level (slope {b:.2f} on the "
297
+ f"log scale, p = {lin_p:.3g}); a single recovery describes the data "
298
+ "only approximately. Check the lowest and highest levels.")
299
+ if detection is not None and n_gof and gof_p < 0.05:
300
+ notes.append(f"The detection curve fits poorly (p = {gof_p:.3g}).")
301
+
302
+ profile = MethodProfile(
303
+ factor=factor, recovery=r, k=k, percentiles=PERCENTILES, recovery_q=r_q, k_q=k_q,
304
+ detection=detection, counts_data=(tuple(float(v) for v in levels),
305
+ tuple(int(v) for v in y)),
306
+ correction_source="calibrated recovery", max_level=float(levels.max()),
307
+ name=name or "calibrated", source="calibrated")
308
+ return Calibration(profile, r_ci, k_ci, b, lin_p, over_p, curve_limits, gof_p, tuple(rows),
309
+ n_gof, tuple(notes))
310
+
311
+
312
+ def report(cal, conf=0.95):
313
+ """Calibration report in Markdown."""
314
+ p = cal.profile
315
+ fmt_k = (lambda v: "inf" if math.isinf(v) else f"{v:.3g}")
316
+ w = []
317
+ w.append(f"# Calibration: {p.name}")
318
+ w.append("")
319
+ n = sum(row[1] for row in cal.table)
320
+ w.append(f"{n} spiked samples at {len(cal.table)} levels "
321
+ f"({cal.table[0][0]:g} to {cal.table[-1][0]:g} eggs/g); nominal factor {p.factor:g}.")
322
+ w.append("")
323
+ w.append("## Estimates")
324
+ w.append("")
325
+ w.append("| Parameter | Estimate | 95% interval |")
326
+ w.append("|---|---:|---:|")
327
+ w.append(f"| Recovery | {p.recovery:.3f} | {cal.recovery_ci[0]:.3f} to {cal.recovery_ci[1]:.3f} "
328
+ "(profile likelihood) |")
329
+ w.append(f"| Corrected factor (factor / recovery) | {p.effective_factor:.1f} | "
330
+ f"{p.factor / cal.recovery_ci[1]:.1f} to "
331
+ f"{(p.factor / cal.recovery_ci[0]) if cal.recovery_ci[0] > 0 else math.inf:.1f} |")
332
+ w.append(f"| Dispersion k | {fmt_k(p.k)} | {fmt_k(cal.k_ci[0])} to {fmt_k(cal.k_ci[1])} "
333
+ "(profile likelihood) |")
334
+ limits = p.limits(conf)
335
+ for key, label in (("lod50", "LOD50 (eggs/g)"), ("lod95", "LOD95 (eggs/g)")):
336
+ est, lo, hi = limits[key]
337
+ extra = ", extrapolated" if p.extrapolated(est) else ""
338
+ w.append(f"| {label} | {est:.1f} | {lo:.1f} to {fmt_k(hi) if math.isinf(hi) else f'{hi:.1f}'} "
339
+ f"(count model, profile likelihood{extra}) |")
340
+ w.append("")
341
+ w.append("## Checks")
342
+ w.append("")
343
+ w.append(f"- Linearity: slope of log mean count on log level {cal.linearity_slope:.3f}; "
344
+ f"test of slope 1: p = {cal.linearity_p:.3g}.")
345
+ w.append(f"- Overdispersion against Poisson: p = {cal.overdispersion_p:.3g}.")
346
+ if cal.curve_limits is not None:
347
+ c = p.curve()
348
+ (a50, l50, h50), (a95, l95, h95) = cal.curve_limits["lod50"], cal.curve_limits["lod95"]
349
+ gof = (f"; goodness of fit p = {cal.detection_gof_p:.3g}"
350
+ if not math.isnan(cal.detection_gof_p) else "")
351
+ w.append(f"- Detection curve fitted to the share of positive samples (independent of "
352
+ f"the count model): LOD50 {a50:.1f} ({l50:.1f} to {h50:.1f}), LOD95 "
353
+ f"{a95:.1f} ({l95:.1f} to {fmt_k(h95) if math.isinf(h95) else f'{h95:.1f}'}), "
354
+ f"slope {c.slope:.2f} (1 = Poisson-like){gof}.")
355
+ w.append("")
356
+ w.append("## Levels")
357
+ w.append("")
358
+ w.append("| Level (eggs/g) | Samples | Mean count | SD | Positive | Predicted mean | Predicted positive |")
359
+ w.append("|---:|---:|---:|---:|---:|---:|---:|")
360
+ for lv, n_i, m, sd, pos, mp, pp in cal.table:
361
+ w.append(f"| {lv:g} | {n_i} | {m:.2f} | {sd:.2f} | {pos:.0%} | {mp:.2f} | {pp:.0%} |")
362
+ if cal.notes:
363
+ w.append("")
364
+ w.append("## Notes")
365
+ w.append("")
366
+ for note in cal.notes:
367
+ w.append(f"- {note}")
368
+ w.append("")
369
+ w.append("Model: counts negative binomial with mean recovery x level / factor and "
370
+ "dispersion k, fitted by maximum likelihood; each row is assumed to be an "
371
+ "independently prepared spiked sample.")
372
+ return "\n".join(w) + "\n"