bobleesj commited on
Commit
880a720
·
verified ·
1 Parent(s): ab58e44

workshop: add berk_workshop_v1 (browse + BF/DF + probe + DPC, Colab T4)

Browse files
Files changed (1) hide show
  1. notebooks/berk_workshop_v1.ipynb +295 -0
notebooks/berk_workshop_v1.ipynb ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
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": null,
26
+ "id": "c15f382c",
27
+ "metadata": {},
28
+ "outputs": [],
29
+ "source": [
30
+ "!pip install -q --pre --extra-index-url https://test.pypi.org/simple/ quantem.widget huggingface_hub\n",
31
+ "!pip install -q git+https://github.com/bobleesj/quantem.git@berk-workshop"
32
+ ]
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "execution_count": null,
37
+ "id": "30258881",
38
+ "metadata": {},
39
+ "outputs": [],
40
+ "source": [
41
+ "import quantem as em\n",
42
+ "import quantem.widget\n",
43
+ "import torch\n",
44
+ "\n",
45
+ "print(\"quantem \", em.__version__)\n",
46
+ "print(\"quantem.widget \", quantem.widget.__version__)\n",
47
+ "print(\"torch \", torch.__version__)\n",
48
+ "print(\"cuda available:\", torch.cuda.is_available(),\n",
49
+ " torch.cuda.get_device_name(0) if torch.cuda.is_available() else \"(no GPU runtime)\")"
50
+ ]
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "execution_count": null,
55
+ "id": "b491687f",
56
+ "metadata": {},
57
+ "outputs": [],
58
+ "source": [
59
+ "# Download a pre-binned NumPy bundle from the public Hugging Face dataset and\n",
60
+ "# wrap it as a torch tensor on the GPU. The 4D shape is (scan_row, scan_col,\n",
61
+ "# k_row, k_col) = (512, 512, 24, 24); detector binned 8x from the original 192x192\n",
62
+ "# to keep the Colab download small (~300 MB).\n",
63
+ "import os, json\n",
64
+ "import numpy as np\n",
65
+ "from huggingface_hub import snapshot_download\n",
66
+ "\n",
67
+ "folder = snapshot_download(\"bobleesj/quantem-data\", repo_type=\"dataset\",\n",
68
+ " allow_patterns=[\"4dstem/gold_512_npy_bin8/*\"])\n",
69
+ "asset = os.path.join(folder, \"4dstem\", \"gold_512_npy_bin8\")\n",
70
+ "data = np.load(os.path.join(asset, \"data.npy\")) # (512, 512, 24, 24) uint16\n",
71
+ "meta = json.load(open(os.path.join(asset, \"meta.json\")))\n",
72
+ "\n",
73
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
74
+ "t = torch.from_numpy(data).to(device)\n",
75
+ "dset = em.core.datastructures.Dataset4dstem.from_tensor(\n",
76
+ " t, sampling=meta[\"sampling\"], units=meta[\"units\"], name=meta[\"name\"],\n",
77
+ ")\n",
78
+ "print(f\"dataset on {dset.tensor.device}: shape {dset.shape}, dtype {dset.tensor.dtype}\")\n",
79
+ "print(f\"sampling {meta['sampling']} {meta['units']}\")\n",
80
+ "print(f\"optics: {meta['voltage_kV']} kV, probe {meta['probe_semiangle_mrad']} mrad, CL {meta['camera_length_mm']} mm\")"
81
+ ]
82
+ },
83
+ {
84
+ "cell_type": "markdown",
85
+ "id": "a3f9a244",
86
+ "metadata": {},
87
+ "source": [
88
+ "## Step 1 — Browse the 4D-STEM dataset interactively\n",
89
+ "\n",
90
+ "Drag the scan cursor in the left panel. The CBED on the right updates live.\n",
91
+ "This is your real-time bright-field / dark-field — pixels INSIDE the central\n",
92
+ "disk are BF, OUTSIDE are DF. The widget renders in your browser via WebGPU\n",
93
+ "(works in Chrome on free Colab)."
94
+ ]
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "execution_count": null,
99
+ "id": "59204966",
100
+ "metadata": {},
101
+ "outputs": [],
102
+ "source": [
103
+ "quantem.widget.Show4DSTEM(dset)"
104
+ ]
105
+ },
106
+ {
107
+ "cell_type": "markdown",
108
+ "id": "61add712",
109
+ "metadata": {},
110
+ "source": [
111
+ "## Step 2 — The probe (mean diffraction pattern)\n",
112
+ "\n",
113
+ "Average all diffraction patterns over the scan. What's left is the probe — the\n",
114
+ "shape of the electron beam at the detector. A clean BF disk should appear."
115
+ ]
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "execution_count": null,
120
+ "id": "e49b4f3d",
121
+ "metadata": {},
122
+ "outputs": [],
123
+ "source": [
124
+ "mean_dp = dset.tensor.to(torch.float32).mean(dim=(0, 1)) # (24, 24) on GPU\n",
125
+ "print(f\"mean_dp shape {tuple(mean_dp.shape)}, device {mean_dp.device}\")\n",
126
+ "\n",
127
+ "em.core.visualization.show_2d(\n",
128
+ " mean_dp.cpu().numpy(),\n",
129
+ " title=\"Probe (mean DP)\",\n",
130
+ " cmap=\"inferno\",\n",
131
+ " cbar=True,\n",
132
+ ")"
133
+ ]
134
+ },
135
+ {
136
+ "cell_type": "markdown",
137
+ "id": "c09a9ae6",
138
+ "metadata": {},
139
+ "source": [
140
+ "## Step 3 — Probe center via center-of-mass\n",
141
+ "\n",
142
+ "Weighted average of the detector coordinates. Should land near the middle of\n",
143
+ "the detector (~12, 12) for a centered beam — small offset is normal."
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": null,
149
+ "id": "eee02115",
150
+ "metadata": {},
151
+ "outputs": [],
152
+ "source": [
153
+ "H, W = mean_dp.shape\n",
154
+ "row = torch.arange(H, device=mean_dp.device, dtype=torch.float32)[:, None]\n",
155
+ "col = torch.arange(W, device=mean_dp.device, dtype=torch.float32)[None, :]\n",
156
+ "total = mean_dp.sum()\n",
157
+ "cy = (mean_dp * row).sum() / total\n",
158
+ "cx = (mean_dp * col).sum() / total\n",
159
+ "print(f\"probe center: row={cy.item():.3f}, col={cx.item():.3f} \"\n",
160
+ " f\"(detector {H}x{W}, geometric center ~{H/2:.1f}, ~{W/2:.1f})\")"
161
+ ]
162
+ },
163
+ {
164
+ "cell_type": "markdown",
165
+ "id": "5028708e",
166
+ "metadata": {},
167
+ "source": [
168
+ "## Step 4 — Bright field + dark field virtual images\n",
169
+ "\n",
170
+ "Build an aperture mask at the probe center. For every scan position, sum the\n",
171
+ "pixels inside the disk (BF) and outside (DF). One line of torch, runs on the\n",
172
+ "GPU in milliseconds."
173
+ ]
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "execution_count": null,
178
+ "id": "0c72f95d",
179
+ "metadata": {},
180
+ "outputs": [],
181
+ "source": [
182
+ "BF_RADIUS_PX = 6.0 # ~30 mrad on the bin8 detector\n",
183
+ "\n",
184
+ "rr, cc = torch.meshgrid(row.squeeze(), col.squeeze(), indexing=\"ij\")\n",
185
+ "r_from_center = ((rr - cy) ** 2 + (cc - cx) ** 2).sqrt()\n",
186
+ "bf_mask = (r_from_center <= BF_RADIUS_PX).float()\n",
187
+ "df_mask = 1.0 - bf_mask\n",
188
+ "\n",
189
+ "data_f = dset.tensor.to(torch.float32)\n",
190
+ "bf = (data_f * bf_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
191
+ "df = (data_f * df_mask).sum(dim=(-2, -1)).cpu().numpy()\n",
192
+ "\n",
193
+ "em.core.visualization.show_2d(\n",
194
+ " [bf, df, mean_dp.cpu().numpy()],\n",
195
+ " title=[\"Bright field\", \"Dark field\", \"Probe\"],\n",
196
+ " cmap=[\"gray\", \"gray\", \"inferno\"],\n",
197
+ " scalebar=[\n",
198
+ " {\"sampling\": meta[\"sampling\"][0], \"units\": meta[\"units\"][0]},\n",
199
+ " {\"sampling\": meta[\"sampling\"][0], \"units\": meta[\"units\"][0]},\n",
200
+ " {\"sampling\": meta[\"sampling\"][2], \"units\": meta[\"units\"][2]},\n",
201
+ " ],\n",
202
+ " axsize=(4, 4),\n",
203
+ ")"
204
+ ]
205
+ },
206
+ {
207
+ "cell_type": "markdown",
208
+ "id": "ed35980e",
209
+ "metadata": {},
210
+ "source": [
211
+ "## Step 5 — Differential phase contrast (DPC)\n",
212
+ "\n",
213
+ "Per-scan-position center-of-mass. Each detector pattern's centroid shifts when\n",
214
+ "local electric fields deflect the probe. The maps below show those shifts as\n",
215
+ "signed deflection — red/blue around features means real DPC contrast.\n",
216
+ "\n",
217
+ "Implemented inline as a single torch reduction on the GPU."
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "execution_count": null,
223
+ "id": "1fa064b1",
224
+ "metadata": {},
225
+ "outputs": [],
226
+ "source": [
227
+ "data_f = dset.tensor.to(torch.float32)\n",
228
+ "H, W = data_f.shape[-2:]\n",
229
+ "qx = torch.arange(H, device=data_f.device, dtype=torch.float32)[:, None]\n",
230
+ "qy = torch.arange(W, device=data_f.device, dtype=torch.float32)[None, :]\n",
231
+ "\n",
232
+ "total_per_dp = data_f.sum(dim=(-2, -1)) # (scan_r, scan_c)\n",
233
+ "com_row = (data_f * qx).sum(dim=(-2, -1)) / total_per_dp\n",
234
+ "com_col = (data_f * qy).sum(dim=(-2, -1)) / total_per_dp\n",
235
+ "\n",
236
+ "# Detrend (subtract mean) so the colormap is zero-centered on signed deflection.\n",
237
+ "com_row -= com_row.mean()\n",
238
+ "com_col -= com_col.mean()\n",
239
+ "\n",
240
+ "em.core.visualization.show_2d(\n",
241
+ " [com_row.cpu().numpy(), com_col.cpu().numpy()],\n",
242
+ " title=[\"DPC — CoM row (qx)\", \"DPC — CoM col (qy)\"],\n",
243
+ " cmap=\"RdBu_r\",\n",
244
+ " cbar=True,\n",
245
+ " scalebar={\"sampling\": meta[\"sampling\"][0], \"units\": meta[\"units\"][0]},\n",
246
+ " axsize=(4, 4),\n",
247
+ ")\n",
248
+ "print(f\"CoM row range [{com_row.min().item():.4f}, {com_row.max().item():.4f}] px\")\n",
249
+ "print(f\"CoM col range [{com_col.min().item():.4f}, {com_col.max().item():.4f}] px\")"
250
+ ]
251
+ },
252
+ {
253
+ "cell_type": "markdown",
254
+ "id": "8585e78a",
255
+ "metadata": {},
256
+ "source": [
257
+ "## What you just did\n",
258
+ "\n",
259
+ "1. Loaded real 4D-STEM gold from Hugging Face → torch tensor on the Colab T4.\n",
260
+ "2. Browsed it interactively with `Show4DSTEM`.\n",
261
+ "3. Computed the probe (mean DP) and found its center on the detector.\n",
262
+ "4. Computed BF and DF virtual images with one aperture mask.\n",
263
+ "5. Computed DPC (per-scan-position CoM) showing electric-field deflection.\n",
264
+ "\n",
265
+ "Everything ran on the GPU in seconds.\n",
266
+ "\n",
267
+ "## Try next\n",
268
+ "\n",
269
+ "- Swap `gold_512_npy_bin8` → `gold_512_npy_bin4` (factor-of-2 finer detector\n",
270
+ " sampling at 4× the download).\n",
271
+ "- Change `BF_RADIUS_PX` to expand/shrink the BF disk.\n",
272
+ "- Detrend DPC differently (e.g. subtract a plane fit) to reveal smaller features.\n",
273
+ "\n",
274
+ "v2 will add iterative ptychography (`PtychoLite`) on the same data."
275
+ ]
276
+ }
277
+ ],
278
+ "metadata": {
279
+ "accelerator": "GPU",
280
+ "colab": {
281
+ "gpuType": "T4",
282
+ "include_colab_link": true,
283
+ "provenance": []
284
+ },
285
+ "kernelspec": {
286
+ "display_name": "Python 3",
287
+ "name": "python3"
288
+ },
289
+ "language_info": {
290
+ "name": "python"
291
+ }
292
+ },
293
+ "nbformat": 4,
294
+ "nbformat_minor": 5
295
+ }