bobleesj commited on
Commit
70585dc
·
verified ·
1 Parent(s): c261006

Delete denoise/01_tv.ipynb

Browse files
Files changed (1) hide show
  1. denoise/01_tv.ipynb +0 -454
denoise/01_tv.ipynb DELETED
@@ -1,454 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "# 1. Denoise one diffraction scan with Denova TV\n",
8
- "\n",
9
- "**Question.** How much smoothing removes noise without washing out diffraction spots?\n",
10
- "\n",
11
- "**What you will learn.** Load one synthetic dose, automatically fit the detector from independent saved exposures, reconstruct a native scan, then inspect selection, residuals and truth separately.\n",
12
- "\n",
13
- "**Before you run it.** Predict what too little and too much regularization will leave in the residual. Download the single-dose synthetic bundle below; running the abTEM generator is optional. This notebook regenerates detector measurements from the shared abTEM expectation, then independently fits noise from dark/flat repeats.\n",
14
- "\n",
15
- "**Data.** [Downloadable synthetic bundle](https://huggingface.co/datasets/bobleesj/quantem-data/tree/main/denoise/simulated_au_nanobeam_pg_dose1): one relative dose (1.0), 32×32 scan positions and 192×192 detector pixels. No experimental observations are included.\n",
16
- "\n",
17
- "**Typical run time.** Start here: TV1 took about **36 s** for strength selection and reconstruction, **42 s** across the original full notebook before download, on one RTX PRO 6000 GPU. The compact-data version additionally generates noise and calibration exposures locally. First download, kernel startup and GPU contention are separate. Under one minute is a measured example, not a hardware-independent guarantee.\n",
18
- "\n",
19
- "**Measured outcome.** TV1 reduced RMSE from 2.45 to 1.67 ADU. The small central detector band still failed the declared residual criteria; `no_feasible_candidate` remains visible.\n",
20
- "\n",
21
- "## Environment\n",
22
- "Use the matching Denova development checkout with `pip install -e '.[fourdstem]'` and compatible QuantEM.Widget. A released Denova version with this revised API has not been verified. Keep `synthetic_detector.py` beside this notebook. abTEM and abtem-cuda are not needed for this download-and-denoise workflow. Check GPU availability before starting; select GPU 0 before launching Jupyter. QuantEM.GPU loads the encoded source and reads only the explicit working region."
23
- ],
24
- "id": "9d7a7e90"
25
- },
26
- {
27
- "cell_type": "code",
28
- "metadata": {},
29
- "source": [
30
- "from pathlib import Path\n",
31
- "from time import perf_counter\n",
32
- "import json\n",
33
- "from math import ceil, floor\n",
34
- "import torch\n",
35
- "import pandas as pd\n",
36
- "import quantem.widget as qw\n",
37
- "from quantem.gpu import io as qio\n",
38
- "from quantem.widget.io import hub\n",
39
- "from synthetic_detector import prepare_measurements\n",
40
- "from denova import load, denoise\n",
41
- "from denova.noise import PoissonGaussian\n",
42
- "from denova.fourdstem import ResidualCriteria, radial_regions\n",
43
- "\n",
44
- "DATASET = \"simulated_au_nanobeam_pg_dose1\"\n",
45
- "DOSE = 1.0\n",
46
- "RUN = Path(\"4dstem-results\") / f\"tv-dose-{DOSE:.1f}\"\n",
47
- "qw.profile()"
48
- ],
49
- "execution_count": null,
50
- "outputs": [],
51
- "id": "66542c62"
52
- },
53
- {
54
- "cell_type": "markdown",
55
- "metadata": {},
56
- "source": [
57
- "## Download only the abTEM expectation\n",
58
- "\n",
59
- "The public bundle contains **one noiseless 32×32×192×192 abTEM scan**, geometry and a small noise recipe (about **121 MiB**). QuantEM downloads it once and reuses its cache; no Hugging Face account is required. Keep the HDF5 master with its linked data shard. No noisy scans, dark/flat stacks, fitted calibration, network weights or `.pt` files are downloaded.\n",
60
- "\n",
61
- "The next cell generates one dose-1 observation and independent dark/flat repeats on CUDA with declared separate seeds. QuantEM.GPU saves these local measurements. Calibration is fitted later from those repeats, never copied from the generator. The known generator maps are retained locally only for simulation and final truth evaluation. Generating noise from truth does not make the denoiser supervised: neither truth nor the generator maps are passed to `denoise`.\n",
62
- "\n",
63
- "Local inputs and results go to `4dstem-results/`, outside the download cache. To use your own abTEM output, replace `SOURCE` with the directory generated by notebook 1. Run TV before SHINE.\n"
64
- ],
65
- "id": "d5278ab3"
66
- },
67
- {
68
- "cell_type": "code",
69
- "execution_count": null,
70
- "metadata": {},
71
- "outputs": [],
72
- "source": [
73
- "SOURCE = Path(hub.download(DATASET, repo=\"bobleesj/quantem-data\"))\n",
74
- "started = perf_counter()\n",
75
- "DATA = prepare_measurements(SOURCE, RUN.parent / \"inputs\", dose=DOSE)\n",
76
- "print(f\"Local measurement preparation: {perf_counter() - started:.1f} s\")\n",
77
- "DATA\n"
78
- ],
79
- "id": "ed08bee9"
80
- },
81
- {
82
- "cell_type": "markdown",
83
- "metadata": {},
84
- "source": [
85
- "## Inspect before choosing the working region\n",
86
- "\n",
87
- "Load the acquisition once with QuantEM.GPU. It stays encoded while Show4DSTEM reads diffraction patterns and virtual images on demand. Scan spacing and detector angular sampling come from the file; check the scale bars before continuing. Unknown experimental calibration must stay in pixels until measured.\n",
88
- "\n",
89
- "Move or resize the rectangle on the **real-space/virtual-image panel** to inspect a particle, an edge, or the liquid background. The diffraction panel shows the selected region's mean for inspection. This average is **not** the denoiser input: the next cell loads every original pattern inside the rectangle. The detector aperture only controls virtual-image contrast and does not crop the detector for denoising.\n"
90
- ],
91
- "id": "355c0329"
92
- },
93
- {
94
- "cell_type": "code",
95
- "metadata": {},
96
- "source": [
97
- "geometry = json.loads((DATA / \"geometry.json\").read_text())\n",
98
- "acquisition = qio.load(\n",
99
- " DATA / f\"dose-{DOSE:.1f}_master.h5\", representation=\"encoded\", backend=\"cuda\",\n",
100
- " apply_mask=False, hot_pixel_correction=\"none\",\n",
101
- ")\n",
102
- "rows, cols = acquisition.shape[:2]\n",
103
- "viewer = qw.Show4DSTEM(acquisition, center=tuple(geometry[\"detector_center\"]),\n",
104
- " title=\"Inspect the noisy acquisition; choose a scan rectangle\")\n",
105
- "with viewer.hold_trait_notifications():\n",
106
- " viewer.vi_roi_mode = \"rect\"\n",
107
- " viewer.vi_roi_center = [(rows - 1) / 2, (cols - 1) / 2]\n",
108
- " viewer.vi_roi_height = rows - 1\n",
109
- " viewer.vi_roi_width = cols - 1\n",
110
- "viewer\n"
111
- ],
112
- "execution_count": null,
113
- "outputs": [],
114
- "id": "39a96775"
115
- },
116
- {
117
- "cell_type": "markdown",
118
- "metadata": {},
119
- "source": [
120
- "### Freeze the chosen scan region\n",
121
- "\n",
122
- "Run the next cell after dragging the rectangle. It records exclusive `(row_start, row_stop, col_start, col_stop)` bounds, loads that native GPU region, and saves the viewing choices. Moving the viewer later does not silently change this recorded input; rerun this cell to choose again. For SHINE keep at least 12 scan rows and 3 columns for disjoint contexts. Calibration below still uses independent dark/flat exposures, not this specimen rectangle.\n"
123
- ],
124
- "id": "039e8115"
125
- },
126
- {
127
- "cell_type": "code",
128
- "metadata": {},
129
- "source": [
130
- "if viewer.vi_roi_mode != \"rect\":\n",
131
- " raise ValueError(\"Choose a rectangular region on the virtual image before continuing.\")\n",
132
- "row, col = viewer.vi_roi_center\n",
133
- "scan_region = (\n",
134
- " max(0, ceil(row - viewer.vi_roi_height / 2)),\n",
135
- " min(rows, floor(row + viewer.vi_roi_height / 2) + 1),\n",
136
- " max(0, ceil(col - viewer.vi_roi_width / 2)),\n",
137
- " min(cols, floor(col + viewer.vi_roi_width / 2) + 1),\n",
138
- ")\n",
139
- "scan = load(acquisition, scan_region=scan_region)\n",
140
- "view_calibration = dict(sampling=acquisition.sampling, units=acquisition.units,\n",
141
- " center=tuple(geometry[\"detector_center\"]))\n",
142
- "RUN.mkdir(parents=True, exist_ok=True)\n",
143
- "(RUN / \"region-selection.json\").write_text(json.dumps({\n",
144
- " \"scan_region\": scan_region, \"source_shape\": acquisition.shape,\n",
145
- " \"sampling\": acquisition.sampling, \"units\": acquisition.units,\n",
146
- " \"widget_state\": viewer.state_dict(),\n",
147
- "}, indent=2) + \"\\n\")\n",
148
- "scan.report()\n"
149
- ],
150
- "execution_count": null,
151
- "outputs": [],
152
- "id": "85fa4359"
153
- },
154
- {
155
- "cell_type": "markdown",
156
- "metadata": {},
157
- "source": [
158
- "## Calibrate the detector before denoising\n",
159
- "**Predict.** Which information comes from a beam-blanked exposure, and which needs illumination?\n",
160
- "\n",
161
- "Dark repeats determine offset and read-noise variance. Repeated stable flat exposures at several intensities determine gain from temporal variance versus dark-subtracted mean. An empty-specimen pattern with the beam on is not a dark frame. QuantEM.GPU loads these independent exposures; Denova fits their moments on CUDA in bounded blocks. No specimen values or truth enter the fit. The numerical mapping used for compact storage is separate from this physical noise calibration.\n"
162
- ],
163
- "id": "2ac9fb65"
164
- },
165
- {
166
- "cell_type": "code",
167
- "execution_count": null,
168
- "metadata": {},
169
- "outputs": [],
170
- "source": [
171
- "valid_t = torch.load(DATA / \"detector-valid.pt\", map_location=\"cuda\", weights_only=True)\n",
172
- "noise = PoissonGaussian.calibrate(DATA / \"flats_master.h5\", dark=DATA / \"dark_master.h5\", valid=valid_t)\n",
173
- "noise.save(RUN / \"detector-calibration.pt\")\n",
174
- "noise.plot()"
175
- ],
176
- "id": "e2b2d424"
177
- },
178
- {
179
- "cell_type": "markdown",
180
- "metadata": {},
181
- "source": [
182
- "**Observe.** Inspect the three detector maps and whether the measured flat variances follow the fitted curve. The curve averages each pixel's temporal variance; it does not fit spatial differences between detector pixels. This chart assesses the fit, not independent validation. Notebook 1 challenges it with separate flat repeats and shows their normalized residual energy and row/column correlations. All three notebooks use the same calibration exposures; the model is fixed throughout reconstruction.\n"
183
- ],
184
- "id": "296439cf"
185
- },
186
- {
187
- "cell_type": "markdown",
188
- "metadata": {},
189
- "source": [
190
- "## What should be checked before choosing the result?\n",
191
- "Declare the native radial bands and lags before fitting. For this 192×192 detector, 100% means a radius of 96 pixels, not detector area. Its beam center comes from the synthetic geometry; experimental data require a measured center. The small central band supports detector lags through four."
192
- ],
193
- "id": "aac6b005"
194
- },
195
- {
196
- "cell_type": "code",
197
- "metadata": {},
198
- "source": [
199
- "regions = radial_regions(noise.valid, center=tuple(geometry[\"detector_center\"]), radius=96)\n",
200
- "criteria = ResidualCriteria(detector_lags=(1, 2, 4), scan_lags=(1, 2, 4))"
201
- ],
202
- "execution_count": null,
203
- "outputs": [],
204
- "id": "37584103"
205
- },
206
- {
207
- "cell_type": "markdown",
208
- "metadata": {},
209
- "source": [
210
- "## How does TV choose its strength?\n",
211
- "\n",
212
- "TV1 penalizes variation along native scan and detector axes while fitting the observation with an intensity-dependent variance model. `regularization=\"auto\"` is the default: probe the overall penalty until standardized residual energy approaches one, then assess regional correlations. `scan_ratio=10` sets the relative scan penalty; it is not independently selected in this tutorial. The amplitude-space prior matches the form used in the paper, not the package's event-space default.\n",
213
- "\n",
214
- "Too little smoothing leaves random noise in the estimate; too much can transfer spots into the residual. A pooled target near one does not ensure that every detector region is correct. All failed gates remain visible in `result.selection`.\n",
215
- "\n",
216
- "TV2 and TV12 use the same interface: change only `method` to compare a second-order or mixed prior in a separate run."
217
- ],
218
- "id": "03010bae"
219
- },
220
- {
221
- "cell_type": "code",
222
- "metadata": {},
223
- "source": [
224
- "started = perf_counter()\n",
225
- "result = denoise(\n",
226
- " scan, noise=noise, method=\"tv1\",\n",
227
- " prior_units=\"amplitude\", scan_ratio=10,\n",
228
- " detector_regions=regions, criteria=criteria,\n",
229
- ")\n",
230
- "print(f\"Denoising and selection: {perf_counter() - started:.1f} s\")\n"
231
- ],
232
- "execution_count": null,
233
- "outputs": [],
234
- "id": "16764b63"
235
- },
236
- {
237
- "cell_type": "markdown",
238
- "metadata": {},
239
- "source": [
240
- "## Before, after, and what was removed\n",
241
- "Inspect several scan positions: particle centers, boundaries and diffuse background. Each labeled column shows its own diffraction pattern at the same scan position; patterns are not averaged across truth, noisy and denoised data. Use the same contrast for comparisons. Display controls change appearance, not the saved measurements."
242
- ],
243
- "id": "7168e184"
244
- },
245
- {
246
- "cell_type": "code",
247
- "metadata": {},
248
- "source": [
249
- "result.show(**view_calibration, compare_dp_mode=\"all\", compare_cols=2)"
250
- ],
251
- "execution_count": null,
252
- "outputs": [],
253
- "id": "d671f166"
254
- },
255
- {
256
- "cell_type": "code",
257
- "metadata": {},
258
- "source": [
259
- "qw.Show4DSTEM(scan.array - result.output, **view_calibration)"
260
- ],
261
- "execution_count": null,
262
- "outputs": [],
263
- "id": "ccf9e8e9"
264
- },
265
- {
266
- "cell_type": "markdown",
267
- "metadata": {},
268
- "source": [
269
- "## Which candidate was actually selected?\n",
270
- "The plot and table expose the history and selection outcome. Read the status even when the image looks clean."
271
- ],
272
- "id": "24fc91ad"
273
- },
274
- {
275
- "cell_type": "code",
276
- "metadata": {},
277
- "source": [
278
- "result.plot()"
279
- ],
280
- "execution_count": null,
281
- "outputs": [],
282
- "id": "1b56d443"
283
- },
284
- {
285
- "cell_type": "code",
286
- "metadata": {},
287
- "source": [
288
- "result.selection"
289
- ],
290
- "execution_count": null,
291
- "outputs": [],
292
- "id": "0f7a4fad"
293
- },
294
- {
295
- "cell_type": "markdown",
296
- "metadata": {},
297
- "source": [
298
- "## Does the residual agree across detector regions?\n",
299
- "In event units, measured $f=(Y-b)/\\alpha$ and read-noise SD $\\sigma_0=s/\\alpha$ give\n",
300
- "$$z_i=\\frac{f_i-\\hat u_i}{\\sqrt{\\hat u_i+\\sigma_{0,i}^2}},\\qquad Q=\\frac{1}{N}\\sum_i z_i^2.$$\n",
301
- "$Q$ measures residual magnitude; signed correlations measure residual structure. Both endpoints of a pair must be valid and processed. $Q$ is not a degrees-of-freedom-corrected significance test. Unsupported lags are unassessed, not zero.\n",
302
- "\n",
303
- "**Observe.** Is the central band different from the outer bands? Do row and column residuals agree? A pass does not certify the absence of added or missed peaks."
304
- ],
305
- "id": "ccef413c"
306
- },
307
- {
308
- "cell_type": "code",
309
- "metadata": {},
310
- "source": [
311
- "result.report()"
312
- ],
313
- "execution_count": null,
314
- "outputs": [],
315
- "id": "8b2e1816"
316
- },
317
- {
318
- "cell_type": "code",
319
- "metadata": {},
320
- "source": [
321
- "result.plot(kind=\"correlations\")"
322
- ],
323
- "execution_count": null,
324
- "outputs": [],
325
- "id": "4457a9dc"
326
- },
327
- {
328
- "cell_type": "markdown",
329
- "metadata": {},
330
- "source": [
331
- "## How close is it to the synthetic expectation?\n",
332
- "Reload the source expectation only for final evaluation. It was used to generate the measurement, but not by the denoiser or selector. This does not change the selected output. The expected ADU includes the generator's offset and gain; comparing event truth directly with ADU would be wrong.\n",
333
- "\n",
334
- "**Observe.** Do spot widths, intensity and diffuse background agree? Inspect the signed error as well as RMSE. Local maxima or visible false reflections need their own feature assessment; this tutorial does not certify zero false peaks."
335
- ],
336
- "id": "4745a464"
337
- },
338
- {
339
- "cell_type": "code",
340
- "metadata": {},
341
- "source": [
342
- "truth = load(SOURCE / \"truth-events-dose-1.0_master.h5\", scan_region=scan_region)\n",
343
- "known = PoissonGaussian.load(DATA / \"generator-only.pt\", device=\"cuda\")\n",
344
- "truth_t = known.mean(DOSE * truth.array)\n",
345
- "qw.Show4DSTEM(\n",
346
- " torch.stack([truth_t, scan.array, result.output]), **view_calibration,\n",
347
- " view_mode=\"multiple\", compare_dp_mode=\"all\", compare_cols=3, frame_labels=[\"Synthetic expectation (ADU)\", \"Noisy\", \"Denova TV1\"],\n",
348
- ")"
349
- ],
350
- "execution_count": null,
351
- "outputs": [],
352
- "id": "f2293da2"
353
- },
354
- {
355
- "cell_type": "code",
356
- "metadata": {},
357
- "source": [
358
- "qw.Show4DSTEM(result.output - truth_t, **view_calibration)"
359
- ],
360
- "execution_count": null,
361
- "outputs": [],
362
- "id": "1417a3b3"
363
- },
364
- {
365
- "cell_type": "code",
366
- "metadata": {},
367
- "source": [
368
- "support_t = result.processed[..., None, None] & noise.valid\n",
369
- "error_t = (result.output - truth_t)[support_t]\n",
370
- "noisy_error_t = (scan.array - truth_t)[support_t]\n",
371
- "pd.DataFrame({\n",
372
- " \"method\": [\"Noisy\", \"TV1\"],\n",
373
- " \"ADU_RMSE_processed_valid\": [float(noisy_error_t.square().mean().sqrt()),\n",
374
- " float(error_t.square().mean().sqrt())],\n",
375
- "})"
376
- ],
377
- "execution_count": null,
378
- "outputs": [],
379
- "id": "add49982"
380
- },
381
- {
382
- "cell_type": "markdown",
383
- "metadata": {},
384
- "source": [
385
- "## Save the output and evidence\n",
386
- "QuantEM.GPU saves the denoised result with `scaled_uint16` codes and an automatic scale/offset per region. Reopening restores ADU, including negative values within the saved range. This is an approximate storage conversion, not a new detector calibration. The report records actual file bytes, conversion RMSE, maximum error and its ratio to the smallest read-noise SD.\n",
387
- "\n",
388
- "The calibration, validity/processed masks and original reconstruction audit remain exact. That audit describes the in-memory reconstruction **before** storage conversion. Inspect the conversion error before using the compact file for quantitative work; `result.save(RUN, dtype=None)` keeps float32 exactly with compression. Keep the whole result directory together. Use a distinct path for every dose and method."
389
- ],
390
- "id": "259af9a3"
391
- },
392
- {
393
- "cell_type": "code",
394
- "metadata": {},
395
- "source": [
396
- "paths = result.save(RUN, dtype=\"scaled_uint16\")\n",
397
- "storage = json.loads(paths[\"storage\"].read_text())\n",
398
- "storage"
399
- ],
400
- "execution_count": null,
401
- "outputs": [],
402
- "id": "836e4541"
403
- },
404
- {
405
- "cell_type": "code",
406
- "execution_count": null,
407
- "metadata": {},
408
- "outputs": [],
409
- "source": [
410
- "saved = load(paths[\"output\"], scan_region=(0, scan.shape[0], 0, scan.shape[1]))\n",
411
- "qw.Show4DSTEM(saved.array, **view_calibration)"
412
- ],
413
- "id": "df0497ef"
414
- },
415
- {
416
- "cell_type": "markdown",
417
- "metadata": {},
418
- "source": [
419
- "## Answer\n",
420
- "One independent detector model supplies the intensity-dependent uncertainty for this method. The selection record and regional residual tests state what passed and failed. Truth is an independent final evaluation, not a training target or a selection oracle.\n",
421
- "\n",
422
- "When comparing this notebook with the other method, evaluate on the intersection of their processed scan masks: TV processes the whole ROI; SHINE leaves the outer scan border unchanged. Their individual `report()` tables do not automatically impose that common support.\n",
423
- "\n",
424
- "The generator is a physically motivated synthetic test, not validated ARINA noise physics or proof of experimental indistinguishability. Credit for the motivating experimental data: **Serin Lee and Andrew Barnum**, [Zenodo 10.5281/zenodo.18167694](https://doi.org/10.5281/zenodo.18167694), CC BY 4.0."
425
- ],
426
- "id": "4bebcc8c"
427
- },
428
- {
429
- "cell_type": "markdown",
430
- "metadata": {},
431
- "source": [
432
- "When finished inspecting, close the views and call `acquisition.close()` to release the encoded source. Keep it open while the acquisition viewer is in use. Geometry calibration (scale bars) and independently measured detector-noise calibration are separate.\n"
433
- ],
434
- "id": "5f8846e9"
435
- }
436
- ],
437
- "metadata": {
438
- "denova": {
439
- "role": "reader-tutorial",
440
- "run_all": true
441
- },
442
- "kernelspec": {
443
- "display_name": "live-env",
444
- "language": "python",
445
- "name": "python3"
446
- },
447
- "language_info": {
448
- "name": "python",
449
- "version": "3.14.6"
450
- }
451
- },
452
- "nbformat": 4,
453
- "nbformat_minor": 5
454
- }