# 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}