bobleesj commited on
Commit
5e2f2da
·
verified ·
1 Parent(s): 90b3c35

workshop: consolidated v1 (BF/DF/DPC + 5 direct kernels + cross-modality)

Browse files
Files changed (1) hide show
  1. notebooks/berk_workshop_v1.ipynb +197 -219
notebooks/berk_workshop_v1.ipynb CHANGED
@@ -2,28 +2,28 @@
2
  "cells": [
3
  {
4
  "cell_type": "markdown",
5
- "id": "686f9970",
6
  "metadata": {},
7
  "source": [
8
- "# Workshop: real-gold 4D-STEM — browse, BF, DF, probe, DPC (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
- "Load a real 4D-STEM gold dataset from Hugging Face, browse it interactively,\n",
13
- "compute bright field / dark field, find the probe center, and visualize DPC —\n",
14
- "all in your browser, on Colab's free T4 GPU. No local install, no `quantem.live`.\n",
15
  "\n",
16
- "Two installs only: `quantem.widget` (TestPyPI prerelease) and `quantem`\n",
17
- "(from the `berk-workshop` branch on `bobleesj/quantem`). Everything runs on\n",
18
- "torch on the GPU.\n",
19
  "\n",
20
- "**Total runtime: 2–3 minutes** (install dominates)."
21
  ]
22
  },
23
  {
24
  "cell_type": "code",
25
- "execution_count": 1,
26
- "id": "c15f382c",
27
  "metadata": {},
28
  "outputs": [],
29
  "source": [
@@ -33,82 +33,32 @@
33
  },
34
  {
35
  "cell_type": "code",
36
- "execution_count": 2,
37
- "id": "30258881",
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\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",
54
  "import torch\n",
55
  "\n",
 
 
 
56
  "print(\"quantem \", em.__version__)\n",
57
  "print(\"quantem.widget \", quantem.widget.__version__)\n",
58
- "print(\"torch \", torch.__version__)\n",
59
  "print(\"cuda available:\", torch.cuda.is_available(),\n",
60
- " torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"(no GPU runtime)\")"
61
  ]
62
  },
63
  {
64
  "cell_type": "code",
65
- "execution_count": 3,
66
- "id": "b491687f",
67
  "metadata": {},
68
- "outputs": [
69
- {
70
- "data": {
71
- "application/vnd.jupyter.widget-view+json": {
72
- "model_id": "4857082fc463409cbe993d633f8b24e5",
73
- "version_major": 2,
74
- "version_minor": 0
75
- },
76
- "text/plain": [
77
- "Downloading (incomplete total...): 0.00B [00:00, ?B/s]"
78
- ]
79
- },
80
- "metadata": {},
81
- "output_type": "display_data"
82
- },
83
- {
84
- "data": {
85
- "application/vnd.jupyter.widget-view+json": {
86
- "model_id": "a00c63d8797545ebb1de8a6c2a5a471e",
87
- "version_major": 2,
88
- "version_minor": 0
89
- },
90
- "text/plain": [
91
- "Fetching 2 files: 0%| | 0/2 [00:00<?, ?it/s]"
92
- ]
93
- },
94
- "metadata": {},
95
- "output_type": "display_data"
96
- },
97
- {
98
- "name": "stdout",
99
- "output_type": "stream",
100
- "text": [
101
- "dataset on cuda:0: shape (512, 512, 24, 24), dtype torch.uint16\n",
102
- "sampling [0.5, 0.5, 3.68, 3.68] ['A', 'A', 'mrad', 'mrad']\n",
103
- "optics: 300 kV, probe 30 mrad, CL 91 mm\n"
104
- ]
105
- }
106
- ],
107
  "source": [
108
- "# Download a pre-binned NumPy bundle from the public Hugging Face dataset and\n",
109
- "# wrap it as a torch tensor on the GPU. The 4D shape is (scan_row, scan_col,\n",
110
- "# k_row, k_col) = (512, 512, 24, 24); detector binned 8x from the original 192x192\n",
111
- "# to keep the Colab download small (~300 MB).\n",
112
  "import os, json\n",
113
  "import numpy as np\n",
114
  "from huggingface_hub import snapshot_download\n",
@@ -116,243 +66,281 @@
116
  "folder = snapshot_download(\"bobleesj/quantem-data\", repo_type=\"dataset\",\n",
117
  " allow_patterns=[\"4dstem/gold_512_npy_bin8/*\"])\n",
118
  "asset = os.path.join(folder, \"4dstem\", \"gold_512_npy_bin8\")\n",
119
- "data = np.load(os.path.join(asset, \"data.npy\")) # (512, 512, 24, 24) uint16\n",
120
  "meta = json.load(open(os.path.join(asset, \"meta.json\")))\n",
121
  "\n",
122
- "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
123
- "t = torch.from_numpy(data).to(device)\n",
124
- "dset = em.core.datastructures.Dataset4dstem.from_tensor(\n",
125
- " t, sampling=meta[\"sampling\"], units=meta[\"units\"], name=meta[\"name\"],\n",
126
  ")\n",
127
- "print(f\"dataset on {dset.tensor.device}: shape {dset.shape}, dtype {dset.tensor.dtype}\")\n",
128
  "print(f\"sampling {meta['sampling']} {meta['units']}\")\n",
129
  "print(f\"optics: {meta['voltage_kV']} kV, probe {meta['probe_semiangle_mrad']} mrad, CL {meta['camera_length_mm']} mm\")"
130
  ]
131
  },
132
  {
133
  "cell_type": "markdown",
134
- "id": "a3f9a244",
135
  "metadata": {},
136
  "source": [
137
  "## Step 1 — Browse the 4D-STEM dataset interactively\n",
138
  "\n",
139
- "Drag the scan cursor in the left panel. The CBED on the right updates live.\n",
140
- "This is your real-time bright-field / dark-field — pixels INSIDE the central\n",
141
- "disk are BF, OUTSIDE are DF. The widget renders in your browser via WebGPU\n",
142
- "(works in Chrome on free Colab)."
143
  ]
144
  },
145
  {
146
  "cell_type": "code",
147
- "execution_count": 4,
148
- "id": "59204966",
149
  "metadata": {},
150
- "outputs": [
151
- {
152
- "name": "stdout",
153
- "output_type": "stream",
154
- "text": [
155
- " to cuda:0: 0.00s (0.3 GB)\n",
156
- " auto_detect_center: 0.08s\n",
157
- " virtual image + frame: 0.00s\n",
158
- "Show4DSTEM: 512x512x24x24 cuda:0, 0.24s total\n"
159
- ]
160
- },
161
- {
162
- "data": {
163
- "application/vnd.jupyter.widget-view+json": {
164
- "model_id": "cfb26ffc6dcb4f02a72772a2fbf05b47",
165
- "version_major": 2,
166
- "version_minor": 1
167
- },
168
- "text/plain": [
169
- "Show4DSTEM(shape=(512, 512, 24, 24), sampling=(0.5 A, 3.68 mrad), pos=(256, 256), title='gold_512_npy_bin8')"
170
- ]
171
- },
172
- "execution_count": 4,
173
- "metadata": {},
174
- "output_type": "execute_result"
175
- }
176
- ],
177
  "source": [
178
- "quantem.widget.Show4DSTEM(dset)"
 
 
 
 
 
179
  ]
180
  },
181
  {
182
  "cell_type": "markdown",
183
- "id": "c09a9ae6",
184
  "metadata": {},
185
  "source": [
186
- "## Step 2 — Detector geometry + aperture center\n",
187
  "\n",
188
- "Detector size comes from the dataset; aperture center is hardcoded to the\n",
189
- "geometric center of the detector (for the binned data here it lands close to\n",
190
- "the real beam center)."
191
  ]
192
  },
193
  {
194
  "cell_type": "code",
195
- "execution_count": 6,
196
- "id": "eee02115",
197
  "metadata": {},
198
- "outputs": [
199
- {
200
- "name": "stdout",
201
- "output_type": "stream",
202
- "text": [
203
- "probe center: row=11.289, col=11.503 (detector 24x24, geometric center ~12.0, ~12.0)\n"
204
- ]
205
- }
206
- ],
207
  "source": [
208
- "H, W = dset.tensor.shape[-2:] # detector dims\n",
209
- "cy, cx = H / 2, W / 2 # hardcoded — geometric center\n",
210
- "device = dset.tensor.device\n",
211
  "\n",
212
- "row = torch.arange(H, device=device, dtype=torch.float32)[:, None]\n",
213
- "col = torch.arange(W, device=device, dtype=torch.float32)[None, :]\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  "\n",
215
- "print(f\"detector {H}x{W}, aperture center hardcoded to (row={cy}, col={cx})\")"
 
 
216
  ]
217
  },
218
  {
219
  "cell_type": "markdown",
220
- "id": "8e3f80bd",
221
  "metadata": {},
222
  "source": [
223
- "## Step 3 — Bright field\n",
224
- "\n",
225
- "Aperture mask at the probe center → for every scan position, sum the detector\n",
226
- "pixels INSIDE the BF disk. One torch reduction on the GPU; renders as an\n",
227
- "interactive `Show2D` widget."
228
  ]
229
  },
230
  {
231
  "cell_type": "code",
232
  "execution_count": null,
233
- "id": "89c29b87",
234
  "metadata": {},
235
  "outputs": [],
236
  "source": [
237
- "BF_RADIUS_PX = 6.0 # ~30 mrad on the bin8 detector\n",
238
- "\n",
239
- "rr, cc = torch.meshgrid(row.squeeze(), col.squeeze(), indexing=\"ij\")\n",
240
- "r_from_center = ((rr - cy) ** 2 + (cc - cx) ** 2).sqrt()\n",
241
- "bf_mask = (r_from_center <= BF_RADIUS_PX).float()\n",
242
- "df_mask = 1.0 - bf_mask # for the next step\n",
243
- "\n",
244
- "data_f = dset.tensor.to(torch.float32)\n",
245
- "bf = (data_f * bf_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
246
- "\n",
247
  "quantem.widget.Show2D(\n",
248
- " bf,\n",
249
- " title=\"Bright field\",\n",
250
- " sampling=meta[\"sampling\"][:2],\n",
251
- " units=meta[\"units\"][:2],\n",
252
  " cmap=\"gray\",\n",
253
  ")"
254
  ]
255
  },
256
  {
257
  "cell_type": "markdown",
258
- "id": "f7b8d437",
259
  "metadata": {},
260
  "source": [
261
- "## Step 4 — Dark field\n",
262
- "\n",
263
- "Same data, opposite mask — sum the detector pixels OUTSIDE the BF disk."
264
  ]
265
  },
266
  {
267
  "cell_type": "code",
268
  "execution_count": null,
269
- "id": "8b495a66",
270
  "metadata": {},
271
  "outputs": [],
272
  "source": [
273
- "df = (data_f * df_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
274
- "\n",
275
  "quantem.widget.Show2D(\n",
276
- " df,\n",
277
- " title=\"Dark field\",\n",
278
- " sampling=meta[\"sampling\"][:2],\n",
279
- " units=meta[\"units\"][:2],\n",
280
- " cmap=\"gray\",\n",
281
  ")"
282
  ]
283
  },
284
  {
285
  "cell_type": "markdown",
286
- "id": "fbd73db0",
287
  "metadata": {},
288
  "source": [
289
- "## Step 5 — Center of mass (DPC) per scan position\n",
290
  "\n",
291
- "For every scan position, the centroid of its diffraction pattern shifts when a\n",
292
- "local electric field deflects the probe. Compute that centroid in torch on the\n",
293
- "GPU. Three interactive `Show2D` widgets follow:\n",
294
  "\n",
295
- "- **CoM row (qx)** — signed deflection along the rows of the detector.\n",
296
- "- **CoM col (qy)** — signed deflection along the columns.\n",
297
- "- **|CoM|** — total deflection magnitude (rotation-invariant)."
 
 
 
 
298
  ]
299
  },
300
  {
301
  "cell_type": "code",
302
  "execution_count": null,
303
- "id": "d2519bd0",
304
  "metadata": {},
305
  "outputs": [],
306
  "source": [
307
- "H, W = data_f.shape[-2:]\n",
308
- "qx = torch.arange(H, device=data_f.device, dtype=torch.float32)[:, None]\n",
309
- "qy = torch.arange(W, device=data_f.device, dtype=torch.float32)[None, :]\n",
310
  "\n",
311
- "total_per_dp = data_f.sum(dim=(-2, -1)) # (scan_r, scan_c)\n",
312
- "com_row = (data_f * qx).sum(dim=(-2, -1)) / total_per_dp\n",
313
- "com_col = (data_f * qy).sum(dim=(-2, -1)) / total_per_dp\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  "\n",
315
- "# Detrend so RdBu_r is zero-centered on the signed deflection.\n",
316
- "com_row -= com_row.mean()\n",
317
- "com_col -= com_col.mean()\n",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  "\n",
319
- "com_mag = (com_row ** 2 + com_col ** 2).sqrt() # |CoM|, always >= 0\n",
320
  "\n",
321
- "print(f\"CoM row range [{com_row.min().item():.4f}, {com_row.max().item():.4f}] px\")\n",
322
- "print(f\"CoM col range [{com_col.min().item():.4f}, {com_col.max().item():.4f}] px\")\n",
323
- "print(f\"|CoM| max {com_mag.max().item():.4f} px\")\n",
324
  "\n",
 
 
 
 
 
 
 
 
 
 
325
  "quantem.widget.Show2D(\n",
326
- " [com_row.cpu().numpy(), com_col.cpu().numpy(), com_mag.cpu().numpy()],\n",
327
- " labels=[\"CoM row (qx)\", \"CoM col (qy)\", \"|CoM| total\"],\n",
328
- " sampling=meta[\"sampling\"][:2],\n",
329
- " units=meta[\"units\"][:2],\n",
330
- " cmap=\"RdBu_r\",\n",
331
  ")"
332
  ]
333
  },
334
  {
335
  "cell_type": "markdown",
336
- "id": "8585e78a",
337
  "metadata": {},
338
  "source": [
339
  "## What you just did\n",
340
  "\n",
341
- "1. Loaded real 4D-STEM gold from Hugging Face → torch tensor on the Colab T4.\n",
342
- "2. Browsed it with `Show4DSTEM`; hardcoded the aperture at the detector center.\n",
343
- "3. Bright field via aperture mask × per-scan sum (`Show2D`).\n",
344
- "4. Dark field via the complementary mask (`Show2D`).\n",
345
- "5. DPC / CoM: a single `Show2D` with three panels — CoM row, CoM col, and `|CoM|` magnitude.\n",
346
  "\n",
347
- "Every reduction on the GPU in milliseconds; every viz is an interactive WebGPU widget.\n",
348
  "\n",
349
- "## Try next\n",
 
 
 
 
350
  "\n",
351
- "- Swap `gold_512_npy_bin8` → `gold_512_npy_bin4` for a finer (4× larger) detector.\n",
352
- "- Change `BF_RADIUS_PX` to grow/shrink the BF disk.\n",
353
- "- Detrend DPC differently (subtract a plane fit) to surface smaller features.\n",
 
354
  "\n",
355
- "v2 will add iterative ptychography (`PtychoLite`) on the same data."
 
 
356
  ]
357
  }
358
  ],
@@ -364,21 +352,11 @@
364
  "provenance": []
365
  },
366
  "kernelspec": {
367
- "display_name": "Python 3 (ipykernel)",
368
- "language": "python",
369
  "name": "python3"
370
  },
371
  "language_info": {
372
- "codemirror_mode": {
373
- "name": "ipython",
374
- "version": 3
375
- },
376
- "file_extension": ".py",
377
- "mimetype": "text/x-python",
378
- "name": "python",
379
- "nbconvert_exporter": "python",
380
- "pygments_lexer": "ipython3",
381
- "version": "3.13.12"
382
  }
383
  },
384
  "nbformat": 4,
 
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": [
 
33
  },
34
  {
35
  "cell_type": "code",
36
+ "execution_count": null,
37
+ "id": "c5cc149e",
38
  "metadata": {},
39
+ "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
40
  "source": [
41
  "import quantem as em\n",
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",
49
  "print(\"quantem.widget \", quantem.widget.__version__)\n",
50
+ "print(\"torch \", torch.__version__, \"(cuDNN disabled)\")\n",
51
  "print(\"cuda available:\", torch.cuda.is_available(),\n",
52
+ " torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"(no GPU)\")"
53
  ]
54
  },
55
  {
56
  "cell_type": "code",
57
+ "execution_count": null,
58
+ "id": "fb1fd0b9",
59
  "metadata": {},
60
+ "outputs": [],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  "source": [
 
 
 
 
62
  "import os, json\n",
63
  "import numpy as np\n",
64
  "from huggingface_hub import snapshot_download\n",
 
66
  "folder = snapshot_download(\"bobleesj/quantem-data\", repo_type=\"dataset\",\n",
67
  " allow_patterns=[\"4dstem/gold_512_npy_bin8/*\"])\n",
68
  "asset = os.path.join(folder, \"4dstem\", \"gold_512_npy_bin8\")\n",
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",
77
+ "print(f\"dataset: shape {dset.shape}, dtype {dset.array.dtype}\")\n",
78
  "print(f\"sampling {meta['sampling']} {meta['units']}\")\n",
79
  "print(f\"optics: {meta['voltage_kV']} kV, probe {meta['probe_semiangle_mrad']} mrad, CL {meta['camera_length_mm']} mm\")"
80
  ]
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",
103
+ ")\n",
104
+ "quantem.widget.Show4DSTEM(dset_torch)"
105
  ]
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
  ")"
177
  ]
178
  },
179
  {
180
  "cell_type": "markdown",
181
+ "id": "07490d6d",
182
  "metadata": {},
183
  "source": [
184
+ "### DPC — CoM 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 3 — DirectPtychography — 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": [
228
+ "from quantem.diffractive_imaging import DirectPtychography\n",
 
 
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 4 — Compare 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 5 — Why 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
  ],
 
352
  "provenance": []
353
  },
354
  "kernelspec": {
355
+ "display_name": "Python 3",
 
356
  "name": "python3"
357
  },
358
  "language_info": {
359
+ "name": "python"
 
 
 
 
 
 
 
 
 
360
  }
361
  },
362
  "nbformat": 4,