DisProt / scripts /prepare_disprot_dataset.py
anindya64's picture
Add normalized Parquet train/test DisProt protein table
5e142fe verified
#!/usr/bin/env python3
"""Build viewer-friendly Parquet splits for LiteFold/DisProt."""
from __future__ import annotations
import argparse
import hashlib
import json
import shutil
from collections import Counter
from pathlib import Path
from typing import Any
import pandas as pd
ENTRY_COLUMNS = [
"disprot_id",
"accession",
"uniparc",
"name",
"organism",
"ncbi_taxon_id",
"length",
"disorder_content",
"dataset_labels",
"taxonomy",
"released",
"date",
"creator",
"uniref100",
"uniref90",
"uniref50",
"sequence",
"region_count",
"region_ids",
"region_starts",
"region_ends",
"region_lengths",
"region_terms",
"region_term_ids",
"region_namespaces",
"evidence_codes",
"reference_ids",
"reference_sources",
"curator_names",
"cross_refs",
"feature_databases",
"feature_ids",
"feature_names",
"feature_count",
"gene_names",
"consensus_starts",
"consensus_ends",
"consensus_types",
"split_bucket",
]
REGION_COLUMNS = [
"region_id",
"disprot_id",
"accession",
"start",
"end",
"length",
"term_id",
"term_name",
"term_namespace",
"term_ontology",
"evidence_code",
"evidence_name",
"ec_go",
"reference_id",
"reference_source",
"curator_name",
"curator_orcid",
"date",
"released",
"statement_texts",
"statement_types",
"cross_refs",
"uniprot_changed",
"version",
]
def stable_bucket(value: str, buckets: int = 10) -> int:
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16]
return int(digest, 16) % buckets
def strings(values: list[Any]) -> list[str]:
return [str(value) for value in values if value is not None and value != ""]
def flatten_cross_refs(items: list[dict[str, Any]]) -> list[str]:
refs = []
for item in items or []:
db = item.get("db")
ident = item.get("id")
if db and ident:
refs.append(f"{db}:{ident}")
elif ident:
refs.append(str(ident))
return refs
def gene_names(record: dict[str, Any]) -> list[str]:
names = []
for gene in record.get("genes") or []:
name = ((gene.get("name") or {}).get("value"))
if name:
names.append(name)
for key in ["synonyms", "orfNames", "olnNames"]:
for item in gene.get(key) or []:
value = item.get("value") if isinstance(item, dict) else item
if value:
names.append(str(value))
return sorted(set(names))
def feature_lists(record: dict[str, Any]) -> tuple[list[str], list[str], list[str]]:
databases = []
ids = []
names = []
for database, features in (record.get("features") or {}).items():
for item in features or []:
databases.append(database)
ids.append(str(item.get("id") or ""))
names.append(str(item.get("name") or ""))
return databases, ids, names
def consensus(record: dict[str, Any]) -> tuple[list[int], list[int], list[str]]:
starts = []
ends = []
types = []
for item in ((record.get("disprot_consensus") or {}).get("full") or []):
if item.get("start") is not None and item.get("end") is not None:
starts.append(int(item["start"]))
ends.append(int(item["end"]))
types.append(str(item.get("type") or ""))
return starts, ends, types
def region_row(record: dict[str, Any], region: dict[str, Any]) -> dict[str, Any]:
start = region.get("start")
end = region.get("end")
statements = region.get("statement") or []
return {
"region_id": region.get("region_id"),
"disprot_id": record.get("disprot_id"),
"accession": record.get("acc"),
"start": int(start) if start is not None else None,
"end": int(end) if end is not None else None,
"length": int(end) - int(start) + 1 if start is not None and end is not None else None,
"term_id": region.get("term_id"),
"term_name": region.get("term_name"),
"term_namespace": region.get("term_namespace") or region.get("disprot_namespace"),
"term_ontology": region.get("term_ontology"),
"evidence_code": region.get("ec_id"),
"evidence_name": region.get("ec_name"),
"ec_go": region.get("ec_go"),
"reference_id": region.get("reference_id"),
"reference_source": region.get("reference_source"),
"curator_name": region.get("curator_name"),
"curator_orcid": region.get("curator_orcid"),
"date": region.get("date"),
"released": region.get("released"),
"statement_texts": strings([item.get("text") for item in statements if isinstance(item, dict)]),
"statement_types": strings([item.get("type") for item in statements if isinstance(item, dict)]),
"cross_refs": flatten_cross_refs(region.get("cross_refs") or []),
"uniprot_changed": region.get("uniprot_changed"),
"version": region.get("version"),
}
def entry_row(record: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]]]:
regions = record.get("regions") or []
region_rows = [region_row(record, region) for region in regions]
feature_databases, feature_ids, feature_names = feature_lists(record)
consensus_starts, consensus_ends, consensus_types = consensus(record)
region_starts = [row["start"] for row in region_rows if row["start"] is not None]
region_ends = [row["end"] for row in region_rows if row["end"] is not None]
row = {
"disprot_id": record.get("disprot_id"),
"accession": record.get("acc"),
"uniparc": record.get("UniParc"),
"name": record.get("name"),
"organism": record.get("organism"),
"ncbi_taxon_id": record.get("ncbi_taxon_id"),
"length": record.get("length"),
"disorder_content": record.get("disorder_content"),
"dataset_labels": strings(record.get("dataset") or []),
"taxonomy": strings(record.get("taxonomy") or []),
"released": record.get("released"),
"date": record.get("date"),
"creator": record.get("creator"),
"uniref100": record.get("uniref100"),
"uniref90": record.get("uniref90"),
"uniref50": record.get("uniref50"),
"sequence": record.get("sequence"),
"region_count": len(region_rows),
"region_ids": strings([row["region_id"] for row in region_rows]),
"region_starts": region_starts,
"region_ends": region_ends,
"region_lengths": [row["length"] for row in region_rows if row["length"] is not None],
"region_terms": strings([row["term_name"] for row in region_rows]),
"region_term_ids": strings([row["term_id"] for row in region_rows]),
"region_namespaces": strings([row["term_namespace"] for row in region_rows]),
"evidence_codes": strings([row["evidence_code"] for row in region_rows]),
"reference_ids": strings([row["reference_id"] for row in region_rows]),
"reference_sources": strings([row["reference_source"] for row in region_rows]),
"curator_names": strings([row["curator_name"] for row in region_rows]),
"cross_refs": sorted({xref for row in region_rows for xref in row["cross_refs"]}),
"feature_databases": feature_databases,
"feature_ids": feature_ids,
"feature_names": feature_names,
"feature_count": len(feature_ids),
"gene_names": gene_names(record),
"consensus_starts": consensus_starts,
"consensus_ends": consensus_ends,
"consensus_types": consensus_types,
"split_bucket": stable_bucket(str(record.get("disprot_id") or record.get("acc"))),
}
return row, region_rows
def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]:
source = raw_dir / "tables/annotation_disprot_disprot_current.json.jsonl"
wrapper = json.loads(source.read_text(encoding="utf-8"))
records = wrapper["row"]["data"]
rows = []
region_rows = []
for record in records:
row, regions = entry_row(record)
rows.append(row)
region_rows.extend(regions)
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)
train = df[df["split_bucket"].ne(0)].sort_values("disprot_id", kind="mergesort")
test = df[df["split_bucket"].eq(0)].sort_values("disprot_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")
region_df = pd.DataFrame.from_records(region_rows, columns=REGION_COLUMNS)
region_df.to_parquet(metadata_dir / "regions.parquet", index=False, compression="zstd")
dataset_counts = Counter(label for labels in df["dataset_labels"] for label in labels)
term_counts = Counter(term for terms in df["region_terms"] for term in terms)
namespace_counts = Counter(ns for namespaces in df["region_namespaces"] for ns in namespaces)
summary = {
"source": "LiteFold/DisProt",
"entry_rows": int(len(df)),
"region_rows": int(len(region_df)),
"splits": {"train": int(len(train)), "test": int(len(test))},
"split_strategy": "deterministic sha256(disprot_id) % 10; bucket 0 is test, buckets 1-9 are train",
"dataset_label_counts": dict(dataset_counts.most_common()),
"top_region_terms": dict(term_counts.most_common(20)),
"region_namespace_counts": dict(namespace_counts.most_common()),
"columns": ENTRY_COLUMNS,
"metadata_tables": ["metadata/regions.parquet"],
}
(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_DisProt_raw"))
parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_DisProt_processed"))
args = parser.parse_args()
summary = build_dataset(args.raw_dir, args.out_dir)
print(json.dumps(summary, indent=2))
if __name__ == "__main__":
main()