| |
| """Build viewer-friendly Parquet splits for LiteFold/HumanProteinAtlas.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import hashlib |
| import json |
| import re |
| import shutil |
| from collections import Counter |
| from pathlib import Path |
| from typing import Any |
|
|
| import pandas as pd |
|
|
|
|
| ENTRY_COLUMNS = [ |
| "ensembl_id", |
| "gene", |
| "gene_description", |
| "uniprot", |
| "chromosome", |
| "position", |
| "evidence", |
| "hpa_evidence", |
| "uniprot_evidence", |
| "nextprot_evidence", |
| "antibodies", |
| "gene_synonyms", |
| "protein_classes", |
| "biological_processes", |
| "molecular_functions", |
| "disease_involvement", |
| "subcellular_main_locations", |
| "subcellular_additional_locations", |
| "secretome_locations", |
| "secretome_functions", |
| "reliability_if", |
| "reliability_ih", |
| "reliability_mouse_brain", |
| "interactions", |
| "ccd_protein", |
| "ccd_transcript", |
| "blood_expression_cluster", |
| "brain_expression_cluster", |
| "cell_line_expression_cluster", |
| "single_cell_expression_cluster", |
| "tissue_expression_cluster", |
| "rna_tissue_specificity", |
| "rna_tissue_distribution", |
| "rna_tissue_specificity_score", |
| "rna_cell_line_specificity", |
| "rna_cell_line_distribution", |
| "rna_cell_line_specificity_score", |
| "rna_cancer_specificity", |
| "rna_cancer_distribution", |
| "rna_cancer_specificity_score", |
| "rna_single_cell_type_specificity", |
| "rna_single_cell_type_distribution", |
| "rna_single_cell_type_specificity_score", |
| "rna_blood_cell_specificity", |
| "rna_blood_cell_distribution", |
| "rna_blood_cell_specificity_score", |
| "prognostic_cancer_count", |
| "validated_prognostic_cancer_count", |
| "potential_prognostic_cancer_count", |
| "favorable_prognostic_cancers", |
| "unfavorable_prognostic_cancers", |
| "prognostic_cancers", |
| "source_row_index", |
| "split_bucket", |
| ] |
|
|
|
|
| PROGNOSIS_COLUMNS = [ |
| "ensembl_id", |
| "gene", |
| "cancer", |
| "source", |
| "is_prognostic", |
| "p_value", |
| "prognostic", |
| "prognostic_type", |
| ] |
|
|
|
|
| EXPRESSION_COLUMNS = [ |
| "ensembl_id", |
| "gene", |
| "measurement", |
| "sample", |
| "value", |
| ] |
|
|
|
|
| def stable_bucket(value: str, buckets: int = 10) -> int: |
| digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16] |
| return int(digest, 16) % buckets |
|
|
|
|
| def as_list(value: Any) -> list[str]: |
| if value is None or value == "NA": |
| return [] |
| if isinstance(value, list): |
| return [str(item) for item in value if item is not None and item != ""] |
| return [str(value)] if value != "" else [] |
|
|
|
|
| def clean_scalar(value: Any) -> Any: |
| if value in {"NA", ""}: |
| return None |
| return value |
|
|
|
|
| def parse_float(value: Any) -> float | None: |
| if value in {None, "", "NA"}: |
| return None |
| try: |
| return float(value) |
| except (TypeError, ValueError): |
| return None |
|
|
|
|
| def score(value: Any) -> float | None: |
| return parse_float(value) |
|
|
|
|
| def normalize_cancer_name(column: str) -> tuple[str, str]: |
| label = column.removeprefix("Cancer prognostics - ") |
| source = "validation" if "(validation)" in label else "TCGA" if "(TCGA)" in label else "" |
| cancer = re.sub(r"\s*\((TCGA|validation)\)\s*$", "", label).strip() |
| return cancer, source |
|
|
|
|
| def entry_row(wrapper: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: |
| row = wrapper["row"] |
| ensembl = row.get("Ensembl") |
| gene = row.get("Gene") |
| prognosis_rows = [] |
| prognostic_cancers = [] |
| validated = 0 |
| potential = 0 |
| favorable = [] |
| unfavorable = [] |
|
|
| expression_rows = [] |
| for key, value in row.items(): |
| if key.startswith("Cancer prognostics -") and isinstance(value, dict): |
| cancer, source = normalize_cancer_name(key) |
| is_prognostic = bool(value.get("is_prognostic")) |
| prognostic = value.get("prognostic") or None |
| prognostic_type = value.get("prognostic type") or None |
| if is_prognostic: |
| prognostic_cancers.append(cancer) |
| if prognostic == "validated prognostic": |
| validated += 1 |
| elif prognostic == "potential prognostic": |
| potential += 1 |
| if prognostic_type == "favorable": |
| favorable.append(cancer) |
| elif prognostic_type == "unfavorable": |
| unfavorable.append(cancer) |
| prognosis_rows.append( |
| { |
| "ensembl_id": ensembl, |
| "gene": gene, |
| "cancer": cancer, |
| "source": source, |
| "is_prognostic": is_prognostic, |
| "p_value": parse_float(value.get("p_val")), |
| "prognostic": prognostic, |
| "prognostic_type": prognostic_type, |
| } |
| ) |
| elif key.startswith("RNA ") and isinstance(value, dict): |
| for sample, measurement in value.items(): |
| expression_rows.append( |
| { |
| "ensembl_id": ensembl, |
| "gene": gene, |
| "measurement": key, |
| "sample": sample, |
| "value": parse_float(measurement), |
| } |
| ) |
|
|
| entry = { |
| "ensembl_id": ensembl, |
| "gene": gene, |
| "gene_description": row.get("Gene description"), |
| "uniprot": row.get("Uniprot"), |
| "chromosome": row.get("Chromosome"), |
| "position": row.get("Position"), |
| "evidence": row.get("Evidence"), |
| "hpa_evidence": row.get("HPA evidence"), |
| "uniprot_evidence": row.get("UniProt evidence"), |
| "nextprot_evidence": row.get("NeXtProt evidence"), |
| "antibodies": as_list(row.get("Antibody")), |
| "gene_synonyms": as_list(row.get("Gene synonym")), |
| "protein_classes": as_list(row.get("Protein class")), |
| "biological_processes": as_list(row.get("Biological process")), |
| "molecular_functions": as_list(row.get("Molecular function")), |
| "disease_involvement": as_list(row.get("Disease involvement")), |
| "subcellular_main_locations": as_list(row.get("Subcellular main location")), |
| "subcellular_additional_locations": as_list(row.get("Subcellular additional location")), |
| "secretome_locations": as_list(row.get("Secretome location")), |
| "secretome_functions": as_list(row.get("Secretome function")), |
| "reliability_if": clean_scalar(row.get("Reliability (IF)")), |
| "reliability_ih": clean_scalar(row.get("Reliability (IH)")), |
| "reliability_mouse_brain": clean_scalar(row.get("Reliability (Mouse Brain)")), |
| "interactions": row.get("Interactions"), |
| "ccd_protein": clean_scalar(row.get("CCD Protein")), |
| "ccd_transcript": clean_scalar(row.get("CCD Transcript")), |
| "blood_expression_cluster": clean_scalar(row.get("Blood expression cluster")), |
| "brain_expression_cluster": clean_scalar(row.get("Brain expression cluster")), |
| "cell_line_expression_cluster": clean_scalar(row.get("Cell line expression cluster")), |
| "single_cell_expression_cluster": clean_scalar(row.get("Single cell expression cluster")), |
| "tissue_expression_cluster": clean_scalar(row.get("Tissue expression cluster")), |
| "rna_tissue_specificity": clean_scalar(row.get("RNA tissue specificity")), |
| "rna_tissue_distribution": clean_scalar(row.get("RNA tissue distribution")), |
| "rna_tissue_specificity_score": score(row.get("RNA tissue specificity score")), |
| "rna_cell_line_specificity": clean_scalar(row.get("RNA cell line specificity")), |
| "rna_cell_line_distribution": clean_scalar(row.get("RNA cell line distribution")), |
| "rna_cell_line_specificity_score": score(row.get("RNA cell line specificity score")), |
| "rna_cancer_specificity": clean_scalar(row.get("RNA cancer specificity")), |
| "rna_cancer_distribution": clean_scalar(row.get("RNA cancer distribution")), |
| "rna_cancer_specificity_score": score(row.get("RNA cancer specificity score")), |
| "rna_single_cell_type_specificity": clean_scalar(row.get("RNA single cell type specificity")), |
| "rna_single_cell_type_distribution": clean_scalar(row.get("RNA single cell type distribution")), |
| "rna_single_cell_type_specificity_score": score(row.get("RNA single cell type specificity score")), |
| "rna_blood_cell_specificity": clean_scalar(row.get("RNA blood cell specificity")), |
| "rna_blood_cell_distribution": clean_scalar(row.get("RNA blood cell distribution")), |
| "rna_blood_cell_specificity_score": score(row.get("RNA blood cell specificity score")), |
| "prognostic_cancer_count": len(set(prognostic_cancers)), |
| "validated_prognostic_cancer_count": validated, |
| "potential_prognostic_cancer_count": potential, |
| "favorable_prognostic_cancers": sorted(set(favorable)), |
| "unfavorable_prognostic_cancers": sorted(set(unfavorable)), |
| "prognostic_cancers": sorted(set(prognostic_cancers)), |
| "source_row_index": wrapper.get("row_index"), |
| "split_bucket": stable_bucket(str(ensembl or gene or wrapper.get("row_index"))), |
| } |
| return entry, prognosis_rows, expression_rows |
|
|
|
|
| def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]: |
| source = raw_dir / "tables/annotation_human_protein_atlas_proteinatlas.json.gz.jsonl" |
| rows = [] |
| prognosis_rows = [] |
| expression_rows = [] |
| with source.open("r", encoding="utf-8") as handle: |
| for line in handle: |
| wrapper = json.loads(line) |
| entry, prognosis, expression = entry_row(wrapper) |
| rows.append(entry) |
| prognosis_rows.extend(prognosis) |
| expression_rows.extend(expression) |
|
|
| 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("ensembl_id", kind="mergesort") |
| test = df[df["split_bucket"].eq(0)].sort_values("ensembl_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") |
|
|
| prognosis_df = pd.DataFrame.from_records(prognosis_rows, columns=PROGNOSIS_COLUMNS) |
| prognosis_df.to_parquet(metadata_dir / "cancer_prognostics.parquet", index=False, compression="zstd") |
| expression_df = pd.DataFrame.from_records(expression_rows, columns=EXPRESSION_COLUMNS) |
| expression_df.to_parquet(metadata_dir / "rna_expression_measurements.parquet", index=False, compression="zstd") |
|
|
| evidence_counts = df["evidence"].fillna("missing").value_counts().to_dict() |
| tissue_specificity_counts = df["rna_tissue_specificity"].fillna("missing").value_counts().to_dict() |
| location_counts = Counter(location for values in df["subcellular_main_locations"] for location in values) |
| protein_class_counts = Counter(item for values in df["protein_classes"] for item in values) |
| summary = { |
| "source": "LiteFold/HumanProteinAtlas", |
| "entry_rows": int(len(df)), |
| "cancer_prognostic_rows": int(len(prognosis_df)), |
| "rna_expression_measurement_rows": int(len(expression_df)), |
| "splits": {"train": int(len(train)), "test": int(len(test))}, |
| "split_strategy": "deterministic sha256(ensembl_id) % 10; bucket 0 is test, buckets 1-9 are train", |
| "evidence_counts": {str(k): int(v) for k, v in evidence_counts.items()}, |
| "rna_tissue_specificity_counts": {str(k): int(v) for k, v in tissue_specificity_counts.items()}, |
| "top_subcellular_main_locations": dict(location_counts.most_common(20)), |
| "top_protein_classes": dict(protein_class_counts.most_common(20)), |
| "columns": ENTRY_COLUMNS, |
| "metadata_tables": [ |
| "metadata/cancer_prognostics.parquet", |
| "metadata/rna_expression_measurements.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_HumanProteinAtlas_raw")) |
| parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_HumanProteinAtlas_processed")) |
| args = parser.parse_args() |
| summary = build_dataset(args.raw_dir, args.out_dir) |
| print(json.dumps(summary, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|