CATH / scripts /prepare_cath_dataset.py
anindya64's picture
Add normalized Parquet train/test splits
e499a9b verified
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold/CATH."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
from pathlib import Path
import pandas as pd
DOMAIN_COLUMNS = [
"domain_id",
"class_number",
"architecture_number",
"topology_number",
"homologous_superfamily_number",
"s35_cluster_id",
"s60_cluster_id",
"s95_cluster_id",
"s100_cluster_id",
"s100_sequence_count",
"domain_length",
"raw_structure_resolution_angstrom",
]
def iter_data_lines(path: Path):
with path.open("r", encoding="utf-8") as handle:
for line in handle:
line = line.rstrip("\n")
if not line or line.startswith("#"):
continue
yield line
def parse_domain_list(path: Path) -> pd.DataFrame:
records = []
for line in iter_data_lines(path):
parts = line.split()
if len(parts) != len(DOMAIN_COLUMNS):
raise ValueError(f"Expected {len(DOMAIN_COLUMNS)} columns in {path}, got {len(parts)}: {line}")
records.append(parts)
df = pd.DataFrame(records, columns=DOMAIN_COLUMNS)
int_columns = [
"class_number",
"architecture_number",
"topology_number",
"homologous_superfamily_number",
"s35_cluster_id",
"s60_cluster_id",
"s95_cluster_id",
"s100_cluster_id",
"s100_sequence_count",
"domain_length",
]
for col in int_columns:
df[col] = df[col].astype("int64")
df["raw_structure_resolution_angstrom"] = df["raw_structure_resolution_angstrom"].astype("float64")
df["structure_resolution_is_unknown"] = df["raw_structure_resolution_angstrom"].eq(999.0)
df["structure_resolution_angstrom"] = df["raw_structure_resolution_angstrom"].mask(
df["structure_resolution_is_unknown"]
)
df["structure_resolution_angstrom"] = df["structure_resolution_angstrom"].astype("Float64")
df["pdb_id"] = df["domain_id"].str.slice(0, 4)
df["chain_id"] = df["domain_id"].str.slice(4, 5)
df["pdb_chain_id"] = df["domain_id"].str.slice(0, 5)
df["domain_suffix"] = df["domain_id"].str.slice(5, 7)
df["domain_index"] = df["domain_suffix"].astype("int64")
df["class_code"] = df["class_number"].astype(str)
df["architecture_code"] = df["class_code"] + "." + df["architecture_number"].astype(str)
df["topology_code"] = df["architecture_code"] + "." + df["topology_number"].astype(str)
df["homologous_superfamily_code"] = (
df["topology_code"] + "." + df["homologous_superfamily_number"].astype(str)
)
df["cath_code"] = df["homologous_superfamily_code"]
df["s35_cluster_key"] = df["homologous_superfamily_code"] + ":S35:" + df["s35_cluster_id"].astype(str)
return df
def parse_names(path: Path) -> pd.DataFrame:
records = []
for line in iter_data_lines(path):
if ":" not in line:
continue
left, name = line.split(":", 1)
parts = left.split()
if len(parts) < 2:
continue
records.append(
{
"cath_node_code": parts[0],
"example_domain_id": parts[1],
"cath_node_name": name.strip(),
}
)
return pd.DataFrame.from_records(records)
_RANGE_SEGMENT_RE = re.compile(r"^\s*(-?\d+)(?:\([A-Za-z0-9]+\))?-(-?\d+)(?:\([A-Za-z0-9]+\))?\s*$")
def parse_range_summary(sequence_range: str) -> tuple[int | None, int | None, int]:
starts: list[int] = []
ends: list[int] = []
segments = [segment for segment in sequence_range.split("_") if segment]
for segment in segments:
match = _RANGE_SEGMENT_RE.match(segment)
if not match:
continue
starts.append(int(match.group(1)))
ends.append(int(match.group(2)))
if not starts:
return None, None, len(segments)
return min(starts), max(ends), len(segments)
def parse_fasta(path: Path) -> pd.DataFrame:
records = []
header: str | None = None
sequence_chunks: list[str] = []
def flush() -> None:
if header is None:
return
try:
_, version, payload = header.split("|", 2)
domain_id, sequence_range = payload.split("/", 1)
except ValueError as exc:
raise ValueError(f"Unexpected FASTA header in {path}: {header}") from exc
sequence = "".join(sequence_chunks)
start, end, segment_count = parse_range_summary(sequence_range)
records.append(
{
"domain_id": domain_id,
"cath_version": version.replace("_", "."),
"sequence": sequence,
"sequence_length": len(sequence),
"sequence_range": sequence_range,
"sequence_range_start": start,
"sequence_range_end": end,
"sequence_segment_count": segment_count,
}
)
with path.open("r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
if line.startswith(">"):
flush()
header = line[1:]
sequence_chunks = []
else:
sequence_chunks.append(line)
flush()
return pd.DataFrame.from_records(records)
def subset_domain_ids(path: Path) -> set[str]:
return {line.split()[0] for line in iter_data_lines(path)}
def stable_hash_int(value: str) -> int:
return int(hashlib.sha256(value.encode("utf-8")).hexdigest()[:16], 16)
def add_cluster_aware_split(df: pd.DataFrame, test_size: float) -> pd.DataFrame:
cluster_counts = (
df.groupby("s35_cluster_key", sort=False)
.size()
.rename("row_count")
.reset_index()
)
cluster_counts["hash"] = cluster_counts["s35_cluster_key"].map(stable_hash_int)
cluster_counts = cluster_counts.sort_values(["hash", "s35_cluster_key"], kind="mergesort")
target_rows = round(len(df) * test_size)
test_keys: set[str] = set()
test_rows = 0
for row in cluster_counts.itertuples(index=False):
if test_rows >= target_rows:
break
test_keys.add(row.s35_cluster_key)
test_rows += int(row.row_count)
df = df.copy()
df["split"] = df["s35_cluster_key"].map(lambda key: "test" if key in test_keys else "train")
return df
def build_dataset(raw_dir: Path, out_dir: Path, test_size: float) -> dict:
domains = parse_domain_list(raw_dir / "cath-domain-list.txt")
names = parse_names(raw_dir / "cath-names.txt")
names_by_code = names.set_index("cath_node_code")
for level, code_col in [
("class", "class_code"),
("architecture", "architecture_code"),
("topology", "topology_code"),
("homologous_superfamily", "homologous_superfamily_code"),
]:
domains[f"{level}_name"] = domains[code_col].map(names_by_code["cath_node_name"])
domains[f"{level}_example_domain_id"] = domains[code_col].map(names_by_code["example_domain_id"])
sequences = parse_fasta(raw_dir / "cath-domain-seqs.fa")
df = domains.merge(sequences, on="domain_id", how="left", validate="one_to_one")
missing_sequences = int(df["sequence"].isna().sum())
if missing_sequences:
raise ValueError(f"{missing_sequences} domain-list rows did not have FASTA sequences")
for subset in ["S35", "S60", "S95", "S100"]:
ids = subset_domain_ids(raw_dir / f"cath-domain-list-{subset}.txt")
df[f"in_{subset.lower()}_nonredundant_subset"] = df["domain_id"].isin(ids)
df = add_cluster_aware_split(df, test_size)
ordered_columns = [
"domain_id",
"pdb_id",
"chain_id",
"pdb_chain_id",
"domain_suffix",
"domain_index",
"cath_version",
"cath_code",
"class_number",
"class_code",
"class_name",
"class_example_domain_id",
"architecture_number",
"architecture_code",
"architecture_name",
"architecture_example_domain_id",
"topology_number",
"topology_code",
"topology_name",
"topology_example_domain_id",
"homologous_superfamily_number",
"homologous_superfamily_code",
"homologous_superfamily_name",
"homologous_superfamily_example_domain_id",
"s35_cluster_id",
"s60_cluster_id",
"s95_cluster_id",
"s100_cluster_id",
"s100_sequence_count",
"s35_cluster_key",
"domain_length",
"raw_structure_resolution_angstrom",
"structure_resolution_angstrom",
"structure_resolution_is_unknown",
"sequence",
"sequence_length",
"sequence_range",
"sequence_range_start",
"sequence_range_end",
"sequence_segment_count",
"in_s35_nonredundant_subset",
"in_s60_nonredundant_subset",
"in_s95_nonredundant_subset",
"in_s100_nonredundant_subset",
"split",
]
df = df[ordered_columns].sort_values(["split", "domain_id"], kind="mergesort")
data_dir = out_dir / "data"
data_dir.mkdir(parents=True, exist_ok=True)
split_counts = {}
for split in ["train", "test"]:
split_df = df[df["split"].eq(split)].drop(columns=["split"])
split_counts[split] = len(split_df)
split_df.to_parquet(
data_dir / f"{split}-00000-of-00001.parquet",
index=False,
compression="zstd",
)
summary = {
"source": "LiteFold/CATH",
"cath_version": str(df["cath_version"].iloc[0]),
"total_rows": len(df),
"splits": split_counts,
"test_size_requested": test_size,
"split_strategy": "deterministic S35-cluster-aware split using sha256(s35_cluster_key)",
"unique_s35_clusters": int(df["s35_cluster_key"].nunique()),
"columns": [column for column in ordered_columns if column != "split"],
"subset_rows": {
"s35": int(df["in_s35_nonredundant_subset"].sum()),
"s60": int(df["in_s60_nonredundant_subset"].sum()),
"s95": int(df["in_s95_nonredundant_subset"].sum()),
"s100": int(df["in_s100_nonredundant_subset"].sum()),
},
}
(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_CATH_raw"))
parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_CATH_processed"))
parser.add_argument("--test-size", type=float, default=0.10)
args = parser.parse_args()
summary = build_dataset(args.raw_dir, args.out_dir, args.test_size)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()