File size: 10,458 Bytes
5e142fe | 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 | #!/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()
|