Add TV-first calibrated denoising tutorials with local noise generation
Browse files- denoise/01_tv.ipynb +454 -0
- denoise/02_shine.ipynb +454 -0
- denoise/03_generate_abtem.ipynb +311 -0
- denoise/README.md +43 -0
- denoise/abtem_nanobeam.py +241 -0
- denoise/synthetic_detector.py +145 -0
denoise/01_tv.ipynb
ADDED
|
@@ -0,0 +1,454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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**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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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# 2. Learn from noisy diffraction with Denova SHINE-PG\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"**Question.** Can neighboring measurements predict a detector value without reading that noisy target?\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 which weak features will be hard to infer when neighboring scan positions have different crystal orientations. 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\u00d732 scan positions and 192\u00d7192 detector pixels. No experimental observations are included.\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"**Typical run time.** About **4\u00bd\u20139 min** (271\u2013523 s observed) for 64 epochs \u00d7 128 steps and reconstruction, on one RTX PRO 6000 GPU. The latest live run took 523 s with other GPU workloads present. Download and local noise generation are separate. **Try the TV notebook first**: its denoising took about 36 s.\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"**Measured outcome.** This SHINE example is experimental: RMSE increased from 2.44 to 3.02 ADU in the latest live run (3.59 in the initial run) and the inner detector bands failed the residual criteria. Successful execution is not scientific acceptance. Keep the failure visible when exploring the model.\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": "b3cb0bd8"
|
| 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\"shine-dose-{DOSE:.1f}\"\n",
|
| 47 |
+
"qw.profile()"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": [],
|
| 51 |
+
"id": "a96ca7cd"
|
| 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\u00d732\u00d7192\u00d7192 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": "dc894241"
|
| 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": "12b4a2b6"
|
| 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": "6fb23523"
|
| 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": "46d1a455"
|
| 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": "ea2545fd"
|
| 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": "d9e3ad08"
|
| 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": "30abdb77"
|
| 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": "fe8ff3e9"
|
| 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": "491c83ed"
|
| 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\u00d7192 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": "0568a5a5"
|
| 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": "fa70dd8e"
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "markdown",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"## How does the network learn without clean targets?\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"The detector blind spot removes the target measurement from its predictor. A 3\u00d73 scan context and neighboring detector values supply information, but they can also carry a different diffraction pattern. The calibrated likelihood measures how plausible the observed target is under the predicted intensity.\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"One convolutional SHINE backbone is trained. Calibration maps remain fixed. Ground truth is not loaded until the final assessment. Training, validation and confirmation raw contexts are disjoint in the current package. This differs from the frozen paper's historical split.\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"The default selector ranks residual-feasible epochs by noisy validation loss. If none qualify, it returns an exploratory checkpoint with `no_feasible_candidate`; it does not claim that the closest-looking output is calibrated. A subsequent confirmation or final audit can also fail."
|
| 217 |
+
],
|
| 218 |
+
"id": "b0838111"
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"started = perf_counter()\n",
|
| 225 |
+
"result = denoise(\n",
|
| 226 |
+
" scan, noise=noise, method=\"shine\",\n",
|
| 227 |
+
" epochs=64, steps_per_epoch=128,\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": "cdac4629"
|
| 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": "522b2646"
|
| 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": "89a582d0"
|
| 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": "5932e148"
|
| 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": "be5331c2"
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"cell_type": "code",
|
| 276 |
+
"metadata": {},
|
| 277 |
+
"source": [
|
| 278 |
+
"result.plot()"
|
| 279 |
+
],
|
| 280 |
+
"execution_count": null,
|
| 281 |
+
"outputs": [],
|
| 282 |
+
"id": "fb9a1231"
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"metadata": {},
|
| 287 |
+
"source": [
|
| 288 |
+
"result.selection"
|
| 289 |
+
],
|
| 290 |
+
"execution_count": null,
|
| 291 |
+
"outputs": [],
|
| 292 |
+
"id": "4a63d938"
|
| 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": "60d945f4"
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"metadata": {},
|
| 310 |
+
"source": [
|
| 311 |
+
"result.report()"
|
| 312 |
+
],
|
| 313 |
+
"execution_count": null,
|
| 314 |
+
"outputs": [],
|
| 315 |
+
"id": "b2f68ac0"
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"source": [
|
| 321 |
+
"result.plot(kind=\"correlations\")"
|
| 322 |
+
],
|
| 323 |
+
"execution_count": null,
|
| 324 |
+
"outputs": [],
|
| 325 |
+
"id": "647be597"
|
| 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": "73c61826"
|
| 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 SHINE-PG\"],\n",
|
| 348 |
+
")"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": [],
|
| 352 |
+
"id": "be381219"
|
| 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": "b133fc2d"
|
| 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\", \"SHINE-PG\"],\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": "253edd33"
|
| 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": "fec3e1af"
|
| 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": "7e09dfd4"
|
| 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": "8d296faa"
|
| 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": "f7d81c52"
|
| 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": "930cde4d"
|
| 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 |
+
}
|
denoise/03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",
|
| 9 |
+
"**Question.** If the specimen is unchanged, what disappears first when fewer electrons are measured?\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"**What you will learn.** Generate Au diffraction with abTEM-cuda, add a declared liquid-inspired diffuse response, draw a dose-1.0 observation, then independently recover one reusable detector calibration. Optional doses 0.8, 0.6 and 0.4 reuse the same specimen.\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"**Before you run it.** Predict whether lowering dose changes expected spot positions, absolute noise, relative noise, or all three. This tutorial generates data only; TV and SHINE have separate notebooks. It is physically motivated, not a validated ARINA simulator or a reproduction of the frozen paper benchmark.\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"**Typical run time.** About 12 s across the code cells in the tested 32×32 example on one RTX PRO 6000 GPU, excluding kernel startup. Propagation, diffuse response and detector integration took about 7 s. Noise draws reuse the same noiseless scan. GPU contention and first-use compilation affect timing.\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"## Environment\n",
|
| 18 |
+
"Use a CUDA environment with Denova's `fourdstem` extra, abTEM, ASE and CuPy. The optional `abtem-cuda` accelerator is a local repository, not an assumed PyPI package; install the reviewed checkout according to its README. The shipped `abtem_nanobeam.py` is tutorial support for GPU potential construction and bounded propagation, not a Denova solver.\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"Open this notebook in its `docs/tutorials/` directory so its neighboring support module is importable. Check `nvidia-smi`, then launch the kernel with `CUDA_VISIBLE_DEVICES=0`. CPU orchestration/atomic coordinates and file export are allowed; potential, propagation, noise and calibration arithmetic stay on GPU 0.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"The shared tutorial example uses one relative dose, 1.0. To compare dose dependence, extend `DOSES` after validating the single-dose workflow. TV and SHINE can instead download the shared bundle, so this generation notebook is optional for denoising users.\n"
|
| 23 |
+
],
|
| 24 |
+
"id": "0e935b49"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"source": [
|
| 30 |
+
"from pathlib import Path\n",
|
| 31 |
+
"from hashlib import sha256\n",
|
| 32 |
+
"import json\n",
|
| 33 |
+
"from importlib.metadata import version\n",
|
| 34 |
+
"import pandas as pd\n",
|
| 35 |
+
"import torch\n",
|
| 36 |
+
"import cupy as cp\n",
|
| 37 |
+
"import abtem_cuda\n",
|
| 38 |
+
"import quantem.widget as qw\n",
|
| 39 |
+
"from quantem.gpu import io as qio\n",
|
| 40 |
+
"from ase.io import write as write_atoms\n",
|
| 41 |
+
"from abtem_nanobeam import generate_diffraction\n",
|
| 42 |
+
"from synthetic_detector import RECIPE, detector_model\n",
|
| 43 |
+
"from denova.noise import PoissonGaussian\n",
|
| 44 |
+
"from denova.fourdstem import simulate\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"DATA = Path(\"4dstem-tutorial\")\n",
|
| 47 |
+
"SCAN_SIDE = 32\n",
|
| 48 |
+
"DOSES = (1.0,) # Optional dose study: (1.0, 0.8, 0.6, 0.4)\n",
|
| 49 |
+
"INCIDENT_EVENTS = 90000\n",
|
| 50 |
+
"DATA.mkdir(exist_ok=True)\n",
|
| 51 |
+
"qw.profile()"
|
| 52 |
+
],
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"outputs": [],
|
| 55 |
+
"id": "8dd165e1"
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "markdown",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"## What remains fixed while dose changes?\n",
|
| 62 |
+
"Four static Au spheres span [001], [011], [111] and a general orientation. The beam is 300 kV with 0.622 mrad convergence. The 220×220 Å cell is scanned directly on a 32×32 grid; set `SCAN_SIDE=64` for a denser scan, without interpolating scan positions. The final detector is 192×192.\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"A declared 25% diffuse angular response with 4 mrad width represents an **illustrative liquid-like background**. It is not atomistic water/window scattering and is not fitted to Serin's measurements. The retained infinite-projection, static-lattice approximation also needs convergence checks before quantitative materials claims.\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"The helper first compares four accelerated Au patterns with native GPU abTEM and stops if they are not bit-identical. This checks numerical execution, not physical realism."
|
| 67 |
+
],
|
| 68 |
+
"id": "b23a7626"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"probability_cp, atoms, geometry = generate_diffraction(\n",
|
| 75 |
+
" scan_side=SCAN_SIDE, diffuse_fraction=0.25, diffuse_sigma_mrad=4,\n",
|
| 76 |
+
")\n",
|
| 77 |
+
"probability_t = torch.from_dlpack(probability_cp)\n",
|
| 78 |
+
"truth1_t = probability_t * INCIDENT_EVENTS\n",
|
| 79 |
+
"write_atoms(DATA / \"au-scene.extxyz\", atoms)\n",
|
| 80 |
+
"pd.DataFrame([geometry[\"abtem_parity\"]])"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": [],
|
| 84 |
+
"id": "f0f4d4c0"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"qw.Show4DSTEM(truth1_t)"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": [],
|
| 94 |
+
"id": "b3818506"
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "markdown",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"## What should a lower-dose observation look like?\n",
|
| 101 |
+
"Select different particles and liquid-like positions in the viewer. The noiseless intensity scales with dose; spot positions do not move. The expected signal is $u_d=d\\,u_1$.\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"`INCIDENT_EVENTS` is an assumed incident count per probe position. The detector captures only part of the scattered intensity: we do **not** renormalize each cropped pattern to unit sum. This is relative dose, not a measured experimental electrons/Ų calibration.\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"The synthetic detector below has gain, pedestal and positive Gaussian read noise. These parameters are declared assumptions, not recovered ARINA parameters. The four invalid detector pixels remain separately masked; zero observations elsewhere are valid."
|
| 106 |
+
],
|
| 107 |
+
"id": "02ca40ef"
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"known = detector_model(RECIPE)\n",
|
| 114 |
+
"valid_t = known.valid\n",
|
| 115 |
+
"known.save(DATA / \"generator-only.pt\")\n",
|
| 116 |
+
"(DATA / \"noise-recipe.json\").write_text(json.dumps(RECIPE, indent=2) + \"\\n\")\n",
|
| 117 |
+
"observations = {\n",
|
| 118 |
+
" dose: simulate(dose * truth1_t, noise=known, seed=1000 + index)\n",
|
| 119 |
+
" for index, dose in enumerate(DOSES)\n",
|
| 120 |
+
"}"
|
| 121 |
+
],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": [],
|
| 124 |
+
"id": "057672d9"
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"qw.Show4DSTEM(torch.stack(list(observations.values())), view_mode=\"multiple\",\n",
|
| 131 |
+
" frame_labels=[f\"Relative dose {dose:.1f}\" for dose in DOSES])"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": [],
|
| 135 |
+
"id": "dd58eb8d"
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "markdown",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"## Observe first, then explain the noise\n",
|
| 142 |
+
"**Observe.** Compare the same detector region and scan position at each dose. Do faint spots become harder to distinguish? Does the diffuse region contain more zero or below-pedestal values? Change contrast consistently across panels.\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"The simulator draws counting noise before read noise:\n",
|
| 145 |
+
"$$K_d\\sim\\mathrm{Poisson}(d u_1),\\qquad Y_d=b+\\alpha K_d+\\epsilon,\\quad\\epsilon\\sim\\mathcal N(0,s^2).$$\n",
|
| 146 |
+
"Thus $\\operatorname{Var}(Y_d)=\\alpha^2d u_1+s^2$. Absolute shot fluctuations fall with dose, but fractional uncertainty grows; the read-noise term does not shrink. Each dose has a fresh noise draw, rather than a rescaled noisy image. Signed ADU are preserved, with no clipping or integer rounding.\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"## How would we discover those detector parameters independently?\n",
|
| 149 |
+
"In real work, blank the beam for repeated dark frames, then acquire repeated stable flats at several illumination levels in the **same detector mode**. Do not estimate detector noise from particle-to-particle differences. Here distinct seeds separate these calibration exposures from all science observations."
|
| 150 |
+
],
|
| 151 |
+
"id": "3127219c"
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"dark_t = simulate(torch.zeros((512, 192, 192), device=\"cuda\"), noise=known, seed=2000)\n",
|
| 158 |
+
"levels_t = torch.tensor([1., 16., 256., 4096., 32768.], device=\"cuda\")\n",
|
| 159 |
+
"flats_t = simulate(levels_t[:, None, None, None].expand(-1, 256, 192, 192),\n",
|
| 160 |
+
" noise=known, seed=2001)\n",
|
| 161 |
+
"qio.save(DATA / \"dark_master.h5\", dark_t[None],\n",
|
| 162 |
+
" metadata={\"exposure_axes\": \"dark_set, repeat, detector_row, detector_col\"})\n",
|
| 163 |
+
"qio.save(DATA / \"flats_master.h5\", flats_t,\n",
|
| 164 |
+
" metadata={\"exposure_axes\": \"illumination_level, repeat, detector_row, detector_col\"})\n",
|
| 165 |
+
"torch.save(valid_t, DATA / \"detector-valid.pt\")\n",
|
| 166 |
+
"noise = PoissonGaussian.calibrate(DATA / \"flats_master.h5\", dark=DATA / \"dark_master.h5\", valid=valid_t)\n",
|
| 167 |
+
"noise.save(DATA / \"detector-calibration.pt\")\n",
|
| 168 |
+
"noise.plot()"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": [],
|
| 172 |
+
"id": "3de99cb2"
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "markdown",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"## Does the calibration predict new repeated measurements?\n",
|
| 179 |
+
"Dark means estimate offset; dark variance estimates read variance. At each detector pixel the slope of flat variance versus dark-subtracted mean estimates gain. Calibration maps are frozen before either denoiser runs.\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"The difference of two independent flats cancels their fixed mean and has twice the single-frame variance. Test that on another, held-out sequence. The mean used in the prediction comes from calibration flats, not from the specimen or its truth.\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"The preceding chart shows offset, read-noise SD, gain and the photon-transfer curve. Points are averages of **temporal variance at each valid pixel**; spatial intensity variation is not treated as noise. The line averages the pixelwise fitted predictions. Dark frames alone cannot determine gain. QuantEM.GPU loads the saved exposures in encoded form, and Denova combines bounded repeat blocks on CUDA."
|
| 184 |
+
],
|
| 185 |
+
"id": "88da925a"
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"check_t = simulate(levels_t[:, None, None, None].expand(-1, 128, 192, 192),\n",
|
| 192 |
+
" noise=known, seed=2002)\n",
|
| 193 |
+
"qio.save(DATA / \"check-flats_master.h5\", check_t,\n",
|
| 194 |
+
" metadata={\"purpose\": \"independent calibration validation\"})\n",
|
| 195 |
+
"expected_t = noise.electrons(flats_t.mean(1)).clamp_min(0)\n",
|
| 196 |
+
"variance_t = noise.variance(expected_t)\n",
|
| 197 |
+
"z_t = (check_t[:, 0::2] - check_t[:, 1::2]) / (2 * variance_t[:, None]).sqrt()\n",
|
| 198 |
+
"calibration_check = pd.DataFrame({\n",
|
| 199 |
+
" \"flat_level_events\": levels_t.cpu().tolist(),\n",
|
| 200 |
+
" \"pair_difference_mean_square\": z_t[..., valid_t].square().mean((1, 2)).cpu().tolist(),\n",
|
| 201 |
+
"})\n",
|
| 202 |
+
"for direction, left_t, right_t, pairs_t in (\n",
|
| 203 |
+
" (\"row\", z_t[..., :-1, :], z_t[..., 1:, :], valid_t[:-1, :] & valid_t[1:, :]),\n",
|
| 204 |
+
" (\"col\", z_t[..., :, :-1], z_t[..., :, 1:], valid_t[:, :-1] & valid_t[:, 1:]),\n",
|
| 205 |
+
"):\n",
|
| 206 |
+
" left_t = left_t[..., pairs_t].flatten(1)\n",
|
| 207 |
+
" right_t = right_t[..., pairs_t].flatten(1)\n",
|
| 208 |
+
" left_t = left_t - left_t.mean(1, keepdim=True)\n",
|
| 209 |
+
" right_t = right_t - right_t.mean(1, keepdim=True)\n",
|
| 210 |
+
" rho_t = (left_t * right_t).mean(1) / (\n",
|
| 211 |
+
" left_t.square().mean(1) * right_t.square().mean(1)\n",
|
| 212 |
+
" ).sqrt()\n",
|
| 213 |
+
" calibration_check[f\"detector_{direction}_lag1_correlation\"] = rho_t.cpu().tolist()\n",
|
| 214 |
+
"calibration_check"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": [],
|
| 218 |
+
"id": "b5b12e9d"
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "markdown",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"**Observe.** Do all levels give mean-square residuals near one? This is a finite-repeat check, not a guarantee of calibration. Inspect row/column structure as well; unstable illumination, count-rate correction or correlated noise can invalidate the independent Poisson–Gaussian law. The demonstration repeat counts are not a validated acquisition minimum.\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"The API fits the slope through the independently estimated dark-variance intercept:\n",
|
| 227 |
+
"$$m_{\\ell j}=\\bar F_{\\ell j}-\\bar D_j,\\qquad\n",
|
| 228 |
+
"\\hat\\alpha_j=\\frac{\\sum_\\ell m_{\\ell j}(v_{F,\\ell j}-v_{D,j})}{\\sum_\\ell m_{\\ell j}^2}.$$\n",
|
| 229 |
+
"The read-noise parameter $s_j$ is a **standard deviation**. In event units $\\sigma_{0,j}=s_j/\\alpha_j$ and the shot-variance slope is one.\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"## Save once, reuse across both methods\n",
|
| 232 |
+
"QuantEM.GPU compresses the CUDA arrays directly to HDF5, with no full host-array copy. Keep each `*_master.h5` with its `*_data_*.h5` shards. Measurements and calibration exposures retain float32 values exactly, including signed fluctuations. A plain integer cast would change the noise model.\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"Only one dose-1 expectation is stored. Each denoiser later constructs the dose-specific ADU truth from that expectation and the generator maps, **after selection**. Optional additional doses share that expectation but require independent observations; rescaling a noisy image would give the wrong variance. File sizes below are measured when you run the cell; no compression ratio is assumed.\n"
|
| 235 |
+
],
|
| 236 |
+
"id": "5b764f2e"
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"axis_metadata = {\n",
|
| 243 |
+
" \"sampling\": [geometry[\"scan_step_A\"]] * 2 + [geometry[\"angular_sampling_mrad\"]] * 2,\n",
|
| 244 |
+
" \"units\": [\"angstrom\", \"angstrom\", \"mrad\", \"mrad\"],\n",
|
| 245 |
+
" \"origin\": [0., 0., *[-value * geometry[\"angular_sampling_mrad\"]\n",
|
| 246 |
+
" for value in geometry[\"detector_center\"]]],\n",
|
| 247 |
+
" \"calibration_source\": \"Synthetic geometry; not experimental hardware calibration\",\n",
|
| 248 |
+
"}\n",
|
| 249 |
+
"storage_rows = []\n",
|
| 250 |
+
"volumes = {f\"dose-{dose:.1f}\": observations[dose] for dose in DOSES}\n",
|
| 251 |
+
"volumes[\"truth-events-dose-1.0\"] = truth1_t\n",
|
| 252 |
+
"for name, values_t in volumes.items():\n",
|
| 253 |
+
" master = DATA / f\"{name}_master.h5\"\n",
|
| 254 |
+
" qio.save(master, values_t, metadata={**axis_metadata, \"intensity_units\": \"events\" if name.startswith(\"truth\") else \"ADU\"})\n",
|
| 255 |
+
" stored_bytes = master.stat().st_size + sum(p.stat().st_size for p in DATA.glob(f\"{name}_data_*.h5\"))\n",
|
| 256 |
+
" storage_rows.append({\"volume\": name, \"raw_MiB\": values_t.numel() * values_t.element_size() / 2**20,\n",
|
| 257 |
+
" \"stored_MiB\": stored_bytes / 2**20})\n",
|
| 258 |
+
"geometry.update(\n",
|
| 259 |
+
" relative_doses=list(DOSES), incident_events_per_position=INCIDENT_EVENTS,\n",
|
| 260 |
+
" science_seeds=[1000 + index for index in range(len(DOSES))],\n",
|
| 261 |
+
" calibration_seeds={\"dark\": 2000, \"flat\": 2001, \"check\": 2002},\n",
|
| 262 |
+
" noise_model=\"independent Poisson arrivals plus additive Gaussian ADU\",\n",
|
| 263 |
+
" versions={**{name: version(name) for name in (\"denova\", \"abtem\", \"quantem.gpu\")},\n",
|
| 264 |
+
" \"cupy\": cp.__version__,\n",
|
| 265 |
+
" \"abtem_cuda_module_sha256\": sha256(Path(abtem_cuda.__file__).read_bytes()).hexdigest()},\n",
|
| 266 |
+
" storage=\"QuantEM.GPU bitshuffle/LZ4 HDF5; lossless float32; one dose-1 expectation\",\n",
|
| 267 |
+
" data_credit=\"Serin Lee and Andrew Barnum, Zenodo 10.5281/zenodo.18167694 (inspiration only)\",\n",
|
| 268 |
+
")\n",
|
| 269 |
+
"(DATA / \"geometry.json\").write_text(json.dumps(geometry, indent=2) + \"\\n\")\n",
|
| 270 |
+
"calibration_check.to_csv(DATA / \"calibration-check.csv\", index=False)\n",
|
| 271 |
+
"pd.DataFrame(storage_rows)"
|
| 272 |
+
],
|
| 273 |
+
"execution_count": null,
|
| 274 |
+
"outputs": [],
|
| 275 |
+
"id": "5ef70d66"
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "markdown",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"## Answer\n",
|
| 282 |
+
"One simulated specimen supplies the fixed diffraction expectation. Dose controls independent electron arrivals; detector response stays fixed. Independent dark/flat sequences recover a reusable noise model, then new flat repeats challenge it. The TV and SHINE notebooks read the **same** observations and calibration exposures, fit the same model automatically, and plot it before denoising.\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"Next: `01_tv.ipynb` and `02_shine.ipynb`. Neither uses `generator-only.pt` or synthetic truth to select its result.\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"The tutorial does not model nonlinear count-rate correction, charge sharing, drift, liquid dynamics or thermal convergence. Native ARINA is an electron counter with nominal zero readout noise; this positive-Gaussian model is a general baseline, not verified ARINA physics. Do not invent a Gaussian floor to fit zero dark counts. Quantitative transfer needs independently measured detector statistics and physical simulation validation.\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"Credit for the motivating experimental reference: **Serin Lee and Andrew Barnum**, [Zenodo 10.5281/zenodo.18167694](https://doi.org/10.5281/zenodo.18167694), CC BY 4.0. No experimental measurements are distributed in this tutorial.\n",
|
| 289 |
+
"For sharing, upload only the noiseless event master/data pair, `geometry.json` and `noise-recipe.json`. The TV/SHINE tutorials regenerate observations and calibration exposures locally; `.pt` artifacts stay local.\n"
|
| 290 |
+
],
|
| 291 |
+
"id": "0db10bbb"
|
| 292 |
+
}
|
| 293 |
+
],
|
| 294 |
+
"metadata": {
|
| 295 |
+
"denova": {
|
| 296 |
+
"role": "reader-tutorial",
|
| 297 |
+
"run_all": true
|
| 298 |
+
},
|
| 299 |
+
"kernelspec": {
|
| 300 |
+
"display_name": "live-env",
|
| 301 |
+
"language": "python",
|
| 302 |
+
"name": "python3"
|
| 303 |
+
},
|
| 304 |
+
"language_info": {
|
| 305 |
+
"name": "python",
|
| 306 |
+
"version": "3.14.6"
|
| 307 |
+
}
|
| 308 |
+
},
|
| 309 |
+
"nbformat": 4,
|
| 310 |
+
"nbformat_minor": 5
|
| 311 |
+
}
|
denoise/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Calibrated 4D-STEM denoising tutorials
|
| 2 |
+
|
| 3 |
+
**Start with TV.** These notebooks use the same single-dose synthetic Au scan
|
| 4 |
+
and an independently fitted Poisson–Gaussian detector model.
|
| 5 |
+
|
| 6 |
+
| Notebook | What it does | Measured compute time |
|
| 7 |
+
| --- | --- | ---: |
|
| 8 |
+
| [01_tv.ipynb](01_tv.ipynb) | Download, inspect, calibrate, TV1, compare and save | **35–36 s** for TV; about 42 s across cells before download |
|
| 9 |
+
| [02_shine.ipynb](02_shine.ipynb) | Same workflow with one self-supervised neural model | **4½–9 min** (271–523 s observed), 64 epochs × 128 steps |
|
| 10 |
+
| [03_generate_abtem.ipynb](03_generate_abtem.ipynb) | Optional regeneration of the specimen | **12 s** across code cells |
|
| 11 |
+
|
| 12 |
+
Measured on one RTX PRO 6000 GPU for 32×32×192×192. First download,
|
| 13 |
+
kernel startup, compilation and GPU contention can add time. Local noisy
|
| 14 |
+
observation and dark/flat preparation took 0.9–3.1 s. The under-one-minute
|
| 15 |
+
TV result is for this example, not a guarantee for larger scans.
|
| 16 |
+
|
| 17 |
+
Download the notebook and **synthetic_detector.py** into the same directory.
|
| 18 |
+
For optional abTEM generation also download **abtem_nanobeam.py** and install
|
| 19 |
+
abTEM, CuPy, ASE and the separate abtem-cuda accelerator. The denoising
|
| 20 |
+
notebooks do not require abTEM.
|
| 21 |
+
|
| 22 |
+
Use the matching Denova development checkout: `pip install -e '.[fourdstem]'`.
|
| 23 |
+
These examples use the revised calibrated 4D-STEM API; a released Denova
|
| 24 |
+
version containing it has not been verified. Tested installed versions:
|
| 25 |
+
QuantEM.GPU 0.0.1rc15 and QuantEM.Widget 0.0.1rc41. Select an available CUDA
|
| 26 |
+
GPU before starting Jupyter, for example `CUDA_VISIBLE_DEVICES=0 jupyter lab`.
|
| 27 |
+
Run the notebook from top to bottom.
|
| 28 |
+
|
| 29 |
+
The [shared input](simulated_au_nanobeam_pg_dose1/) is only the **noiseless
|
| 30 |
+
abTEM expectation plus geometry and a noise recipe**, about 120 MiB.
|
| 31 |
+
The notebook creates noisy science observations, independent dark/flat
|
| 32 |
+
exposures and `.pt` calibration artifacts locally. QuantEM.GPU loads/saves
|
| 33 |
+
the data; Show4DSTEM displays native patterns and allows scan-region inspection.
|
| 34 |
+
|
| 35 |
+
**Quality status is explicit.** TV improves RMSE but fails the central residual
|
| 36 |
+
gate. SHINE worsens RMSE on this example and remains experimental. Both
|
| 37 |
+
currently return `no_feasible_candidate`; neither is certified to add zero
|
| 38 |
+
false peaks. Read the regional audit before treating an image as quantitative.
|
| 39 |
+
|
| 40 |
+
The Poisson–Gaussian recipe is an assumed synthetic detector, not validated
|
| 41 |
+
ARINA electronics or a new experimental result. Experimental inspiration:
|
| 42 |
+
**Serin Lee and Andrew Barnum**, [Au liquid-cell data](https://doi.org/10.5281/zenodo.18167694).
|
| 43 |
+
No experimental observations are shared here.
|
denoise/abtem_nanobeam.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GPU-only abTEM support for the single-scan synthetic tutorial.
|
| 2 |
+
|
| 3 |
+
The Lobato integrator and detector integration are adapted from the retained
|
| 4 |
+
calibrated-4dstem research scripts (see FOURDSTEM-SIMULATION.md). This file is
|
| 5 |
+
not a Denova solver or an installed package dependency. CPU work is restricted
|
| 6 |
+
to atomic coordinates, metadata and export. Potential grids and propagation
|
| 7 |
+
use the selected CUDA device.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from typing import TYPE_CHECKING
|
| 13 |
+
|
| 14 |
+
import cupy as cp
|
| 15 |
+
from abtem.core.constants import kappa
|
| 16 |
+
from abtem.core.utils import get_dtype
|
| 17 |
+
from abtem.integrals import ScatteringFactorProjectionIntegrals
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from ase import Atoms
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class _CudaLobatoIntegrals(ScatteringFactorProjectionIntegrals):
|
| 24 |
+
"""Keep both potential-grid construction and propagation on the selected GPU.
|
| 25 |
+
|
| 26 |
+
The expression is abTEM's Lobato projected scattering factor. Only the
|
| 27 |
+
small published coefficient table enters from host metadata; coefficient
|
| 28 |
+
scaling, reciprocal grids, and potential values are evaluated on CUDA.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self):
|
| 32 |
+
super().__init__(parametrization="lobato")
|
| 33 |
+
|
| 34 |
+
def _calculate_scattering_factor(self, symbol, gpts, sampling, device="gpu"):
|
| 35 |
+
if device != "gpu":
|
| 36 |
+
raise RuntimeError(
|
| 37 |
+
"CudaLobatoIntegrals requires device='gpu'; CPU fallback is forbidden."
|
| 38 |
+
)
|
| 39 |
+
raw = cp.asarray(self.parametrization.parameters[symbol], dtype=cp.float64)
|
| 40 |
+
a = (cp.pi**2 * raw[0] / raw[1] ** 1.5 / kappa).astype(cp.float32)
|
| 41 |
+
b = (2 * cp.pi / cp.sqrt(raw[1])).astype(cp.float32)
|
| 42 |
+
row_frequency = cp.fft.fftfreq(gpts[0], sampling[0]).astype(cp.float32)
|
| 43 |
+
col_frequency = cp.fft.fftfreq(gpts[1], sampling[1]).astype(cp.float32)
|
| 44 |
+
spatial_squared = row_frequency[:, None] ** 2 + col_frequency[None, :] ** 2
|
| 45 |
+
pi = cp.asarray(cp.pi, dtype=cp.float32)
|
| 46 |
+
pi_squared = cp.asarray(cp.pi**2, dtype=cp.float32)
|
| 47 |
+
angular_squared = 4 * pi_squared * spatial_squared
|
| 48 |
+
total = cp.zeros(gpts, dtype=cp.float32)
|
| 49 |
+
for index in range(5):
|
| 50 |
+
denominator = angular_squared + b[index] ** 2
|
| 51 |
+
total += (
|
| 52 |
+
a[index] / b[index] / denominator + a[index] * b[index] / denominator**2
|
| 53 |
+
)
|
| 54 |
+
total *= 8 * pi
|
| 55 |
+
if symbol in self.parametrization.sigmas:
|
| 56 |
+
sigma = self.parametrization.sigmas[symbol]
|
| 57 |
+
total *= cp.exp(-spatial_squared * (cp.pi * sigma / cp.sqrt(0.5)) ** 2)
|
| 58 |
+
assert total.device.id == 0
|
| 59 |
+
return total.astype(get_dtype(complex=False))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _gold_scene() -> Atoms:
|
| 63 |
+
"""Construct four oriented Au spheres in a periodic 220 x 220 x 60 A cell."""
|
| 64 |
+
import numpy as np
|
| 65 |
+
from ase import Atoms
|
| 66 |
+
from ase.build import bulk
|
| 67 |
+
|
| 68 |
+
atoms = Atoms(cell=[220, 220, 60], pbc=True)
|
| 69 |
+
specifications = [
|
| 70 |
+
(0.25, 0.27, 25, (0, 0, 1), 0),
|
| 71 |
+
(0.65, 0.60, 36, (0, 1, 1), 0.2),
|
| 72 |
+
(0.70, 0.15, 20, (1, 1, 1), -0.4),
|
| 73 |
+
(0.23, 0.83, 48, (0.32, 0.67, 0.669), 0.7),
|
| 74 |
+
]
|
| 75 |
+
for row, col, diameter, axis, tilt in specifications:
|
| 76 |
+
repeats = int(np.ceil(diameter / 4.078)) + 2
|
| 77 |
+
particle = bulk("Au", "fcc", a=4.078, cubic=True) * (repeats, repeats, repeats)
|
| 78 |
+
particle.positions -= particle.positions.mean(0)
|
| 79 |
+
particle = particle[np.sum(particle.positions**2, axis=1) < (diameter / 2) ** 2]
|
| 80 |
+
particle.rotate(axis, (0, 0, 1), center=(0, 0, 0))
|
| 81 |
+
particle.rotate(tilt, "x", center=(0, 0, 0))
|
| 82 |
+
particle.positions += [row * 220, col * 220, 30]
|
| 83 |
+
atoms += particle
|
| 84 |
+
return atoms
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _integrate_detector(
|
| 88 |
+
patterns: cp.ndarray, center: tuple[float, float]
|
| 89 |
+
) -> cp.ndarray:
|
| 90 |
+
"""Translate expected probability and sum four angular samples per axis."""
|
| 91 |
+
from cupyx.scipy.ndimage import shift
|
| 92 |
+
|
| 93 |
+
group = 4
|
| 94 |
+
nominal_center = 100 - (group - 1) / (2 * group)
|
| 95 |
+
displacement = (0, *(group * (v + 4 - nominal_center) for v in center))
|
| 96 |
+
moved = shift(
|
| 97 |
+
patterns, displacement, order=1, mode="constant", cval=0, prefilter=False
|
| 98 |
+
)
|
| 99 |
+
start = (moved.shape[-1] - 800) // 2
|
| 100 |
+
selected = moved[:, start : start + 800, start : start + 800]
|
| 101 |
+
native = selected.reshape(-1, 200, group, 200, group).sum((2, 4))
|
| 102 |
+
return native[:, 4:-4, 4:-4]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def generate_diffraction(
|
| 106 |
+
*,
|
| 107 |
+
scan_side: int = 32,
|
| 108 |
+
diffuse_fraction: float = 0.25,
|
| 109 |
+
diffuse_sigma_mrad: float = 4,
|
| 110 |
+
) -> tuple[cp.ndarray, Atoms, dict]:
|
| 111 |
+
"""Generate a static Au scan with an assumed liquid-inspired angular response.
|
| 112 |
+
|
| 113 |
+
Parameters
|
| 114 |
+
----------
|
| 115 |
+
scan_side : int, optional
|
| 116 |
+
Native scan positions per axis, at least 32, over the 220 Å cell.
|
| 117 |
+
diffuse_fraction : float, optional
|
| 118 |
+
Fraction redistributed by an assumed Gaussian angular response.
|
| 119 |
+
diffuse_sigma_mrad : float, optional
|
| 120 |
+
Standard deviation of that response in milliradians.
|
| 121 |
+
|
| 122 |
+
Returns
|
| 123 |
+
-------
|
| 124 |
+
probability : cupy.ndarray
|
| 125 |
+
CUDA probability per incident electron, shaped
|
| 126 |
+
``(scan_row, scan_col, 192, 192)``. No dose or noise is applied.
|
| 127 |
+
atoms : ase.Atoms
|
| 128 |
+
Static oriented Au coordinates, suitable for provenance export.
|
| 129 |
+
geometry : dict
|
| 130 |
+
Geometry, native/accelerated parity, assumptions and scan timing.
|
| 131 |
+
|
| 132 |
+
Notes
|
| 133 |
+
-----
|
| 134 |
+
The infinite projection,
|
| 135 |
+
static lattice and illustrative diffuse response are not an atomistic
|
| 136 |
+
liquid model or a detector calibration.
|
| 137 |
+
"""
|
| 138 |
+
import time
|
| 139 |
+
import abtem
|
| 140 |
+
import abtem_cuda
|
| 141 |
+
import numpy as np
|
| 142 |
+
from cupyx.scipy.signal import fftconvolve
|
| 143 |
+
|
| 144 |
+
if not isinstance(scan_side, int) or scan_side < 32:
|
| 145 |
+
raise ValueError("Use scan_side >= 32 to retain the nanobeam sampling bound.")
|
| 146 |
+
if not 0 <= diffuse_fraction <= 1 or diffuse_sigma_mrad <= 0:
|
| 147 |
+
raise ValueError("Use diffuse_fraction in [0, 1] and positive angular width.")
|
| 148 |
+
abtem.config.set({"device": "gpu"})
|
| 149 |
+
atoms = _gold_scene()
|
| 150 |
+
potential = abtem.Potential(
|
| 151 |
+
atoms,
|
| 152 |
+
gpts=(1728, 1728),
|
| 153 |
+
slice_thickness=2,
|
| 154 |
+
projection="infinite",
|
| 155 |
+
parametrization="lobato",
|
| 156 |
+
device="gpu",
|
| 157 |
+
integrator=_CudaLobatoIntegrals(),
|
| 158 |
+
)
|
| 159 |
+
probe = abtem.Probe(
|
| 160 |
+
energy=300e3,
|
| 161 |
+
semiangle_cutoff=0.622,
|
| 162 |
+
defocus=0,
|
| 163 |
+
device="gpu",
|
| 164 |
+
gpts=(1728, 1728),
|
| 165 |
+
extent=(220, 220),
|
| 166 |
+
)
|
| 167 |
+
coordinates = np.arange(scan_side) * 220 / scan_side
|
| 168 |
+
positions = np.stack(
|
| 169 |
+
np.meshgrid(coordinates, coordinates, indexing="ij"), -1
|
| 170 |
+
).reshape(-1, 2)
|
| 171 |
+
check_positions = np.asarray([[55, 59.4], [143, 132], [154, 33], [10, 10]])
|
| 172 |
+
detector = abtem.PixelatedDetector(max_angle=50, to_cpu=False)
|
| 173 |
+
abtem_cuda.disable()
|
| 174 |
+
native = (
|
| 175 |
+
probe.scan(
|
| 176 |
+
potential, scan=abtem.CustomScan(check_positions), detectors=detector
|
| 177 |
+
)
|
| 178 |
+
.compute()
|
| 179 |
+
.array
|
| 180 |
+
)
|
| 181 |
+
accelerated = abtem_cuda.scan_patterns(
|
| 182 |
+
potential, probe, check_positions, 50, batch=3, exactness="bit"
|
| 183 |
+
)
|
| 184 |
+
if not isinstance(native, cp.ndarray) or not isinstance(accelerated, cp.ndarray):
|
| 185 |
+
raise RuntimeError("abTEM returned host patterns; GPU execution is required.")
|
| 186 |
+
difference = cp.abs(native - accelerated)
|
| 187 |
+
parity = dict(
|
| 188 |
+
bit_identical=bool(cp.array_equal(native, accelerated)),
|
| 189 |
+
max_abs_error=float(difference.max()),
|
| 190 |
+
relative_l2=float(cp.linalg.norm(difference) / cp.linalg.norm(native)),
|
| 191 |
+
)
|
| 192 |
+
if not parity["bit_identical"]:
|
| 193 |
+
raise RuntimeError(f"Native and accelerated Au patterns differ: {parity}.")
|
| 194 |
+
angular_sampling = float(probe.wavelength / 220 * 1000)
|
| 195 |
+
radius = int(np.ceil(5 * diffuse_sigma_mrad / angular_sampling))
|
| 196 |
+
axis = cp.arange(-radius, radius + 1, dtype=cp.float32) * angular_sampling
|
| 197 |
+
kernel = cp.exp(
|
| 198 |
+
-(axis[:, None] ** 2 + axis[None, :] ** 2) / (2 * diffuse_sigma_mrad**2)
|
| 199 |
+
)
|
| 200 |
+
kernel *= diffuse_fraction / kernel.sum()
|
| 201 |
+
kernel[radius, radius] += 1 - diffuse_fraction
|
| 202 |
+
center = (98.56053351439273, 100.36161400706591)
|
| 203 |
+
resident = abtem_cuda.resident_potential(potential, probe.energy)
|
| 204 |
+
output = cp.empty((len(positions), 192, 192), dtype=cp.float32)
|
| 205 |
+
cp.cuda.Stream.null.synchronize()
|
| 206 |
+
started = time.perf_counter()
|
| 207 |
+
for first in range(0, len(positions), 3):
|
| 208 |
+
fine = abtem_cuda.scan_patterns(
|
| 209 |
+
resident, probe, positions[first : first + 3], 50, batch=3, exactness="bit"
|
| 210 |
+
)
|
| 211 |
+
hybrid = fftconvolve(fine, kernel[None], mode="same", axes=(-2, -1))
|
| 212 |
+
output[first : first + len(fine)] = _integrate_detector(
|
| 213 |
+
cp.maximum(hybrid, 0), center
|
| 214 |
+
)
|
| 215 |
+
cp.cuda.Stream.null.synchronize()
|
| 216 |
+
geometry = dict(
|
| 217 |
+
scan_shape=[scan_side, scan_side],
|
| 218 |
+
detector_shape=[192, 192],
|
| 219 |
+
detector_center=list(center),
|
| 220 |
+
radius_100_percent=96,
|
| 221 |
+
scan_step_A=220 / scan_side,
|
| 222 |
+
cell_A=[220, 220, 60],
|
| 223 |
+
energy_eV=300000,
|
| 224 |
+
semiangle_mrad=0.622,
|
| 225 |
+
defocus_A=0,
|
| 226 |
+
grid=[1728, 1728],
|
| 227 |
+
slice_thickness_A=list(resident.slice_thickness),
|
| 228 |
+
angular_sampling_mrad=4 * angular_sampling,
|
| 229 |
+
detector_integration="4x4 simulated angular samples; native 192x192 output",
|
| 230 |
+
projection="infinite",
|
| 231 |
+
lattice="static; no frozen phonon convergence",
|
| 232 |
+
diffuse_fraction=diffuse_fraction,
|
| 233 |
+
diffuse_sigma_mrad=diffuse_sigma_mrad,
|
| 234 |
+
liquid_model="assumed angular convolution, not atomistic liquid/window physics",
|
| 235 |
+
abtem_parity=parity,
|
| 236 |
+
scan_seconds=time.perf_counter() - started,
|
| 237 |
+
timing_scope="propagation, diffuse response, detector integration; excludes setup/parity",
|
| 238 |
+
axis_convention="abTEM x,y mapped to scan/detector row,col in this example",
|
| 239 |
+
realism="physically motivated synthetic; not validated ARINA or matched to Serin",
|
| 240 |
+
)
|
| 241 |
+
return output.reshape(scan_side, scan_side, 192, 192), atoms, geometry
|
denoise/synthetic_detector.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regenerate tutorial measurements from shared abTEM truth on CUDA.
|
| 2 |
+
|
| 3 |
+
This is tutorial support, not a detector calibration implementation. Denova's
|
| 4 |
+
public simulator draws the measurements; its calibration API independently
|
| 5 |
+
fits the saved dark and flat exposures in the notebook.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from quantem.gpu import io as qio
|
| 13 |
+
|
| 14 |
+
from denova import load
|
| 15 |
+
from denova.fourdstem import simulate
|
| 16 |
+
from denova.noise import PoissonGaussian
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
RECIPE = {
|
| 20 |
+
"detector_shape": [192, 192],
|
| 21 |
+
"gain": 1.5, "gain_modulation": 0.04,
|
| 22 |
+
"gain_row_scale": 13, "gain_col_scale": 19,
|
| 23 |
+
"offset": 2, "offset_modulation": 0.15, "offset_row_scale": 21,
|
| 24 |
+
"read_noise_sd": 0.6, "max_events": 32768,
|
| 25 |
+
"invalid_pixels": [[12, 22], [30, 161], [150, 32], [177, 170]],
|
| 26 |
+
"science_seed": 1000, "dark_seed": 2000, "flat_seed": 2001,
|
| 27 |
+
"check_seed": 2002, "dark_repeats": 512, "flat_repeats": 256,
|
| 28 |
+
"check_repeats": 128, "flat_levels": [1., 16., 256., 4096., 32768.],
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def detector_model(recipe: dict[str, object]) -> PoissonGaussian:
|
| 33 |
+
"""Construct the declared synthetic detector maps on CUDA.
|
| 34 |
+
|
| 35 |
+
Parameters
|
| 36 |
+
----------
|
| 37 |
+
recipe : dict
|
| 38 |
+
Numerical parameters from the example's ``noise-recipe.json``.
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
-------
|
| 42 |
+
PoissonGaussian
|
| 43 |
+
Known generator, used for simulation and final truth evaluation only.
|
| 44 |
+
Reconstruction uses a separate model fitted from dark/flat repeats.
|
| 45 |
+
|
| 46 |
+
Examples
|
| 47 |
+
--------
|
| 48 |
+
>>> known = detector_model(RECIPE)
|
| 49 |
+
"""
|
| 50 |
+
detector_rows, detector_cols = recipe["detector_shape"]
|
| 51 |
+
row_t, col_t = torch.meshgrid(
|
| 52 |
+
torch.arange(detector_rows, device="cuda"),
|
| 53 |
+
torch.arange(detector_cols, device="cuda"), indexing="ij",
|
| 54 |
+
)
|
| 55 |
+
gain_t = recipe["gain"] * (
|
| 56 |
+
1 + recipe["gain_modulation"]
|
| 57 |
+
* torch.sin(row_t / recipe["gain_row_scale"])
|
| 58 |
+
* torch.cos(col_t / recipe["gain_col_scale"])
|
| 59 |
+
)
|
| 60 |
+
offset_t = recipe["offset"] + recipe["offset_modulation"] * torch.cos(
|
| 61 |
+
row_t / recipe["offset_row_scale"]
|
| 62 |
+
).expand(detector_rows, detector_cols)
|
| 63 |
+
read_t = torch.full_like(gain_t, recipe["read_noise_sd"])
|
| 64 |
+
valid_t = torch.ones_like(gain_t, dtype=torch.bool)
|
| 65 |
+
invalid_t = torch.tensor(recipe["invalid_pixels"], device="cuda")
|
| 66 |
+
valid_t[invalid_t[:, 0], invalid_t[:, 1]] = False
|
| 67 |
+
return PoissonGaussian(
|
| 68 |
+
gain_t, offset_t, read_t, valid_t, recipe["max_events"],
|
| 69 |
+
calibration={"method": "assumed synthetic generator, not hardware fit"},
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def prepare_measurements(source: Path, output: Path, *, dose: float = 1.0) -> Path:
|
| 74 |
+
"""Generate one science observation and independent calibration repeats.
|
| 75 |
+
|
| 76 |
+
Parameters
|
| 77 |
+
----------
|
| 78 |
+
source : pathlib.Path
|
| 79 |
+
Downloaded folder with abTEM event truth, geometry and noise recipe.
|
| 80 |
+
output : pathlib.Path
|
| 81 |
+
Local output directory outside the read-only download cache. Existing
|
| 82 |
+
files of the same names are regenerated with the declared seeds.
|
| 83 |
+
dose : float, optional
|
| 84 |
+
Positive relative exposure multiplier. The default is 1.0.
|
| 85 |
+
|
| 86 |
+
Returns
|
| 87 |
+
-------
|
| 88 |
+
pathlib.Path
|
| 89 |
+
Folder of QuantEM.GPU HDF5 measurements and locally generated maps.
|
| 90 |
+
Neither abTEM nor abtem-cuda is required for this step.
|
| 91 |
+
|
| 92 |
+
Examples
|
| 93 |
+
--------
|
| 94 |
+
>>> data = prepare_measurements(source, Path("4dstem-results/inputs"))
|
| 95 |
+
"""
|
| 96 |
+
recipe = json.loads((source / "noise-recipe.json").read_text())
|
| 97 |
+
geometry = json.loads((source / "geometry.json").read_text())
|
| 98 |
+
output.mkdir(parents=True, exist_ok=True)
|
| 99 |
+
known = detector_model(recipe)
|
| 100 |
+
scan_rows, scan_cols = geometry["scan_shape"]
|
| 101 |
+
truth = load(
|
| 102 |
+
source / "truth-events-dose-1.0_master.h5",
|
| 103 |
+
scan_region=(0, scan_rows, 0, scan_cols),
|
| 104 |
+
)
|
| 105 |
+
observed_t = simulate(
|
| 106 |
+
dose * truth.array, noise=known, seed=recipe["science_seed"],
|
| 107 |
+
)
|
| 108 |
+
axis_metadata = {
|
| 109 |
+
"sampling": [geometry["scan_step_A"]] * 2
|
| 110 |
+
+ [geometry["angular_sampling_mrad"]] * 2,
|
| 111 |
+
"units": ["angstrom", "angstrom", "mrad", "mrad"],
|
| 112 |
+
"origin": [0., 0., *[-v * geometry["angular_sampling_mrad"]
|
| 113 |
+
for v in geometry["detector_center"]]],
|
| 114 |
+
"intensity_units": "ADU",
|
| 115 |
+
}
|
| 116 |
+
qio.save(
|
| 117 |
+
output / f"dose-{dose:.1f}_master.h5", observed_t, metadata=axis_metadata,
|
| 118 |
+
)
|
| 119 |
+
dark_t = simulate(
|
| 120 |
+
torch.zeros(
|
| 121 |
+
(recipe["dark_repeats"], *recipe["detector_shape"]), device="cuda",
|
| 122 |
+
),
|
| 123 |
+
noise=known, seed=recipe["dark_seed"],
|
| 124 |
+
)
|
| 125 |
+
levels_t = torch.tensor(recipe["flat_levels"], device="cuda")
|
| 126 |
+
flats_t = simulate(
|
| 127 |
+
levels_t[:, None, None, None].expand(
|
| 128 |
+
-1, recipe["flat_repeats"], *recipe["detector_shape"],
|
| 129 |
+
),
|
| 130 |
+
noise=known, seed=recipe["flat_seed"],
|
| 131 |
+
)
|
| 132 |
+
qio.save(
|
| 133 |
+
output / "dark_master.h5", dark_t[None],
|
| 134 |
+
metadata={"exposure_axes": "dark_set, repeat, detector_row, detector_col"},
|
| 135 |
+
)
|
| 136 |
+
qio.save(
|
| 137 |
+
output / "flats_master.h5", flats_t,
|
| 138 |
+
metadata={
|
| 139 |
+
"exposure_axes": "illumination_level, repeat, detector_row, detector_col",
|
| 140 |
+
},
|
| 141 |
+
)
|
| 142 |
+
torch.save(known.valid, output / "detector-valid.pt")
|
| 143 |
+
known.save(output / "generator-only.pt")
|
| 144 |
+
(output / "geometry.json").write_text(json.dumps(geometry, indent=2) + "\n")
|
| 145 |
+
return output
|