Five open cryo-EM archives in one notebook
Cryo-EM sample notebook on Scigantic.
Subspatial's 1,829 tomograms, the EMPIAR and EMDB records behind them, the CZ cryo-ET portal and KEK's RELION re-runs on AWS, read side by side.
Figure: Slice through a cryo-electron tomogram of a frozen Chlamydomonas cell: a mitochondrion with internal cristae, dark ribosomes in the cytoplasm around it, and a microtubule running diagonally at the lower right
The notebook
5 code cells, shown with the output each one printed.
Five open cryo-EM archives in one notebook
Cryo-EM data is spread across archives that each hold one stage of the same work. This notebook reads five of them at once and joins them on the entries they share:
- Subspatial (mounted at /mnt/archive): 1,829 cryo-electron tomograms of *Chlamydomonas* cells, on AWS in Stockholm.
- EMPIAR: the raw-image archive that Subspatial mirrors one entry of.
- EMDB: the map archive that records each entry's reconstruction and, for single-particle work, its resolution.
- CZ CryoET Data Portal: a catalog of about 370 tomography datasets, with annotations.
- KEK Cryo-EM SPA Workflow Records: complete RELION job trees from re-processing EMPIAR entries on AWS, in Tokyo.
Everything is read in place or through a library. Nothing is downloaded beyond a few slices and a few small text files.
Start here. Click the grey cell below and press Shift+Enter. It reads one slice of a Subspatial tomogram, then looks the same deposit up in EMDB and EMPIAR. Then change TOMO_NUMBER and run it again.
import os, struct, urllib.request
import numpy as np, pandas as pd
from scigantic_emdb import EmdbCatalog
import scigantic_empiar as se
TOMO_NUMBER = 298 # try 2189, 1903 or 2084; any tomogram number 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."""
with open(path, "rb") as f:
b = f.read(1024)
nx, ny, nz, mode = struct.unpack("<4i", b[:16])
nsymbt = struct.unpack("<i", b[92:96])[0]
return dict(nx=nx, ny=ny, nz=nz, dtype=DTYPES[mode], offset=1024 + nsymbt)
def read_slice(path, z, info=None):
"""One z-slice of an MRC volume: a single ranged read."""
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)
sl = read_slice(path, info["nz"] // 2, info)
emdb = EmdbCatalog().entry("EMD-18306")
empiar = se.EmpiarClient().summary(11830)
print(f"Subspatial : tomogram {TOMO_NUMBER} = {row.Tomo_name}, flagged {[c for c in ORGANELLES if row[c]]}")
print(f" mid slice mean {sl.mean():.1f}, read {sl.nbytes / 2**20:.0f} MiB of a {os.path.getsize(path) / 2**30:.1f} GiB file")
print(f"EMDB : {emdb['id']} ({emdb['method']}, {emdb['organism']}), raw data in EMPIAR {emdb['empiar_ids']}")
print(f"EMPIAR : {empiar['id']}, {empiar['size']} of {empiar['format']} {empiar['category']}, doi {empiar['doi']}")
1. One deposit, three archives
EMPIAR-11830 is a raw deposit of tilt series. EMDB holds a representative tomogram from it (EMD-18306). Subspatial mirrors the whole deposit on S3, plus four sets of reconstructed tomograms. Counting each set once (one folder listing each, never a recursive walk):
sets = ["must_bin8", "must_bin4", "cryocare_bin4", "ctf3d_bin4"]
counts = {k: len(os.listdir(f"{D}/{k}")) for k in sets}
counts["tilt-series folders"] = sum(os.path.isdir(f"{D}/chlamy_visual_proteomics/{e}") for e in os.listdir(f"{D}/chlamy_visual_proteomics"))
print(f"EMPIAR-11830, as EMPIAR describes it : {empiar['size']}, {empiar['format']} tilt series")
print(f"EMDB, as EMDB describes it : {emdb['id']} {emdb['title'][:70]}")
print("Subspatial, as mounted here :")
for k, v in counts.items():
print(f" {k:20s} {v:5,d}")
Output:
EMPIAR-11830, as EMPIAR describes it : 32.1 TB, EER tilt series EMDB, as EMDB describes it : EMD-18306 Towards the Visual Proteomics of C. reinhardtii using High-throughput Subspatial, as mounted here : must_bin8 1,805 must_bin4 1,802 cryocare_bin4 1,829 ctf3d_bin4 1,829 tilt-series folders 1,871
2. Tomography elsewhere: the CZ CryoET Data Portal
The portal is the other big open tomography source, indexed by dataset rather than by session. Ribosomes are the classic in situ target, so here are its ribosome datasets that carry annotations, and how many tomograms (runs) they hold compared with Subspatial's 1,829. Several of the largest are challenge or phantom datasets rather than cells, as their titles show.
import scigantic_cryoet as cryoet
portal = cryoet.CryoetCatalog()
rib = portal.search("ribosome", has_annotations=True).sort_values("n_runs", ascending=False)
print(f"{len(rib)} annotated ribosome datasets, {int(rib.n_runs.sum()):,} tomograms (runs) in total; Subspatial's EMPIAR-11830 alone has {counts['cryocare_bin4']:,}\n")
print(rib[["id", "title", "organism", "n_runs"]].head(6).to_string(index=False, max_colwidth=48))
Output:
13 annotated ribosome datasets, 1,760 tomograms (runs) in total; Subspatial's EMPIAR-11830 alone has 1,829 id title organism n_runs 10446 CZII - CryoET Object Identification Challenge... NaN 364 10007 S. cerevisiae Saccharomyces cerevisiae 270 10442 CryoET of near-minimal cells Mycoplasma mycoi... Mycoplasma mycoides subsp. capri str. GM12 262 10468 CZII 2-protein phantom (version 1.0) with def... NaN 197 10474 Cryo-FIB milled S. cerevisiae lamellas with p... Saccharomyces cerevisiae 170 10445 CZII - CryoET Object Identification Challenge... NaN 121
3. Single particle: KEK's re-processing against what EMDB deposited
KEK's archive holds complete RELION job trees from re-processing EMPIAR entries on AWS, with a per-job compute-cost table. Each tree names its EMPIAR entry, and EMDB records the resolution of the map the original authors deposited for that entry. Putting them together answers a concrete question: what did a re-run on AWS reach, and what did it cost? The hours column adds up each job's process time; the cost column is the AWS charge for those jobs. The KEK bucket is in Tokyo, so it is read here over plain HTTPS, only the small text files in each tree.
KEK = "https://cryoem-spa-workflow-records-public.s3.ap-northeast-1.amazonaws.com/ArXiv/EMPIAR"
RUNS = { # EMPIAR id -> (job tree, cost table); the two process records in the archive
10581: ("260123_tmoriya_relion5o0o0_res2o75_run05_nosplit_FSx9600", "cc_result_260123_empiar10581_nir_run05o01.csv"),
10673: ("260208_tmoriya_relion5o0o0_res2o62_run08_nosplit_fsx9600", "cc_result_260208_empiar10673_gpcr_run08o01.csv"),
}
def kek(eid, rel):
tree = RUNS[eid][0]
return urllib.request.urlopen(f"{KEK}/EMPIAR{eid}/{tree}/{rel}", timeout=60).read().decode()
emdb_all = EmdbCatalog().load()
rows = []
for eid, (tree, cc_name) in RUNS.items():
final = kek(eid, "final_maps.csv").split(",") # headerless: path, resolution, note
cost = pd.read_csv(f"{KEK}/EMPIAR{eid}/{tree}/{cc_name}")
deposited = emdb_all[emdb_all.empiar_ids.map(lambda v: str(eid) in v if isinstance(v, (list, tuple)) else False)].iloc[0]
rows.append({
"EMPIAR": eid,
"sample": se.EmpiarClient().summary(eid)["title"],
"raw": se.EmpiarClient().summary(eid)["size"],
"EMDB map": deposited["id"],
"deposited A": deposited["resolution_a"],
"KEK rerun A": round(float(final[1]), 2),
"jobs": len(cost),
"job hours": round(pd.to_numeric(cost["Process time(hours)"], errors="coerce").sum(), 1),
"AWS USD": round(pd.to_numeric(cost["Cost(ProcessTime,USD)"], errors="coerce").sum()),
})
kek_table = pd.DataFrame(rows)
print(kek_table.to_string(index=False, max_colwidth=40))
Output:
EMPIAR sample raw EMDB map deposited A KEK rerun A jobs job hours AWS USD 10581 CryoEM map and model of Nitrite Reduc... 1.0 TB EMD-0731 2.85 2.75 47 15.6 328 10673 Cryo-EM of GLP-1 receptor bound to GL... 1.9 TB EMD-21992 2.10 2.62 46 47.2 1268
Resolution depends on the particle set and masks each group chose, so read the gap between the two columns as a rough comparison, not a verdict on either pipeline. Below: a Subspatial tomogram slice next to the two resolution pairs.
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
im = np.asarray(read_slice(f"{D}/cryocare_bin4/298.mrc", 256), dtype="f4")
im = gaussian_filter(im[:1000, :1000].reshape(100, 10, 100, 10).mean(axis=(1, 3)), 1.2)
lo, hi = np.percentile(im, [1, 99])
fig, (a, b) = plt.subplots(1, 2, figsize=(9, 3.4), dpi=60, gridspec_kw={"width_ratios": [1, 1.3]})
a.imshow(im, cmap="gray", vmin=lo, vmax=hi, interpolation="bilinear")
a.set_title("Subspatial: tomogram 298, mid slice", fontsize=9); a.axis("off")
x = np.arange(len(kek_table)); w = 0.36
b.bar(x - w / 2, kek_table["deposited A"], w, color="#94a3b8", label="deposited in EMDB")
b.bar(x + w / 2, kek_table["KEK rerun A"], w, color="#2563eb", label="KEK rerun on AWS")
b.set_xticks(x); b.set_xticklabels([f"EMPIAR-{e}" for e in kek_table.EMPIAR])
b.set_ylabel("resolution (A, lower is finer)"); b.set_ylim(0, 3.7); b.legend(fontsize=8, frameon=False, loc="upper center", ncol=2)
for side in ("top", "right"):
b.spines[side].set_visible(False)
plt.tight_layout()
plt.show()
What each source is for
| Source | Holds | Read here by |
| Subspatial | Raw tilt series and 1,829 reconstructed tomograms (EMPIAR-11830) | the mount, one slice at a time |
| EMPIAR | Raw cryo-EM images, with each entry's size and format | scigantic_empiar |
| EMDB | Reconstructed maps, resolution, deposit details, links to EMPIAR and PDB | scigantic_emdb |
| CZ CryoET Data Portal | Tomography datasets with annotations | scigantic_cryoet |
| KEK SPA Workflow Records | RELION job trees and AWS cost per job | plain HTTPS from the open bucket |
Next. Search EMDB for in situ ribosome maps (EmdbCatalog().search("ribosome", method="subtomogram averaging")), pull the same tomograms' particle picks from the portal, and compare them with what the Subspatial tomograms contain. The Subspatial archive's own starter goes deeper on its file layout and header pitfalls.
Run it yourself
This sample opens as a hosted JupyterLab notebook with its datasets already mounted, so nothing has to be downloaded first. The notebook arrives with its outputs already rendered, and an AI assistant in the notebook can explain each step or change the analysis. Open the sample or browse the full catalog.