PDB-CCD / scripts /prepare_pdb_ccd_dataset.py
anindya64's picture
Add normalized Parquet train/test PDB CCD table
f10c90f verified
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold/PDB-CCD."""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
import re
import shutil
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterator
import pandas as pd
COMPONENT_COLUMNS = [
"component_id",
"name",
"component_type",
"pdbx_type",
"formula",
"formula_weight",
"formal_charge",
"mon_nstd_parent_comp_id",
"one_letter_code",
"three_letter_code",
"pdbx_synonyms",
"synonym_names",
"synonym_provenances",
"synonym_types",
"initial_date",
"modified_date",
"release_status",
"ambiguous_flag",
"replaced_by",
"replaces",
"model_coordinates_missing_flag",
"ideal_coordinates_missing_flag",
"model_coordinates_db_code",
"processing_site",
"atom_ids",
"atom_alt_ids",
"atom_elements",
"atom_charges",
"atom_aromatic_flags",
"atom_leaving_flags",
"atom_stereo_configs",
"atom_count",
"heavy_atom_count",
"hydrogen_atom_count",
"bond_atom_id_1",
"bond_atom_id_2",
"bond_orders",
"bond_aromatic_flags",
"bond_stereo_configs",
"bond_count",
"descriptor_types",
"descriptor_programs",
"descriptor_program_versions",
"descriptors",
"canonical_smiles",
"smiles",
"inchi",
"inchikey",
"identifier_types",
"identifier_programs",
"identifier_program_versions",
"identifiers",
"systematic_names",
"audit_actions",
"audit_dates",
"audit_processing_sites",
"related_component_ids",
"related_relationship_types",
"pcm_ids",
"pcm_modified_residue_ids",
"pcm_types",
"pcm_categories",
"pcm_positions",
"feature_types",
"feature_values",
"split_bucket",
]
@dataclass
class TokenStream:
iterator: Iterator[str]
pushed: list[str]
def next(self) -> str | None:
if self.pushed:
return self.pushed.pop()
return next(self.iterator, None)
def push(self, token: str) -> None:
self.pushed.append(token)
def cif_tokens(path: Path) -> Iterator[str]:
with gzip.open(path, "rt", encoding="utf-8", errors="replace") as handle:
multiline: list[str] | None = None
for raw_line in handle:
line = raw_line.rstrip("\n")
if multiline is not None:
if line.startswith(";"):
yield "\n".join(multiline).strip()
multiline = None
else:
multiline.append(line)
continue
if line.startswith(";"):
multiline = [line[1:]]
continue
i = 0
length = len(line)
while i < length:
while i < length and line[i].isspace():
i += 1
if i >= length:
break
if line[i] == "#":
break
if line[i] in {"'", '"'}:
quote = line[i]
i += 1
value: list[str] = []
while i < length:
char = line[i]
if char == quote:
next_index = i + 1
if next_index >= length or line[next_index].isspace() or line[next_index] == "#":
i += 1
break
value.append(char)
i += 1
yield "".join(value)
continue
start = i
while i < length and not line[i].isspace() and line[i] != "#":
i += 1
yield line[start:i]
if i < length and line[i] == "#":
break
def clean_value(value: str | None) -> Any:
if value in {None, "?", "."}:
return None
return re.sub(r"\s+", " ", value).strip()
def parse_int(value: Any) -> int | None:
value = clean_value(value)
if value is None:
return None
try:
return int(value)
except (TypeError, ValueError):
return None
def parse_float(value: Any) -> float | None:
value = clean_value(value)
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def stable_bucket(value: str, buckets: int = 10) -> int:
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
return int(digest, 16) % buckets
def split_tag(tag: str) -> tuple[str, str]:
body = tag[1:]
category, field = body.split(".", 1)
return category, field
def finish_loop(tags: list[str], values: list[str], loops: dict[str, list[dict[str, Any]]]) -> None:
if not tags:
return
categories = {split_tag(tag)[0] for tag in tags}
if len(categories) != 1:
return
category = categories.pop()
fields = [split_tag(tag)[1] for tag in tags]
width = len(fields)
rows = []
for start in range(0, len(values) - (len(values) % width), width):
rows.append({field: clean_value(values[start + index]) for index, field in enumerate(fields)})
loops.setdefault(category, []).extend(rows)
def parse_cif_blocks(path: Path) -> Iterator[dict[str, Any]]:
stream = TokenStream(cif_tokens(path), [])
block: dict[str, Any] | None = None
while True:
token = stream.next()
if token is None:
if block is not None:
yield block
break
if token.startswith("data_"):
if block is not None:
yield block
block = {"name": token[5:], "scalars": {}, "loops": {}}
continue
if block is None:
continue
if token == "loop_":
tags: list[str] = []
values: list[str] = []
while True:
item = stream.next()
if item is None:
break
if item.startswith("_"):
tags.append(item)
continue
stream.push(item)
break
while True:
item = stream.next()
if item is None:
finish_loop(tags, values, block["loops"])
return
if item == "loop_" or item.startswith("data_") or item.startswith("_"):
stream.push(item)
break
values.append(item)
finish_loop(tags, values, block["loops"])
continue
if token.startswith("_"):
value = stream.next()
if value is None:
continue
if value == "loop_" or value.startswith("data_") or value.startswith("_"):
stream.push(value)
continue
category, field = split_tag(token)
block["scalars"].setdefault(category, {})[field] = clean_value(value)
def first_by_type(rows: list[dict[str, Any]], wanted_type: str) -> str | None:
for row in rows:
if row.get("type") == wanted_type and row.get("descriptor"):
return str(row["descriptor"])
return None
def values(rows: list[dict[str, Any]], field: str) -> list[Any]:
return [row[field] for row in rows if row.get(field) is not None]
def string_values(rows: list[dict[str, Any]], field: str) -> list[str]:
return [str(row[field]) for row in rows if row.get(field) is not None]
def int_values(rows: list[dict[str, Any]], field: str) -> list[int]:
parsed = []
for row in rows:
value = parse_int(row.get(field))
if value is not None:
parsed.append(value)
return parsed
def component_row(block: dict[str, Any]) -> dict[str, Any]:
scalars = block["scalars"].get("chem_comp", {})
loops = block["loops"]
atoms = loops.get("chem_comp_atom", [])
bonds = loops.get("chem_comp_bond", [])
descriptors = loops.get("pdbx_chem_comp_descriptor", [])
identifiers = loops.get("pdbx_chem_comp_identifier", [])
audits = loops.get("pdbx_chem_comp_audit", [])
synonyms = loops.get("pdbx_chem_comp_synonyms", [])
related = loops.get("pdbx_chem_comp_related", [])
pcms = loops.get("pdbx_chem_comp_pcm", [])
features = loops.get("pdbx_chem_comp_feature", [])
component_id = str(scalars.get("id") or block["name"])
atom_elements = string_values(atoms, "type_symbol")
heavy_atom_count = sum(1 for element in atom_elements if element.upper() != "H")
hydrogen_atom_count = sum(1 for element in atom_elements if element.upper() == "H")
return {
"component_id": component_id,
"name": scalars.get("name"),
"component_type": scalars.get("type"),
"pdbx_type": scalars.get("pdbx_type"),
"formula": scalars.get("formula"),
"formula_weight": parse_float(scalars.get("formula_weight")),
"formal_charge": parse_int(scalars.get("pdbx_formal_charge")),
"mon_nstd_parent_comp_id": scalars.get("mon_nstd_parent_comp_id"),
"one_letter_code": scalars.get("one_letter_code"),
"three_letter_code": scalars.get("three_letter_code"),
"pdbx_synonyms": scalars.get("pdbx_synonyms"),
"synonym_names": string_values(synonyms, "name"),
"synonym_provenances": string_values(synonyms, "provenance"),
"synonym_types": string_values(synonyms, "type"),
"initial_date": scalars.get("pdbx_initial_date"),
"modified_date": scalars.get("pdbx_modified_date"),
"release_status": scalars.get("pdbx_release_status"),
"ambiguous_flag": scalars.get("pdbx_ambiguous_flag"),
"replaced_by": scalars.get("pdbx_replaced_by"),
"replaces": scalars.get("pdbx_replaces"),
"model_coordinates_missing_flag": scalars.get("pdbx_model_coordinates_missing_flag"),
"ideal_coordinates_missing_flag": scalars.get("pdbx_ideal_coordinates_missing_flag"),
"model_coordinates_db_code": scalars.get("pdbx_model_coordinates_db_code"),
"processing_site": scalars.get("pdbx_processing_site"),
"atom_ids": string_values(atoms, "atom_id"),
"atom_alt_ids": string_values(atoms, "alt_atom_id"),
"atom_elements": atom_elements,
"atom_charges": int_values(atoms, "charge"),
"atom_aromatic_flags": string_values(atoms, "pdbx_aromatic_flag"),
"atom_leaving_flags": string_values(atoms, "pdbx_leaving_atom_flag"),
"atom_stereo_configs": string_values(atoms, "pdbx_stereo_config"),
"atom_count": len(atoms),
"heavy_atom_count": heavy_atom_count,
"hydrogen_atom_count": hydrogen_atom_count,
"bond_atom_id_1": string_values(bonds, "atom_id_1"),
"bond_atom_id_2": string_values(bonds, "atom_id_2"),
"bond_orders": string_values(bonds, "value_order"),
"bond_aromatic_flags": string_values(bonds, "pdbx_aromatic_flag"),
"bond_stereo_configs": string_values(bonds, "pdbx_stereo_config"),
"bond_count": len(bonds),
"descriptor_types": string_values(descriptors, "type"),
"descriptor_programs": string_values(descriptors, "program"),
"descriptor_program_versions": string_values(descriptors, "program_version"),
"descriptors": string_values(descriptors, "descriptor"),
"canonical_smiles": first_by_type(descriptors, "SMILES_CANONICAL"),
"smiles": first_by_type(descriptors, "SMILES"),
"inchi": first_by_type(descriptors, "InChI"),
"inchikey": first_by_type(descriptors, "InChIKey"),
"identifier_types": string_values(identifiers, "type"),
"identifier_programs": string_values(identifiers, "program"),
"identifier_program_versions": string_values(identifiers, "program_version"),
"identifiers": string_values(identifiers, "identifier"),
"systematic_names": [
str(row["identifier"])
for row in identifiers
if row.get("type") == "SYSTEMATIC NAME" and row.get("identifier") is not None
],
"audit_actions": string_values(audits, "action_type"),
"audit_dates": string_values(audits, "date"),
"audit_processing_sites": string_values(audits, "processing_site"),
"related_component_ids": string_values(related, "related_comp_id"),
"related_relationship_types": string_values(related, "relationship_type"),
"pcm_ids": string_values(pcms, "pcm_id"),
"pcm_modified_residue_ids": string_values(pcms, "modified_residue_id"),
"pcm_types": string_values(pcms, "type"),
"pcm_categories": string_values(pcms, "category"),
"pcm_positions": string_values(pcms, "position"),
"feature_types": string_values(features, "type"),
"feature_values": string_values(features, "value"),
"split_bucket": stable_bucket(component_id),
}
def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]:
cif_path = raw_dir / "components.cif.gz"
rows = [component_row(block) for block in parse_cif_blocks(cif_path)]
if out_dir.exists():
shutil.rmtree(out_dir)
data_dir = out_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
df = pd.DataFrame.from_records(rows, columns=COMPONENT_COLUMNS)
df = df.sort_values(["split_bucket", "component_id"], kind="mergesort")
train = df[df["split_bucket"].ne(0)].sort_values("component_id", kind="mergesort")
test = df[df["split_bucket"].eq(0)].sort_values("component_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")
def count_column(column: str) -> dict[str, int]:
return {
str(key): int(value)
for key, value in df[column].fillna("missing").value_counts(dropna=False).to_dict().items()
}
release_status_counts = count_column("release_status")
type_counts = count_column("component_type")
pdbx_type_counts = count_column("pdbx_type")
element_counts = Counter(element for elements in df["atom_elements"] for element in elements)
descriptor_type_counts = Counter(kind for kinds in df["descriptor_types"] for kind in kinds)
identifier_type_counts = Counter(kind for kinds in df["identifier_types"] for kind in kinds)
max_modified_date = max((value for value in df["modified_date"].dropna().tolist()), default=None)
summary = {
"source": "LiteFold/PDB-CCD",
"component_rows": int(len(df)),
"splits": {
"train": int(len(train)),
"test": int(len(test)),
},
"split_strategy": "deterministic sha256(component_id) % 10; bucket 0 is test, buckets 1-9 are train",
"release_status_counts": release_status_counts,
"component_type_counts": type_counts,
"pdbx_type_counts": pdbx_type_counts,
"max_modified_date": max_modified_date,
"components_with_atoms": int(df["atom_count"].gt(0).sum()),
"components_with_bonds": int(df["bond_count"].gt(0).sum()),
"components_with_descriptors": int(df["descriptors"].map(len).gt(0).sum()),
"components_with_identifiers": int(df["identifiers"].map(len).gt(0).sum()),
"components_with_pcm": int(df["pcm_ids"].map(len).gt(0).sum()),
"top_elements": dict(element_counts.most_common(30)),
"descriptor_type_counts": dict(descriptor_type_counts.most_common()),
"identifier_type_counts": dict(identifier_type_counts.most_common()),
"columns": COMPONENT_COLUMNS,
"source_files_used": ["components.cif.gz"],
}
(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_PDB_CCD_raw"))
parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_PDB_CCD_processed"))
args = parser.parse_args()
summary = build_dataset(args.raw_dir, args.out_dir)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()