High-Throughput Processing using Mofography and Dask

In this notebook:

The same code scales to an HPC or cloud cluster by swapping the LocalCluster() for a SLURMCluster or KubeCluster. See the Dask docs for details.

Note — this is a long-running notebook. It is kept as a .ipynb (not a .qmd) because it includes a multi-material Dask run that you will likely want to re-run against different datasets. The rendered HTML in _freeze/ is built from a frozen execution for fast browsing.

Show code
# --- General imports --------------------------------------------------------
import os
import sys
import shutil
import tarfile
import pickle
from io import BytesIO
from pathlib import Path

import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px

# --- ASE + mofography --------------------------------------------------------
import mofography as mgr
from ase.io import read
from mofography.cif_io import read_cif_to_ase  # fast Rust CIF reader (returns ase.Atoms)
from ase.build import make_supercell
from ase.geometry import complete_cell

# --- Dask for HTS ------------------------------------------------------------
import dask
from dask import delayed
from dask.distributed import Client, LocalCluster, progress

# --- Notebook hygiene --------------------------------------------------------
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning, module="pymatgen")

# --- Path to the repo / docs folder (works from any cwd) --------------------
# Adjust REPO_ROOT to point at your local mofography clone. The default
# assumes the notebook lives at <repo>/docs/hts_using_mofography.ipynb.
REPO_ROOT = Path(mgr.__file__).resolve().parent.parent
DOCS_DIR  = REPO_ROOT / "docs"
TESTCIF_DIR = REPO_ROOT / "examples" / "TestCIFs"
sys.path.insert(0, str(REPO_ROOT))

print(f"mofography version: {mgr.__version__ if hasattr(mgr, '__version__') else 'dev'}")
print(f"REPO_ROOT           = {REPO_ROOT}")
print(f"TESTCIF_DIR         = {TESTCIF_DIR}  ({len(list(TESTCIF_DIR.glob('*.cif')))} CIFs)")

1. Load the dataset

The original notebook pulled a pre-built MOFdb feather file. To make this tutorial self-contained we read a small set of CIFs directly from examples/TestCIFs/. Drop your own CIFs into a folder of your choice and point cif_dir at it.

For very large datasets (1000+ structures) it is much faster to pre-pack the CIFs into a compressed Parquet dataframe first — see hts_periodic_seg_benchmark.ipynb for the same trick used in batch benchmarking.

Show code
# Pick a small set of test MOFs for the demo. The first is the canonical
# IRMOF-1; the rest are pulled from examples/TestCIFs/. Replace with your own
# folder if you have one.
cif_dir = TESTCIF_DIR
all_cifs = sorted(cif_dir.glob("*.cif"))

# Use a small, diverse subset so the demo runs in a few minutes on a laptop.
demo_stems = ["IRMOF-1", "UiO-66-RASPA", "ZIF-8-RASPA", "NU-1000_S1", "P1-Cu-BTC"]
cif_paths = [cif_dir / f"{stem}.cif" for stem in demo_stems if (cif_dir / f"{stem}.cif").exists()]
# Fall back to the first five available CIFs if the canonical set is missing.
if not cif_paths:
    cif_paths = all_cifs[:5]

print(f"Loading {len(cif_paths)} CIFs:")
for p in cif_paths:
    print(f"  {p.name}")
Show code
# Read CIFs into ASE Atoms objects. We attach the stem to atoms.info['name']
# so the saved output files keep their material name.
def load_cif_to_atoms(cif_path: Path):
    atoms = read_cif_to_ase(cif_path)  # Rust CIF reader, much faster than ase.io.read over many files
    atoms.info["name"] = cif_path.stem
    return atoms

iza_atoms = [load_cif_to_atoms(p) for p in cif_paths]
for a in iza_atoms:
    print(f"  {a.info['name']:<20s}  {len(a):>4d} atoms  cell={a.cell.cellpar()[:3].round(1)}")

2. Single-material workflow (new merged API)

The new API collapses what used to be five separate calls (dgrid_from_atoms_cpu → regions_from_dgrid → apply_pbc → get_rag_from_regions_and_grid → get_connections_for_rag) into two:

dgrid = mgr.dgrid_from_atoms_rust(atoms, spacing=0.5).astype(np.float32)
seg   = mgr.do_periodic_segmentation_rust(dgrid, atoms, ...)

The seg dict returns everything you used to assemble by hand: regions, PBC-merged regions, maxima, PBC groups, connections, and the input parameters used. See pbc_considerations.qmd for the full key reference.

Don’t use dgrid_from_atoms_gpu or dgrid_from_atoms_cpu_no_aabb. They are known to mis-handle non-orthorhombic cells. The *_rust backends are correct for all cell types.

Show code
# Pick one material and run the new merged pipeline on it.
mat_atoms = iza_atoms[0]
mat_name  = mat_atoms.info["name"]
print(f"Working on: {mat_name}  ({len(mat_atoms)} atoms)")

# --- Step 1: distance grid (Rust exact) --------------------------------------
spacing = 0.5
dgrid = mgr.dgrid_from_atoms_rust(mat_atoms, spacing=spacing)
dgrid = dgrid.astype(np.float32)        # Rust kernel requires float32
print(f"dgrid shape={dgrid.shape}  void_max={dgrid.max():.2f} Å  size={dgrid.nbytes/1e6:.1f} MB")
Show code
# --- Step 2: periodic segmentation (one call) ------------------------------
seg = mgr.do_periodic_segmentation_rust(
    dgrid, mat_atoms,
    mask_thickness=0.05,
    h=0.2,
    min_distance=1.5,
    threshold_abs=1.5,
    spacing=spacing,
    compute_connections=True,    # also fill seg['connections']
    extra_padding=5.0,           # default halo
    watershed_backend="rust_det", # default; see Section 9 for alternatives
    disable_tqdm=True,
)
print("Segmentation keys:")
for k, v in seg.items():
    if hasattr(v, "shape"):
        print(f"  {k:30s} ndarray  shape={v.shape}  dtype={v.dtype}")
    elif isinstance(v, (list, tuple, set)):
        print(f"  {k:30s} {type(v).__name__:6s}  ({len(v)} items)")
    elif isinstance(v, dict):
        print(f"  {k:30s} dict    ({len(v)} entries)")
    else:
        print(f"  {k:30s} {type(v).__name__}")

print()
print(f"  Pockets (PBC-merged): {len(seg['maxima_pbc'])}")
print(f"  Unique regions:       {len(seg['unique_regions'])}")
print(f"  PBC groups:           {len(seg['pbc_groups'])}")

3. Pocket type detection (HTS feature)

The interactive app exposes pocket type detection on every saved material. The same call works in Python: assign_pocket_types clusters pockets by their environment (peak probe radius, framework fingerprint, connectivity) using env_cluster by default.

enrich_segmentation_with_pocket_psds should be run once before typing so the per-pocket PSD sampling cost is paid only once. Both modify the dict in place by default.

Show code
# Cache pocket PSDs and assign types. This is exactly the call the
# Streamlit "Pocket types" panel makes.
seg = mgr.enrich_segmentation_with_pocket_psds(seg, mat_atoms)
print(f"pocket_psds cached:   {seg.get('pocket_psds') is not None}")
print(f"probe radius used:    {seg.get('pocket_psd_probe_radius_a'):.2f} Å")

typed = mgr.assign_pocket_types(seg, mat_atoms, method="env_cluster")
print(f"\nPocketTypingResult.ok = {typed.ok}  (method={typed.method})")
print(f"  n_types:   {typed.n_types}")
print(f"  n_pockets: {typed.n_pockets}")
print()
for t in typed.type_summary:
    print(f"  type {t['type_id']}: n={t['n_pockets']:<3d}  "
          f"max_r ∈ [{t['max_r_min_a']:.2f}, {t['max_r_max_a']:.2f}] Å  "
          f"vol ∈ [{t['volume_min_a3']:.0f}, {t['volume_max_a3']:.0f}] ų")

4. Accessibility — LCD / PLD / DFSD

Once the segmentation is done, get_pore_dia_mgr_winding runs the winding-number percolation sweep to compute the largest cavity diameter (LCD), the pore-limiting diameter (PLD), and the dominant flat surface diameter (DFSD). This is the same routine the app runs on the Accessibility tab.

The sweep also stores a per-radius percolation_history that is saved into the results .npz (and into the *_pore_dia.csv we build later).

Show code
from mofography import get_pore_dia_mgr_winding

# get_pore_dia_mgr_winding returns (lcd, pld, dfsd, percolation_grid).
lcd, pld, dfsd, _perco_grid = get_pore_dia_mgr_winding(
    mat_atoms, dgrid=dgrid,
    kwargs=dict(seg=seg, spacing=spacing, extra_padding=5.0, disable_tqdm=True),
)
print(f"LCD  = {lcd:.3f} Å")
print(f"PLD  = {pld:.3f} Å")
print(f"DFSD = {dfsd:.3f} Å")

5. Visualize the single material

show_mof_plotly is the canonical figure used by the web app. Pass the typed_result to colour the cavity surface by pocket type.

Show code
fig = mgr.show_mof_plotly(seg, mat_atoms, typed_result=typed, stylize=True)
fig.update_layout(title=f"{mat_name} — pocket types (env_cluster)")
# NB: fig.show() is interactive; the rendered HTML in _freeze/ embeds a PNG snapshot
# of the same scene so the static build stays light. We avoid fig.write_html() here
# because Plotly HTML embeds the whole grid as JSON (~4 MB per material) and is the
# reason the previous version of this notebook ballooned to 9.2 MB.
fig.show()

6. Wrap the workflow for Dask

The new merged API makes the per-material wrapper much smaller than the old multi-step function. We return the segmentation dict and the typing result together so downstream code (savers, RAG builder) doesn’t have to re-thread inputs through the dask graph.

Show code
import time

# Per-material HTS worker. The Rust dgrid + segmentation pair is the hot
# path; pocket-typing is optional and slightly slower (extra PSD sampling).
def run_one(mat_atoms, *,
            spacing=0.5,
            do_pocket_typing=True,
            do_pore_dia=True,
            watershed_backend="rust_det",
            extra_padding=5.0,
            ):
    """Compute the segmentation, pocket types, and pore diameters for one MOF.

    Returns a dict ready to be saved to .npz, or None on failure.
    """
    t0 = time.perf_counter()
    try:
        dgrid = mgr.dgrid_from_atoms_rust(mat_atoms, spacing=spacing)
        dgrid = dgrid.astype(np.float32)
        seg = mgr.do_periodic_segmentation_rust(
            dgrid, mat_atoms,
            mask_thickness=0.05, h=0.2, min_distance=1.5, threshold_abs=1.5,
            spacing=spacing, compute_connections=True,
            extra_padding=extra_padding, watershed_backend=watershed_backend,
            disable_tqdm=True,
        )

        typed = None
        if do_pocket_typing:
            seg = mgr.enrich_segmentation_with_pocket_psds(seg, mat_atoms)
            typed = mgr.assign_pocket_types(seg, mat_atoms, method="env_cluster")

        pore_dia = None
        if do_pore_dia:
            _lcd, _pld, _dfsd, _perco = get_pore_dia_mgr_winding(
                mat_atoms, dgrid=dgrid,
                kwargs=dict(seg=seg, spacing=spacing, extra_padding=extra_padding, disable_tqdm=True),
            )
            pore_dia = {
                "lcd":  float(_lcd),
                "pld":  float(_pld),
                "dfsd": float(_dfsd),
                "history_points": int(_perco.size),
            }

        return {
            "name":           mat_atoms.info.get("name", "unknown"),
            "num_atoms":      int(len(mat_atoms)),
            "cellpar":        np.asarray(mat_atoms.cell.cellpar(), dtype=np.float64),
            "dgrid_shape":    np.asarray(dgrid.shape, dtype=np.int32),
            "maxima_pbc":     np.asarray(seg["maxima_pbc"]),
            "regions_pbc":    np.asarray(seg["regions_pbc"]),
            "pbc_groups":     seg["pbc_groups"],
            "connections":    seg["connections"],
            "n_pockets":      int(len(seg["maxima_pbc"])),
            "n_regions":      int(len(seg["unique_regions"])),
            "pocket_types":   typed.n_types        if typed is not None and typed.ok else 0,
            "pocket_summary": typed.type_summary  if typed is not None and typed.ok else None,
            "pore_dia":       pore_dia,
            "wall_seconds":   float(time.perf_counter() - t0),
        }
    except Exception as exc:
        return {"name": mat_atoms.info.get("name", "unknown"), "error": repr(exc)}

7. Build the delayed futures

Each material becomes one delayed task. With Dask’s threaded scheduler this also lets us overlap the file I/O on the front end (CIF reads) with the Rust dgrid/segmentation work on the back end.

Show code
delayed_futures = [delayed(run_one)(a) for a in iza_atoms]
print(f"{len(delayed_futures)} delayed tasks queued.")

# Smoke-test the wrapper on the first material *before* starting the cluster.
# This is the canonical "test one to make sure it works" step from the
# original notebook — it surfaces import / API errors without spinning up
# Dask.
print()
print("--- test one ---")
first = delayed_futures[0].compute()
print(f"name      : {first['name']}")
print(f"n_pockets : {first['n_pockets']}")
print(f"n_types   : {first['pocket_types']}")
print(f"pore_dia  : {first['pore_dia']}")
print(f"wall      : {first['wall_seconds']:.2f} s")

8. Start a local Dask cluster

LocalCluster() gives one process per CPU core by default. On a laptop that’s usually 4–16 workers; on an HPC use SLURMCluster instead and set n_workers = # cores on one node so data transfer stays local.

Show code
# Shutdown any prior cluster (idempotent — fine to re-run).
try:
    client.close()
    cluster.close()
except (NameError, AttributeError):
    pass

cluster = LocalCluster(n_workers=min(4, os.cpu_count() or 1), threads_per_worker=1)
client  = Client(cluster)
print("Dashboard link:", client.dashboard_link)

9. Persist the workflow

dask.persist submits every task to the cluster and returns the running futures. We then attach a progress bar so you can watch the queue drain.

Show code
futures = dask.persist(*delayed_futures)
progress(futures)

10. Collect the results

We pull each future’s result with a None fallback for any that errored. Dask’s progress(futures) cell above should be fully done before you run this.

Show code
collected = client.compute(futures)
results = [f.result() if f.status == "finished" else None for f in collected]
n_ok    = sum(r is not None for r in results)
n_fail  = sum(r is None for r in results)
print(f"finished: {n_ok}/{len(results)}   failed: {n_fail}")
print()
for r in results:
    if r is None:
        print("  <None>")
    elif "error" in r:
        print(f"  {r['name']:<20s}  ERROR: {r['error']}")
    else:
        print(f"  {r['name']:<20s}  pockets={r['n_pockets']:>2d}  "
              f"types={r['pocket_types']:>2d}  "
              f"PLD={r['pore_dia']['pld']:.2f} Å  wall={r['wall_seconds']:.1f} s")

11. Save options

The interactive app stores per-material results under hts_output/<stem>/ with a small set of canonical files. We replicate that layout here so the hts_output/ folder can be opened by the Streamlit app for browsing or by the mgrcli CLI for downstream work (mgrcli aggregate ...).

The four canonical files per material are:

File Contents
<stem>_results.npz Full segmentation dict (dgrid, regions, maxima, connections, typing)
<stem>_pore_dia.csv LCD, PLD, DFSD + history point count
<stem>_psd_psd_uniform.csv Globally sampled pore-size distribution
<stem>_psd_psd_pockets.csv Per-pocket probe-occupiable PSDs
<stem>_rag_clustered.pkl NetworkX region-adjacency graph (RAG)

We build the same files here, then tar -czf the whole folder at the end so a 1000-MOF HTS run ships as a single archive.

Show code
# Point the output at the repo's docs/hts_output folder so the rendered
# HTML can be browsed without a separate demo step.
hts_root = DOCS_DIR / "hts_output"
hts_root.mkdir(parents=True, exist_ok=True)

# We re-run each material to produce the full output set. The `run_one`
# wrapper above returns a *summary* dict; here we write a richer saver
# that mirrors the Streamlit / mgrcli output format.
def save_one(mat_atoms, out_dir, *, spacing=0.5, do_pocket_typing=True, do_pore_dia=True):
    """Run the full pipeline and save all canonical files under out_dir."""
    out_dir.mkdir(parents=True, exist_ok=True)
    stem = mat_atoms.info.get("name", out_dir.name)

    dgrid = mgr.dgrid_from_atoms_rust(mat_atoms, spacing=spacing).astype(np.float32)
    seg = mgr.do_periodic_segmentation_rust(
        dgrid, mat_atoms, mask_thickness=0.05, h=0.2, min_distance=1.5,
        threshold_abs=1.5, spacing=spacing, compute_connections=True,
        extra_padding=5.0, watershed_backend="rust_det", disable_tqdm=True,
    )

    typed = None
    if do_pocket_typing:
        seg = mgr.enrich_segmentation_with_pocket_psds(seg, mat_atoms)
        typed = mgr.assign_pocket_types(seg, mat_atoms, method="env_cluster")

    _lcd, _pld, _dfsd, _perco = get_pore_dia_mgr_winding(
        mat_atoms, dgrid=dgrid,
        kwargs=dict(seg=seg, spacing=spacing, extra_padding=5.0, disable_tqdm=True),
    )
    pore_dia = {"lcd": float(_lcd),
                "pld": float(_pld),
                "dfsd": float(_dfsd),
                "history_points": int(_perco.size)}

    # --- 1) <stem>_results.npz ---------------------------------------------
    save_dict = {
        "dgrid":            dgrid,
        "maxima_pbc":       np.asarray(seg["maxima_pbc"]),
        "regions_pbc":      np.asarray(seg["regions_pbc"]),
        "pbc_groups":       np.asarray(seg["pbc_groups"], dtype=object),
        "connections":      np.asarray(seg["connections"], dtype=object),
        "lcd":              pore_dia["lcd"],
        "pld":              pore_dia["pld"],
        "dfsd":             pore_dia["dfsd"],
        "n_pockets":        int(len(seg["maxima_pbc"])),
        "n_regions":        int(len(seg["unique_regions"])),
    }
    if typed is not None and typed.ok:
        save_dict["regions_cluster"]      = np.asarray(typed.regions_cluster)
        save_dict["pocket_types_detected"]= typed.n_types
        save_dict["pocket_typing_method"] = typed.method
        save_dict["pocket_type_summary"]  = np.asarray(typed.type_summary, dtype=object)
        save_dict["pocket_rep_to_type"]   = np.asarray(typed.rep_to_type)
    np.savez_compressed(out_dir / f"{stem}_results.npz", **save_dict)

    # --- 2) <stem>_pore_dia.csv --------------------------------------------
    pd.DataFrame(
        [
            ("LCD", pore_dia["lcd"],  "Å"),
            ("PLD", pore_dia["pld"],  "Å"),
            ("DFSD", pore_dia["dfsd"], "Å"),
            ("Percolation history points", pore_dia["history_points"], "count"),
        ],
        columns=["Metric", "Value", "Unit"],
    ).to_csv(out_dir / f"{stem}_pore_dia.csv", index=False)

    # --- 3) PSDs (uniform + pocketwise) -----------------------------------
    # compute_pocket_psds_for_segmentation is the same call used by
    # enrich_segmentation_with_pocket_psds; we just write the result out.
    if do_pocket_typing and "pocket_psds" in seg:
        # pocket_psds is dict[region_label -> {bin_centers, hist, num_samples, ...}]
        psd_pockets = seg["pocket_psds"]
        rows = []
        for region_label, p in psd_pockets.items():
            centers = p["bin_centers"]
            counts  = p["hist"]
            bw = float(centers[1] - centers[0]) if len(centers) > 1 else 0.25
            for b, c in zip(centers, counts):
                rows.append({
                    "region_label": int(region_label),
                    "bin_start":    float(b) - bw / 2,
                    "bin_end":      float(b) + bw / 2,
                    "bin_center":   float(b),
                    "count":        int(c),
                })
        if rows:
            pd.DataFrame(rows).to_csv(out_dir / f"{stem}_psd_psd_pockets.csv", index=False)

    from mofography.rust_fun import compute_pore_sizes_uniform_rust
    _pts, pore_sizes = compute_pore_sizes_uniform_rust(
        dgrid, mat_atoms, num_samples_total=20000,
    )
    _bins = np.linspace(0, 50, 200)
    _hist, _edges = np.histogram(pore_sizes * 2, bins=_bins)
    pd.DataFrame({
        "bin_start":  _edges[:-1],
        "bin_end":    _edges[1:],
        "bin_center": (_edges[:-1] + _edges[1:]) / 2,
        "count":      _hist,
    }).to_csv(out_dir / f"{stem}_psd_psd_uniform.csv", index=False)

    # --- 4) RAG pickle -----------------------------------------------------
    from mofography.compute import rag_from_connections
    maxima = seg["maxima_pbc"]
    rag = rag_from_connections(seg["connections"], maxima)
    with open(out_dir / f"{stem}_rag_clustered.pkl", "wb") as f:
        pickle.dump(rag, f)

    return {"name": stem, "out_dir": str(out_dir), "pore_dia": pore_dia}
Show code
# Save every material. The dask wrapper already ran the workflow above;
# here we re-run inside save_one so the on-disk format matches the Streamlit
# layout exactly. (For real HTS runs, fold save_one into the dask task
# function so the segmentation runs only once.)
saved = []
for a in iza_atoms:
    out_dir = hts_root / a.info["name"]
    rec = save_one(a, out_dir)
    saved.append(rec)
    print(f"  {rec['name']:<20s}  PLD={rec['pore_dia']['pld']:.2f} Å  ->  {rec['out_dir']}")
Show code
# Spot-check the saved files: sizes + a peek at the pore-dia CSVs.
print(f"{'material':<22s}  {'files':>5s}  {'total KB':>8s}")
for rec in saved:
    p = Path(rec["out_dir"])
    files = sorted(p.iterdir())
    total = sum(f.stat().st_size for f in files)
    print(f"{rec['name']:<22s}  {len(files):>5d}  {total/1024:>8.1f}")
print()
print("--- example pore_dia.csv ---")
print(pd.read_csv(Path(saved[0]["out_dir"]) / f"{saved[0]['name']}_pore_dia.csv").to_string(index=False))

12. Tar on done

For large HTS runs (100+ materials) the per-material folder layout is annoying to ship. The tar-on-done helper bundles the whole hts_output/ folder into a single .tar.gz and (optionally) moves it to a release location. The Streamlit app can read straight from a tarball, so this is also the format the HTS tab expects when ingesting a completed run from another machine.

Show code
def tar_on_done(hts_root: Path, archive_path: Path, *, glob="*"):
    """Bundle hts_root into a gzipped tarball. Returns the archive path.

    `glob` lets you restrict the bundle (e.g. glob='IRMOF-1*' to ship one MOF).
    """
    archive_path = Path(archive_path)
    archive_path.parent.mkdir(parents=True, exist_ok=True)
    if archive_path.exists():
        archive_path.unlink()
    with tarfile.open(archive_path, "w:gz") as tf:
        for sub in sorted(hts_root.glob(glob)):
            if sub.is_dir():
                tf.add(sub, arcname=sub.name)
    return archive_path

archive = REPO_ROOT / "outputs" / "hts_using_mofography_demo.tar.gz"
archive.parent.mkdir(parents=True, exist_ok=True)
tar_on_done(hts_root, archive)

print(f"Archived {hts_root} -> {archive}  ({archive.stat().st_size/1024:.1f} KB)")
print()
# List the contents to confirm.
with tarfile.open(archive, "r:gz") as tf:
    for m in tf.getmembers()[:12]:
        print(f"  {m.size:>9,d}  {m.name}")
    if len(tf.getmembers()) > 12:
        print(f"  ... ({len(tf.getmembers()) - 12} more)")

13. Watershed backend comparison (mini-tutorial)

do_periodic_segmentation_rust ships with four watershed backends. They all return the same segmentation keys; the differences are determinism, speed, and the order in which basins are explored (which can shift the integer labels of equal-volume pockets).

Backend Determinism Speed When to use
rust_det ✅ (default) fast Web app default. Stable labels, good for HTS re-runs.
rust_det_parallel ✅ (deterministic by basin) fastest on big cells Drop-in for rust_det when scaling past ~1 M voxels.
rust_bucket ⚠️ basin order varies fastest on small cells Legacy. Keep for parity checks; don’t trust label IDs.
skimage ✅ slowest (Python) Pure-Python cross-check. Requires scikit-image.

The cell below re-runs the segmentation for IRMOF-1 with each backend and compares (a) wall time, (b) number of PBC-merged pockets, and (c) the label mapping. For most MOFs the basin count is identical across backends; label IDs can differ but pocket_psd_probe_radius_a and type_summary are backend-invariant (the env_cluster typing reads pocket_psds, not labels).

Show code
backends = ["rust_det", "rust_det_parallel", "rust_bucket", "skimage"]
rows = []
seg_dicts = {}

for b in backends:
    t0 = time.perf_counter()
    try:
        s = mgr.do_periodic_segmentation_rust(
            dgrid, mat_atoms,
            mask_thickness=0.05, h=0.2, min_distance=1.5, threshold_abs=1.5,
            spacing=spacing, compute_connections=True, extra_padding=5.0,
            watershed_backend=b, disable_tqdm=True,
        )
        ok = True
        err = ""
    except Exception as exc:
        ok = False
        err = repr(exc)
        s = None
    dt = time.perf_counter() - t0
    if ok:
        rows.append({
            "backend":      b,
            "wall_s":       dt,
            "n_pockets":    int(len(s["maxima_pbc"])),
            "n_regions":    int(len(s["unique_regions"])),
            "n_pbc_groups": int(len(s["pbc_groups"])),
        })
        seg_dicts[b] = s
    else:
        rows.append({"backend": b, "wall_s": dt, "error": err})

cmp_df = pd.DataFrame(rows)
print("Backend comparison on IRMOF-1 (single core, same dgrid):")
print(cmp_df.to_string(index=False))
Show code
# Cross-check: do all backends agree on the *physical* number of pockets
# (maxima_pbc)? For most cells they should.
if len(seg_dicts) > 1:
    pock_counts = {b: len(s["maxima_pbc"]) for b, s in seg_dicts.items()}
    print("Pocket counts per backend:", pock_counts)
    if len(set(pock_counts.values())) == 1:
        print("  ✓ All backends agree on the number of pockets.")
    else:
        print("  ✗ Backend counts differ — investigate the basin-ordering difference.")

14. Conclusions and next steps

In this notebook we:

  1. Loaded a small MOF set from examples/TestCIFs/ (no MOFdb token required).
  2. Computed the full segmentation in two API calls per material (dgrid_from_atoms_rust → do_periodic_segmentation_rust).
  3. Added pocket-type detection with enrich_segmentation_with_pocket_psds + assign_pocket_types (the HTS feature exposed on the app’s Pocket types tab).
  4. Computed accessibility metrics (LCD/PLD/DFSD) with the winding percolation sweep.
  5. Parallelized the workflow with Dask delayed and a LocalCluster.
  6. Saved every material to the canonical hts_output/<stem>/ layout (_results.npz, _pore_dia.csv, PSD CSVs, RAG pickle).
  7. Bundled the whole run as a single tar.gz for shipping (tar_on_done).
  8. Compared the four watershed backends on a single material.

Exercises

  • HPC run. Swap LocalCluster() for SLURMCluster and point the same run_one at a 10k-MOF dataset on your cluster’s scratch.
  • Re-run on change. Persist the futures list and re-compute() only the materials whose CIF mtime changed (skip already-processed stems).
  • CLI parity. Compare the .npz keys here with the mgrcli process output on the same CIF (the CLI saves a superset including RAG-as-arrays, timing, and accessibility method flags). See cli_quickstart.qmd.
  • Backend sensitivity. Re-run the comparison on a MOF with many tiny cages (e.g. ZIF-8) and see whether the basin-order difference matters for assign_pocket_types.