width-debias 0.4.0__tar.gz
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.
- width_debias-0.4.0/LICENSE +21 -0
- width_debias-0.4.0/PKG-INFO +239 -0
- width_debias-0.4.0/README.md +204 -0
- width_debias-0.4.0/pyproject.toml +70 -0
- width_debias-0.4.0/setup.cfg +4 -0
- width_debias-0.4.0/src/width_debias/__init__.py +73 -0
- width_debias-0.4.0/src/width_debias/bias_lookup.py +637 -0
- width_debias-0.4.0/src/width_debias/calibration.py +492 -0
- width_debias-0.4.0/src/width_debias/cnr.py +82 -0
- width_debias-0.4.0/src/width_debias/fisher.py +173 -0
- width_debias-0.4.0/src/width_debias/fit.py +157 -0
- width_debias-0.4.0/src/width_debias/models.py +394 -0
- width_debias-0.4.0/src/width_debias/montecarlo.py +202 -0
- width_debias-0.4.0/src/width_debias/noise.py +113 -0
- width_debias-0.4.0/src/width_debias/simulate.py +191 -0
- width_debias-0.4.0/src/width_debias/smoothing.py +139 -0
- width_debias-0.4.0/src/width_debias/validate.py +291 -0
- width_debias-0.4.0/src/width_debias/weights.py +235 -0
- width_debias-0.4.0/src/width_debias.egg-info/PKG-INFO +239 -0
- width_debias-0.4.0/src/width_debias.egg-info/SOURCES.txt +22 -0
- width_debias-0.4.0/src/width_debias.egg-info/dependency_links.txt +1 -0
- width_debias-0.4.0/src/width_debias.egg-info/requires.txt +15 -0
- width_debias-0.4.0/src/width_debias.egg-info/top_level.txt +1 -0
- width_debias-0.4.0/tests/test_basic.py +542 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joseph J. Thiebes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: width-debias
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Correction of the noise bias in fitted profile widths, for mean-squared-displacement (MSD) diffusion measurements.
|
|
5
|
+
Author-email: "Joseph J. Thiebes" <joseph@thiebes.org>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Source, https://github.com/thiebes/width-debias
|
|
8
|
+
Project-URL: Changelog, https://github.com/thiebes/width-debias/blob/master/CHANGELOG.md
|
|
9
|
+
Project-URL: Issues, https://github.com/thiebes/width-debias/issues
|
|
10
|
+
Keywords: diffusion,mean-squared displacement,bias correction,contrast-to-noise ratio,transient microscopy
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
19
|
+
Requires-Python: >=3.11
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy<3,>=1.24
|
|
23
|
+
Requires-Dist: scipy<2,>=1.10
|
|
24
|
+
Provides-Extra: cnr
|
|
25
|
+
Requires-Dist: fft-cnr<0.5,>=0.3.3; extra == "cnr"
|
|
26
|
+
Provides-Extra: plot
|
|
27
|
+
Requires-Dist: matplotlib<4,>=3.7; extra == "plot"
|
|
28
|
+
Requires-Dist: curved-text<1,>=0.5; extra == "plot"
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
31
|
+
Requires-Dist: matplotlib<4,>=3.7; extra == "dev"
|
|
32
|
+
Requires-Dist: fft-cnr<0.5,>=0.3.3; extra == "dev"
|
|
33
|
+
Requires-Dist: curved-text<1,>=0.5; extra == "dev"
|
|
34
|
+
Dynamic: license-file
|
|
35
|
+
|
|
36
|
+
# width-debias
|
|
37
|
+
|
|
38
|
+
**Correction of the noise bias in fitted profile widths, for
|
|
39
|
+
mean-squared-displacement (MSD) diffusion measurements.**
|
|
40
|
+
|
|
41
|
+
A width fitted to a noisy profile scatters about the true width, and squaring
|
|
42
|
+
it to form the variance turns that scatter into a bias. On average the fitted
|
|
43
|
+
variance exceeds the true one by the width's estimation variance,
|
|
44
|
+
`E[sigma_hat^2] = sigma^2 + Var(sigma_hat)`. To leading order Var(sigma_hat) is
|
|
45
|
+
the Cramér-Rao value, which for a Gaussian profile at a fixed pixel spacing `dx`
|
|
46
|
+
is `(2/sqrt(pi)) sigma dx / CNR^2`, so the bias grows as the contrast-to-noise
|
|
47
|
+
ratio (CNR) falls. In a transient measurement the CNR falls frame by frame as
|
|
48
|
+
the population decays, so the bias rises over time, tilts the MSD curve upward,
|
|
49
|
+
and inflates the diffusion coefficient D. In simulation (Gaussian profile,
|
|
50
|
+
D = 0.02 sigma_0^2/tau, initial CNR 34) an unweighted fit returns 1.20 times the
|
|
51
|
+
reference D. Inverse-variance weighting corrects the unequal noise across
|
|
52
|
+
frames but cannot remove a mean bias present in every point.
|
|
53
|
+
|
|
54
|
+
The package corrects each profile's fitted width, and the MSD and D follow. It
|
|
55
|
+
subtracts a Monte Carlo calibrated bias `var_bias(CNR)` from each frame's fitted
|
|
56
|
+
variance before the slope fit, keyed on the per-frame CNR; in the same
|
|
57
|
+
simulation the corrected fit returns 1.00 times the reference. The calibration
|
|
58
|
+
is built at D = 0, so it does not require a prior value of D. Removing the
|
|
59
|
+
fit's lower bound on the width does not help: above a per-frame CNR of about
|
|
60
|
+
1.5 the bounded and unbounded fits are identical, and both carry the full bias.
|
|
61
|
+
Below a per-frame CNR of about 1 the fits spread into a broad upper tail and the
|
|
62
|
+
correction no longer holds (see [On real data](#on-real-data)). The derivation,
|
|
63
|
+
which reaches the same additive form from a folded-normal model of the width
|
|
64
|
+
estimate, is in
|
|
65
|
+
[`docs/DERIVATION.md`](https://github.com/thiebes/width-debias/blob/v0.4.0/docs/DERIVATION.md).
|
|
66
|
+
|
|
67
|
+
## Install
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pip install width-debias # core: NumPy and SciPy
|
|
71
|
+
pip install "width-debias[cnr]" # adds fft-cnr, for per-frame CNR from measured profiles
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
To run the experiments and tests, install from a clone of the
|
|
75
|
+
[repository](https://github.com/thiebes/width-debias):
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
python -m venv .venv
|
|
79
|
+
.venv/Scripts/activate # Windows; source .venv/bin/activate elsewhere
|
|
80
|
+
pip install -e .[dev] # core + matplotlib + pytest + fft-cnr
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`uv.lock` in the repository records the exact environment that produced the
|
|
84
|
+
committed results.
|
|
85
|
+
|
|
86
|
+
## Quick start
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import numpy as np
|
|
90
|
+
from width_debias import Experiment, calibrate_d_free, evaluate
|
|
91
|
+
|
|
92
|
+
cnr0 = np.array([5, 8, 13, 21, 34, 55, 90])
|
|
93
|
+
lookup = calibrate_d_free(cnr0, n_runs=300) # D-free lookup var_bias(CNR)
|
|
94
|
+
|
|
95
|
+
exp = Experiment(D=0.02) # sigma_0^2/tau; L_D/FWHM_0 ~ 0.085
|
|
96
|
+
results = evaluate(exp, cnr0, lookup, n_runs=300)
|
|
97
|
+
|
|
98
|
+
r = results["subtract"]
|
|
99
|
+
se = np.hypot(r.spread / np.sqrt(300), r.cal_se) # evaluation + calibration SE
|
|
100
|
+
print(r.mean_bias, se) # <D_est>/D_ref per CNR_0
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
On a measurement, the per-frame CNR comes from `width_debias.cnr.per_frame_cnr`
|
|
104
|
+
(which wraps `fft-cnr`), the corrected MSD and weights from
|
|
105
|
+
`width_debias.weights.msd_and_weights("subtract", ...)`, the slope from
|
|
106
|
+
`width_debias.fit.fit_D`, and the calibration's contribution to the
|
|
107
|
+
uncertainty from `width_debias.weights.calibration_D_se`:
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import numpy as np
|
|
111
|
+
from width_debias import calibrate_d_free
|
|
112
|
+
from width_debias.cnr import per_frame_cnr
|
|
113
|
+
from width_debias.fit import fit_D
|
|
114
|
+
from width_debias.weights import calibration_D_se, msd_and_weights
|
|
115
|
+
|
|
116
|
+
# times (n_frames,); profiles (n_frames, n_pixels) cut to about +/-4 sigma_0
|
|
117
|
+
# around the spot; variance (n_frames,) the fitted widths in px^2;
|
|
118
|
+
# sigma0_px the t = 0 width in pixels
|
|
119
|
+
n_pixels = profiles.shape[1]
|
|
120
|
+
lookup = calibrate_d_free(cnr0, half_window=(n_pixels / 2) / sigma0_px,
|
|
121
|
+
n_pixels=n_pixels) # the data's grid, in units of sigma_0
|
|
122
|
+
cnr = per_frame_cnr(profiles)
|
|
123
|
+
msd, w = msd_and_weights("subtract", variance / sigma0_px**2, cnr, lookup)
|
|
124
|
+
w = np.where(cnr >= 1.3, w, 0.0) # drop frames below the floor
|
|
125
|
+
fit = fit_D(times, msd, w)
|
|
126
|
+
D = fit.D * sigma0_px**2 # px^2 per unit time
|
|
127
|
+
se = np.hypot(fit.D_se, calibration_D_se(times, msd, w, cnr, lookup)) * sigma0_px**2
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## On real data
|
|
131
|
+
|
|
132
|
+
The validation keys the lookup on the exact per-frame CNR, uses a calibration
|
|
133
|
+
built for the same geometry as the data, and drops frames below the floor. On a
|
|
134
|
+
measurement each of these is a step for the user; the library does not check
|
|
135
|
+
them.
|
|
136
|
+
|
|
137
|
+
- **Match the calibration to the data.** `var_bias` is a variance in the length
|
|
138
|
+
unit of the calibration, and its size depends on the pixel grid, the profile
|
|
139
|
+
model and its fit bound, and the noise law. Work in units of the measured
|
|
140
|
+
t = 0 width sigma_0: divide the pixel axis by sigma_0 and the fitted
|
|
141
|
+
variances by sigma_0^2, build the calibration with the data's pixel count and
|
|
142
|
+
half-window in those units
|
|
143
|
+
(`calibrate_d_free(cnr0, half_window=(n_pixels / 2) / sigma0_px, n_pixels=n_pixels, model=..., noise_model=...)`),
|
|
144
|
+
and multiply the fitted D and its SE by sigma_0^2 at the end. A calibration in
|
|
145
|
+
units of sigma_0 applied to widths in micrometres subtracts a bias that is
|
|
146
|
+
off by the square of the unit ratio (16 for sigma_0 = 0.25 μm).
|
|
147
|
+
- **Drop frames below the floor.** The correction holds above a per-frame CNR
|
|
148
|
+
of about 1 (0.7 to 1.5 depending on shape). `msd_and_weights` applies no
|
|
149
|
+
floor, and a CNR outside the calibrated grid takes the value at the nearest
|
|
150
|
+
grid edge. The validations set the weight of frames below a per-frame CNR of
|
|
151
|
+
1.0 or 1.3 to zero before `fit_D`, as in the example above.
|
|
152
|
+
- **The estimated CNR holds over a narrower range.** With the CNR estimated
|
|
153
|
+
from each frame by `fft-cnr` instead of known, the corrected mean D holds in
|
|
154
|
+
simulation only where every fitted frame stays well above the floor: from an
|
|
155
|
+
initial CNR of about 34 at D = 0.02 sigma_0^2/tau for the Gaussian profile
|
|
156
|
+
(about 55 for p = 1.5 and 13 for p = 4), and from about 21 at D >= 0.05.
|
|
157
|
+
Below that, the pooled Gaussian mean at D = 0.02 over initial CNR 8 to 90 is
|
|
158
|
+
1.9 of the reference (standard error 0.4). See
|
|
159
|
+
[`experiments/wse2-strobescat`](https://github.com/thiebes/width-debias/tree/v0.4.0/experiments/wse2-strobescat).
|
|
160
|
+
- **Estimate the CNR on the spot.** Cut each profile to about ±4 sigma_0 around
|
|
161
|
+
the spot before calling `per_frame_cnr`. Background and fringe structure in a
|
|
162
|
+
full line cut corrupts the spectral CNR estimate at low signal.
|
|
163
|
+
|
|
164
|
+
## What the validation shows
|
|
165
|
+
|
|
166
|
+
- Above a per-frame CNR of about 1.5 the fit's lower bound does not bind: the
|
|
167
|
+
bounded and unbounded fits return the same widths and the same biased D
|
|
168
|
+
(`experiments/estimator-comparison`). Below it, the bounded fit reflects
|
|
169
|
+
rather than clips at the bound (`experiments/boundary-diagnostic`).
|
|
170
|
+
- With the calibration's own Monte Carlo error included, 4 of 96 cells lie
|
|
171
|
+
beyond two combined standard errors of the reference (Gaussian, Voigt, and
|
|
172
|
+
generalized-Gaussian p = 1.5 and p = 4 profiles; D = 0.005, 0.02, and 0.1
|
|
173
|
+
sigma_0^2/tau; initial CNR 3 to 90; `slope_fit_check.txt`). The cells share
|
|
174
|
+
noise seeds across shapes and one calibration per shape, so the count is
|
|
175
|
+
indicative rather than a test against a binomial null. At small D and low
|
|
176
|
+
initial CNR the combined SE is large, so those cells constrain the bias only
|
|
177
|
+
loosely (`experiments/dfree-calibration`).
|
|
178
|
+
- The correction holds above a per-frame CNR of about 1 (0.7 to 1.5 depending on
|
|
179
|
+
shape), where the leading-order bias model `var_bias = A / CNR^2` itself
|
|
180
|
+
breaks (`experiments/correction-floor`). With single-exponential decay to
|
|
181
|
+
3 tau, every frame stays above the floor from an initial CNR of about 20.
|
|
182
|
+
- It corrects the anomalous exponent of subdiffusive transport as well as D
|
|
183
|
+
(`experiments/subdiffusive-alpha`, `experiments/nc-solid`).
|
|
184
|
+
|
|
185
|
+
[`docs/REPO_MAP.md`](https://github.com/thiebes/width-debias/blob/v0.4.0/docs/REPO_MAP.md)
|
|
186
|
+
lists every experiment set with its result, and each set's README gives the
|
|
187
|
+
details and how to run it.
|
|
188
|
+
|
|
189
|
+
## Profile models
|
|
190
|
+
|
|
191
|
+
The bias affects any non-negative width estimator, so the profile model is
|
|
192
|
+
pluggable (`width_debias.models`): `GaussianModel`, `VoigtModel` (a diffusing
|
|
193
|
+
Gaussian convolved with a fixed Lorentzian point-spread function), and
|
|
194
|
+
`GeneralizedGaussianModel` (shape exponent p; p = 2 is the Gaussian).
|
|
195
|
+
`model_from_spec("generalized_gaussian:1.5")` builds a model from a spec
|
|
196
|
+
string. The experiment scripts in the repository take a model spec; name the
|
|
197
|
+
generalized-Gaussian shape explicitly:
|
|
198
|
+
|
|
199
|
+
```bash
|
|
200
|
+
python experiments/poc-bias-correction/poc_demo.py voigt
|
|
201
|
+
python experiments/boundary-diagnostic/diagnose_boundary.py generalized_gaussian:1.5
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
## Tests
|
|
205
|
+
|
|
206
|
+
```bash
|
|
207
|
+
pytest
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Layout
|
|
211
|
+
|
|
212
|
+
| Path | Role |
|
|
213
|
+
| ------- | ------- |
|
|
214
|
+
| `src/width_debias/simulate.py` | profile geometry: diffusion, decay, noise |
|
|
215
|
+
| `src/width_debias/noise.py` | noise laws: white, shot, Poisson, read floor |
|
|
216
|
+
| `src/width_debias/models.py` | profile models and `model_from_spec` |
|
|
217
|
+
| `src/width_debias/fit.py` | per-frame width fit; MSD to D linear fit |
|
|
218
|
+
| `src/width_debias/montecarlo.py` | Monte Carlo ensembles |
|
|
219
|
+
| `src/width_debias/bias_lookup.py` | per-frame statistics; `BiasLookup` lookups and their SE |
|
|
220
|
+
| `src/width_debias/calibration.py` | single-frame calibration cells; joint (CNR, sigma^2) calibration |
|
|
221
|
+
| `src/width_debias/fisher.py` | Fisher-information width variance, leading-order bias, CRLB on D |
|
|
222
|
+
| `src/width_debias/smoothing.py` | P-spline smoother for the calibration residual |
|
|
223
|
+
| `src/width_debias/weights.py` | the four schemes; calibration SE of D |
|
|
224
|
+
| `src/width_debias/validate.py` | calibration and evaluation sweeps |
|
|
225
|
+
| `src/width_debias/cnr.py` | per-frame CNR from measured profiles via `fft-cnr` |
|
|
226
|
+
| `experiments/` | one folder per experiment set (see `docs/REPO_MAP.md`) |
|
|
227
|
+
| `illustrations/` | schematic figures |
|
|
228
|
+
| `scripts/` | shared calibration tooling and figure rendering |
|
|
229
|
+
|
|
230
|
+
## Related work
|
|
231
|
+
|
|
232
|
+
- **DICE**: Monte Carlo engine for optical diffusion measurements (Thiebes and
|
|
233
|
+
Grumstrup, *J. Chem. Phys.* 2024).
|
|
234
|
+
- **fft-cnr**: single-profile CNR estimation
|
|
235
|
+
([PyPI](https://pypi.org/project/fft-cnr/)).
|
|
236
|
+
|
|
237
|
+
## License
|
|
238
|
+
|
|
239
|
+
MIT, see [`LICENSE`](https://github.com/thiebes/width-debias/blob/v0.4.0/LICENSE).
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# width-debias
|
|
2
|
+
|
|
3
|
+
**Correction of the noise bias in fitted profile widths, for
|
|
4
|
+
mean-squared-displacement (MSD) diffusion measurements.**
|
|
5
|
+
|
|
6
|
+
A width fitted to a noisy profile scatters about the true width, and squaring
|
|
7
|
+
it to form the variance turns that scatter into a bias. On average the fitted
|
|
8
|
+
variance exceeds the true one by the width's estimation variance,
|
|
9
|
+
`E[sigma_hat^2] = sigma^2 + Var(sigma_hat)`. To leading order Var(sigma_hat) is
|
|
10
|
+
the Cramér-Rao value, which for a Gaussian profile at a fixed pixel spacing `dx`
|
|
11
|
+
is `(2/sqrt(pi)) sigma dx / CNR^2`, so the bias grows as the contrast-to-noise
|
|
12
|
+
ratio (CNR) falls. In a transient measurement the CNR falls frame by frame as
|
|
13
|
+
the population decays, so the bias rises over time, tilts the MSD curve upward,
|
|
14
|
+
and inflates the diffusion coefficient D. In simulation (Gaussian profile,
|
|
15
|
+
D = 0.02 sigma_0^2/tau, initial CNR 34) an unweighted fit returns 1.20 times the
|
|
16
|
+
reference D. Inverse-variance weighting corrects the unequal noise across
|
|
17
|
+
frames but cannot remove a mean bias present in every point.
|
|
18
|
+
|
|
19
|
+
The package corrects each profile's fitted width, and the MSD and D follow. It
|
|
20
|
+
subtracts a Monte Carlo calibrated bias `var_bias(CNR)` from each frame's fitted
|
|
21
|
+
variance before the slope fit, keyed on the per-frame CNR; in the same
|
|
22
|
+
simulation the corrected fit returns 1.00 times the reference. The calibration
|
|
23
|
+
is built at D = 0, so it does not require a prior value of D. Removing the
|
|
24
|
+
fit's lower bound on the width does not help: above a per-frame CNR of about
|
|
25
|
+
1.5 the bounded and unbounded fits are identical, and both carry the full bias.
|
|
26
|
+
Below a per-frame CNR of about 1 the fits spread into a broad upper tail and the
|
|
27
|
+
correction no longer holds (see [On real data](#on-real-data)). The derivation,
|
|
28
|
+
which reaches the same additive form from a folded-normal model of the width
|
|
29
|
+
estimate, is in
|
|
30
|
+
[`docs/DERIVATION.md`](https://github.com/thiebes/width-debias/blob/v0.4.0/docs/DERIVATION.md).
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install width-debias # core: NumPy and SciPy
|
|
36
|
+
pip install "width-debias[cnr]" # adds fft-cnr, for per-frame CNR from measured profiles
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
To run the experiments and tests, install from a clone of the
|
|
40
|
+
[repository](https://github.com/thiebes/width-debias):
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
python -m venv .venv
|
|
44
|
+
.venv/Scripts/activate # Windows; source .venv/bin/activate elsewhere
|
|
45
|
+
pip install -e .[dev] # core + matplotlib + pytest + fft-cnr
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`uv.lock` in the repository records the exact environment that produced the
|
|
49
|
+
committed results.
|
|
50
|
+
|
|
51
|
+
## Quick start
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import numpy as np
|
|
55
|
+
from width_debias import Experiment, calibrate_d_free, evaluate
|
|
56
|
+
|
|
57
|
+
cnr0 = np.array([5, 8, 13, 21, 34, 55, 90])
|
|
58
|
+
lookup = calibrate_d_free(cnr0, n_runs=300) # D-free lookup var_bias(CNR)
|
|
59
|
+
|
|
60
|
+
exp = Experiment(D=0.02) # sigma_0^2/tau; L_D/FWHM_0 ~ 0.085
|
|
61
|
+
results = evaluate(exp, cnr0, lookup, n_runs=300)
|
|
62
|
+
|
|
63
|
+
r = results["subtract"]
|
|
64
|
+
se = np.hypot(r.spread / np.sqrt(300), r.cal_se) # evaluation + calibration SE
|
|
65
|
+
print(r.mean_bias, se) # <D_est>/D_ref per CNR_0
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
On a measurement, the per-frame CNR comes from `width_debias.cnr.per_frame_cnr`
|
|
69
|
+
(which wraps `fft-cnr`), the corrected MSD and weights from
|
|
70
|
+
`width_debias.weights.msd_and_weights("subtract", ...)`, the slope from
|
|
71
|
+
`width_debias.fit.fit_D`, and the calibration's contribution to the
|
|
72
|
+
uncertainty from `width_debias.weights.calibration_D_se`:
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
import numpy as np
|
|
76
|
+
from width_debias import calibrate_d_free
|
|
77
|
+
from width_debias.cnr import per_frame_cnr
|
|
78
|
+
from width_debias.fit import fit_D
|
|
79
|
+
from width_debias.weights import calibration_D_se, msd_and_weights
|
|
80
|
+
|
|
81
|
+
# times (n_frames,); profiles (n_frames, n_pixels) cut to about +/-4 sigma_0
|
|
82
|
+
# around the spot; variance (n_frames,) the fitted widths in px^2;
|
|
83
|
+
# sigma0_px the t = 0 width in pixels
|
|
84
|
+
n_pixels = profiles.shape[1]
|
|
85
|
+
lookup = calibrate_d_free(cnr0, half_window=(n_pixels / 2) / sigma0_px,
|
|
86
|
+
n_pixels=n_pixels) # the data's grid, in units of sigma_0
|
|
87
|
+
cnr = per_frame_cnr(profiles)
|
|
88
|
+
msd, w = msd_and_weights("subtract", variance / sigma0_px**2, cnr, lookup)
|
|
89
|
+
w = np.where(cnr >= 1.3, w, 0.0) # drop frames below the floor
|
|
90
|
+
fit = fit_D(times, msd, w)
|
|
91
|
+
D = fit.D * sigma0_px**2 # px^2 per unit time
|
|
92
|
+
se = np.hypot(fit.D_se, calibration_D_se(times, msd, w, cnr, lookup)) * sigma0_px**2
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## On real data
|
|
96
|
+
|
|
97
|
+
The validation keys the lookup on the exact per-frame CNR, uses a calibration
|
|
98
|
+
built for the same geometry as the data, and drops frames below the floor. On a
|
|
99
|
+
measurement each of these is a step for the user; the library does not check
|
|
100
|
+
them.
|
|
101
|
+
|
|
102
|
+
- **Match the calibration to the data.** `var_bias` is a variance in the length
|
|
103
|
+
unit of the calibration, and its size depends on the pixel grid, the profile
|
|
104
|
+
model and its fit bound, and the noise law. Work in units of the measured
|
|
105
|
+
t = 0 width sigma_0: divide the pixel axis by sigma_0 and the fitted
|
|
106
|
+
variances by sigma_0^2, build the calibration with the data's pixel count and
|
|
107
|
+
half-window in those units
|
|
108
|
+
(`calibrate_d_free(cnr0, half_window=(n_pixels / 2) / sigma0_px, n_pixels=n_pixels, model=..., noise_model=...)`),
|
|
109
|
+
and multiply the fitted D and its SE by sigma_0^2 at the end. A calibration in
|
|
110
|
+
units of sigma_0 applied to widths in micrometres subtracts a bias that is
|
|
111
|
+
off by the square of the unit ratio (16 for sigma_0 = 0.25 μm).
|
|
112
|
+
- **Drop frames below the floor.** The correction holds above a per-frame CNR
|
|
113
|
+
of about 1 (0.7 to 1.5 depending on shape). `msd_and_weights` applies no
|
|
114
|
+
floor, and a CNR outside the calibrated grid takes the value at the nearest
|
|
115
|
+
grid edge. The validations set the weight of frames below a per-frame CNR of
|
|
116
|
+
1.0 or 1.3 to zero before `fit_D`, as in the example above.
|
|
117
|
+
- **The estimated CNR holds over a narrower range.** With the CNR estimated
|
|
118
|
+
from each frame by `fft-cnr` instead of known, the corrected mean D holds in
|
|
119
|
+
simulation only where every fitted frame stays well above the floor: from an
|
|
120
|
+
initial CNR of about 34 at D = 0.02 sigma_0^2/tau for the Gaussian profile
|
|
121
|
+
(about 55 for p = 1.5 and 13 for p = 4), and from about 21 at D >= 0.05.
|
|
122
|
+
Below that, the pooled Gaussian mean at D = 0.02 over initial CNR 8 to 90 is
|
|
123
|
+
1.9 of the reference (standard error 0.4). See
|
|
124
|
+
[`experiments/wse2-strobescat`](https://github.com/thiebes/width-debias/tree/v0.4.0/experiments/wse2-strobescat).
|
|
125
|
+
- **Estimate the CNR on the spot.** Cut each profile to about ±4 sigma_0 around
|
|
126
|
+
the spot before calling `per_frame_cnr`. Background and fringe structure in a
|
|
127
|
+
full line cut corrupts the spectral CNR estimate at low signal.
|
|
128
|
+
|
|
129
|
+
## What the validation shows
|
|
130
|
+
|
|
131
|
+
- Above a per-frame CNR of about 1.5 the fit's lower bound does not bind: the
|
|
132
|
+
bounded and unbounded fits return the same widths and the same biased D
|
|
133
|
+
(`experiments/estimator-comparison`). Below it, the bounded fit reflects
|
|
134
|
+
rather than clips at the bound (`experiments/boundary-diagnostic`).
|
|
135
|
+
- With the calibration's own Monte Carlo error included, 4 of 96 cells lie
|
|
136
|
+
beyond two combined standard errors of the reference (Gaussian, Voigt, and
|
|
137
|
+
generalized-Gaussian p = 1.5 and p = 4 profiles; D = 0.005, 0.02, and 0.1
|
|
138
|
+
sigma_0^2/tau; initial CNR 3 to 90; `slope_fit_check.txt`). The cells share
|
|
139
|
+
noise seeds across shapes and one calibration per shape, so the count is
|
|
140
|
+
indicative rather than a test against a binomial null. At small D and low
|
|
141
|
+
initial CNR the combined SE is large, so those cells constrain the bias only
|
|
142
|
+
loosely (`experiments/dfree-calibration`).
|
|
143
|
+
- The correction holds above a per-frame CNR of about 1 (0.7 to 1.5 depending on
|
|
144
|
+
shape), where the leading-order bias model `var_bias = A / CNR^2` itself
|
|
145
|
+
breaks (`experiments/correction-floor`). With single-exponential decay to
|
|
146
|
+
3 tau, every frame stays above the floor from an initial CNR of about 20.
|
|
147
|
+
- It corrects the anomalous exponent of subdiffusive transport as well as D
|
|
148
|
+
(`experiments/subdiffusive-alpha`, `experiments/nc-solid`).
|
|
149
|
+
|
|
150
|
+
[`docs/REPO_MAP.md`](https://github.com/thiebes/width-debias/blob/v0.4.0/docs/REPO_MAP.md)
|
|
151
|
+
lists every experiment set with its result, and each set's README gives the
|
|
152
|
+
details and how to run it.
|
|
153
|
+
|
|
154
|
+
## Profile models
|
|
155
|
+
|
|
156
|
+
The bias affects any non-negative width estimator, so the profile model is
|
|
157
|
+
pluggable (`width_debias.models`): `GaussianModel`, `VoigtModel` (a diffusing
|
|
158
|
+
Gaussian convolved with a fixed Lorentzian point-spread function), and
|
|
159
|
+
`GeneralizedGaussianModel` (shape exponent p; p = 2 is the Gaussian).
|
|
160
|
+
`model_from_spec("generalized_gaussian:1.5")` builds a model from a spec
|
|
161
|
+
string. The experiment scripts in the repository take a model spec; name the
|
|
162
|
+
generalized-Gaussian shape explicitly:
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
python experiments/poc-bias-correction/poc_demo.py voigt
|
|
166
|
+
python experiments/boundary-diagnostic/diagnose_boundary.py generalized_gaussian:1.5
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## Tests
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
pytest
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Layout
|
|
176
|
+
|
|
177
|
+
| Path | Role |
|
|
178
|
+
| ------- | ------- |
|
|
179
|
+
| `src/width_debias/simulate.py` | profile geometry: diffusion, decay, noise |
|
|
180
|
+
| `src/width_debias/noise.py` | noise laws: white, shot, Poisson, read floor |
|
|
181
|
+
| `src/width_debias/models.py` | profile models and `model_from_spec` |
|
|
182
|
+
| `src/width_debias/fit.py` | per-frame width fit; MSD to D linear fit |
|
|
183
|
+
| `src/width_debias/montecarlo.py` | Monte Carlo ensembles |
|
|
184
|
+
| `src/width_debias/bias_lookup.py` | per-frame statistics; `BiasLookup` lookups and their SE |
|
|
185
|
+
| `src/width_debias/calibration.py` | single-frame calibration cells; joint (CNR, sigma^2) calibration |
|
|
186
|
+
| `src/width_debias/fisher.py` | Fisher-information width variance, leading-order bias, CRLB on D |
|
|
187
|
+
| `src/width_debias/smoothing.py` | P-spline smoother for the calibration residual |
|
|
188
|
+
| `src/width_debias/weights.py` | the four schemes; calibration SE of D |
|
|
189
|
+
| `src/width_debias/validate.py` | calibration and evaluation sweeps |
|
|
190
|
+
| `src/width_debias/cnr.py` | per-frame CNR from measured profiles via `fft-cnr` |
|
|
191
|
+
| `experiments/` | one folder per experiment set (see `docs/REPO_MAP.md`) |
|
|
192
|
+
| `illustrations/` | schematic figures |
|
|
193
|
+
| `scripts/` | shared calibration tooling and figure rendering |
|
|
194
|
+
|
|
195
|
+
## Related work
|
|
196
|
+
|
|
197
|
+
- **DICE**: Monte Carlo engine for optical diffusion measurements (Thiebes and
|
|
198
|
+
Grumstrup, *J. Chem. Phys.* 2024).
|
|
199
|
+
- **fft-cnr**: single-profile CNR estimation
|
|
200
|
+
([PyPI](https://pypi.org/project/fft-cnr/)).
|
|
201
|
+
|
|
202
|
+
## License
|
|
203
|
+
|
|
204
|
+
MIT, see [`LICENSE`](https://github.com/thiebes/width-debias/blob/v0.4.0/LICENSE).
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools==84.0.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "width-debias"
|
|
7
|
+
# The version lives in one place, width_debias.__version__.
|
|
8
|
+
dynamic = ["version"]
|
|
9
|
+
description = "Correction of the noise bias in fitted profile widths, for mean-squared-displacement (MSD) diffusion measurements."
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
license = "MIT"
|
|
13
|
+
license-files = ["LICENSE"]
|
|
14
|
+
authors = [
|
|
15
|
+
{ name = "Joseph J. Thiebes", email = "joseph@thiebes.org" },
|
|
16
|
+
]
|
|
17
|
+
keywords = ["diffusion", "mean-squared displacement", "bias correction",
|
|
18
|
+
"contrast-to-noise ratio", "transient microscopy"]
|
|
19
|
+
classifiers = [
|
|
20
|
+
"Development Status :: 3 - Alpha",
|
|
21
|
+
"Intended Audience :: Science/Research",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Programming Language :: Python :: 3.12",
|
|
26
|
+
"Programming Language :: Python :: 3.13",
|
|
27
|
+
"Topic :: Scientific/Engineering :: Physics",
|
|
28
|
+
]
|
|
29
|
+
# A library's metadata carries compatible ranges; the exact, hashed versions
|
|
30
|
+
# that produced the committed results are in uv.lock.
|
|
31
|
+
dependencies = [
|
|
32
|
+
"numpy>=1.24,<3",
|
|
33
|
+
"scipy>=1.10,<2",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
[project.urls]
|
|
37
|
+
Source = "https://github.com/thiebes/width-debias"
|
|
38
|
+
Changelog = "https://github.com/thiebes/width-debias/blob/master/CHANGELOG.md"
|
|
39
|
+
Issues = "https://github.com/thiebes/width-debias/issues"
|
|
40
|
+
|
|
41
|
+
[project.optional-dependencies]
|
|
42
|
+
# fft-cnr supplies per-frame CNR estimates from single 1-D profiles.
|
|
43
|
+
# Used for real experimental data; the Monte Carlo validation knows true CNR.
|
|
44
|
+
# The real-data pipeline needs fft-cnr's refusal of degenerate
|
|
45
|
+
# generalized-Gaussian fits (commit 69cd361); 0.3.3 is the first PyPI release
|
|
46
|
+
# that carries it.
|
|
47
|
+
cnr = ["fft-cnr>=0.3.3,<0.5"]
|
|
48
|
+
# curved-text draws the curved data-series label on the poster figure.
|
|
49
|
+
plot = ["matplotlib>=3.7,<4", "curved-text>=0.5,<1"]
|
|
50
|
+
dev = ["pytest>=7.4", "matplotlib>=3.7,<4", "fft-cnr>=0.3.3,<0.5",
|
|
51
|
+
"curved-text>=0.5,<1"]
|
|
52
|
+
|
|
53
|
+
[tool.setuptools.dynamic]
|
|
54
|
+
version = { attr = "width_debias.__version__" }
|
|
55
|
+
|
|
56
|
+
[tool.setuptools.packages.find]
|
|
57
|
+
where = ["src"]
|
|
58
|
+
|
|
59
|
+
[tool.uv]
|
|
60
|
+
# Lock-only constraints: the environment that produced the committed results
|
|
61
|
+
# and poster figures. They do not enter the published metadata.
|
|
62
|
+
constraint-dependencies = [
|
|
63
|
+
"numpy==2.4.5",
|
|
64
|
+
"scipy==1.17.1",
|
|
65
|
+
"matplotlib==3.10.9",
|
|
66
|
+
"curved-text==0.5.0",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
[tool.pytest.ini_options]
|
|
70
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""width-debias: correcting the noise bias in fitted profile widths.
|
|
2
|
+
|
|
3
|
+
A width fitted to a noisy profile scatters about the true width, so the fitted
|
|
4
|
+
variance exceeds the true one on average by the width's estimation variance,
|
|
5
|
+
which grows as the per-frame CNR falls. In a diffusion measurement the CNR
|
|
6
|
+
falls frame by frame, so the bias rises over time, leaks through the MSD fit,
|
|
7
|
+
and inflates the extracted diffusion coefficient D. Standard inverse-variance
|
|
8
|
+
weighting corrects the unequal noise across frames but cannot remove a mean
|
|
9
|
+
bias from a slope fit.
|
|
10
|
+
|
|
11
|
+
The package subtracts a calibrated bias ``var_bias(CNR)`` from each frame's
|
|
12
|
+
fitted variance, then weights by inverse variance; the MSD and D corrections
|
|
13
|
+
follow from the corrected widths. ``docs/DERIVATION.md`` derives the additive
|
|
14
|
+
form from a folded-normal model of the fitted width. The per-frame CNR (from
|
|
15
|
+
the ``fft-cnr`` package) is the input.
|
|
16
|
+
|
|
17
|
+
Typical use::
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from width_debias import Experiment, calibrate_d_free, evaluate
|
|
21
|
+
from width_debias.fit import fit_D
|
|
22
|
+
from width_debias.weights import msd_and_weights
|
|
23
|
+
|
|
24
|
+
cnr0 = np.array([5, 8, 13, 21, 34, 55, 90])
|
|
25
|
+
lookup = calibrate_d_free(cnr0) # D-free lookup var_bias(CNR)
|
|
26
|
+
|
|
27
|
+
# Monte Carlo bias curves <D_est>/D_ref for ols, inverse_variance,
|
|
28
|
+
# subtract, and mas
|
|
29
|
+
results = evaluate(Experiment(D=0.02), cnr0, lookup)
|
|
30
|
+
|
|
31
|
+
# A measurement: fitted widths in units of sigma_0^2 and per-frame CNR
|
|
32
|
+
msd, w = msd_and_weights("subtract", variance, cnr, lookup)
|
|
33
|
+
w = np.where(cnr >= 1.3, w, 0.0) # drop frames below the floor
|
|
34
|
+
D = fit_D(times, msd, w).D
|
|
35
|
+
|
|
36
|
+
``subtract`` is the recommended scheme and :func:`calibrate_d_free` the
|
|
37
|
+
recommended calibration. The README states the conditions for real data: a
|
|
38
|
+
calibration that matches the data's geometry and units, and the per-frame CNR
|
|
39
|
+
floor.
|
|
40
|
+
"""
|
|
41
|
+
from .simulate import (AnomalousExperiment, Experiment, MultiExpExperiment,
|
|
42
|
+
cnr_per_frame, noisy_series)
|
|
43
|
+
from .models import (GaussianModel, GeneralizedGaussianModel, MODELS,
|
|
44
|
+
MomentModel, UnboundedGaussianModel, VoigtModel,
|
|
45
|
+
model_from_spec, spec_tag)
|
|
46
|
+
from .montecarlo import Ensemble, run_ensemble
|
|
47
|
+
from .bias_lookup import FrameStats, BiasLookup, frame_stats
|
|
48
|
+
from .weights import (SCHEMES, calibration_D_se, corrected_variance,
|
|
49
|
+
msd_and_weights)
|
|
50
|
+
from .validate import (FrameDiagnostic, SchemeResult, calibrate,
|
|
51
|
+
calibrate_d_free, calibrate_fisher, evaluate,
|
|
52
|
+
per_frame_diagnostic, sweep_stats)
|
|
53
|
+
from .calibration import (CalibrationCells, CalibrationGrid, calibrate_cells,
|
|
54
|
+
calibrate_cnr_sigma2)
|
|
55
|
+
from .fisher import LeadingOrderTerms, leading_order_terms
|
|
56
|
+
|
|
57
|
+
__version__ = "0.4.0"
|
|
58
|
+
|
|
59
|
+
__all__ = [
|
|
60
|
+
"Experiment", "AnomalousExperiment", "MultiExpExperiment",
|
|
61
|
+
"cnr_per_frame", "noisy_series",
|
|
62
|
+
"GaussianModel", "VoigtModel", "GeneralizedGaussianModel", "MomentModel",
|
|
63
|
+
"UnboundedGaussianModel", "MODELS", "model_from_spec", "spec_tag",
|
|
64
|
+
"Ensemble", "run_ensemble",
|
|
65
|
+
"FrameStats", "BiasLookup", "frame_stats",
|
|
66
|
+
"SCHEMES", "msd_and_weights", "corrected_variance", "calibration_D_se",
|
|
67
|
+
"SchemeResult", "calibrate", "calibrate_d_free", "calibrate_fisher",
|
|
68
|
+
"evaluate", "sweep_stats",
|
|
69
|
+
"FrameDiagnostic", "per_frame_diagnostic",
|
|
70
|
+
"CalibrationGrid", "calibrate_cnr_sigma2",
|
|
71
|
+
"CalibrationCells", "calibrate_cells",
|
|
72
|
+
"LeadingOrderTerms", "leading_order_terms",
|
|
73
|
+
]
|