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

workshop v2: SSB working via aberration override; CoM via upstream model; per-panel Show2D

Browse files
Files changed (1) hide show
  1. notebooks/berk_workshop_v1.ipynb +173 -101
notebooks/berk_workshop_v1.ipynb CHANGED
@@ -2,28 +2,28 @@
2
  "cells": [
3
  {
4
  "cell_type": "markdown",
5
- "id": "4bc9d2fa",
6
  "metadata": {},
7
  "source": [
8
- "# Workshop: real-gold 4D-STEM — browse, BF, DF, DPC, and 5 direct-ptycho kernels (Colab T4)\n",
9
  "\n",
10
  "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/gist/bobleesj/a05a90185c6cddbb331342cae6d7e9c1/berk_workshop_v1.ipynb)\n",
11
  "\n",
12
  "ONE notebook. Real gold from Hugging Face → load → browse → bright field → dark\n",
13
- "field → DPC → all five direct-ptychography kernels (parallax, SSB, OBF, MF, ICOM)\n",
14
- "→ side-by-side comparison.\n",
15
  "\n",
16
- "Everything runs on torch on the Colab T4. Two installs only — `quantem.widget`\n",
17
- "(TestPyPI prerelease) + `quantem` (`berk-workshop` branch on `bobleesj/quantem`).\n",
18
- "No `quantem.live`.\n",
19
  "\n",
20
- "**Total runtime on T4: ~3-4 min** (install dominates)."
 
21
  ]
22
  },
23
  {
24
  "cell_type": "code",
25
  "execution_count": null,
26
- "id": "7343e468",
27
  "metadata": {},
28
  "outputs": [],
29
  "source": [
@@ -34,7 +34,7 @@
34
  {
35
  "cell_type": "code",
36
  "execution_count": null,
37
- "id": "c5cc149e",
38
  "metadata": {},
39
  "outputs": [],
40
  "source": [
@@ -42,7 +42,7 @@
42
  "import quantem.widget\n",
43
  "import torch\n",
44
  "\n",
45
- "# cuDNN grid_sample bug at these detector dims disable for the DirectPtycho path.\n",
46
  "torch.backends.cudnn.enabled = False\n",
47
  "\n",
48
  "print(\"quantem \", em.__version__)\n",
@@ -55,7 +55,7 @@
55
  {
56
  "cell_type": "code",
57
  "execution_count": null,
58
- "id": "fb1fd0b9",
59
  "metadata": {},
60
  "outputs": [],
61
  "source": [
@@ -69,8 +69,7 @@
69
  "data = np.ascontiguousarray(np.load(os.path.join(asset, \"data.npy\")).astype(np.float32))\n",
70
  "meta = json.load(open(os.path.join(asset, \"meta.json\")))\n",
71
  "\n",
72
- "# Numpy-backed Dataset4dstem feeds both Show4DSTEM (via torch tensor) and\n",
73
- "# DirectPtychography (which reads dataset.array internally).\n",
74
  "dset = em.core.datastructures.Dataset4dstem.from_array(\n",
75
  " data, sampling=meta[\"sampling\"], units=meta[\"units\"], name=meta[\"name\"],\n",
76
  ")\n",
@@ -81,22 +80,22 @@
81
  },
82
  {
83
  "cell_type": "markdown",
84
- "id": "4e03791e",
85
  "metadata": {},
86
  "source": [
87
  "## Step 1 — Browse the 4D-STEM dataset interactively\n",
88
  "\n",
89
- "Drag the scan cursor; CBED updates live. This is real-time per-scan-position BF/DF."
90
  ]
91
  },
92
  {
93
  "cell_type": "code",
94
  "execution_count": null,
95
- "id": "847d780a",
96
  "metadata": {},
97
  "outputs": [],
98
  "source": [
99
- "# Build a torch-backed view for Show4DSTEM so cursor drag is GPU-fast.\n",
100
  "dset_torch = em.core.datastructures.Dataset4dstem.from_tensor(\n",
101
  " torch.from_numpy(data).to(\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n",
102
  " sampling=meta[\"sampling\"], units=meta[\"units\"], name=meta[\"name\"],\n",
@@ -106,71 +105,69 @@
106
  },
107
  {
108
  "cell_type": "markdown",
109
- "id": "0d59a9e8",
110
  "metadata": {},
111
  "source": [
112
- "## Step 2 — Bright field, dark field, DPC (inline torch on GPU)\n",
113
  "\n",
114
- "Hardcode aperture at the detector center. One torch reduction per panel."
 
 
115
  ]
116
  },
117
  {
118
  "cell_type": "code",
119
  "execution_count": null,
120
- "id": "a22b761f",
121
  "metadata": {},
122
  "outputs": [],
123
  "source": [
124
  "data_f = torch.from_numpy(data).to(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
125
  "\n",
126
- "# Detector grid + hardcoded aperture center (geometric).\n",
127
  "H, W = data_f.shape[-2:]\n",
128
- "cy, cx = H / 2, W / 2\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 + DF\n",
135
  "BF_RADIUS_PX = 6.0\n",
136
  "bf_mask = (r_from_center <= BF_RADIUS_PX).float()\n",
137
- "df_mask = 1.0 - bf_mask\n",
138
- "bf = (data_f * bf_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
139
- "df = (data_f * df_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
140
  "\n",
141
- "# CoM / DPC — per-scan-position centroid (qx, qy) → row, col deflection + magnitude\n",
142
- "qx = row.expand(H, W)\n",
143
- "qy = col.expand(H, W)\n",
144
- "total_per_dp = data_f.sum(dim=(-2, -1))\n",
145
- "com_row = (data_f * qx).sum(dim=(-2, -1)) / total_per_dp\n",
146
- "com_col = (data_f * qy).sum(dim=(-2, -1)) / total_per_dp\n",
147
- "com_row -= com_row.mean()\n",
148
- "com_col -= com_col.mean()\n",
149
- "com_mag = (com_row ** 2 + com_col ** 2).sqrt()\n",
150
  "\n",
151
- "print(f\"BF range [{bf.min():.1f}, {bf.max():.1f}]\")\n",
152
- "print(f\"DF range [{df.min():.1f}, {df.max():.1f}]\")\n",
153
- "print(f\"|CoM| max {com_mag.max().item():.4f} px\")"
 
 
154
  ]
155
  },
156
  {
157
  "cell_type": "markdown",
158
- "id": "3175e3e9",
159
  "metadata": {},
160
  "source": [
161
- "### BF + DF side by side"
 
 
 
162
  ]
163
  },
164
  {
165
  "cell_type": "code",
166
  "execution_count": null,
167
- "id": "5b00e878",
168
  "metadata": {},
169
  "outputs": [],
170
  "source": [
 
 
 
171
  "quantem.widget.Show2D(\n",
172
- " [bf, df],\n",
173
- " labels=[\"Bright field\", \"Dark field\"],\n",
174
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
175
  " cmap=\"gray\",\n",
176
  ")"
@@ -178,50 +175,74 @@
178
  },
179
  {
180
  "cell_type": "markdown",
181
- "id": "07490d6d",
182
  "metadata": {},
183
  "source": [
184
- "### DPCCoM row + CoM col + |CoM|"
 
 
 
 
185
  ]
186
  },
187
  {
188
  "cell_type": "code",
189
  "execution_count": null,
190
- "id": "5cd86abd",
191
  "metadata": {},
192
  "outputs": [],
193
  "source": [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  "quantem.widget.Show2D(\n",
195
  " [com_row.cpu().numpy(), com_col.cpu().numpy(), com_mag.cpu().numpy()],\n",
196
  " labels=[\"CoM row (qx)\", \"CoM col (qy)\", \"|CoM| total\"],\n",
197
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
198
  " cmap=\"RdBu_r\",\n",
 
199
  ")"
200
  ]
201
  },
202
  {
203
  "cell_type": "markdown",
204
- "id": "51bd59e3",
205
  "metadata": {},
206
  "source": [
207
- "## Step 3DirectPtychography five single-shot kernels\n",
208
  "\n",
209
- "`DirectPtychography` runs CoM + origin fit + auto-rotation, then a single forward\n",
210
- "pass to recover phase via one of five deconvolution kernels:\n",
211
  "\n",
212
  "- **`parallax`** — parallax / tilt approximation\n",
213
  "- **`ssb`** — single-sideband (a.k.a. aberration-corrected bright field)\n",
214
- "- **`obf`** — optimum bright field\n",
215
- "- **`mf`** — matched filter\n",
216
  "- **`icom`** — integrated CoM\n",
217
  "\n",
218
- "Build once, sweep all five kernels."
 
 
 
 
 
219
  ]
220
  },
221
  {
222
  "cell_type": "code",
223
  "execution_count": null,
224
- "id": "330903f6",
225
  "metadata": {},
226
  "outputs": [],
227
  "source": [
@@ -229,118 +250,169 @@
229
  "\n",
230
  "direct = DirectPtychography.from_dataset4d(\n",
231
  " dset,\n",
232
- " energy=meta[\"voltage_kV\"] * 1e3, # 300 kV -> 300000 eV\n",
233
- " semiangle_cutoff=meta[\"probe_semiangle_mrad\"] * 1e-3, # 30 mrad -> 0.030 rad\n",
234
- " rotation_angle=None, # auto-estimate\n",
235
  " device=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n",
236
  " verbose=True,\n",
237
  ")\n",
238
- "print(f\"DirectPtychography built on {'cuda' if torch.cuda.is_available() else 'cpu'}\")"
239
  ]
240
  },
241
  {
242
  "cell_type": "code",
243
  "execution_count": null,
244
- "id": "b1264ee0",
245
  "metadata": {},
246
  "outputs": [],
247
  "source": [
248
  "import time\n",
249
- "KERNELS = [\"parallax\", \"ssb\", \"obf\", \"mf\", \"icom\"]\n",
 
 
 
 
 
250
  "phases = {}\n",
251
  "for k in KERNELS:\n",
252
  " t0 = time.time()\n",
253
- " direct.reconstruct(deconvolution_kernel=k, verbose=False)\n",
 
 
 
 
 
254
  " phases[k] = direct.corrected_bf.detach().cpu().numpy()\n",
255
- " print(f\" {k:>10}: {time.time()-t0:.2f}s, range [{phases[k].min():.2f}, {phases[k].max():.2f}]\")"
256
  ]
257
  },
258
  {
259
  "cell_type": "markdown",
260
- "id": "d8101615",
261
  "metadata": {},
262
  "source": [
263
- "## Step 4Compare all five kernels side by side\n",
264
  "\n",
265
- "Same data, same forward pass, different deconvolution kernels different\n",
266
- "contrast / resolution tradeoffs."
267
  ]
268
  },
269
  {
270
  "cell_type": "code",
271
  "execution_count": null,
272
- "id": "95ef0d43",
273
  "metadata": {},
274
  "outputs": [],
275
  "source": [
276
  "quantem.widget.Show2D(\n",
277
- " [phases[k] for k in KERNELS],\n",
278
- " labels=[k for k in KERNELS],\n",
279
  " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
280
  " cmap=\"gray\",\n",
 
281
  ")"
282
  ]
283
  },
284
  {
285
  "cell_type": "markdown",
286
- "id": "a7ac1bb0",
287
  "metadata": {},
288
  "source": [
289
- "## Step 5Why does this matter? Phase retrieval vs classic imaging\n",
290
  "\n",
291
- "Look at the panels below side by side, in this order: **BF · DF · |CoM| · parallax · SSB**.\n",
292
  "\n",
293
- "- **BF / DF** = intensity contrast. Gold lattice fringes mostly washed out — the contrast is whatever survives integration over the BF disk (or its complement). Dose-efficient but resolution-limited by the disk size.\n",
294
- "- **|CoM|** = first-moment information per scan position. Sees first-order electric-field deflection; better than BF/DF but still a single scalar per position.\n",
295
- "- **`parallax`, `SSB`** = phase retrieval. Each scan position contributes its full diffraction pattern; the kernel deconvolves the probe-transfer function to recover the **complex object phase**. Result: atomic-lattice fringes, sharper edges, less dose for equivalent SNR.\n",
 
 
296
  "\n",
297
- "This is the workshop's scientific punchline: phase retrieval recovers contrast + resolution that BF/DF integration physically can't access."
 
298
  ]
299
  },
300
  {
301
  "cell_type": "code",
302
  "execution_count": null,
303
- "id": "87cbe2f9",
304
  "metadata": {},
305
  "outputs": [],
306
  "source": [
307
- "quantem.widget.Show2D(\n",
308
- " [bf, df, com_mag.cpu().numpy(), phases[\"parallax\"], phases[\"ssb\"]],\n",
309
- " labels=[\"BF\", \"DF\", \"|CoM|\", \"parallax\", \"SSB\"],\n",
310
- " sampling=meta[\"sampling\"][:2], units=meta[\"units\"][:2],\n",
311
- " cmap=\"gray\",\n",
312
- ")"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  ]
314
  },
315
  {
316
  "cell_type": "markdown",
317
- "id": "c2fdc17c",
318
  "metadata": {},
319
  "source": [
320
  "## What you just did\n",
321
  "\n",
322
  "1. Loaded real 4D-STEM gold from Hugging Face → torch GPU + numpy `Dataset4dstem`.\n",
323
  "2. Browsed it with `Show4DSTEM`.\n",
324
- "3. Computed BF / DF / DPC (CoM_row, CoM_col, |CoM|) inline in torch.\n",
325
- "4. Built `DirectPtychography` and swept five deconvolution kernels (parallax, SSB, OBF, MF, ICOM) in seconds each.\n",
326
- "5. Compared all the modalities side by side: classic imaging (BF/DF) vs first-moment (|CoM|) vs phase retrieval (parallax, SSB).\n",
327
- "\n",
328
- "## Why phase retrieval beats BF/DF the workshop takeaway\n",
329
  "\n",
330
- "| Method | Information used | Contrast mechanism | Resolution ceiling |\n",
331
- "|---|---|---|---|\n",
332
- "| BF, DF | total counts inside / outside the BF disk | intensity (atomic Z, thickness) | ~probe size; integration smears |\n",
333
- "| DPC (|CoM|) | first moment of each CBED | first-order field deflection | better than BF, still scalar/pixel |\n",
334
- "| Phase retrieval (parallax, SSB, OBF, MF, ICOM) | the **full** CBED at every scan position | recovers the complex object phase | sub-Ångström possible |\n",
335
  "\n",
336
- "Single forward pass on T4 every kernel finishes in seconds. The phase image\n",
337
- "shows atomic-lattice fringes that BF/DF can't physically resolve at the same dose.\n",
338
  "\n",
339
  "## Try next\n",
340
  "\n",
341
- "- Swap to `gold_512_npy_bin4` for a 4× finer detector — sharpest phase images.\n",
342
- "- Pass explicit `rotation_angle=` to `DirectPtychography.from_dataset4d` if the auto-estimate is off.\n",
343
- "- v2 will add iterative ptychography (`PtychoLite`) even higher-resolution phase, multi-slice support, refinement on top of these single-shot kernels."
 
 
344
  ]
345
  }
346
  ],
 
2
  "cells": [
3
  {
4
  "cell_type": "markdown",
5
+ "id": "d3f97498",
6
  "metadata": {},
7
  "source": [
8
+ "# Workshop: real-gold 4D-STEM — browse, BF, DF, DPC, and 3 direct-ptycho kernels (Colab T4)\n",
9
  "\n",
10
  "[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/gist/bobleesj/a05a90185c6cddbb331342cae6d7e9c1/berk_workshop_v1.ipynb)\n",
11
  "\n",
12
  "ONE notebook. Real gold from Hugging Face → load → browse → bright field → dark\n",
13
+ "field → DPC (via `CenterOfMassOriginModel`) three single-shot phase-retrieval\n",
14
+ "kernels (parallax, SSB, ICOM) → side-by-side comparison.\n",
15
  "\n",
16
+ "Everything on torch on the Colab T4. Two installs only — `quantem.widget`\n",
17
+ "(TestPyPI prerelease) + `quantem` (`berk-workshop` branch). No `quantem.live`.\n",
 
18
  "\n",
19
+ "**Workshop punchline:** phase retrieval (parallax, SSB) recovers atomic-lattice\n",
20
+ "contrast that BF/DF physically cannot, at the same dose."
21
  ]
22
  },
23
  {
24
  "cell_type": "code",
25
  "execution_count": null,
26
+ "id": "2230b09b",
27
  "metadata": {},
28
  "outputs": [],
29
  "source": [
 
34
  {
35
  "cell_type": "code",
36
  "execution_count": null,
37
+ "id": "88b999e7",
38
  "metadata": {},
39
  "outputs": [],
40
  "source": [
 
42
  "import quantem.widget\n",
43
  "import torch\n",
44
  "\n",
45
+ "# cuDNN grid_sample bug at these detector dims; disable for DirectPtycho path.\n",
46
  "torch.backends.cudnn.enabled = False\n",
47
  "\n",
48
  "print(\"quantem \", em.__version__)\n",
 
55
  {
56
  "cell_type": "code",
57
  "execution_count": null,
58
+ "id": "9face372",
59
  "metadata": {},
60
  "outputs": [],
61
  "source": [
 
69
  "data = np.ascontiguousarray(np.load(os.path.join(asset, \"data.npy\")).astype(np.float32))\n",
70
  "meta = json.load(open(os.path.join(asset, \"meta.json\")))\n",
71
  "\n",
72
+ "# numpy-backed for upstream CoM + DirectPtychography (they read dataset.array)\n",
 
73
  "dset = em.core.datastructures.Dataset4dstem.from_array(\n",
74
  " data, sampling=meta[\"sampling\"], units=meta[\"units\"], name=meta[\"name\"],\n",
75
  ")\n",
 
80
  },
81
  {
82
  "cell_type": "markdown",
83
+ "id": "e754cba7",
84
  "metadata": {},
85
  "source": [
86
  "## Step 1 — Browse the 4D-STEM dataset interactively\n",
87
  "\n",
88
+ "Drag the scan cursor; CBED updates live. Real-time per-scan-position BF/DF."
89
  ]
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",
100
  " torch.from_numpy(data).to(\"cuda\" if torch.cuda.is_available() else \"cpu\"),\n",
101
  " sampling=meta[\"sampling\"], units=meta[\"units\"], name=meta[\"name\"],\n",
 
105
  },
106
  {
107
  "cell_type": "markdown",
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
+ ")"
146
  ]
147
  },
148
  {
149
  "cell_type": "markdown",
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
  ")"
 
175
  },
176
  {
177
  "cell_type": "markdown",
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
  },
221
  {
222
  "cell_type": "markdown",
223
+ "id": "6c89c61d",
224
  "metadata": {},
225
  "source": [
226
+ "## Step 5Phase 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": [
 
250
  "\n",
251
  "direct = DirectPtychography.from_dataset4d(\n",
252
  " dset,\n",
253
+ " energy=meta[\"voltage_kV\"] * 1e3, # 300 kV -> 300000 eV\n",
254
+ " semiangle_cutoff=meta[\"probe_semiangle_mrad\"] * 1e-3, # 30 mrad -> 0.030 rad\n",
255
+ " rotation_angle=None, # auto-estimate\n",
256
  " device=\"cuda\" if torch.cuda.is_available() else \"cpu\",\n",
257
  " verbose=True,\n",
258
  ")\n",
259
+ "print(\"DirectPtychography built\")"
260
  ]
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
  {
290
  "cell_type": "markdown",
291
+ "id": "5ffc4fd8",
292
  "metadata": {},
293
  "source": [
294
+ "## Step 6All three kernels side by side\n",
295
  "\n",
296
+ "`link_contrast=False` so every kernel gets its own min/max (the SSB output is\n",
297
+ "~3 orders of magnitude smaller than ICOM)."
298
  ]
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",
313
  ")"
314
  ]
315
  },
316
  {
317
  "cell_type": "markdown",
318
+ "id": "c2d0e9b4",
319
  "metadata": {},
320
  "source": [
321
+ "## Step 7 — Phase retrieval vs classic imaging\n",
322
  "\n",
323
+ "The workshop punchline.\n",
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
  ]
384
  },
385
  {
386
  "cell_type": "markdown",
387
+ "id": "33a873d6",
388
  "metadata": {},
389
  "source": [
390
  "## What you just did\n",
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 modalitieseach 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
  }
418
  ],