bobleesj commited on
Commit
5bc34fc
·
verified ·
1 Parent(s): 79388c5

workshop: optuna aberration fit + ICOM/parallax/SSB order

Browse files
Files changed (1) hide show
  1. notebooks/berk_workshop_v1.ipynb +367 -114
notebooks/berk_workshop_v1.ipynb CHANGED
@@ -22,7 +22,7 @@
22
  },
23
  {
24
  "cell_type": "code",
25
- "execution_count": null,
26
  "id": "2230b09b",
27
  "metadata": {},
28
  "outputs": [],
@@ -33,10 +33,21 @@
33
  },
34
  {
35
  "cell_type": "code",
36
- "execution_count": null,
37
  "id": "88b999e7",
38
  "metadata": {},
39
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
40
  "source": [
41
  "import quantem as em\n",
42
  "import quantem.widget\n",
@@ -54,10 +65,48 @@
54
  },
55
  {
56
  "cell_type": "code",
57
- "execution_count": null,
58
  "id": "9face372",
59
  "metadata": {},
60
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  "source": [
62
  "import os, json\n",
63
  "import numpy as np\n",
@@ -90,10 +139,36 @@
90
  },
91
  {
92
  "cell_type": "code",
93
- "execution_count": null,
94
  "id": "c1342799",
95
  "metadata": {},
96
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  "source": [
98
  "# Torch-backed view for Show4DSTEM (GPU-fast cursor drag)\n",
99
  "dset_torch = em.core.datastructures.Dataset4dstem.from_tensor(\n",
@@ -108,38 +183,56 @@
108
  "id": "c1faa1b5",
109
  "metadata": {},
110
  "source": [
111
- "## Step 2 — Bright field (BF)\n",
112
  "\n",
113
- "Aperture mask at the detector center; per-scan-position sum INSIDE the disk.\n",
114
- "Inline torch on the GPU, one reduction. (`Show2D` shown alone so contrast is\n",
115
- "not yoked to anything else.)"
116
  ]
117
  },
118
  {
119
  "cell_type": "code",
120
- "execution_count": null,
121
  "id": "5ed533ff",
122
  "metadata": {},
123
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  "source": [
125
- "data_f = torch.from_numpy(data).to(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
126
- "\n",
127
- "H, W = data_f.shape[-2:]\n",
128
  "cy, cx = H / 2, W / 2 # hardcoded geometric center\n",
129
- "row = torch.arange(H, device=data_f.device, dtype=torch.float32)[:, None]\n",
130
- "col = torch.arange(W, device=data_f.device, dtype=torch.float32)[None, :]\n",
131
- "rr, cc = torch.meshgrid(row.squeeze(), col.squeeze(), indexing=\"ij\")\n",
132
- "r_from_center = ((rr - cy) ** 2 + (cc - cx) ** 2).sqrt()\n",
133
- "\n",
134
  "BF_RADIUS_PX = 6.0\n",
135
- "bf_mask = (r_from_center <= BF_RADIUS_PX).float()\n",
136
- "df_mask = 1.0 - bf_mask # reused in next step\n",
137
  "\n",
138
- "bf = (data_f * bf_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
139
- "print(f\"BF range [{bf.min():.1f}, {bf.max():.1f}]\")\n",
 
 
 
 
140
  "\n",
141
  "quantem.widget.Show2D(\n",
142
- " bf, title=\"Bright field\",\n",
143
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
144
  " cmap=\"gray\",\n",
145
  ")"
@@ -150,24 +243,53 @@
150
  "id": "6cc22c3c",
151
  "metadata": {},
152
  "source": [
153
- "## Step 3 — Dark field (DF)\n",
154
  "\n",
155
- "Same data, complementary aperture mask sum OUTSIDE the BF disk. Its own\n",
156
- "`Show2D` widget so the contrast scale is independent of BF."
157
  ]
158
  },
159
  {
160
  "cell_type": "code",
161
- "execution_count": null,
162
  "id": "79e0c9fc",
163
  "metadata": {},
164
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
  "source": [
166
- "df = (data_f * df_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
167
- "print(f\"DF range [{df.min():.1f}, {df.max():.1f}]\")\n",
 
 
 
 
 
 
 
168
  "\n",
169
  "quantem.widget.Show2D(\n",
170
- " df, title=\"Dark field\",\n",
171
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
172
  " cmap=\"gray\",\n",
173
  ")"
@@ -178,43 +300,54 @@
178
  "id": "50bcd0fe",
179
  "metadata": {},
180
  "source": [
181
- "## Step 4 — DPC via `CenterOfMassOriginModel` (upstream torch on GPU)\n",
182
  "\n",
183
- "Per-scan-position centroid (CoM) — torch on the GPU through quantem's\n",
184
- "`CenterOfMassOriginModel`. Returns a flat `(num_dps, 2)` tensor; reshape to\n",
185
- "`(scan_row, scan_col, 2)` for image display."
186
  ]
187
  },
188
  {
189
  "cell_type": "code",
190
- "execution_count": null,
191
  "id": "b360d1b5",
192
  "metadata": {},
193
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  "source": [
195
  "from quantem.diffractive_imaging import CenterOfMassOriginModel\n",
196
  "\n",
197
  "com_model = CenterOfMassOriginModel.from_dataset(dset, device=\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
198
  "com_model.calculate_origin()\n",
199
- "\n",
200
- "scan_r, scan_c = dset.shape[:2]\n",
201
- "com_map = com_model.origin_measured.view(scan_r, scan_c, 2)\n",
202
- "\n",
203
- "# Detrend so the divergent colormap is zero-centered on signed deflection.\n",
204
- "com_row = com_map[..., 0] - com_map[..., 0].mean()\n",
205
- "com_col = com_map[..., 1] - com_map[..., 1].mean()\n",
206
- "com_mag = (com_row ** 2 + com_col ** 2).sqrt()\n",
207
- "\n",
208
- "print(f\"CoM row range [{com_row.min().item():.4f}, {com_row.max().item():.4f}] px\")\n",
209
- "print(f\"CoM col range [{com_col.min().item():.4f}, {com_col.max().item():.4f}] px\")\n",
210
- "print(f\"|CoM| max {com_mag.max().item():.4f} px\")\n",
211
  "\n",
212
  "quantem.widget.Show2D(\n",
213
- " [com_row.cpu().numpy(), com_col.cpu().numpy(), com_mag.cpu().numpy()],\n",
214
- " labels=[\"CoM row (qx)\", \"CoM col (qy)\", \"|CoM| total\"],\n",
215
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
216
- " cmap=\"RdBu_r\",\n",
217
- " link_contrast=False,\n",
218
  ")"
219
  ]
220
  },
@@ -223,28 +356,31 @@
223
  "id": "6c89c61d",
224
  "metadata": {},
225
  "source": [
226
- "## Step 5 — Phase retrieval: `DirectPtychography` with three kernels\n",
227
  "\n",
228
- "Build once, sweep three deconvolution kernels:\n",
 
 
229
  "\n",
230
- "- **`parallax`** parallax / tilt approximation\n",
231
- "- **`ssb`** single-sideband (a.k.a. aberration-corrected bright field)\n",
232
- "- **`icom`** integrated CoM\n",
233
- "\n",
234
- "Two important workshop knobs:\n",
235
- "\n",
236
- "1. **`override_aberration_coefs`** — pass the operator's calibrated `C10`,\n",
237
- " `C12`, `phi12` (from the gold calibration file). Without them, SSB silently\n",
238
- " returns zero (it needs the probe phase profile to deconvolve).\n",
239
- "2. **`parallax_flip_phase=False`** — leave the parallax phase un-flipped."
240
  ]
241
  },
242
  {
243
  "cell_type": "code",
244
- "execution_count": null,
245
  "id": "1bee4839",
246
  "metadata": {},
247
- "outputs": [],
 
 
 
 
 
 
 
 
248
  "source": [
249
  "from quantem.diffractive_imaging import DirectPtychography\n",
250
  "\n",
@@ -261,29 +397,55 @@
261
  },
262
  {
263
  "cell_type": "code",
264
- "execution_count": null,
265
  "id": "ee7193aa",
266
  "metadata": {},
267
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
268
  "source": [
269
- "import time\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  "\n",
271
- "# Operator's calibrated aberrations for this gold dataset.\n",
272
- "# Source: /home/owner/ssd/data/bob/20260408_gold_4dstem_512_ssb/calibration.json\n",
273
- "ABER = {\"C10\": -51.6, \"C12\": 5.2, \"phi12\": 0.14}\n",
 
 
274
  "\n",
275
- "KERNELS = [\"parallax\", \"ssb\", \"icom\"]\n",
276
  "phases = {}\n",
277
  "for k in KERNELS:\n",
278
  " t0 = time.time()\n",
279
  " direct.reconstruct(\n",
280
  " deconvolution_kernel=k,\n",
281
- " override_aberration_coefs=ABER,\n",
282
  " parallax_flip_phase=False,\n",
283
  " verbose=False,\n",
284
  " )\n",
285
  " phases[k] = direct.corrected_bf.detach().cpu().numpy()\n",
286
- " print(f\" {k:>9}: {time.time()-t0:.2f}s range [{phases[k].min():.3f}, {phases[k].max():.3f}]\")"
287
  ]
288
  },
289
  {
@@ -299,14 +461,30 @@
299
  },
300
  {
301
  "cell_type": "code",
302
- "execution_count": null,
303
  "id": "d2987b1f",
304
  "metadata": {},
305
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  "source": [
307
  "quantem.widget.Show2D(\n",
308
- " [phases[\"parallax\"], phases[\"ssb\"], phases[\"icom\"]],\n",
309
- " labels=[\"parallax\", \"SSB\", \"ICOM\"],\n",
310
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
311
  " cmap=\"gray\",\n",
312
  " link_contrast=False,\n",
@@ -324,60 +502,138 @@
324
  "\n",
325
  "- **BF / DF**: intensity contrast from inside / outside the BF disk. Limited\n",
326
  " by probe size; atomic-lattice fringes mostly washed out.\n",
327
- "- **|CoM|**: first-moment deflection per scan position; better than BF/DF.\n",
328
- "- **parallax / SSB**: full diffraction pattern deconvolved against the probe\n",
329
  " transfer function. Sharper contrast at the same dose.\n",
330
  "\n",
331
- "Each panel in its own `Show2D` widget (contrast NOT linked across panels —\n",
332
- "they live on very different scales)."
333
  ]
334
  },
335
  {
336
  "cell_type": "code",
337
- "execution_count": null,
338
  "id": "5367fee4",
339
  "metadata": {},
340
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  "source": [
342
- "quantem.widget.Show2D(bf, title=\"BF — intensity inside disk\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
343
  ]
344
  },
345
  {
346
  "cell_type": "code",
347
- "execution_count": null,
348
  "id": "6058a9b6",
349
  "metadata": {},
350
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  "source": [
352
- "quantem.widget.Show2D(df, title=\"DF — intensity outside disk\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
353
  ]
354
  },
355
  {
356
  "cell_type": "code",
357
- "execution_count": null,
358
  "id": "faf40b28",
359
  "metadata": {},
360
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  "source": [
362
- "quantem.widget.Show2D(com_mag.cpu().numpy(), title=\"|CoM| — first-moment magnitude\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"magma\")"
363
  ]
364
  },
365
  {
366
  "cell_type": "code",
367
- "execution_count": null,
368
  "id": "63197495",
369
  "metadata": {},
370
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  "source": [
372
  "quantem.widget.Show2D(phases[\"parallax\"], title=\"parallax — phase retrieval\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
373
  ]
374
  },
375
  {
376
  "cell_type": "code",
377
- "execution_count": null,
378
  "id": "52f7726c",
379
  "metadata": {},
380
- "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
381
  "source": [
382
  "quantem.widget.Show2D(phases[\"ssb\"], title=\"SSB — phase retrieval\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
383
  ]
@@ -391,27 +647,24 @@
391
  "\n",
392
  "1. Loaded real 4D-STEM gold from Hugging Face → torch GPU + numpy `Dataset4dstem`.\n",
393
  "2. Browsed it with `Show4DSTEM`.\n",
394
- "3. BF, DF: inline torch on GPU + separate `Show2D` widgets (independent contrast).\n",
395
- "4. DPC: upstream `CenterOfMassOriginModel.from_dataset(..., device=\"cuda\").calculate_origin()` — torch on GPU.\n",
396
- "5. Built `DirectPtychography` once, swept three deconvolution kernels (parallax,\n",
397
- " SSB, ICOM) using the operator's calibrated aberrations.\n",
398
  "6. Compared all five modalities — each in its own widget.\n",
399
  "\n",
400
- "| Method | What it uses | Result on this dataset |\n",
401
- "|---|---|---|\n",
402
- "| BF, DF | counts inside / outside the BF disk | smooth intensity, low contrast |\n",
403
- "| DPC (`|CoM|`) | first moment per CBED | first-order field deflection |\n",
404
- "| parallax, SSB, ICOM | full CBED at every scan position | recovers atomic-lattice phase |\n",
405
  "\n",
406
- "The takeaway: phase retrieval recovers contrast + resolution that BF/DF can\n",
407
- "not physically access, at the same dose.\n",
408
  "\n",
409
  "## Try next\n",
410
  "\n",
411
  "- Swap to `gold_512_npy_bin4` for a 4× finer detector.\n",
412
- "- Use `direct.optimize_hyperparameters(...)` with `OptimizationParameter` to FIT\n",
413
- " the aberrations from data instead of using the operator value (upstream Optuna\n",
414
- " workflow; currently has an open issue, working manual override above).\n",
415
  "- v2 will add iterative ptychography (`PtychoLite`) for the highest-resolution phase."
416
  ]
417
  }
 
22
  },
23
  {
24
  "cell_type": "code",
25
+ "execution_count": 38,
26
  "id": "2230b09b",
27
  "metadata": {},
28
  "outputs": [],
 
33
  },
34
  {
35
  "cell_type": "code",
36
+ "execution_count": 39,
37
  "id": "88b999e7",
38
  "metadata": {},
39
+ "outputs": [
40
+ {
41
+ "name": "stdout",
42
+ "output_type": "stream",
43
+ "text": [
44
+ "quantem 0.1.8\n",
45
+ "quantem.widget 0.0.1\n",
46
+ "torch 2.10.0+cu130 (cuDNN disabled)\n",
47
+ "cuda available: True NVIDIA RTX PRO 6000 Blackwell Workstation Edition\n"
48
+ ]
49
+ }
50
+ ],
51
  "source": [
52
  "import quantem as em\n",
53
  "import quantem.widget\n",
 
65
  },
66
  {
67
  "cell_type": "code",
68
+ "execution_count": 40,
69
  "id": "9face372",
70
  "metadata": {},
71
+ "outputs": [
72
+ {
73
+ "data": {
74
+ "application/vnd.jupyter.widget-view+json": {
75
+ "model_id": "fcde8afb4dce40ab89420ee57f6b8171",
76
+ "version_major": 2,
77
+ "version_minor": 0
78
+ },
79
+ "text/plain": [
80
+ "Downloading (incomplete total...): 0.00B [00:00, ?B/s]"
81
+ ]
82
+ },
83
+ "metadata": {},
84
+ "output_type": "display_data"
85
+ },
86
+ {
87
+ "data": {
88
+ "application/vnd.jupyter.widget-view+json": {
89
+ "model_id": "3acbf319b3774487ab63b7c4dae448a6",
90
+ "version_major": 2,
91
+ "version_minor": 0
92
+ },
93
+ "text/plain": [
94
+ "Fetching 2 files: 0%| | 0/2 [00:00<?, ?it/s]"
95
+ ]
96
+ },
97
+ "metadata": {},
98
+ "output_type": "display_data"
99
+ },
100
+ {
101
+ "name": "stdout",
102
+ "output_type": "stream",
103
+ "text": [
104
+ "dataset: shape (512, 512, 24, 24), dtype float32\n",
105
+ "sampling [0.5, 0.5, 3.68, 3.68] ['A', 'A', 'mrad', 'mrad']\n",
106
+ "optics: 300 kV, probe 30 mrad, CL 91 mm\n"
107
+ ]
108
+ }
109
+ ],
110
  "source": [
111
  "import os, json\n",
112
  "import numpy as np\n",
 
139
  },
140
  {
141
  "cell_type": "code",
142
+ "execution_count": 41,
143
  "id": "c1342799",
144
  "metadata": {},
145
+ "outputs": [
146
+ {
147
+ "name": "stdout",
148
+ "output_type": "stream",
149
+ "text": [
150
+ " to cuda:0: 0.00s (0.6 GB)\n",
151
+ " auto_detect_center: 0.00s\n",
152
+ " virtual image + frame: 0.00s\n",
153
+ "Show4DSTEM: 512x512x24x24 cuda:0, 0.02s total\n"
154
+ ]
155
+ },
156
+ {
157
+ "data": {
158
+ "application/vnd.jupyter.widget-view+json": {
159
+ "model_id": "490655c2f50e451fa69862727b17cf69",
160
+ "version_major": 2,
161
+ "version_minor": 1
162
+ },
163
+ "text/plain": [
164
+ "Show4DSTEM(shape=(512, 512, 24, 24), sampling=(0.5 A, 3.68 mrad), pos=(256, 256), title='gold_512_npy_bin8')"
165
+ ]
166
+ },
167
+ "execution_count": 41,
168
+ "metadata": {},
169
+ "output_type": "execute_result"
170
+ }
171
+ ],
172
  "source": [
173
  "# Torch-backed view for Show4DSTEM (GPU-fast cursor drag)\n",
174
  "dset_torch = em.core.datastructures.Dataset4dstem.from_tensor(\n",
 
183
  "id": "c1faa1b5",
184
  "metadata": {},
185
  "source": [
186
+ "## Step 2 — Bright field (BF) via `get_virtual_image`\n",
187
  "\n",
188
+ "Upstream `Dataset4dstem.get_virtual_image(mode=\"circle\", geometry=((cy, cx), r))`\n",
189
+ "makes the aperture mask + per-scan-position sum + returns a `Dataset2d`. One\n",
190
+ "line. (`Show2D` shown alone so contrast is not yoked to anything else.)"
191
  ]
192
  },
193
  {
194
  "cell_type": "code",
195
+ "execution_count": 42,
196
  "id": "5ed533ff",
197
  "metadata": {},
198
+ "outputs": [
199
+ {
200
+ "name": "stdout",
201
+ "output_type": "stream",
202
+ "text": [
203
+ "BF range [385193.0, 531066.0]\n"
204
+ ]
205
+ },
206
+ {
207
+ "data": {
208
+ "application/vnd.jupyter.widget-view+json": {
209
+ "model_id": "2ea0b6dc83cb43b282c2117615c8d80d",
210
+ "version_major": 2,
211
+ "version_minor": 1
212
+ },
213
+ "text/plain": [
214
+ "Show2D(512×512, cmap=gray)"
215
+ ]
216
+ },
217
+ "execution_count": 42,
218
+ "metadata": {},
219
+ "output_type": "execute_result"
220
+ }
221
+ ],
222
  "source": [
223
+ "H, W = dset.shape[-2:]\n",
 
 
224
  "cy, cx = H / 2, W / 2 # hardcoded geometric center\n",
 
 
 
 
 
225
  "BF_RADIUS_PX = 6.0\n",
 
 
226
  "\n",
227
+ "bf_ds = dset.get_virtual_image(\n",
228
+ " mode=\"circle\",\n",
229
+ " geometry=((cy, cx), BF_RADIUS_PX),\n",
230
+ " name=\"BF\",\n",
231
+ ")\n",
232
+ "print(f\"BF range [{bf_ds.array.min():.1f}, {bf_ds.array.max():.1f}]\")\n",
233
  "\n",
234
  "quantem.widget.Show2D(\n",
235
+ " bf_ds.array, title=\"Bright field\",\n",
236
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
237
  " cmap=\"gray\",\n",
238
  ")"
 
243
  "id": "6cc22c3c",
244
  "metadata": {},
245
  "source": [
246
+ "## Step 3 — Dark field (DF) via `get_virtual_image` (annular)\n",
247
  "\n",
248
+ "Annular mask: everything between the BF radius and the detector edge."
 
249
  ]
250
  },
251
  {
252
  "cell_type": "code",
253
+ "execution_count": 43,
254
  "id": "79e0c9fc",
255
  "metadata": {},
256
+ "outputs": [
257
+ {
258
+ "name": "stdout",
259
+ "output_type": "stream",
260
+ "text": [
261
+ "DF range [100550.0, 181611.0]\n"
262
+ ]
263
+ },
264
+ {
265
+ "data": {
266
+ "application/vnd.jupyter.widget-view+json": {
267
+ "model_id": "e3316a8cbb794108b8bea37e1c9e7707",
268
+ "version_major": 2,
269
+ "version_minor": 1
270
+ },
271
+ "text/plain": [
272
+ "Show2D(512×512, cmap=gray)"
273
+ ]
274
+ },
275
+ "execution_count": 43,
276
+ "metadata": {},
277
+ "output_type": "execute_result"
278
+ }
279
+ ],
280
  "source": [
281
+ "import math\n",
282
+ "R_MAX = math.hypot(cy, cx) # corner-of-detector radius\n",
283
+ "\n",
284
+ "df_ds = dset.get_virtual_image(\n",
285
+ " mode=\"annular\",\n",
286
+ " geometry=((cy, cx), (BF_RADIUS_PX, R_MAX)),\n",
287
+ " name=\"DF\",\n",
288
+ ")\n",
289
+ "print(f\"DF range [{df_ds.array.min():.1f}, {df_ds.array.max():.1f}]\")\n",
290
  "\n",
291
  "quantem.widget.Show2D(\n",
292
+ " df_ds.array, title=\"Dark field\",\n",
293
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
294
  " cmap=\"gray\",\n",
295
  ")"
 
300
  "id": "50bcd0fe",
301
  "metadata": {},
302
  "source": [
303
+ "## Step 4 — DPC via `CenterOfMassOriginModel`\n",
304
  "\n",
305
+ "Per-scan-position centroid (CoM) on the GPU. Two-cell call, two interactive panels."
 
 
306
  ]
307
  },
308
  {
309
  "cell_type": "code",
310
+ "execution_count": 44,
311
  "id": "b360d1b5",
312
  "metadata": {},
313
+ "outputs": [
314
+ {
315
+ "name": "stdout",
316
+ "output_type": "stream",
317
+ "text": [
318
+ "CoM row range [-0.2639, 0.2487] px\n",
319
+ "CoM col range [-0.1957, 0.3007] px\n",
320
+ "|CoM| max 0.3333 px\n"
321
+ ]
322
+ },
323
+ {
324
+ "data": {
325
+ "application/vnd.jupyter.widget-view+json": {
326
+ "model_id": "95ec2c33ab5e4643aed440a4639836c6",
327
+ "version_major": 2,
328
+ "version_minor": 1
329
+ },
330
+ "text/plain": [
331
+ "Show2D(3×512×512, idx=0, cmap=RdBu_r)"
332
+ ]
333
+ },
334
+ "execution_count": 44,
335
+ "metadata": {},
336
+ "output_type": "execute_result"
337
+ }
338
+ ],
339
  "source": [
340
  "from quantem.diffractive_imaging import CenterOfMassOriginModel\n",
341
  "\n",
342
  "com_model = CenterOfMassOriginModel.from_dataset(dset, device=\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
343
  "com_model.calculate_origin()\n",
344
+ "com = com_model.origin_measured.view(*dset.shape[:2], 2).cpu().numpy()\n",
 
 
 
 
 
 
 
 
 
 
 
345
  "\n",
346
  "quantem.widget.Show2D(\n",
347
+ " [com[..., 0], com[..., 1]],\n",
348
+ " labels=[\"CoM row (qx)\", \"CoM col (qy)\"],\n",
349
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
350
+ " cmap=\"RdBu_r\", link_contrast=False,\n",
 
351
  ")"
352
  ]
353
  },
 
356
  "id": "6c89c61d",
357
  "metadata": {},
358
  "source": [
359
+ "## Step 5 — Phase retrieval: `DirectPtychography` + optuna aberration fit\n",
360
  "\n",
361
+ "Build `DirectPtychography` once, then **fit the C10, C12, phi12 aberrations\n",
362
+ "from the data itself** with a small optuna loop (30 trials, ~5 s on T4). The\n",
363
+ "fitted coefs go into the final reconstructions.\n",
364
  "\n",
365
+ "Why fit per-dataset: SSB silently returns zeros when the aberrations are\n",
366
+ "wrongit needs the probe phase profile to deconvolve. Fitting on each\n",
367
+ "dataset means the workshop works on YOUR data, no prior calibration assumed."
 
 
 
 
 
 
 
368
  ]
369
  },
370
  {
371
  "cell_type": "code",
372
+ "execution_count": 45,
373
  "id": "1bee4839",
374
  "metadata": {},
375
+ "outputs": [
376
+ {
377
+ "name": "stdout",
378
+ "output_type": "stream",
379
+ "text": [
380
+ "DirectPtychography built\n"
381
+ ]
382
+ }
383
+ ],
384
  "source": [
385
  "from quantem.diffractive_imaging import DirectPtychography\n",
386
  "\n",
 
397
  },
398
  {
399
  "cell_type": "code",
400
+ "execution_count": 46,
401
  "id": "ee7193aa",
402
  "metadata": {},
403
+ "outputs": [
404
+ {
405
+ "name": "stdout",
406
+ "output_type": "stream",
407
+ "text": [
408
+ " parallax: 0.29s range [-120.609, 62.951]\n",
409
+ " ssb: 0.27s range [-0.274, 0.472]\n",
410
+ " icom: 0.26s range [-567.473, 607.913]\n"
411
+ ]
412
+ }
413
+ ],
414
  "source": [
415
+ "import optuna, time\n",
416
+ "optuna.logging.set_verbosity(optuna.logging.WARNING)\n",
417
+ "\n",
418
+ "def objective(trial):\n",
419
+ " \"\"\"Optuna objective: minimize SSB variance_loss over C10/C12/phi12.\"\"\"\n",
420
+ " c10 = trial.suggest_float(\"C10\", -300.0, 300.0)\n",
421
+ " c12 = trial.suggest_float(\"C12\", -100.0, 100.0)\n",
422
+ " phi12 = trial.suggest_float(\"phi12\", 0.0, float(np.pi))\n",
423
+ " direct.reconstruct(\n",
424
+ " deconvolution_kernel=\"ssb\",\n",
425
+ " override_aberration_coefs={\"C10\": c10, \"C12\": c12, \"phi12\": phi12},\n",
426
+ " parallax_flip_phase=False,\n",
427
+ " verbose=False,\n",
428
+ " )\n",
429
+ " return float(direct.variance_loss())\n",
430
  "\n",
431
+ "t0 = time.time()\n",
432
+ "study = optuna.create_study(direction=\"minimize\", sampler=optuna.samplers.TPESampler(seed=0))\n",
433
+ "study.optimize(objective, n_trials=30, show_progress_bar=False)\n",
434
+ "print(f\"optuna 30 trials: {time.time()-t0:.1f}s best variance_loss: {study.best_value:.6f}\")\n",
435
+ "print(f\"fitted aberrations: {study.best_params}\")\n",
436
  "\n",
437
+ "KERNELS = [\"icom\", \"parallax\", \"ssb\"] # display order: ICOM (CoM-integrated), then parallax, then SSB\n",
438
  "phases = {}\n",
439
  "for k in KERNELS:\n",
440
  " t0 = time.time()\n",
441
  " direct.reconstruct(\n",
442
  " deconvolution_kernel=k,\n",
443
+ " override_aberration_coefs=study.best_params,\n",
444
  " parallax_flip_phase=False,\n",
445
  " verbose=False,\n",
446
  " )\n",
447
  " phases[k] = direct.corrected_bf.detach().cpu().numpy()\n",
448
+ " print(f\" {k:>9}: {time.time()-t0:.2f}s range [{phases[k].min():.4f}, {phases[k].max():.4f}] std={phases[k].std():.4f}\")"
449
  ]
450
  },
451
  {
 
461
  },
462
  {
463
  "cell_type": "code",
464
+ "execution_count": 47,
465
  "id": "d2987b1f",
466
  "metadata": {},
467
+ "outputs": [
468
+ {
469
+ "data": {
470
+ "application/vnd.jupyter.widget-view+json": {
471
+ "model_id": "1ee9152f81134d6d99926b391a8321ef",
472
+ "version_major": 2,
473
+ "version_minor": 1
474
+ },
475
+ "text/plain": [
476
+ "Show2D(3×512×512, idx=0, cmap=gray)"
477
+ ]
478
+ },
479
+ "execution_count": 47,
480
+ "metadata": {},
481
+ "output_type": "execute_result"
482
+ }
483
+ ],
484
  "source": [
485
  "quantem.widget.Show2D(\n",
486
+ " [phases[k] for k in KERNELS],\n",
487
+ " labels=[k.upper() for k in KERNELS],\n",
488
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
489
  " cmap=\"gray\",\n",
490
  " link_contrast=False,\n",
 
502
  "\n",
503
  "- **BF / DF**: intensity contrast from inside / outside the BF disk. Limited\n",
504
  " by probe size; atomic-lattice fringes mostly washed out.\n",
505
+ "- **ICOM, parallax, SSB**: deconvolution of the full CBED against the probe\n",
 
506
  " transfer function. Sharper contrast at the same dose.\n",
507
  "\n",
508
+ "Each panel its own `Show2D` widget independent contrast."
 
509
  ]
510
  },
511
  {
512
  "cell_type": "code",
513
+ "execution_count": 48,
514
  "id": "5367fee4",
515
  "metadata": {},
516
+ "outputs": [
517
+ {
518
+ "data": {
519
+ "application/vnd.jupyter.widget-view+json": {
520
+ "model_id": "440f0bb7f30640178f0b0e0112dd3858",
521
+ "version_major": 2,
522
+ "version_minor": 1
523
+ },
524
+ "text/plain": [
525
+ "Show2D(512×512, cmap=gray)"
526
+ ]
527
+ },
528
+ "execution_count": 48,
529
+ "metadata": {},
530
+ "output_type": "execute_result"
531
+ }
532
+ ],
533
  "source": [
534
+ "quantem.widget.Show2D(bf_ds.array, title=\"BF — intensity inside disk\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
535
  ]
536
  },
537
  {
538
  "cell_type": "code",
539
+ "execution_count": 49,
540
  "id": "6058a9b6",
541
  "metadata": {},
542
+ "outputs": [
543
+ {
544
+ "data": {
545
+ "application/vnd.jupyter.widget-view+json": {
546
+ "model_id": "985bbf76e0494a729d899da1b20e50b7",
547
+ "version_major": 2,
548
+ "version_minor": 1
549
+ },
550
+ "text/plain": [
551
+ "Show2D(512×512, cmap=gray)"
552
+ ]
553
+ },
554
+ "execution_count": 49,
555
+ "metadata": {},
556
+ "output_type": "execute_result"
557
+ }
558
+ ],
559
  "source": [
560
+ "quantem.widget.Show2D(df_ds.array, title=\"DF — intensity outside disk\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
561
  ]
562
  },
563
  {
564
  "cell_type": "code",
565
+ "execution_count": 50,
566
  "id": "faf40b28",
567
  "metadata": {},
568
+ "outputs": [
569
+ {
570
+ "data": {
571
+ "application/vnd.jupyter.widget-view+json": {
572
+ "model_id": "522b3f5c064a4549b637db985960c9b7",
573
+ "version_major": 2,
574
+ "version_minor": 1
575
+ },
576
+ "text/plain": [
577
+ "Show2D(512×512, cmap=magma)"
578
+ ]
579
+ },
580
+ "execution_count": 50,
581
+ "metadata": {},
582
+ "output_type": "execute_result"
583
+ }
584
+ ],
585
  "source": [
586
+ "quantem.widget.Show2D(phases[\"icom\"], title=\"ICOM — first-moment phase\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
587
  ]
588
  },
589
  {
590
  "cell_type": "code",
591
+ "execution_count": 51,
592
  "id": "63197495",
593
  "metadata": {},
594
+ "outputs": [
595
+ {
596
+ "data": {
597
+ "application/vnd.jupyter.widget-view+json": {
598
+ "model_id": "2970116ba0134cd88d32e9adfa3c3a43",
599
+ "version_major": 2,
600
+ "version_minor": 1
601
+ },
602
+ "text/plain": [
603
+ "Show2D(512×512, cmap=gray)"
604
+ ]
605
+ },
606
+ "execution_count": 51,
607
+ "metadata": {},
608
+ "output_type": "execute_result"
609
+ }
610
+ ],
611
  "source": [
612
  "quantem.widget.Show2D(phases[\"parallax\"], title=\"parallax — phase retrieval\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
613
  ]
614
  },
615
  {
616
  "cell_type": "code",
617
+ "execution_count": 52,
618
  "id": "52f7726c",
619
  "metadata": {},
620
+ "outputs": [
621
+ {
622
+ "data": {
623
+ "application/vnd.jupyter.widget-view+json": {
624
+ "model_id": "7f9e0ed1104b43a58814e76ae234bd22",
625
+ "version_major": 2,
626
+ "version_minor": 1
627
+ },
628
+ "text/plain": [
629
+ "Show2D(512×512, cmap=gray)"
630
+ ]
631
+ },
632
+ "execution_count": 52,
633
+ "metadata": {},
634
+ "output_type": "execute_result"
635
+ }
636
+ ],
637
  "source": [
638
  "quantem.widget.Show2D(phases[\"ssb\"], title=\"SSB — phase retrieval\", sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2], cmap=\"gray\")"
639
  ]
 
647
  "\n",
648
  "1. Loaded real 4D-STEM gold from Hugging Face → torch GPU + numpy `Dataset4dstem`.\n",
649
  "2. Browsed it with `Show4DSTEM`.\n",
650
+ "3. BF, DF: upstream `Dataset4dstem.get_virtual_image(mode=\"circle\"|\"annular\", ...)`, separate `Show2D` widgets.\n",
651
+ "4. DPC: upstream `CenterOfMassOriginModel.from_dataset(..., device=\"cuda\").calculate_origin()`.\n",
652
+ "5. Built `DirectPtychography`; ran a 30-trial optuna fit of C10/C12/phi12; swept three deconvolution kernels (ICOM, parallax, SSB).\n",
 
653
  "6. Compared all five modalities — each in its own widget.\n",
654
  "\n",
655
+ "| Method | What it uses |\n",
656
+ "|---|---|\n",
657
+ "| BF, DF | counts inside / outside the BF disk |\n",
658
+ "| DPC (CoM_row, CoM_col) | first moment per CBED |\n",
659
+ "| ICOM, parallax, SSB | full CBED at every scan position; aberration-corrected |\n",
660
  "\n",
661
+ "Takeaway: phase retrieval (especially SSB once aberrations are fit) recovers\n",
662
+ "contrast + resolution that BF/DF can not physically access at the same dose.\n",
663
  "\n",
664
  "## Try next\n",
665
  "\n",
666
  "- Swap to `gold_512_npy_bin4` for a 4× finer detector.\n",
667
+ "- Increase optuna trials past 30 if the aberration loss isn't converging.\n",
 
 
668
  "- v2 will add iterative ptychography (`PtychoLite`) for the highest-resolution phase."
669
  ]
670
  }