#!/usr/bin/env python3 """Build viewer-friendly Parquet splits for LiteFold/SwissSidechain.""" from __future__ import annotations import argparse import hashlib import json import re import shutil import zipfile from collections import Counter, defaultdict from pathlib import Path from typing import Any import pandas as pd ENTRY_COLUMNS = [ "entry_id", "residue_code", "stereochemistry", "smiles", "smiles_reference_file", "source_smi_path", "source_pdb_path", "source_mol2_path", "source_top_path", "source_rtp_path", "source_hdb_path", "has_smi", "has_pdb", "has_mol2", "has_top", "has_rtp", "has_hdb", "has_bundle", "has_png", "has_bundle_bbdep_lib", "has_bundle_bbind_lib", "bundle_file_extensions", "pdb_residue_names", "pdb_atom_names", "pdb_elements", "pdb_atom_count", "pdb_heavy_atom_count", "pdb_hydrogen_atom_count", "mol2_molecule_name", "mol2_molecule_type", "mol2_charge_type", "mol2_atom_names", "mol2_atom_types", "mol2_atom_charges", "mol2_atom_count", "mol2_bond_count", "mol2_total_partial_charge", "charmm_residue_name", "charmm_residue_charge", "charmm_residue_comment", "charmm_atom_names", "charmm_atom_types", "charmm_atom_charges", "charmm_atom_count", "charmm_bond_count", "gromacs_residue_name", "gromacs_residue_comment", "gromacs_atom_names", "gromacs_atom_types", "gromacs_atom_charges", "gromacs_atom_count", "gromacs_bond_count", "gromacs_improper_count", "hdb_rule_count", "hdb_declared_rule_count", "bbind_rotamer_rows", "bbdep_rotamer_rows", "split_bucket", ] def stable_bucket(value: str, buckets: int = 10) -> int: digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16] return int(digest, 16) % buckets def parse_float(value: str | None) -> float | None: if value is None: return None try: return float(value) except ValueError: return None def is_canonical_zip_path(name: str, expected_prefix: str) -> bool: parts = Path(name).parts return len(parts) >= 2 and parts[0] == expected_prefix def read_zip_text_by_stem(path: Path, expected_prefix: str, suffixes: tuple[str, ...]) -> dict[str, dict[str, str]]: items: dict[str, dict[str, str]] = {} with zipfile.ZipFile(path) as zf: for name in zf.namelist(): if name.endswith("/") or not name.lower().endswith(suffixes): continue stem = Path(name).stem text = zf.read(name).decode("utf-8", errors="replace") existing = items.get(stem) if existing is None or ( is_canonical_zip_path(name, expected_prefix) and not is_canonical_zip_path(existing["path"], expected_prefix) ): items[stem] = {"path": name, "text": text} return items def read_rtp_hdb_zip(path: Path, expected_prefix: str) -> tuple[dict[str, dict[str, str]], dict[str, dict[str, str]]]: rtp: dict[str, dict[str, str]] = {} hdb: dict[str, dict[str, str]] = {} with zipfile.ZipFile(path) as zf: for name in zf.namelist(): if name.endswith("/"): continue stem = Path(name).stem suffix = Path(name).suffix.lower() target = rtp if suffix == ".rtp" else hdb if suffix == ".hdb" else None if target is None: continue text = zf.read(name).decode("utf-8", errors="replace") existing = target.get(stem) if existing is None or ( is_canonical_zip_path(name, expected_prefix) and not is_canonical_zip_path(existing["path"], expected_prefix) ): target[stem] = {"path": name, "text": text} return rtp, hdb def parse_smi(text: str) -> tuple[str | None, str | None]: for line in text.splitlines(): stripped = line.strip() if not stripped: continue parts = stripped.split() return parts[0], parts[1] if len(parts) > 1 else None return None, None def parse_pdb(text: str) -> dict[str, Any]: atom_names: list[str] = [] elements: list[str] = [] residue_names: set[str] = set() for line in text.splitlines(): if not (line.startswith("ATOM") or line.startswith("HETATM")): continue atom_name = line[12:16].strip() residue_name = line[17:20].strip() element = line[76:78].strip() if len(line) >= 78 else "" if not element: element = re.sub(r"[^A-Za-z]", "", atom_name)[:1] if atom_name: atom_names.append(atom_name) if residue_name: residue_names.add(residue_name) if element: elements.append(element.upper()) return { "pdb_residue_names": sorted(residue_names), "pdb_atom_names": atom_names, "pdb_elements": elements, "pdb_atom_count": len(atom_names), "pdb_heavy_atom_count": sum(1 for element in elements if element != "H"), "pdb_hydrogen_atom_count": sum(1 for element in elements if element == "H"), } def parse_mol2(text: str) -> dict[str, Any]: section: str | None = None molecule_lines: list[str] = [] atom_names: list[str] = [] atom_types: list[str] = [] charges: list[float] = [] bond_count = 0 for raw in text.splitlines(): line = raw.rstrip() if line.startswith("@"): section = line.removeprefix("@").strip() continue if not line.strip(): continue if section == "MOLECULE": molecule_lines.append(line.strip()) elif section == "ATOM": parts = line.split() if len(parts) >= 6: atom_names.append(parts[1]) atom_types.append(parts[5]) if len(parts) >= 9: charge = parse_float(parts[8]) if charge is not None: charges.append(charge) elif section == "BOND": parts = line.split() if len(parts) >= 4: bond_count += 1 counts = molecule_lines[1].split() if len(molecule_lines) > 1 else [] declared_bonds = int(counts[1]) if len(counts) > 1 and counts[1].isdigit() else bond_count return { "mol2_molecule_name": molecule_lines[0] if molecule_lines else None, "mol2_molecule_type": molecule_lines[2] if len(molecule_lines) > 2 else None, "mol2_charge_type": molecule_lines[3] if len(molecule_lines) > 3 else None, "mol2_atom_names": atom_names, "mol2_atom_types": atom_types, "mol2_atom_charges": charges, "mol2_atom_count": len(atom_names), "mol2_bond_count": declared_bonds, "mol2_total_partial_charge": round(sum(charges), 6) if charges else None, } def parse_charmm_top(text: str) -> dict[str, Any]: residue_name = None residue_charge = None residue_comment = None atom_names: list[str] = [] atom_types: list[str] = [] atom_charges: list[float] = [] bond_count = 0 for raw in text.splitlines(): line = raw.strip() if not line or line.startswith("!"): continue data, _, comment = line.partition("!") parts = data.split() if not parts: continue keyword = parts[0].upper() if keyword == "RESI" and len(parts) >= 3: residue_name = parts[1] residue_charge = parse_float(parts[2]) residue_comment = comment.strip() or None elif keyword == "ATOM" and len(parts) >= 4: atom_names.append(parts[1]) atom_types.append(parts[2]) charge = parse_float(parts[3]) if charge is not None: atom_charges.append(charge) elif keyword in {"BOND", "DOUBLE"}: bond_count += len(parts[1:]) // 2 return { "charmm_residue_name": residue_name, "charmm_residue_charge": residue_charge, "charmm_residue_comment": residue_comment, "charmm_atom_names": atom_names, "charmm_atom_types": atom_types, "charmm_atom_charges": atom_charges, "charmm_atom_count": len(atom_names), "charmm_bond_count": bond_count, } def parse_gromacs_rtp(text: str) -> dict[str, Any]: residue_name = None residue_comment = None section = None atom_names: list[str] = [] atom_types: list[str] = [] atom_charges: list[float] = [] bond_count = 0 improper_count = 0 for raw in text.splitlines(): line = raw.strip() if not line or line.startswith(";"): continue data, _, comment = line.partition(";") data = data.strip() if data.startswith("[") and data.endswith("]"): label = data.strip("[]").strip() if residue_name is None and label not in {"atoms", "bonds", "impropers", "cmap"}: residue_name = label residue_comment = comment.strip() or None section = None else: section = label.lower() continue parts = data.split() if section == "atoms" and len(parts) >= 3: atom_names.append(parts[0]) atom_types.append(parts[1]) charge = parse_float(parts[2]) if charge is not None: atom_charges.append(charge) elif section == "bonds" and len(parts) >= 2: bond_count += 1 elif section == "impropers" and len(parts) >= 4: improper_count += 1 return { "gromacs_residue_name": residue_name, "gromacs_residue_comment": residue_comment, "gromacs_atom_names": atom_names, "gromacs_atom_types": atom_types, "gromacs_atom_charges": atom_charges, "gromacs_atom_count": len(atom_names), "gromacs_bond_count": bond_count, "gromacs_improper_count": improper_count, } def parse_hdb(text: str) -> dict[str, Any]: lines = [line.strip() for line in text.splitlines() if line.strip() and not line.strip().startswith(";")] declared = None if lines: parts = lines[0].split() if len(parts) >= 2: try: declared = int(parts[1]) except ValueError: declared = None return { "hdb_rule_count": max(len(lines) - 1, 0), "hdb_declared_rule_count": declared, } def archive_bundle_manifest(path: Path, stereochemistry: str) -> dict[str, dict[str, Any]]: manifest: dict[str, dict[str, Any]] = defaultdict(lambda: {"extensions": Counter(), "paths": []}) with zipfile.ZipFile(path) as zf: for name in zf.namelist(): if name.endswith("/"): continue parts = Path(name).parts if len(parts) < 2: continue residue_code = parts[-2] suffix = Path(name).suffix.lower() or "" manifest[residue_code]["extensions"][suffix] += 1 manifest[residue_code]["paths"].append(name) result = {} for residue_code, item in manifest.items(): extensions = item["extensions"] result[residue_code] = { "bundle_file_extensions": sorted(extensions), "has_png": extensions.get(".png", 0) > 0, "has_bundle_bbdep_lib": any(path.endswith("_bbdep_Gfeller.lib.zip") for path in item["paths"]), "has_bundle_bbind_lib": any(path.endswith("_bbind_Gfeller.lib.zip") for path in item["paths"]), "stereochemistry": stereochemistry, } return result def parse_rotamer_counts(path: Path, stereochemistry: str, library_type: str) -> tuple[dict[str, int], list[dict[str, Any]]]: counts: Counter[str] = Counter() with zipfile.ZipFile(path) as zf: name = next(n for n in zf.namelist() if n.endswith(".lib")) with zf.open(name) as handle: for raw in handle: line = raw.decode("utf-8", errors="replace").strip() if not line or line.startswith("#"): continue counts[line.split()[0]] += 1 rows = [ { "stereochemistry": stereochemistry, "library_type": library_type, "residue_code": residue_code, "row_count": int(row_count), } for residue_code, row_count in sorted(counts.items()) ] return dict(counts), rows def build_rows_for_stereo(raw_dir: Path, stereochemistry: str) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: prefix = "L" if stereochemistry == "L" else "D" smi = read_zip_text_by_stem(raw_dir / f"{prefix}_SMI.zip", f"{prefix}_SMI", (".smi",)) pdb = read_zip_text_by_stem(raw_dir / f"{prefix}_PDB.zip", f"{prefix}_PDB", (".pdb",)) mol2 = read_zip_text_by_stem(raw_dir / f"{prefix}_MOL2.zip", f"{prefix}_MOL2", (".mol2",)) top = read_zip_text_by_stem(raw_dir / f"{prefix}_top.zip", f"{prefix}_top", (".top",)) rtp, hdb = read_rtp_hdb_zip(raw_dir / f"{prefix}_rtp.zip", f"{prefix}_rtp") bundle = archive_bundle_manifest( raw_dir / ("L_sidechain.zip" if stereochemistry == "L" else "D_residues.zip"), stereochemistry=stereochemistry, ) bbind_counts, bbind_rows = parse_rotamer_counts( raw_dir / f"{prefix}_bbind_Gfeller.lib.zip", stereochemistry=stereochemistry, library_type="bbind", ) bbdep_counts, bbdep_rows = parse_rotamer_counts( raw_dir / f"{prefix}_bbdep_Gfeller.lib.zip", stereochemistry=stereochemistry, library_type="bbdep", ) rows: list[dict[str, Any]] = [] for residue_code in sorted(smi): smiles, reference_file = parse_smi(smi[residue_code]["text"]) entry_id = f"{stereochemistry}:{residue_code}" row = { "entry_id": entry_id, "residue_code": residue_code, "stereochemistry": stereochemistry, "smiles": smiles, "smiles_reference_file": reference_file, "source_smi_path": smi[residue_code]["path"], "source_pdb_path": pdb.get(residue_code, {}).get("path"), "source_mol2_path": mol2.get(residue_code, {}).get("path"), "source_top_path": top.get(residue_code, {}).get("path"), "source_rtp_path": rtp.get(residue_code, {}).get("path"), "source_hdb_path": hdb.get(residue_code, {}).get("path"), "has_smi": True, "has_pdb": residue_code in pdb, "has_mol2": residue_code in mol2, "has_top": residue_code in top, "has_rtp": residue_code in rtp, "has_hdb": residue_code in hdb, "has_bundle": residue_code in bundle, "has_png": bool(bundle.get(residue_code, {}).get("has_png", False)), "has_bundle_bbdep_lib": bool(bundle.get(residue_code, {}).get("has_bundle_bbdep_lib", False)), "has_bundle_bbind_lib": bool(bundle.get(residue_code, {}).get("has_bundle_bbind_lib", False)), "bundle_file_extensions": bundle.get(residue_code, {}).get("bundle_file_extensions", []), "bbind_rotamer_rows": int(bbind_counts.get(residue_code, 0)), "bbdep_rotamer_rows": int(bbdep_counts.get(residue_code, 0)), "split_bucket": stable_bucket(entry_id), } row.update(parse_pdb(pdb[residue_code]["text"]) if residue_code in pdb else parse_pdb("")) row.update(parse_mol2(mol2[residue_code]["text"]) if residue_code in mol2 else parse_mol2("")) row.update(parse_charmm_top(top[residue_code]["text"]) if residue_code in top else parse_charmm_top("")) row.update(parse_gromacs_rtp(rtp[residue_code]["text"]) if residue_code in rtp else parse_gromacs_rtp("")) row.update(parse_hdb(hdb[residue_code]["text"]) if residue_code in hdb else parse_hdb("")) rows.append(row) manifest_rows = [] for label, mapping in [ ("SMI", smi), ("PDB", pdb), ("MOL2", mol2), ("top", top), ("rtp", rtp), ("hdb", hdb), ]: manifest_rows.append( { "stereochemistry": stereochemistry, "archive_kind": label, "unique_residue_codes": len(mapping), "residue_codes": sorted(mapping), } ) return rows, bbind_rows + bbdep_rows + manifest_rows def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]: l_rows, l_metadata = build_rows_for_stereo(raw_dir, "L") d_rows, d_metadata = build_rows_for_stereo(raw_dir, "D") rows = l_rows + d_rows if out_dir.exists(): shutil.rmtree(out_dir) data_dir = out_dir / "data" metadata_dir = out_dir / "metadata" data_dir.mkdir(parents=True, exist_ok=True) metadata_dir.mkdir(parents=True, exist_ok=True) df = pd.DataFrame.from_records(rows, columns=ENTRY_COLUMNS) df = df.sort_values(["split_bucket", "entry_id"], kind="mergesort") train = df[df["split_bucket"].ne(0)].sort_values("entry_id", kind="mergesort") test = df[df["split_bucket"].eq(0)].sort_values("entry_id", kind="mergesort") train.to_parquet(data_dir / "train-00000-of-00001.parquet", index=False, compression="zstd") test.to_parquet(data_dir / "test-00000-of-00001.parquet", index=False, compression="zstd") rotamer_rows = [row for row in l_metadata + d_metadata if row.get("library_type")] manifest_rows = [row for row in l_metadata + d_metadata if row.get("archive_kind")] pd.DataFrame.from_records(rotamer_rows).to_parquet( metadata_dir / "rotamer_library_counts.parquet", index=False, compression="zstd" ) pd.DataFrame.from_records(manifest_rows).to_parquet( metadata_dir / "archive_manifest.parquet", index=False, compression="zstd" ) stereo_counts = df["stereochemistry"].value_counts().to_dict() summary = { "source": "LiteFold/SwissSidechain", "entry_rows": int(len(df)), "splits": { "train": int(len(train)), "test": int(len(test)), }, "split_strategy": "deterministic sha256(entry_id) % 10; bucket 0 is test, buckets 1-9 are train", "stereochemistry_counts": {str(k): int(v) for k, v in stereo_counts.items()}, "entries_with_pdb": int(df["has_pdb"].sum()), "entries_with_mol2": int(df["has_mol2"].sum()), "entries_with_top": int(df["has_top"].sum()), "entries_with_rtp": int(df["has_rtp"].sum()), "entries_with_hdb": int(df["has_hdb"].sum()), "entries_with_bundle": int(df["has_bundle"].sum()), "entries_with_bbdep_rotamers": int(df["bbdep_rotamer_rows"].gt(0).sum()), "entries_with_bbind_rotamers": int(df["bbind_rotamer_rows"].gt(0).sum()), "total_bbdep_rotamer_rows": int(df["bbdep_rotamer_rows"].sum()), "total_bbind_rotamer_rows": int(df["bbind_rotamer_rows"].sum()), "archive_manifest_rows": int(len(manifest_rows)), "rotamer_library_count_rows": int(len(rotamer_rows)), "columns": ENTRY_COLUMNS, "source_files_used": sorted(path.name for path in raw_dir.glob("*.zip")), } (out_dir / "dataset_summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") return summary def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--raw-dir", type=Path, default=Path("LiteFold_SwissSidechain_raw")) parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_SwissSidechain_processed")) args = parser.parse_args() summary = build_dataset(args.raw_dir, args.out_dir) print(json.dumps(summary, indent=2)) if __name__ == "__main__": main()