| |
| """Build viewer-friendly Parquet splits for LiteFold/InterPro.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import gzip |
| import hashlib |
| import json |
| import re |
| import shutil |
| import xml.etree.ElementTree as ET |
| from collections import Counter |
| from pathlib import Path |
| from typing import Any |
|
|
| import pandas as pd |
|
|
|
|
| ENTRY_COLUMNS = [ |
| "interpro_id", |
| "interpro_numeric_id", |
| "name", |
| "short_name", |
| "entry_type", |
| "protein_count", |
| "is_llm", |
| "is_llm_reviewed", |
| "abstract", |
| "go_ids", |
| "go_terms", |
| "go_categories", |
| "go_count", |
| "member_databases", |
| "member_accessions", |
| "member_names", |
| "member_protein_counts", |
| "member_count", |
| "external_databases", |
| "external_accessions", |
| "external_xrefs", |
| "external_xref_count", |
| "pdb_ids", |
| "structure_count", |
| "publication_ids", |
| "pubmed_ids", |
| "publication_titles", |
| "publication_years", |
| "publication_count", |
| "parent_ids", |
| "child_ids", |
| "parent_count", |
| "child_count", |
| "tree_depth", |
| "taxonomy_names", |
| "taxonomy_protein_counts", |
| "taxonomy_count", |
| "key_species_names", |
| "key_species_protein_counts", |
| "key_species_count", |
| "in_entry_list", |
| "entry_list_type", |
| "entry_list_name", |
| "names_dat_name", |
| "short_names_dat_name", |
| "split_bucket", |
| ] |
|
|
|
|
| def normalize_text(value: str | None) -> str | None: |
| if value is None: |
| return None |
| text = re.sub(r"\s+", " ", value).strip() |
| return text or None |
|
|
|
|
| def parse_int(value: str | None) -> int | None: |
| if value is None or value == "": |
| return None |
| try: |
| return int(value) |
| except ValueError: |
| return None |
|
|
|
|
| def parse_bool(value: str | None) -> bool | None: |
| if value is None or value == "": |
| return None |
| lowered = value.lower() |
| if lowered == "true": |
| return True |
| if lowered == "false": |
| return False |
| return None |
|
|
|
|
| def stable_bucket(value: str, buckets: int = 10) -> int: |
| digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:16] |
| return int(digest, 16) % buckets |
|
|
|
|
| def text_of(parent: ET.Element, tag: str) -> str | None: |
| child = parent.find(tag) |
| if child is None: |
| return None |
| return normalize_text("".join(child.itertext())) |
|
|
|
|
| def xref_value(db: str | None, dbkey: str | None) -> str: |
| if db and dbkey: |
| return f"{db}:{dbkey}" |
| return dbkey or db or "" |
|
|
|
|
| def parse_two_column_file(path: Path) -> dict[str, str]: |
| mapping: dict[str, str] = {} |
| if not path.exists(): |
| return mapping |
| with path.open("r", encoding="utf-8", errors="replace") as handle: |
| for line in handle: |
| stripped = line.rstrip("\n") |
| if not stripped: |
| continue |
| parts = stripped.split("\t", 1) |
| if len(parts) == 2 and parts[0].startswith("IPR"): |
| mapping[parts[0]] = parts[1] |
| return mapping |
|
|
|
|
| def parse_entry_list(path: Path) -> dict[str, dict[str, str]]: |
| entries: dict[str, dict[str, str]] = {} |
| if not path.exists(): |
| return entries |
| with path.open("r", encoding="utf-8", errors="replace") as handle: |
| header = next(handle, "").rstrip("\n").split("\t") |
| for line in handle: |
| parts = line.rstrip("\n").split("\t") |
| if len(parts) != len(header): |
| continue |
| row = dict(zip(header, parts)) |
| entry_id = row.get("ENTRY_AC") |
| if entry_id: |
| entries[entry_id] = row |
| return entries |
|
|
|
|
| def parse_tree_depths(path: Path) -> dict[str, int]: |
| depths: dict[str, int] = {} |
| pattern = re.compile(r"^(?P<prefix>-*)(?P<id>IPR\d+)::") |
| if not path.exists(): |
| return depths |
| with path.open("r", encoding="utf-8", errors="replace") as handle: |
| for line in handle: |
| match = pattern.match(line.strip()) |
| if not match: |
| continue |
| entry_id = match.group("id") |
| depth = len(match.group("prefix")) // 2 |
| previous = depths.get(entry_id) |
| if previous is None or depth < previous: |
| depths[entry_id] = depth |
| return depths |
|
|
|
|
| def parse_interpro2go_count(path: Path) -> int: |
| count = 0 |
| if not path.exists(): |
| return count |
| with path.open("r", encoding="utf-8", errors="replace") as handle: |
| for line in handle: |
| stripped = line.strip() |
| if stripped and not stripped.startswith("!"): |
| count += 1 |
| return count |
|
|
|
|
| def parse_release_notes(path: Path) -> dict[str, Any]: |
| notes = path.read_text(encoding="utf-8", errors="replace") if path.exists() else "" |
| release_match = re.search(r"Release\s+([0-9.]+),\s+([^\n]+)", notes) |
| last_entry_match = re.search(r"Last Entry\s+(IPR\d+)", notes) |
| go_match = re.search(r"Number of GO terms mapped to InterPro\s+-\s+([0-9]+)", notes) |
| return { |
| "release": release_match.group(1) if release_match else None, |
| "release_date": release_match.group(2).strip() if release_match else None, |
| "last_entry": last_entry_match.group(1) if last_entry_match else None, |
| "interpro_to_go_mappings": int(go_match.group(1)) if go_match else None, |
| } |
|
|
|
|
| def parse_dbinfo(release: ET.Element) -> list[dict[str, Any]]: |
| rows = [] |
| for item in release.findall("dbinfo"): |
| rows.append( |
| { |
| "dbname": item.attrib.get("dbname"), |
| "version": item.attrib.get("version"), |
| "entry_count": parse_int(item.attrib.get("entry_count")), |
| "file_date": item.attrib.get("file_date"), |
| } |
| ) |
| return rows |
|
|
|
|
| def extract_taxa(container: ET.Element | None) -> tuple[list[str], list[int]]: |
| names = [] |
| counts = [] |
| if container is None: |
| return names, counts |
| for taxon in container.findall("taxon_data"): |
| name = taxon.attrib.get("name") |
| count = parse_int(taxon.attrib.get("proteins_count")) |
| if name: |
| names.append(name) |
| counts.append(count if count is not None else 0) |
| return names, counts |
|
|
|
|
| def interpro_row( |
| elem: ET.Element, |
| entry_list: dict[str, dict[str, str]], |
| names_dat: dict[str, str], |
| short_names_dat: dict[str, str], |
| tree_depths: dict[str, int], |
| ) -> dict[str, Any]: |
| entry_id = elem.attrib.get("id", "") |
| numeric_match = re.match(r"IPR(\d+)$", entry_id) |
| entry_info = entry_list.get(entry_id, {}) |
|
|
| class_list = elem.find("class_list") |
| go_ids: list[str] = [] |
| go_terms: list[str] = [] |
| go_categories: list[str] = [] |
| if class_list is not None: |
| for item in class_list.findall("classification"): |
| go_id = item.attrib.get("id") |
| if not go_id: |
| continue |
| go_ids.append(go_id) |
| go_terms.append(text_of(item, "description") or "") |
| go_categories.append(text_of(item, "category") or "") |
|
|
| member_databases: list[str] = [] |
| member_accessions: list[str] = [] |
| member_names: list[str] = [] |
| member_protein_counts: list[int] = [] |
| member_list = elem.find("member_list") |
| if member_list is not None: |
| for item in member_list.findall("db_xref"): |
| member_databases.append(item.attrib.get("db") or "") |
| member_accessions.append(item.attrib.get("dbkey") or "") |
| member_names.append(item.attrib.get("name") or "") |
| member_protein_counts.append(parse_int(item.attrib.get("protein_count")) or 0) |
|
|
| external_databases: list[str] = [] |
| external_accessions: list[str] = [] |
| external_xrefs: list[str] = [] |
| external_doc_list = elem.find("external_doc_list") |
| if external_doc_list is not None: |
| for item in external_doc_list.findall("db_xref"): |
| db = item.attrib.get("db") |
| dbkey = item.attrib.get("dbkey") |
| external_databases.append(db or "") |
| external_accessions.append(dbkey or "") |
| external_xrefs.append(xref_value(db, dbkey)) |
|
|
| pdb_ids: list[str] = [] |
| structure_db_links = elem.find("structure_db_links") |
| if structure_db_links is not None: |
| for item in structure_db_links.findall("db_xref"): |
| dbkey = item.attrib.get("dbkey") |
| if dbkey: |
| pdb_ids.append(dbkey) |
|
|
| publication_ids: list[str] = [] |
| pubmed_ids: list[str] = [] |
| publication_titles: list[str] = [] |
| publication_years: list[int] = [] |
| pub_list = elem.find("pub_list") |
| if pub_list is not None: |
| for publication in pub_list.findall("publication"): |
| publication_ids.append(publication.attrib.get("id") or "") |
| title = text_of(publication, "title") |
| publication_titles.append(title or "") |
| year = parse_int(text_of(publication, "year")) |
| publication_years.append(year if year is not None else 0) |
| xref = publication.find("db_xref") |
| if xref is not None and xref.attrib.get("db") == "PUBMED": |
| dbkey = xref.attrib.get("dbkey") |
| if dbkey: |
| pubmed_ids.append(dbkey) |
|
|
| parent_ids = [] |
| parent_list = elem.find("parent_list") |
| if parent_list is not None: |
| parent_ids = [item.attrib["ipr_ref"] for item in parent_list.findall("rel_ref") if item.attrib.get("ipr_ref")] |
|
|
| child_ids = [] |
| child_list = elem.find("child_list") |
| if child_list is not None: |
| child_ids = [item.attrib["ipr_ref"] for item in child_list.findall("rel_ref") if item.attrib.get("ipr_ref")] |
|
|
| taxonomy_names, taxonomy_protein_counts = extract_taxa(elem.find("taxonomy_distribution")) |
| key_species_names, key_species_protein_counts = extract_taxa(elem.find("key_species")) |
|
|
| abstract = elem.find("abstract") |
| abstract_text = normalize_text(" ".join(abstract.itertext())) if abstract is not None else None |
|
|
| return { |
| "interpro_id": entry_id, |
| "interpro_numeric_id": int(numeric_match.group(1)) if numeric_match else None, |
| "name": text_of(elem, "name"), |
| "short_name": elem.attrib.get("short_name") or None, |
| "entry_type": elem.attrib.get("type") or None, |
| "protein_count": parse_int(elem.attrib.get("protein_count")), |
| "is_llm": parse_bool(elem.attrib.get("is-llm")), |
| "is_llm_reviewed": parse_bool(elem.attrib.get("is-llm-reviewed")), |
| "abstract": abstract_text, |
| "go_ids": go_ids, |
| "go_terms": go_terms, |
| "go_categories": go_categories, |
| "go_count": len(go_ids), |
| "member_databases": member_databases, |
| "member_accessions": member_accessions, |
| "member_names": member_names, |
| "member_protein_counts": member_protein_counts, |
| "member_count": len(member_accessions), |
| "external_databases": external_databases, |
| "external_accessions": external_accessions, |
| "external_xrefs": external_xrefs, |
| "external_xref_count": len(external_xrefs), |
| "pdb_ids": pdb_ids, |
| "structure_count": len(pdb_ids), |
| "publication_ids": publication_ids, |
| "pubmed_ids": pubmed_ids, |
| "publication_titles": publication_titles, |
| "publication_years": publication_years, |
| "publication_count": len(publication_ids), |
| "parent_ids": parent_ids, |
| "child_ids": child_ids, |
| "parent_count": len(parent_ids), |
| "child_count": len(child_ids), |
| "tree_depth": tree_depths.get(entry_id), |
| "taxonomy_names": taxonomy_names, |
| "taxonomy_protein_counts": taxonomy_protein_counts, |
| "taxonomy_count": len(taxonomy_names), |
| "key_species_names": key_species_names, |
| "key_species_protein_counts": key_species_protein_counts, |
| "key_species_count": len(key_species_names), |
| "in_entry_list": entry_id in entry_list, |
| "entry_list_type": entry_info.get("ENTRY_TYPE"), |
| "entry_list_name": entry_info.get("ENTRY_NAME"), |
| "names_dat_name": names_dat.get(entry_id), |
| "short_names_dat_name": short_names_dat.get(entry_id), |
| "split_bucket": stable_bucket(entry_id), |
| } |
|
|
|
|
| def parse_xml( |
| path: Path, |
| entry_list: dict[str, dict[str, str]], |
| names_dat: dict[str, str], |
| short_names_dat: dict[str, str], |
| tree_depths: dict[str, int], |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: |
| rows: list[dict[str, Any]] = [] |
| dbinfo_rows: list[dict[str, Any]] = [] |
| with gzip.open(path, "rb") as handle: |
| for _, elem in ET.iterparse(handle, events=("end",)): |
| if elem.tag == "release": |
| dbinfo_rows = parse_dbinfo(elem) |
| elem.clear() |
| elif elem.tag == "interpro": |
| rows.append(interpro_row(elem, entry_list, names_dat, short_names_dat, tree_depths)) |
| elem.clear() |
| return rows, dbinfo_rows |
|
|
|
|
| def build_dataset(raw_dir: Path, out_dir: Path) -> dict[str, Any]: |
| current_dir = raw_dir / "current_release" |
| entry_list = parse_entry_list(current_dir / "entry.list") |
| names_dat = parse_two_column_file(current_dir / "names.dat") |
| short_names_dat = parse_two_column_file(current_dir / "short_names.dat") |
| tree_depths = parse_tree_depths(current_dir / "ParentChildTreeFile.txt") |
| release_notes = parse_release_notes(current_dir / "release_notes.txt") |
| interpro2go_count = parse_interpro2go_count(current_dir / "interpro2go") |
| rows, dbinfo_rows = parse_xml( |
| current_dir / "interpro.xml.gz", |
| entry_list=entry_list, |
| names_dat=names_dat, |
| short_names_dat=short_names_dat, |
| tree_depths=tree_depths, |
| ) |
|
|
| 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) |
| df = df.sort_values(["split_bucket", "interpro_id"], kind="mergesort") |
| train = df[df["split_bucket"].ne(0)].sort_values("interpro_id", kind="mergesort") |
| test = df[df["split_bucket"].eq(0)].sort_values("interpro_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") |
|
|
| dbinfo_df = pd.DataFrame.from_records(dbinfo_rows) |
| dbinfo_df.to_parquet(metadata_dir / "database_info.parquet", index=False, compression="zstd") |
|
|
| entry_type_counts = df["entry_type"].value_counts(dropna=False).to_dict() |
| member_database_counts = Counter(database for values in df["member_databases"] for database in values) |
| go_category_counts = Counter(category for values in df["go_categories"] for category in values) |
| external_database_counts = Counter(database for values in df["external_databases"] for database in values) |
|
|
| summary = { |
| "source": "LiteFold/InterPro", |
| "release": release_notes.get("release"), |
| "release_date": release_notes.get("release_date"), |
| "last_entry": release_notes.get("last_entry"), |
| "entry_rows": int(len(df)), |
| "database_info_rows": int(len(dbinfo_df)), |
| "entry_list_rows": int(len(entry_list)), |
| "names_dat_rows": int(len(names_dat)), |
| "short_names_dat_rows": int(len(short_names_dat)), |
| "tree_entries": int(len(tree_depths)), |
| "interpro2go_mapping_rows": int(interpro2go_count), |
| "release_notes_interpro2go_mappings": release_notes.get("interpro_to_go_mappings"), |
| "splits": { |
| "train": int(len(train)), |
| "test": int(len(test)), |
| }, |
| "split_strategy": "deterministic sha256(interpro_id) % 10; bucket 0 is test, buckets 1-9 are train", |
| "entry_type_counts": {str(k): int(v) for k, v in entry_type_counts.items()}, |
| "entries_with_go": int(df["go_count"].gt(0).sum()), |
| "entries_with_members": int(df["member_count"].gt(0).sum()), |
| "entries_with_structures": int(df["structure_count"].gt(0).sum()), |
| "entries_with_publications": int(df["publication_count"].gt(0).sum()), |
| "top_member_databases": dict(member_database_counts.most_common(20)), |
| "go_category_counts": dict(go_category_counts.most_common()), |
| "top_external_databases": dict(external_database_counts.most_common(20)), |
| "columns": ENTRY_COLUMNS, |
| "source_files_used": [ |
| "current_release/interpro.xml.gz", |
| "current_release/entry.list", |
| "current_release/names.dat", |
| "current_release/short_names.dat", |
| "current_release/ParentChildTreeFile.txt", |
| "current_release/interpro2go", |
| "current_release/release_notes.txt", |
| ], |
| } |
| (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_InterPro_raw")) |
| parser.add_argument("--out-dir", type=Path, default=Path("LiteFold_InterPro_processed")) |
| args = parser.parse_args() |
| summary = build_dataset(args.raw_dir, args.out_dir) |
| print(json.dumps(summary, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|