Subspatial Cryo-ET Open Data: EMPIAR-11830, 1,829 Chlamydomonas In Situ Tomograms: sample notebook
A worked notebook for Subspatial Cryo-ET Open Data: EMPIAR-11830, 1,829 Chlamydomonas In Situ Tomograms, with 9 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.
- Provider
- Subspatial (data: Kelley, Khavnekar, Righetto et al., Max Planck Institute of Biochemistry)
- License
- CC0-1.0
- Stored at
- Amazon S3, s3://subspatial-opendata (eu-north-1)
- Access
- Free and public. No account with the data provider is needed.
The notebook
Subspatial cryo-ET: Getting Started
This archive is EMPIAR-11830: 1,829 cryo-electron tomograms of *Chlamydomonas reinhardtii*, a green alga, imaged inside the cell. Each cell was frozen, thinned to a thin lamella with a plasma-FIB beam, and tilted in a Krios microscope to reconstruct a 3D volume. Subspatial hosts the data in an open AWS bucket (eu-north-1, CC0), mounted here read-only at /mnt/archive, so nothing has to be downloaded.
A tomogram is a stack of slices, and the reconstructed volumes are plain MRC files. One slice is one contiguous read, so you can look at a 2 GiB tomogram while touching 4 MiB of it. This notebook shows how, and covers the three things that trip people up: the two naming schemes, the volume sets that are not the same size, and a wrong pixel size in one set's headers.
Start here. Click the grey cell below and press Shift+Enter. It reads the curators' annotation sheet and one slice of tomogram 298, and prints what is in it. Then change TOMO_NUMBER and run it again.
import os, struct
import numpy as np, pandas as pd
TOMO_NUMBER = 298 # try 2189, 1903 or 2084; any number in the sheet that is also in cryocare_bin4/
root = os.environ.get("SCIGANTIC_MOUNT_PATH", "/mnt/archive")
D = f"{root}/empiar-mirror/empiar-11830/data"
ORGANELLES = ["Chloroplast", "Pyrenoid", "Mitochondria", "Nucleus", "Golgi", "ER", "Microtubules", "Actin"]
DTYPES = {0: "i1", 1: "<i2", 2: "<f4", 6: "<u2"}
def mrc_info(path):
"""Read just the 1024-byte MRC header: shape, dtype, pixel size, byte offset of the data."""
with open(path, "rb") as f:
b = f.read(1024)
nx, ny, nz, mode = struct.unpack("<4i", b[:16])
mx = struct.unpack("<i", b[28:32])[0]
cell_x = struct.unpack("<f", b[40:44])[0]
nsymbt = struct.unpack("<i", b[92:96])[0]
return dict(nx=nx, ny=ny, nz=nz, dtype=DTYPES[mode], pixel_A=cell_x / mx, offset=1024 + nsymbt)
def read_slice(path, z, info=None):
"""One z-slice of an MRC volume: a single ranged read, not the whole file."""
info = info or mrc_info(path)
n = info["nx"] * info["ny"]
size = np.dtype(info["dtype"]).itemsize
with open(path, "rb") as f:
f.seek(info["offset"] + z * n * size)
return np.frombuffer(f.read(n * size), dtype=info["dtype"]).reshape(info["ny"], info["nx"])
ann = pd.read_excel(f"{D}/Chlamy_Tomo_Annotations.xlsx", sheet_name="Annotation")
row = ann[ann.Tomo_number == TOMO_NUMBER].iloc[0]
path = f"{D}/cryocare_bin4/{TOMO_NUMBER}.mrc"
info = mrc_info(path)
stack = mrc_info(f"{D}/chlamy_visual_proteomics/{row.Tomo_name}/{row.Tomo_name}_dose-filt.st")
px = stack["pixel_A"] * 4 # this volume is the tilt stack binned 4x; see section 3 for why not the volume's own header
sl = read_slice(path, info["nz"] // 2, info)
print("tomogram :", TOMO_NUMBER, "=", row.Tomo_name)
print("flagged :", [c for c in ORGANELLES if row[c]], "| note:", row.Comments)
print(f"volume : {info['nx']} x {info['ny']} x {info['nz']} voxels at {px:.2f} A/pixel, {info['dtype']}")
print(f"mid slice: mean {sl.mean():.1f}, std {sl.std():.1f} (read {sl.nbytes / 2**20:.0f} MiB of a {os.path.getsize(path) / 2**30:.1f} GiB file)")
1. What is in the bucket
Everything sits under empiar-mirror/empiar-11830/data/: the raw tilt series in chlamy_visual_proteomics/ and four sets of reconstructed tomograms. Listing one folder is cheap; recursing into this bucket is not (the deposit is 32 TB), so we count each folder once and never walk below it.
sets = {
"must_bin8": ("MUST reconstruction, binned 8x", ".rec"),
"must_bin4": ("MUST reconstruction, binned 4x", ".rec"),
"cryocare_bin4": ("CryoCARE denoised, binned 4x", ".mrc"),
"ctf3d_bin4": ("3D-CTF corrected, binned 4x", ".rec"),
}
names = {k: sorted(os.listdir(f"{D}/{k}")) for k in sets}
tilt_dirs = [e for e in os.listdir(f"{D}/chlamy_visual_proteomics") if os.path.isdir(f"{D}/chlamy_visual_proteomics/{e}")]
table = pd.DataFrame(
[(k, v[0], len(names[k])) for k, v in sets.items()] + [("chlamy_visual_proteomics", "raw frames + tilt stacks (folders)", len(tilt_dirs))],
columns=["folder", "what", "entries"],
)
sessions = pd.read_excel(f"{D}/Chlamy_Tomo_Annotations.xlsx", sheet_name="Sessions overview")
print(table.to_string(index=False))
print(f"\nannotation sheet: {len(ann):,} acquisitions in {len(sessions)} sessions, {sessions.Date.min():%Y-%m-%d} to {sessions.Date.max():%Y-%m-%d}")
Output:
folder what entries
must_bin8 MUST reconstruction, binned 8x 1805
must_bin4 MUST reconstruction, binned 4x 1802
cryocare_bin4 CryoCARE denoised, binned 4x 1829
ctf3d_bin4 3D-CTF corrected, binned 4x 1829
chlamy_visual_proteomics raw frames + tilt stacks (folders) 1871
annotation sheet: 2,991 acquisitions in 55 sessions, 2021-12-01 to 2023-09-11
2. Two naming schemes, one join table
cryocare_bin4 and ctf3d_bin4 are named by number (298.mrc). must_bin8, must_bin4 and the tilt-series folders are named by position (27042022_BrnoKrios_Arctis_grid9_hGIS_Position_13). The only place the two meet is Chlamy_Tomo_Annotations.xlsx. It lists 2,991 acquisitions, but only some were released, so check membership before opening anything.
numbered = {int(n.split(".")[0]) for n in names["cryocare_bin4"]}
released = ann[ann.Tomo_number.isin(numbered)].copy()
by_name = {k: {n.removesuffix("_dose-filt.rec") for n in names[k]} for k in ("must_bin8", "must_bin4")}
released["in_must_bin8"] = released.Tomo_name.isin(by_name["must_bin8"])
released["in_must_bin4"] = released.Tomo_name.isin(by_name["must_bin4"])
released["in_tilt_series"] = released.Tomo_name.isin(set(tilt_dirs))
print(f"sheet rows : {len(ann):,}")
print(f"released (numbered file): {len(released):,} (the other {len(ann) - len(released):,} sheet rows have no volume in the bucket)")
print(f" with a tilt-series dir: {released.in_tilt_series.sum():,}")
print(f" with must_bin8 : {released.in_must_bin8.sum():,}")
print(f" with must_bin4 : {released.in_must_bin4.sum():,}")
print("must_bin4 is a subset of must_bin8:", by_name["must_bin4"] <= by_name["must_bin8"])
Output:
sheet rows : 2,991 released (numbered file): 1,829 (the other 1,162 sheet rows have no volume in the bucket) with a tilt-series dir: 1,829 with must_bin8 : 1,805 with must_bin4 : 1,802 must_bin4 is a subset of must_bin8: True
3. What the headers say
Before trusting a file, read its header. The tilt stacks carry the pixel size the data were collected at (1.96 A for most sessions, a little different for a few), and a bin4 volume should be exactly 4x that and a bin8 volume 8x. Checking each set's header against that rule shows which pixel sizes you can trust. The must_* headers do not follow it.
n298 = released[released.Tomo_number == 298].iloc[0]
paths = {
"must_bin8": f"{D}/must_bin8/{n298.Tomo_name}_dose-filt.rec",
"must_bin4": f"{D}/must_bin4/{n298.Tomo_name}_dose-filt.rec",
"cryocare_bin4": f"{D}/cryocare_bin4/298.mrc",
"ctf3d_bin4": f"{D}/ctf3d_bin4/298.rec",
}
binning = {"must_bin8": 8, "must_bin4": 4, "cryocare_bin4": 4, "ctf3d_bin4": 4}
infos = {k: mrc_info(p) for k, p in paths.items()}
stack_px = mrc_info(f"{D}/chlamy_visual_proteomics/{n298.Tomo_name}/{n298.Tomo_name}_dose-filt.st")["pixel_A"]
hdr = pd.DataFrame(
{
"voxels (x,y,z)": [f"{i['nx']}x{i['ny']}x{i['nz']}" for i in infos.values()],
"dtype": [i["dtype"] for i in infos.values()],
"header A/px": [round(i["pixel_A"], 2) for i in infos.values()],
"stack x binning": [round(stack_px * binning[k], 2) for k in infos],
},
index=list(infos),
)
print(f"tomogram 298, tilt-stack pixel size {stack_px:.2f} A\n")
print(hdr.to_string())
Output:
tomogram 298, tilt-stack pixel size 1.96 A
voxels (x,y,z) dtype header A/px stack x binning
must_bin8 512x512x256 <f4 125.44 15.68
must_bin4 1024x1024x512 <f4 31.36 7.84
cryocare_bin4 1024x1024x512 <f4 7.60 7.84
ctf3d_bin4 1024x1024x512 <i2 7.84 7.84
That is one tomogram. Here is the same check over a random sample of 30 released tomograms, comparing each header with four times the tilt-stack pixel size.
rng = np.random.default_rng(0)
sample = rng.choice(released.Tomo_number.values, 30, replace=False)
tomo_name = ann.set_index("Tomo_number").Tomo_name
rows = []
for n in sample:
nm = tomo_name[n]
rec = {
"tomo": int(n),
"stack_px": mrc_info(f"{D}/chlamy_visual_proteomics/{nm}/{nm}_dose-filt.st")["pixel_A"],
"cryocare_bin4": mrc_info(f"{D}/cryocare_bin4/{n}.mrc")["pixel_A"],
"ctf3d_bin4": mrc_info(f"{D}/ctf3d_bin4/{n}.rec")["pixel_A"],
}
if nm in by_name["must_bin4"]:
rec["must_bin4"] = mrc_info(f"{D}/must_bin4/{nm}_dose-filt.rec")["pixel_A"]
rows.append(rec)
sv = pd.DataFrame(rows)
print("tilt-stack pixel sizes in the sample:", sv.stack_px.round(2).value_counts().to_dict())
for k in ("ctf3d_bin4", "cryocare_bin4", "must_bin4"):
ok = np.isclose(sv[k], sv.stack_px * 4, atol=0.011)[sv[k].notna()]
print(f"{k:14s} header == 4 x stack in {ok.sum():2d} of {len(ok)} tomograms")
print("must_bin4 header values seen:", sorted(sv.must_bin4.dropna().round(2).unique().tolist()))
Output:
tilt-stack pixel sizes in the sample: {1.96: 29, 1.82: 1}
ctf3d_bin4 header == 4 x stack in 30 of 30 tomograms
cryocare_bin4 header == 4 x stack in 28 of 30 tomograms
must_bin4 header == 4 x stack in 0 of 29 tomograms
must_bin4 header values seen: [31.36]
4. The same tomogram, three reconstructions
Middle slice of tomogram 298 from the MUST reconstruction (bin8), the CryoCARE-denoised volume and the 3D-CTF-corrected volume. They have different dtypes and grey scales (float32 near zero, float32 in the thousands, int16), so each gets its own percentile contrast window. Never share one window across sets.
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
def show(ax, im, title, n=100):
im = np.asarray(im, dtype="f4")
f = max(1, -(-im.shape[0] // n)) # bin down to about the displayed size, then smooth lightly:
im = gaussian_filter(im[: im.shape[0] // f * f, : im.shape[1] // f * f].reshape(im.shape[0] // f, f, im.shape[1] // f, f).mean(axis=(1, 3)), 1.2) # keeps the figures small
lo, hi = np.percentile(im, [1, 99])
ax.imshow(im, cmap="gray", vmin=lo, vmax=hi, interpolation="bilinear")
ax.set_title(title, fontsize=9)
ax.axis("off")
fig, axes = plt.subplots(1, 3, figsize=(9, 3.2), dpi=60)
panels = [("must_bin8", "MUST, bin8"), ("cryocare_bin4", "CryoCARE, bin4"), ("ctf3d_bin4", "3D-CTF, bin4")]
for ax, (k, title) in zip(axes, panels):
info = infos[k]
z = info["nz"] // 2
im = read_slice(paths[k], z, info)
show(ax, im, title)
plt.tight_layout()
plt.show()
5. What the curators flagged
The sheet carries a True/False flag per tomogram for eight organelles, plus a free-text quality note. These are screening notes, not segmentations: they say an organelle appears somewhere in the volume, with no coordinates. Over the released tomograms:
flags = released[ORGANELLES].astype(float).fillna(0).astype(bool) # Pyrenoid is stored as 0.0 / 1.0, the rest as bool
counts = flags.sum().sort_values()
fig, ax = plt.subplots(figsize=(6.5, 3), dpi=70)
ax.barh(counts.index, counts.values, color="#2563eb")
for y, v in enumerate(counts.values):
ax.text(v + 10, y, f"{v:,}", va="center", fontsize=8)
ax.set_xlim(0, counts.max() * 1.12)
ax.set_xlabel(f"tomograms flagged (of {len(released):,} released)")
for side in ("top", "right"):
ax.spines[side].set_visible(False)
plt.tight_layout()
plt.show()
6. Find tomograms by what is in them
Filter the sheet, then read one slice from each match. The bin8 volumes are 256 MiB with 1 MiB slices, so six panels cost about 6 MiB of reads. Here: tomograms flagged with a nucleus, mitochondria and microtubules.
hits = released[flags.Nucleus & flags.Mitochondria & flags.Microtubules & released.in_must_bin8].sort_values("Tomo_number")
print(f"{len(hits)} tomograms match; showing the first 6\n")
pick = hits.head(6)
fig, axes = plt.subplots(2, 3, figsize=(9, 6), dpi=50)
for ax, (_, r) in zip(axes.ravel(), pick.iterrows()):
p = f"{D}/must_bin8/{r.Tomo_name}_dose-filt.rec"
show(ax, read_slice(p, 128), n=80, title=f"#{r.Tomo_number} " + ("" if pd.isna(r.Comments) else str(r.Comments)[:30]))
plt.tight_layout()
plt.show()
Output:
6 tomograms match; showing the first 6
7. Back to the tilt series
Each tomogram is reconstructed from a tilt series. The tilt-series folder holds the raw EER movies, the aligned 4096 x 4096 stack, the SerialEM .mdoc and the alignment and defocus files. The .mdoc lists tilts in acquisition order, which is dose-symmetric (a few degrees one way, then the other); the stack and its .rawtlt are sorted by angle, and a series can drop tilts that failed alignment. So read angles from the file that matches the order you need. Below: the acquisition order from the mdoc for tomogram 298's tilt series, and the stack image closest to zero tilt at full 1.96 A/pixel, binned for display.
name = n298.Tomo_name
ts_dir = f"{D}/chlamy_visual_proteomics/{name}"
stem = f"{ts_dir}/{name}_dose-filt"
mdoc_angles = np.array([float(l.split("=")[1]) for l in open(f"{ts_dir}/{name}.mdoc") if l.startswith("TiltAngle")])
stack_angles = np.array([float(x) for x in open(f"{stem}.rawtlt").read().split()])
st = mrc_info(f"{stem}.st")
print(f"mdoc : {len(mdoc_angles)} tilts in acquisition order, first six {np.round(mdoc_angles[:6], 1)}")
print(f"stack: {st['nz']} images, {st['nx']} x {st['ny']} at {st['pixel_A']:.2f} A/px, sorted {stack_angles.min():.1f} to {stack_angles.max():.1f} deg")
z0 = int(np.argmin(np.abs(stack_angles)))
im = read_slice(f"{stem}.st", z0, st)
fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.4), dpi=60, gridspec_kw={"width_ratios": [1, 1]})
a.plot(mdoc_angles, "o-", ms=3, lw=0.8, color="#2563eb")
a.set_xlabel("acquisition order"); a.set_ylabel("tilt angle (deg)")
for side in ("top", "right"):
a.spines[side].set_visible(False)
show(b, im, f"stack image {z0} ({stack_angles[z0]:.1f} deg), binned for display", n=200)
plt.tight_layout()
plt.show()
Output:
mdoc : 38 tilts in acquisition order, first six [-10. -7. -13. -16. -4. -1.] stack: 38 images, 4096 x 4096 at 1.96 A/px, sorted -64.0 to 47.0 deg
Where to go next
- Subtomogram work. Build a particle list on the CryoCARE volumes (7.84 A/pixel) and go back to the 1.96 A stacks and the AreTomo alignment in each tilt-series folder for refinement. The frames/*.eer movies are for redoing motion correction in RELION or TOMOMAN.
- Training data. Pair cryocare_bin4 volumes with the organelle flags for a weakly labelled classifier, or hold out by session (Sessions overview) so a model is tested on grids it has not seen.
- Compute. The bucket is in Stockholm (eu-north-1); heavy jobs run faster close to it.
- Cite EMPIAR-11830 (doi 10.6019/EMPIAR-11830) and the bioRxiv preprint (doi 10.1101/2024.12.28.630444). The data is CC0.
Run it
Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.