Datasets:
File size: 12,770 Bytes
9b2f696 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | #!/usr/bin/env python3
"""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()
|