width-debias 0.4.0__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,637 @@
1
+ """Per-frame statistics of the fitted widths, and the CNR-keyed bias lookup.
2
+
3
+ For each frame, the Monte Carlo ensemble gives the sampling distribution of the
4
+ fitted MSD increment. Three quantities summarise that distribution:
5
+
6
+ * ``trunc_fraction`` -- the fraction of realisations with MSD <= 0, i.e. the
7
+ probability mass that has crossed to the wrong side of the D >= 0 wall.
8
+ * ``rel_variance`` -- the variance of the MSD point, the input the *standard*
9
+ inverse-variance scheme already uses.
10
+ * ``skew`` -- the sample skewness, a direct readout of the asymmetry
11
+ that inverse-variance weighting wrongly assumes away.
12
+
13
+ All three are monotone in per-frame CNR. :class:`BiasLookup` packages
14
+ them against CNR so a weighting scheme can look them up from a per-frame CNR
15
+ alone (measured, on real data, with the ``fft-cnr`` package).
16
+
17
+ The class supports **two calibration modes** with the same API:
18
+
19
+ * **1-D** (recommended when built at D = 0): built from :func:`frame_stats`
20
+ via :meth:`BiasLookup.from_stats`. Looks up ``var_bias`` and the
21
+ per-frame width variance from CNR alone.
22
+ :func:`~width_debias.validate.calibrate_d_free` builds it at D = 0, so the
23
+ lookup carries no reference to the application's D;
24
+ :func:`~width_debias.validate.calibrate` builds it at a given D (legacy,
25
+ D-aware) -- see ``docs/DERIVATION.md``.
26
+ * **2-D, joint (CNR, sigma^2)** (experimental): built from a
27
+ :class:`~width_debias.calibration.CalibrationGrid` via
28
+ :meth:`BiasLookup.from_calibration`. Looks up ``var_bias`` and
29
+ per-frame ``rel_variance`` from (CNR, fitted-variance) jointly. Its low-CNR
30
+ cells need far more Monte Carlo runs than the 1-D path, and keying each frame
31
+ on its own fitted width under-corrects when the width grows several-fold
32
+ (see :meth:`var_bias`); see :mod:`width_debias.calibration`.
33
+
34
+ The selection between the two is automatic: pass a ``variance`` argument to
35
+ :meth:`var_bias` or :meth:`rel_variance` to trigger the 2-D lookup when the
36
+ 2-D table is present; otherwise the 1-D fallback runs.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ from dataclasses import dataclass, field, fields
41
+
42
+ import numpy as np
43
+
44
+ from .montecarlo import Ensemble
45
+
46
+
47
+ @dataclass
48
+ class FrameStats:
49
+ """Per-frame summary of the MSD sampling distribution."""
50
+
51
+ cnr: np.ndarray # per-frame CNR
52
+ trunc_fraction: np.ndarray # P(MSD <= 0) per frame
53
+ at_wall_fraction: np.ndarray # fraction of fits pinned at the width wall
54
+ rel_variance: np.ndarray # Var(MSD) per frame
55
+ skew: np.ndarray # sample skewness of MSD per frame
56
+ mean_msd: np.ndarray # mean fitted MSD per frame
57
+ true_msd: np.ndarray # ground-truth MSD per frame
58
+ var_bias: np.ndarray # E[sigma_hat^2] - sigma^2_true per frame
59
+ # (the additive variance bias; see DERIVATION.md)
60
+ var_bias_se: np.ndarray | None = None # Monte Carlo SE of var_bias per frame
61
+ frame_variance: np.ndarray | None = None # Var(sigma_hat^2) per frame
62
+
63
+
64
+ def _skew(a: np.ndarray) -> float:
65
+ a = a[np.isfinite(a)]
66
+ if a.size < 3:
67
+ return np.nan
68
+ d = a - a.mean()
69
+ s2 = (d ** 2).mean()
70
+ if s2 == 0:
71
+ return 0.0
72
+ return float((d ** 3).mean() / s2 ** 1.5)
73
+
74
+
75
+ def frame_stats(ens: Ensemble) -> FrameStats:
76
+ """Reduce a Monte Carlo ensemble to per-frame distribution statistics."""
77
+ n_frames = ens.exp.n_frames
78
+ trunc = np.full(n_frames, np.nan)
79
+ rel_var = np.full(n_frames, np.nan)
80
+ skew = np.full(n_frames, np.nan)
81
+ mean_msd = np.full(n_frames, np.nan)
82
+ var_bias = np.full(n_frames, np.nan)
83
+ var_bias_se = np.full(n_frames, np.nan)
84
+ frame_var = np.full(n_frames, np.nan)
85
+ true_variance = ens.exp.true_variance
86
+
87
+ for f in range(n_frames):
88
+ col = ens.msd[:, f]
89
+ col = col[np.isfinite(col)]
90
+ if col.size:
91
+ trunc[f] = float(np.mean(col <= 0.0))
92
+ rel_var[f] = float(np.var(col, ddof=1)) if col.size > 1 else np.nan
93
+ skew[f] = _skew(col)
94
+ mean_msd[f] = float(np.mean(col))
95
+ # Additive variance bias E[sigma_hat^2] - sigma^2_true (DERIVATION.md s.2).
96
+ vcol = ens.variance[:, f]
97
+ vcol = vcol[np.isfinite(vcol)]
98
+ if vcol.size:
99
+ var_bias[f] = float(np.mean(vcol)) - float(true_variance[f])
100
+ if vcol.size > 1:
101
+ # The lookup's own Monte Carlo error; propagated into D by
102
+ # weights.calibration_D_se.
103
+ var_bias_se[f] = float(np.std(vcol, ddof=1) / np.sqrt(vcol.size))
104
+ # The width variance of this frame alone, a function of its own
105
+ # CNR. rel_variance above also carries this ensemble's t = 0 frame,
106
+ # which belongs to the calibration's CNR_0, not the application's.
107
+ frame_var[f] = float(np.var(vcol, ddof=1))
108
+
109
+ at_wall_frac = np.nanmean(ens.at_wall.astype(float), axis=0)
110
+ return FrameStats(cnr=ens.cnr_frame, trunc_fraction=trunc,
111
+ at_wall_fraction=at_wall_frac, rel_variance=rel_var,
112
+ skew=skew, mean_msd=mean_msd, true_msd=ens.exp.true_msd,
113
+ var_bias=var_bias, var_bias_se=var_bias_se,
114
+ frame_variance=frame_var)
115
+
116
+
117
+ def _bilinear(x_grid: np.ndarray, y_grid: np.ndarray, table: np.ndarray,
118
+ x: np.ndarray, y: np.ndarray) -> np.ndarray:
119
+ """Bilinear interpolation of ``table[i, j]`` defined on ``x_grid`` x ``y_grid``.
120
+
121
+ ``x_grid`` and ``y_grid`` are 1-D ascending; ``table`` has shape
122
+ ``(x_grid.size, y_grid.size)``. Queries outside the grid are clipped to the
123
+ boundary value (i.e. nearest-edge extrapolation in each axis).
124
+ """
125
+ x_arr = np.atleast_1d(np.asarray(x, float))
126
+ y_arr = np.atleast_1d(np.asarray(y, float))
127
+
128
+ xc = np.clip(x_arr, x_grid[0], x_grid[-1])
129
+ yc = np.clip(y_arr, y_grid[0], y_grid[-1])
130
+
131
+ i = np.clip(np.searchsorted(x_grid, xc) - 1, 0, x_grid.size - 2)
132
+ j = np.clip(np.searchsorted(y_grid, yc) - 1, 0, y_grid.size - 2)
133
+
134
+ x_lo = x_grid[i]; x_hi = x_grid[i + 1]
135
+ y_lo = y_grid[j]; y_hi = y_grid[j + 1]
136
+ fx = (xc - x_lo) / np.maximum(x_hi - x_lo, 1e-30)
137
+ fy = (yc - y_lo) / np.maximum(y_hi - y_lo, 1e-30)
138
+
139
+ v00 = table[i, j]
140
+ v01 = table[i, j + 1]
141
+ v10 = table[i + 1, j]
142
+ v11 = table[i + 1, j + 1]
143
+ out = (v00 * (1 - fx) * (1 - fy)
144
+ + v10 * fx * (1 - fy)
145
+ + v01 * (1 - fx) * fy
146
+ + v11 * fx * fy)
147
+ # Return scalar if scalar inputs were passed.
148
+ if np.ndim(x) == 0 and np.ndim(y) == 0:
149
+ return float(out[0])
150
+ return out
151
+
152
+
153
+ def _interp_se(x, xp: np.ndarray, sp: np.ndarray) -> np.ndarray:
154
+ """SE of ``np.interp(x, xp, fp)`` when each ``fp[k]`` has independent SE ``sp[k]``.
155
+
156
+ The interpolant is ``(1 - f) fp[k] + f fp[k+1]``, so its SE is
157
+ ``sqrt((1 - f)^2 sp[k]^2 + f^2 sp[k+1]^2)``; outside the grid it is the
158
+ edge point's SE, matching np.interp's edge clamping.
159
+ """
160
+ xa = np.clip(np.atleast_1d(np.asarray(x, float)), xp[0], xp[-1])
161
+ k = np.clip(np.searchsorted(xp, xa) - 1, 0, xp.size - 2)
162
+ f = (xa - xp[k]) / np.maximum(xp[k + 1] - xp[k], 1e-30)
163
+ out = np.sqrt((1 - f) ** 2 * sp[k] ** 2 + f ** 2 * sp[k + 1] ** 2)
164
+ return float(out[0]) if np.ndim(x) == 0 else out
165
+
166
+
167
+ def _interp_matrix(x: np.ndarray, xp: np.ndarray) -> np.ndarray:
168
+ """Weights W with ``W @ fp == np.interp(x, xp, fp)``, edges clamped as np.interp does."""
169
+ xa = np.clip(np.atleast_1d(np.asarray(x, float)), xp[0], xp[-1])
170
+ k = np.clip(np.searchsorted(xp, xa) - 1, 0, xp.size - 2)
171
+ f = (xa - xp[k]) / np.maximum(xp[k + 1] - xp[k], 1e-30)
172
+ weights = np.zeros((xa.size, xp.size))
173
+ rows = np.arange(xa.size)
174
+ weights[rows, k] = 1.0 - f
175
+ weights[rows, k + 1] = f
176
+ return weights
177
+
178
+
179
+ def _fixed_point_bias(sigma2_obs: np.ndarray, bias_at, var_lo: float,
180
+ var_hi: float, n_iter: int):
181
+ """Bias read at the true variance implied by the observed one, v = v_obs - b(v).
182
+
183
+ The lookup is calibrated against the true variance but only the biased
184
+ observed one is known, so a few fixed-point steps refine the key. The
185
+ iterate is clipped to the calibrated range each step (no extrapolation).
186
+ """
187
+ sigma2_true = sigma2_obs.copy()
188
+ for _ in range(int(n_iter)):
189
+ bias = bias_at(np.clip(sigma2_true, var_lo, var_hi))
190
+ sigma2_true = sigma2_obs - bias
191
+ return sigma2_obs - sigma2_true
192
+
193
+
194
+ def _bilinear_se(x_grid: np.ndarray, y_grid: np.ndarray, se_table: np.ndarray,
195
+ x, y) -> np.ndarray:
196
+ """SE of :func:`_bilinear` when each table cell has an independent SE."""
197
+ xc = np.clip(np.atleast_1d(np.asarray(x, float)), x_grid[0], x_grid[-1])
198
+ yc = np.clip(np.atleast_1d(np.asarray(y, float)), y_grid[0], y_grid[-1])
199
+ i = np.clip(np.searchsorted(x_grid, xc) - 1, 0, x_grid.size - 2)
200
+ j = np.clip(np.searchsorted(y_grid, yc) - 1, 0, y_grid.size - 2)
201
+ fx = (xc - x_grid[i]) / np.maximum(x_grid[i + 1] - x_grid[i], 1e-30)
202
+ fy = (yc - y_grid[j]) / np.maximum(y_grid[j + 1] - y_grid[j], 1e-30)
203
+ var = (((1 - fx) * (1 - fy)) ** 2 * se_table[i, j] ** 2
204
+ + (fx * (1 - fy)) ** 2 * se_table[i + 1, j] ** 2
205
+ + ((1 - fx) * fy) ** 2 * se_table[i, j + 1] ** 2
206
+ + (fx * fy) ** 2 * se_table[i + 1, j + 1] ** 2)
207
+ out = np.sqrt(var)
208
+ return float(out[0]) if (np.ndim(x) == 0 and np.ndim(y) == 0) else out
209
+
210
+
211
+ @dataclass
212
+ class BiasLookup:
213
+ """Per-frame CNR (+ optional variance) -> (p, rel_variance, var_bias).
214
+
215
+ Two calibration modes share one API; see module docstring.
216
+
217
+ Attributes
218
+ ----------
219
+ cnr_grid, p_grid, relvar_grid, varbias_grid : the 1-D lookup arrays
220
+ (always present; the 2-D path also fills them with the variance-grid
221
+ mean of each row so 1-D queries still work).
222
+ variance_grid, varbias_2d, relvar_2d : the 2-D lookups (``None`` for a
223
+ 1-D calibration).
224
+ varbias_se_grid, varbias_se_2d : Monte Carlo SE of each var_bias point
225
+ (``None`` for a model built or saved without it). They give the
226
+ calibration's own error, which :func:`~width_debias.weights.calibration_D_se`
227
+ propagates into D.
228
+ framevar_grid : per-frame ``Var(sigma_hat^2)`` on ``cnr_grid`` (1-D
229
+ models from :meth:`from_stats`; ``None`` for models built or saved
230
+ without it, which weight by the ``relvar_grid`` MSD-point variance).
231
+ See :meth:`frame_variance`.
232
+ varbias_cov_factor : (n_grid, p) factor F of the covariance F F^T of the
233
+ smoothed ``varbias_grid`` (models from :meth:`from_cells`). Smoothed
234
+ values are correlated, so the calibration SE of D needs the full
235
+ covariance, not per-point SEs.
236
+ width_variance_grid, width_scale_grid, calibration_variance : the
237
+ leading-order bias at a true variance over its value at
238
+ ``calibration_variance`` and equal CNR (:meth:`from_cells` with a width
239
+ table). When present, a variance passed to :meth:`var_bias` rescales
240
+ the lookup to that width; see :meth:`_width_lookup_point`.
241
+ cnr_floor : the lowest calibrated CNR, for provenance. Every lookup takes
242
+ the edge value outside ``cnr_grid``.
243
+ pixel_x, model_spec : the calibration's pixel grid and profile model, for
244
+ provenance; an application must match both. Only :meth:`from_cells`
245
+ records these three; :func:`~width_debias.validate.calibrate_d_free`
246
+ leaves them ``None``, so the match is the caller's to keep.
247
+ """
248
+
249
+ cnr_grid: np.ndarray
250
+ p_grid: np.ndarray
251
+ relvar_grid: np.ndarray
252
+ varbias_grid: np.ndarray
253
+ # Optional 2-D extensions, set by from_calibration().
254
+ variance_grid: np.ndarray | None = None
255
+ varbias_2d: np.ndarray | None = None
256
+ relvar_2d: np.ndarray | None = None
257
+ varbias_se_grid: np.ndarray | None = None
258
+ varbias_se_2d: np.ndarray | None = None
259
+ framevar_grid: np.ndarray | None = None
260
+ # Optional Fisher-anchored extensions, set by from_cells().
261
+ varbias_cov_factor: np.ndarray | None = None
262
+ width_variance_grid: np.ndarray | None = None
263
+ width_scale_grid: np.ndarray | None = None
264
+ calibration_variance: float | None = None
265
+ cnr_floor: float | None = None
266
+ pixel_x: np.ndarray | None = None
267
+ model_spec: str | None = None
268
+
269
+ # ------------------------------------------------------------------
270
+ # Constructors
271
+ # ------------------------------------------------------------------
272
+ @classmethod
273
+ def from_stats(cls, stats_list: list[FrameStats]) -> "BiasLookup":
274
+ """1-D calibration from a CNR sweep of full experiments (``calibrate_d_free``'s path)."""
275
+ cnr = np.concatenate([s.cnr for s in stats_list])
276
+ p = np.concatenate([s.trunc_fraction for s in stats_list])
277
+ rv = np.concatenate([s.rel_variance for s in stats_list])
278
+ vb = np.concatenate([s.var_bias for s in stats_list])
279
+ good = (np.isfinite(cnr) & np.isfinite(p) & np.isfinite(rv)
280
+ & np.isfinite(vb) & (cnr > 0))
281
+ order = np.argsort(cnr[good])
282
+ se = fv = None
283
+ if all(s.var_bias_se is not None for s in stats_list):
284
+ se = np.concatenate([s.var_bias_se for s in stats_list])[good][order]
285
+ if all(s.frame_variance is not None for s in stats_list):
286
+ fv = np.concatenate([s.frame_variance for s in stats_list])[good][order]
287
+ return cls(cnr_grid=cnr[good][order],
288
+ p_grid=p[good][order],
289
+ relvar_grid=rv[good][order],
290
+ varbias_grid=vb[good][order],
291
+ varbias_se_grid=se,
292
+ framevar_grid=fv)
293
+
294
+ @classmethod
295
+ def from_calibration(cls, calib) -> "BiasLookup":
296
+ """2-D, D-free calibration from a :class:`CalibrationGrid`.
297
+
298
+ Stores the 2-D lookup directly; also computes a 1-D marginal (mean
299
+ over the variance grid) so 1-D queries still work as a fallback.
300
+ ``p_grid`` is set to zeros: the truncation-fraction quantity is a
301
+ relic of the 1-D mode and is unused by ``subtract`` / ``mas``.
302
+ """
303
+ cnr = np.asarray(calib.cnr_grid, float)
304
+ var_g = np.asarray(calib.variance_grid, float)
305
+ vb2 = np.asarray(calib.var_bias, float)
306
+ rv2 = np.asarray(calib.rel_variance, float)
307
+ # 1-D marginals: mean over the variance grid, for the no-variance path.
308
+ vb_1d = np.nanmean(vb2, axis=1)
309
+ rv_1d = np.nanmean(rv2, axis=1)
310
+ p_1d = np.zeros_like(cnr)
311
+ # Per-cell SE of the mean bias from the cell's sample variance. The
312
+ # bias mean drops fits above the calibration's filter threshold, so
313
+ # this (unfiltered) spread makes the SE slightly conservative.
314
+ se2 = np.sqrt(rv2 / max(int(calib.n_runs), 1))
315
+ n_var = np.sum(np.isfinite(se2), axis=1)
316
+ se_1d = np.sqrt(np.nansum(se2 ** 2, axis=1)) / np.maximum(n_var, 1)
317
+ order = np.argsort(cnr)
318
+ return cls(
319
+ cnr_grid=cnr[order],
320
+ p_grid=p_1d[order],
321
+ relvar_grid=rv_1d[order],
322
+ varbias_grid=vb_1d[order],
323
+ variance_grid=var_g,
324
+ varbias_2d=vb2[order, :],
325
+ relvar_2d=rv2[order, :],
326
+ varbias_se_grid=se_1d[order],
327
+ varbias_se_2d=se2[order, :],
328
+ )
329
+
330
+ @classmethod
331
+ def from_cells(cls, cells, terms, *, knee_cnr: float = 6.0,
332
+ asymptote: float | None = 1.0, n_grid: int = 256,
333
+ cnr_max: float = 1e3) -> "BiasLookup":
334
+ """Fisher-anchored, smoothed 1-D calibration from single-frame cells.
335
+
336
+ ``cells`` is a :class:`~width_debias.calibration.CalibrationCells`;
337
+ ``terms`` the :class:`~width_debias.fisher.LeadingOrderTerms` of the
338
+ same model and pixel grid. The bias is written var_bias = L(CNR)
339
+ rho(CNR): L = ``terms.bias_coef`` / CNR^2 is the leading-order bias (the
340
+ width's Fisher variance), and rho, the ratio of the Monte Carlo bias to
341
+ L, is smoothed over every cell with a P-spline that equals
342
+ ``asymptote`` above ``knee_cnr``.
343
+
344
+ The asymptote is fixed (1 by default) because the Monte Carlo cannot
345
+ pin it: at high CNR the mean bias is only about 0.06/CNR of one fit's
346
+ spread, so an affordable budget leaves the high-CNR ratio uncertain by
347
+ more than its own size. 1 is the exact leading order for scale families
348
+ (Gaussian, generalized-Gaussian); the second-order bias of the Voigt fit
349
+ is 0.91 of the Fisher variance, a difference the free spline absorbs
350
+ below the knee and that is below 2e-4 sigma_0^2 above it.
351
+ ``asymptote=None`` fits it instead. Pooling replaces one cell's Monte
352
+ Carlo error with the error of a curve fitted to all cells; that error is
353
+ correlated along the grid, so its covariance factor is stored for
354
+ :func:`~width_debias.weights.calibration_D_se`. Lookups below the lowest
355
+ cell clamp to it (``cnr_floor``); nothing is extrapolated.
356
+ """
357
+ from .smoothing import pspline_fit
358
+
359
+ if cells.noise_model != "gaussian":
360
+ raise NotImplementedError("the Fisher leading term is implemented for "
361
+ "white noise only")
362
+ good = (np.isfinite(cells.mean_bias) & np.isfinite(cells.bias_sd)
363
+ & (cells.n_finite > 1))
364
+ cnr = cells.cnr[good]
365
+ u = np.log(cnr)
366
+ n_fits = cells.n_finite[good]
367
+ knee = float(np.log(knee_cnr))
368
+ leading = terms.bias_coef / cnr ** 2
369
+
370
+ fit_asymptote = asymptote is None
371
+ offset = 0.0 if fit_asymptote else float(asymptote)
372
+
373
+ # A cell mean's SE is its RMS spread over sqrt(n). Deep-CNR spreads are
374
+ # heavy-tailed, so one cell's sample spread is too noisy to weight by:
375
+ # smooth the sample variance relative to its Fisher value. A smooth of
376
+ # its log (the pilot) estimates a geometric mean, which sits below the
377
+ # arithmetic one where the tail is heavy (it understated the variance of
378
+ # the cell means near CNR 1 two- to fourfold); it only sets the weights
379
+ # and a floor for the smooth of the variance itself.
380
+ framevar_ratio = cells.bias_sd[good] ** 2 / (terms.framevar_coef / cnr ** 2)
381
+ pilot = np.exp(pspline_fit(u, np.log(framevar_ratio), np.ones_like(u)).evaluate(u))
382
+ spread = pspline_fit(u, framevar_ratio, pilot * np.sqrt(2.0 / (n_fits - 1)))
383
+ cell_var = np.maximum(spread.evaluate(u), pilot) * terms.framevar_coef / cnr ** 2
384
+ ratio_se = np.sqrt(cell_var / n_fits) / leading
385
+ ratio_fit = pspline_fit(u, cells.mean_bias[good] / leading - offset,
386
+ ratio_se, knee=knee, intercept=fit_asymptote)
387
+ # The weights need Var(sigma_hat^2) only to leading accuracy: smooth its
388
+ # log ratio to the Fisher value (which the fit attains at high CNR, so
389
+ # the log asymptote is 0), with the normal-theory SE of a log sample
390
+ # variance.
391
+ framevar_fit = pspline_fit(u, np.log(framevar_ratio),
392
+ np.sqrt(2.0 / (n_fits - 1)), knee=knee,
393
+ intercept=fit_asymptote)
394
+
395
+ grid = np.geomspace(cnr.min(), cnr_max, n_grid)
396
+ grid_u = np.log(grid)
397
+ grid_leading = terms.bias_coef / grid ** 2
398
+ design = ratio_fit.design(grid_u)
399
+ eigval, eigvec = np.linalg.eigh(ratio_fit.coef_cov)
400
+ factor = grid_leading[:, None] * (design @ (eigvec * np.sqrt(np.clip(eigval, 0.0, None))))
401
+ framevar = terms.framevar_coef / grid ** 2 * np.exp(framevar_fit.evaluate(grid_u))
402
+ return cls(cnr_grid=grid, p_grid=np.zeros_like(grid),
403
+ relvar_grid=framevar,
404
+ varbias_grid=grid_leading * (offset + design @ ratio_fit.coef),
405
+ varbias_se_grid=np.linalg.norm(factor, axis=1),
406
+ framevar_grid=framevar,
407
+ varbias_cov_factor=factor,
408
+ width_variance_grid=terms.variance_grid,
409
+ width_scale_grid=terms.bias_scale,
410
+ calibration_variance=terms.variance_cal,
411
+ cnr_floor=float(cnr.min()),
412
+ pixel_x=cells.pixel_x,
413
+ model_spec=cells.model_spec)
414
+
415
+ # ------------------------------------------------------------------
416
+ # Lookups
417
+ # ------------------------------------------------------------------
418
+ @property
419
+ def is_2d(self) -> bool:
420
+ return self.variance_grid is not None and self.varbias_2d is not None
421
+
422
+ @property
423
+ def is_width_scaled(self) -> bool:
424
+ return (self.width_scale_grid is not None
425
+ and self.width_variance_grid is not None
426
+ and self.calibration_variance is not None)
427
+
428
+ def p(self, cnr) -> np.ndarray:
429
+ """Interpolated truncation fraction at the given per-frame CNR."""
430
+ return np.interp(cnr, self.cnr_grid, self.p_grid,
431
+ left=self.p_grid[0], right=self.p_grid[-1])
432
+
433
+ def var_bias(self, cnr, variance=None, n_iter: int = 4):
434
+ """Interpolated additive variance bias.
435
+
436
+ ``E[sigma_hat^2] - sigma^2_true``. The folded-normal model
437
+ (DERIVATION.md) identifies this as the estimation-noise variance s^2;
438
+ subtracting it per frame removes the bias the MSD slope would
439
+ otherwise inherit.
440
+
441
+ With a 2-D calibration **and** a ``variance`` argument (the observed
442
+ raw fitted variance), looks up the bias at (CNR, sigma^2_true)
443
+ jointly; otherwise falls back to the 1-D lookup on CNR alone.
444
+
445
+ **Subtlety: the lookup is calibrated against the true variance, but
446
+ the application only knows the biased observed variance.** Querying
447
+ directly at the observed value evaluates the bias at the wrong point,
448
+ which distorts the per-frame correction (especially badly at low CNR,
449
+ where the bias is largest). The fix is a short fixed-point iteration:
450
+ starting from the observed variance, subtract the lookup at the
451
+ current estimate to refine an estimate of the true variance, and
452
+ re-query. Three or four iterations suffice; the bias used for the
453
+ correction is the lookup at the converged estimate.
454
+
455
+ **Choice of key.** ``variance`` is the key that stands in for the
456
+ unknown true sigma^2, and any array can be passed. Keying on each
457
+ frame's own sigma_hat^2 (the usual call) under-corrects when sigma^2
458
+ grows several-fold over the measurement: at low CNR a frame whose fit
459
+ scatters high reads the lookup near the grid edge, and the mean is
460
+ over-subtracted. On the high-N Br-I bed (sigma^2 growing ~64x) this
461
+ left D at 0.89 to 0.96 of the reference at CNR_0 15 to 20 on two of
462
+ the three maps (0.99 on the fastest-spreading one), where a
463
+ measurement-level key (a robust line through the measurement's own
464
+ sigma_hat^2) matched the exact key to 0.003. That key assumes a form
465
+ for sigma^2(t), so it is not the default here; see
466
+ ``experiments/halide-mixing-highn/key_sensitivity.py`` and
467
+ ``smoothed_key`` in ``br_halide_highn_perframe.py`` for a worked
468
+ example and its limits (below CNR_0 ~15 no key determined D).
469
+
470
+ With a width table (:meth:`from_cells`) and a ``variance``, the 1-D
471
+ lookup is rescaled to the key's width (:meth:`_width_lookup_point`),
472
+ with the same fixed-point iteration. Because the leading bias scales as
473
+ sigma, not sigma^2, a key error moves it about half as much as in the
474
+ 2-D lookup. A model with neither ignores ``variance``.
475
+ """
476
+ if variance is None or not (self.is_2d or self.is_width_scaled):
477
+ return np.interp(cnr, self.cnr_grid, self.varbias_grid,
478
+ left=self.varbias_grid[0],
479
+ right=self.varbias_grid[-1])
480
+ if self.is_2d:
481
+ def bias_at(sigma2):
482
+ return _bilinear(self.cnr_grid, self.variance_grid,
483
+ self.varbias_2d, cnr, sigma2)
484
+ var_lo, var_hi = self.variance_grid[0], self.variance_grid[-1]
485
+ else:
486
+ def bias_at(sigma2):
487
+ scale, cnr_eq = self._width_lookup_point(cnr, sigma2)
488
+ return scale * np.interp(cnr_eq, self.cnr_grid, self.varbias_grid)
489
+ var_lo, var_hi = self.width_variance_grid[0], self.width_variance_grid[-1]
490
+ return _fixed_point_bias(np.asarray(variance, float), bias_at,
491
+ float(var_lo), float(var_hi), n_iter)
492
+
493
+ def _width_lookup_point(self, cnr, variance):
494
+ """Scale q and equivalent CNR at which the calibration curve is read.
495
+
496
+ The leading bias at true variance v is r(v) A_cal / CNR^2, with r the
497
+ width table. Reading the calibrated curve at c_eq = CNR sqrt(q / r),
498
+ q = v / v_cal, and multiplying by q reproduces that exactly, and puts
499
+ the higher-order residual at the CNR of equal relative width precision,
500
+ Var(sigma_hat) / sigma^2, which is what it depends on in the continuum
501
+ limit. ``variance`` is clipped to the table.
502
+ """
503
+ variance = np.clip(np.asarray(variance, float), self.width_variance_grid[0],
504
+ self.width_variance_grid[-1])
505
+ ratio = np.interp(variance, self.width_variance_grid, self.width_scale_grid)
506
+ scale = variance / self.calibration_variance
507
+ return scale, np.asarray(cnr, float) * np.sqrt(scale / ratio)
508
+
509
+ def var_bias_factor(self, cnr, variance=None, n_iter: int = 4) -> np.ndarray:
510
+ """Rows M with Cov(looked-up var_bias) = M M^T (needs ``varbias_cov_factor``).
511
+
512
+ The interpolation weights of the lookup applied to the grid's
513
+ covariance factor, rescaled by the width table when one is used.
514
+ """
515
+ cnr_arr = np.atleast_1d(np.asarray(cnr, float))
516
+ if variance is None or not self.is_width_scaled:
517
+ return _interp_matrix(cnr_arr, self.cnr_grid) @ self.varbias_cov_factor
518
+ sigma2_obs = np.atleast_1d(np.asarray(variance, float))
519
+ sigma2_true = sigma2_obs - self.var_bias(cnr_arr, sigma2_obs, n_iter)
520
+ scale, cnr_eq = self._width_lookup_point(cnr_arr, sigma2_true)
521
+ return scale[:, None] * (_interp_matrix(cnr_eq, self.cnr_grid)
522
+ @ self.varbias_cov_factor)
523
+
524
+ def var_bias_cov(self, cnr, variance=None, n_iter: int = 4) -> np.ndarray:
525
+ """Covariance of the looked-up biases at several frames.
526
+
527
+ Smoothed calibrations correlate neighbouring lookups; a raw per-cell
528
+ lookup does not, so without a covariance factor this is diagonal.
529
+ """
530
+ if self.varbias_cov_factor is None:
531
+ return np.diag(np.atleast_1d(self.var_bias_se(cnr, variance, n_iter)) ** 2)
532
+ rows = self.var_bias_factor(cnr, variance, n_iter)
533
+ return rows @ rows.T
534
+
535
+ def var_bias_se(self, cnr, variance=None, n_iter: int = 4):
536
+ """Monte Carlo SE of the looked-up :meth:`var_bias`.
537
+
538
+ The calibration is a finite Monte Carlo, so every subtracted bias
539
+ carries an error the measurement's own SE does not see. At low CNR it
540
+ dominates: two 300-run calibrations of the same sweep differ by 0.22
541
+ in D/D_ref at D = 0.02 sigma_0^2/tau, CNR_0 = 34, against an
542
+ evaluation SE of 0.04. The SE is propagated through the same
543
+ interpolation weights as the lookup (independent cells assumed; for
544
+ the D-free 1-D grid each point is its own ensemble frame, the frames of
545
+ one ensemble are uncorrelated, and the per-point SE matches the spread
546
+ over 16 independent calibrations). With
547
+ a 2-D model and a ``variance``, it is evaluated at the same
548
+ fixed-point estimate of sigma^2_true that :meth:`var_bias` uses.
549
+ A smoothed model (:meth:`from_cells`) takes the SE from its covariance
550
+ factor, which also covers the correlation between grid neighbours.
551
+ Returns NaN when the model carries no SE (a model built or saved
552
+ without it).
553
+ """
554
+ cnr_arr = np.asarray(cnr, float)
555
+ if self.varbias_cov_factor is not None:
556
+ se = np.linalg.norm(self.var_bias_factor(cnr_arr, variance, n_iter), axis=1)
557
+ return float(se[0]) if np.ndim(cnr_arr) == 0 else se
558
+ if variance is None or not self.is_2d:
559
+ if self.varbias_se_grid is None:
560
+ return np.full(np.shape(cnr_arr), np.nan) if np.ndim(cnr_arr) else np.nan
561
+ return _interp_se(cnr_arr, self.cnr_grid, self.varbias_se_grid)
562
+ if self.varbias_se_2d is None:
563
+ return np.full(np.shape(cnr_arr), np.nan) if np.ndim(cnr_arr) else np.nan
564
+ sigma2_obs = np.asarray(variance, float)
565
+ sigma2_true = sigma2_obs - self.var_bias(cnr_arr, sigma2_obs, n_iter)
566
+ sigma2_true = np.clip(sigma2_true, float(self.variance_grid[0]),
567
+ float(self.variance_grid[-1]))
568
+ return _bilinear_se(self.cnr_grid, self.variance_grid,
569
+ self.varbias_se_2d, cnr_arr, sigma2_true)
570
+
571
+ def frame_variance(self, cnr, variance=None):
572
+ """Interpolated per-frame ``Var(sigma_hat^2)`` at the given CNR (1-D).
573
+
574
+ With a width table and an explicit ``variance`` key, the lookup is
575
+ rescaled to that width (Var(sigma_hat^2) = 4 v Var(sigma_hat) to leading
576
+ order, so the same table serves). Pass a measurement-level key, not each
577
+ frame's own fitted variance: a weight that depends on its own point's
578
+ noise biases the slope at the order being corrected.
579
+
580
+ The slope weights are ``1 / Var(sigma_hat_i^2)`` at the application's
581
+ own frame CNR, frame 0 included (see
582
+ :func:`~width_debias.weights.msd_and_weights`). The 1-D
583
+ ``relvar_grid`` holds a different quantity, the MSD-point variance
584
+ ``Var(sigma_hat_i^2) + Var(sigma_hat_0^2)`` measured inside each
585
+ calibration ensemble, whose t = 0 frame sits at the calibration's
586
+ CNR_0. Neighbouring grid points come from different ensembles, so that
587
+ lookup is jagged, and each ensemble's own t = 0 point reads exactly 0:
588
+ a frame whose CNR lay next to a calibration CNR_0 drew 5 to 50 times
589
+ its proper weight. Returns ``None`` when the model carries no such grid.
590
+ """
591
+ if self.framevar_grid is None:
592
+ return None
593
+ if variance is None or not self.is_width_scaled:
594
+ return np.interp(cnr, self.cnr_grid, self.framevar_grid,
595
+ left=self.framevar_grid[0], right=self.framevar_grid[-1])
596
+ scale, cnr_eq = self._width_lookup_point(cnr, variance)
597
+ return scale ** 2 * np.interp(cnr_eq, self.cnr_grid, self.framevar_grid)
598
+
599
+ def rel_variance(self, cnr, variance=None):
600
+ """Interpolated variance of the (fitted-variance) point.
601
+
602
+ With a 1-D calibration from :meth:`from_stats` this is the MSD-point
603
+ variance ``Var(sigma_hat^2(t) - sigma_hat^2(0))`` empirically measured
604
+ per CNR; from :meth:`from_cells` it is the per-frame ``Var(sigma_hat^2)``
605
+ (a copy of ``framevar_grid``). With a 2-D calibration it is the
606
+ per-frame ``Var(sigma_hat^2)``, which :mod:`width_debias.weights` uses
607
+ directly as each frame's weight.
608
+ """
609
+ if variance is None or not self.is_2d:
610
+ return np.interp(cnr, self.cnr_grid, self.relvar_grid,
611
+ left=self.relvar_grid[0],
612
+ right=self.relvar_grid[-1])
613
+ return _bilinear(self.cnr_grid, self.variance_grid, self.relvar_2d,
614
+ cnr, variance)
615
+
616
+ # ------------------------------------------------------------------
617
+ # Persistence
618
+ # ------------------------------------------------------------------
619
+ def save(self, path) -> None:
620
+ """Save every field that is set to one ``.npz`` archive.
621
+
622
+ Unset fields are omitted rather than written empty: an empty
623
+ ``variance_grid`` would read back as a 2-D model, and scripts that pass
624
+ an archive's keys straight to the constructor keep working.
625
+ """
626
+ np.savez_compressed(str(path), **{
627
+ f.name: np.asarray(getattr(self, f.name)) for f in fields(self)
628
+ if getattr(self, f.name) is not None})
629
+
630
+ @classmethod
631
+ def load(cls, path) -> "BiasLookup":
632
+ """Load a model saved with :meth:`save` (or any archive of its fields)."""
633
+ archive = np.load(str(path))
634
+ known = {f.name for f in fields(cls)}
635
+ return cls(**{name: (archive[name].item() if archive[name].ndim == 0
636
+ else archive[name])
637
+ for name in archive.files if name in known})