| |
| """Build viewer-friendly Parquet splits for LiteFold/GO.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import hashlib |
| import json |
| import re |
| from collections import Counter, defaultdict |
| from pathlib import Path |
|
|
| import pandas as pd |
|
|
|
|
| TERM_COLUMNS = [ |
| "go_id", |
| "go_numeric_id", |
| "name", |
| "namespace", |
| "definition", |
| "definition_xrefs", |
| "comment", |
| "synonyms", |
| "synonym_scopes", |
| "alt_ids", |
| "subsets", |
| "xrefs", |
| "is_a_ids", |
| "relationship_edges", |
| "relationship_types", |
| "relationship_target_ids", |
| "parent_ids", |
| "intersection_of", |
| "union_of", |
| "disjoint_from", |
| "replaced_by", |
| "consider", |
| "property_values", |
| "created_by", |
| "creation_date", |
| "is_obsolete", |
| "in_go_basic", |
| "split_bucket", |
| ] |
|
|
|
|
| def split_unquoted_comment(value: str) -> str: |
| in_quote = False |
| escaped = False |
| for index, char in enumerate(value): |
| if escaped: |
| escaped = False |
| continue |
| if char == "\\": |
| escaped = True |
| continue |
| if char == '"': |
| in_quote = not in_quote |
| continue |
| if char == "!" and not in_quote: |
| return value[:index].strip() |
| return value.strip() |
|
|
|
|
| def parse_quoted_xrefs(value: str) -> tuple[str | None, list[str]]: |
| match = re.match(r'^"((?:[^"\\]|\\.)*)"\s*(?:\[(.*)\])?', value.strip()) |
| if not match: |
| return value.strip() or None, [] |
| text = bytes(match.group(1), "utf-8").decode("unicode_escape") |
| xrefs = [] |
| if match.group(2): |
| xrefs = [part.strip() for part in match.group(2).split(",") if part.strip()] |
| return text, xrefs |
|
|
|
|
| def parse_synonym(value: str) -> tuple[str | None, str | None]: |
| match = re.match(r'^"((?:[^"\\]|\\.)*)"\s+([A-Z]+)', value.strip()) |
| if not match: |
| return value.strip() or None, None |
| text = bytes(match.group(1), "utf-8").decode("unicode_escape") |
| return text, match.group(2) |
|
|
|
|
| def stable_bucket(value: str, buckets: int = 10) -> int: |
| digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16] |
| return int(digest, 16) % buckets |
|
|
|
|
| def parse_obo(path: Path) -> tuple[dict[str, list[str]], list[dict[str, list[str]]], list[dict[str, list[str]]]]: |
| header: dict[str, list[str]] = defaultdict(list) |
| terms: list[dict[str, list[str]]] = [] |
| typedefs: list[dict[str, list[str]]] = [] |
| current_type: str | None = None |
| current: dict[str, list[str]] | None = None |
|
|
| def flush() -> None: |
| nonlocal current, current_type |
| if current is None: |
| return |
| if current_type == "Term": |
| terms.append(current) |
| elif current_type == "Typedef": |
| typedefs.append(current) |
| current = None |
| current_type = None |
|
|
| with path.open("r", encoding="utf-8", errors="replace") as handle: |
| for raw_line in handle: |
| line = raw_line.rstrip("\n") |
| if not line or line.startswith("!"): |
| continue |
| if line.startswith("[") and line.endswith("]"): |
| flush() |
| current_type = line.strip("[]") |
| current = defaultdict(list) |
| continue |
| if ": " not in line: |
| continue |
| key, value = line.split(": ", 1) |
| target = header if current is None else current |
| target[key].append(value.strip()) |
| flush() |
| return dict(header), terms, typedefs |
|
|
|
|
| def first(stanza: dict[str, list[str]], key: str) -> str | None: |
| values = stanza.get(key) or [] |
| return values[0] if values else None |
|
|
|
|
| def list_values(stanza: dict[str, list[str]], key: str, strip_comment: bool = False) -> list[str]: |
| values = stanza.get(key) or [] |
| if strip_comment: |
| return [split_unquoted_comment(value) for value in values] |
| return list(values) |
|
|
|
|
| def term_to_row(stanza: dict[str, list[str]], basic_ids: set[str]) -> dict: |
| go_id = first(stanza, "id") or "" |
| definition, definition_xrefs = parse_quoted_xrefs(first(stanza, "def") or "") |
| synonyms = [] |
| synonym_scopes = [] |
| for value in stanza.get("synonym", []): |
| synonym, scope = parse_synonym(value) |
| if synonym: |
| synonyms.append(synonym) |
| synonym_scopes.append(scope or "") |
|
|
| relationship_edges = list_values(stanza, "relationship", strip_comment=True) |
| relationship_types = [] |
| relationship_target_ids = [] |
| for edge in relationship_edges: |
| parts = edge.split() |
| if len(parts) >= 2: |
| relationship_types.append(parts[0]) |
| relationship_target_ids.append(parts[1]) |
|
|
| is_a_ids = [value.split()[0] for value in list_values(stanza, "is_a", strip_comment=True)] |
| parent_ids = sorted(set(is_a_ids + relationship_target_ids)) |
| split_bucket = stable_bucket(go_id) |
| numeric = None |
| match = re.match(r"GO:(\d+)$", go_id) |
| if match: |
| numeric = int(match.group(1)) |
|
|
| return { |
| "go_id": go_id, |
| "go_numeric_id": numeric, |
| "name": first(stanza, "name"), |
| "namespace": first(stanza, "namespace"), |
| "definition": definition, |
| "definition_xrefs": definition_xrefs, |
| "comment": " ".join(stanza.get("comment", [])) or None, |
| "synonyms": synonyms, |
| "synonym_scopes": synonym_scopes, |
| "alt_ids": list_values(stanza, "alt_id"), |
| "subsets": list_values(stanza, "subset"), |
| "xrefs": list_values(stanza, "xref", strip_comment=True), |
| "is_a_ids": is_a_ids, |
| "relationship_edges": relationship_edges, |
| "relationship_types": relationship_types, |
| "relationship_target_ids": relationship_target_ids, |
| "parent_ids": parent_ids, |
| "intersection_of": list_values(stanza, "intersection_of", strip_comment=True), |
| "union_of": list_values(stanza, "union_of", strip_comment=True), |
| "disjoint_from": list_values(stanza, "disjoint_from", strip_comment=True), |
| "replaced_by": list_values(stanza, "replaced_by", strip_comment=True), |
| "consider": list_values(stanza, "consider", strip_comment=True), |
| "property_values": list_values(stanza, "property_value"), |
| "created_by": first(stanza, "created_by"), |
| "creation_date": first(stanza, "creation_date"), |
| "is_obsolete": (first(stanza, "is_obsolete") or "").lower() == "true", |
| "in_go_basic": go_id in basic_ids, |
| "split_bucket": split_bucket, |
| } |
|
|
|
|
| def typedef_to_row(stanza: dict[str, list[str]]) -> dict: |
| definition, definition_xrefs = parse_quoted_xrefs(first(stanza, "def") or "") |
| return { |
| "id": first(stanza, "id"), |
| "name": first(stanza, "name"), |
| "namespace": first(stanza, "namespace"), |
| "definition": definition, |
| "definition_xrefs": definition_xrefs, |
| "is_transitive": first(stanza, "is_transitive"), |
| "is_metadata_tag": first(stanza, "is_metadata_tag"), |
| "is_class_level": first(stanza, "is_class_level"), |
| "domain": list_values(stanza, "domain", strip_comment=True), |
| "range": list_values(stanza, "range", strip_comment=True), |
| "holds_over_chain": list_values(stanza, "holds_over_chain", strip_comment=True), |
| "inverse_of": list_values(stanza, "inverse_of", strip_comment=True), |
| "transitive_over": list_values(stanza, "transitive_over", strip_comment=True), |
| "property_values": list_values(stanza, "property_value"), |
| } |
|
|
|
|
| def build_dataset(raw_dir: Path, out_dir: Path) -> dict: |
| header, terms, typedefs = parse_obo(raw_dir / "go.obo") |
| _, basic_terms, _ = parse_obo(raw_dir / "go-basic.obo") |
| basic_ids = {first(term, "id") for term in basic_terms if first(term, "id")} |
|
|
| rows = [term_to_row(term, basic_ids) for term in terms] |
| df = pd.DataFrame.from_records(rows, columns=TERM_COLUMNS) |
| df = df.sort_values(["split_bucket", "go_id"], kind="mergesort") |
|
|
| data_dir = out_dir / "data" |
| data_dir.mkdir(parents=True, exist_ok=True) |
| train = df[df["split_bucket"].ne(0)].sort_values("go_id", kind="mergesort") |
| test = df[df["split_bucket"].eq(0)].sort_values("go_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") |
|
|
| metadata_dir = out_dir / "metadata" |
| metadata_dir.mkdir(parents=True, exist_ok=True) |
| typedef_df = pd.DataFrame.from_records([typedef_to_row(item) for item in typedefs]) |
| typedef_df.to_parquet(metadata_dir / "typedefs.parquet", index=False, compression="zstd") |
|
|
| namespace_counts = df["namespace"].value_counts(dropna=False).to_dict() |
| obsolete_counts = df["is_obsolete"].value_counts(dropna=False).to_dict() |
| relation_counts = Counter(rel for rels in df["relationship_types"] for rel in rels) |
| subset_counts = Counter(subset for subsets in df["subsets"] for subset in subsets) |
| summary = { |
| "source": "LiteFold/GO", |
| "data_version": (header.get("data-version") or [None])[0], |
| "ontology": (header.get("ontology") or [None])[0], |
| "license": next((value for value in header.get("property_value", []) if "terms:license" in value), None), |
| "term_rows": int(len(df)), |
| "typedef_rows": int(len(typedef_df)), |
| "go_basic_term_rows": int(len(basic_ids)), |
| "terms_in_go_basic": int(df["in_go_basic"].sum()), |
| "splits": { |
| "train": int(len(train)), |
| "test": int(len(test)), |
| }, |
| "split_strategy": "deterministic sha256(go_id) % 10; bucket 0 is test, buckets 1-9 are train", |
| "namespace_counts": {str(k): int(v) for k, v in namespace_counts.items()}, |
| "obsolete_counts": {str(k): int(v) for k, v in obsolete_counts.items()}, |
| "top_relationship_types": dict(relation_counts.most_common(20)), |
| "top_subsets": dict(subset_counts.most_common(20)), |
| "columns": TERM_COLUMNS, |
| } |
| (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_GO_raw")) |
| parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_GO_processed")) |
| args = parser.parse_args() |
| summary = build_dataset(args.raw_dir, args.out_dir) |
| print(json.dumps(summary, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|