|
| 1 | +# SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +# Copyright (C) 2026 dial481 |
| 3 | +"""gnomAD population frequency enrichment. |
| 4 | +
|
| 5 | +gnomAD is not a clinical annotator — it does not produce Annotation |
| 6 | +objects. It enriches existing annotations with population allele |
| 7 | +frequency context. The pipeline calls ``bulk_lookup()`` after all |
| 8 | +annotators have run, and stamps each annotation's ``allele_frequency`` |
| 9 | +field. |
| 10 | +
|
| 11 | +License: ODbL v1.0 (Open Database License). We extract only rsID + |
| 12 | +allele frequencies (no SpliceAI or other restrictively licensed fields). |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +import sqlite3 |
| 19 | +from typing import TYPE_CHECKING, ClassVar |
| 20 | + |
| 21 | +from allelix.annotators.base import Annotator |
| 22 | +from allelix.databases.gnomad_loader import ( |
| 23 | + GNOMAD_CACHE_URL, |
| 24 | + GNOMAD_DB_FILENAME, |
| 25 | + install_prebuilt_cache, |
| 26 | +) |
| 27 | +from allelix.databases.manager import download, get_database_info, head_request_headers |
| 28 | + |
| 29 | +if TYPE_CHECKING: |
| 30 | + from pathlib import Path |
| 31 | + |
| 32 | + from allelix.models import Annotation, Variant |
| 33 | + |
| 34 | +logger = logging.getLogger(__name__) |
| 35 | + |
| 36 | +_BULK_BATCH_SIZE = 900 |
| 37 | + |
| 38 | + |
| 39 | +class GnomadAnnotator(Annotator): |
| 40 | + """Population frequency enrichment from gnomAD. |
| 41 | +
|
| 42 | + Subclasses Annotator for ``db update`` / ``db status`` / ``is_ready()`` |
| 43 | + integration. ``annotate()`` always returns ``[]`` — gnomAD does not |
| 44 | + participate in the per-variant annotation loop. |
| 45 | + """ |
| 46 | + |
| 47 | + name: ClassVar[str] = "gnomad" |
| 48 | + display_name: ClassVar[str] = "gnomAD" |
| 49 | + attribution: ClassVar[str] = "gnomAD" |
| 50 | + requires_download: ClassVar[bool] = True |
| 51 | + |
| 52 | + def __init__(self, data_dir: Path) -> None: |
| 53 | + """Bind to the data directory.""" |
| 54 | + super().__init__(data_dir) |
| 55 | + self._db_path = data_dir / GNOMAD_DB_FILENAME |
| 56 | + self._conn: sqlite3.Connection | None = None |
| 57 | + |
| 58 | + def _connection(self) -> sqlite3.Connection: |
| 59 | + if self._conn is None: |
| 60 | + self._conn = sqlite3.connect(self._db_path) |
| 61 | + return self._conn |
| 62 | + |
| 63 | + def setup(self) -> None: |
| 64 | + """Download the pre-built gnomAD exome frequency cache from HuggingFace.""" |
| 65 | + signal = self.fetch_remote_signal() |
| 66 | + gz_path = self.data_dir / "gnomad_exome_frequencies.sqlite.gz" |
| 67 | + download(GNOMAD_CACHE_URL, gz_path) |
| 68 | + install_prebuilt_cache( |
| 69 | + gz_path, |
| 70 | + self._db_path, |
| 71 | + source_url=GNOMAD_CACHE_URL, |
| 72 | + remote_signal=signal, |
| 73 | + ) |
| 74 | + try: |
| 75 | + gz_path.unlink() |
| 76 | + except OSError: |
| 77 | + logger.warning("Could not remove staged file at %s", gz_path) |
| 78 | + |
| 79 | + def is_ready(self) -> bool: |
| 80 | + """True when the gnomAD SQLite cache exists and is queryable.""" |
| 81 | + return get_database_info(self._db_path, "gnomad") is not None |
| 82 | + |
| 83 | + def version(self) -> str | None: |
| 84 | + """Return the cached database version, or None.""" |
| 85 | + info = get_database_info(self._db_path, "gnomad") |
| 86 | + return info["version"] if info else None |
| 87 | + |
| 88 | + def record_count(self) -> int | None: |
| 89 | + """Return the number of rsIDs in the cache, or None.""" |
| 90 | + info = get_database_info(self._db_path, "gnomad") |
| 91 | + return info["record_count"] if info else None |
| 92 | + |
| 93 | + def close(self) -> None: |
| 94 | + """Close the SQLite connection if open.""" |
| 95 | + if self._conn is not None: |
| 96 | + self._conn.close() |
| 97 | + self._conn = None |
| 98 | + |
| 99 | + def fetch_remote_signal(self) -> str | None: |
| 100 | + """Probe the HuggingFace asset URL for ETag or Last-Modified.""" |
| 101 | + headers = head_request_headers(GNOMAD_CACHE_URL) |
| 102 | + if headers is None: |
| 103 | + return None |
| 104 | + etag = headers.get("ETag") or headers.get("Etag") |
| 105 | + last_modified = headers.get("Last-Modified") or headers.get("Last-modified") |
| 106 | + if etag: |
| 107 | + return f"etag:{etag.strip()}" |
| 108 | + if last_modified: |
| 109 | + return f"lm:{last_modified.strip()}" |
| 110 | + return None |
| 111 | + |
| 112 | + def cached_remote_signal(self) -> str | None: |
| 113 | + """Return the remote signal stored at last successful download.""" |
| 114 | + info = get_database_info(self._db_path, "gnomad") |
| 115 | + if not info or not info["remote_signal"]: |
| 116 | + return None |
| 117 | + return info["remote_signal"] |
| 118 | + |
| 119 | + def annotate(self, variant: Variant) -> list[Annotation]: |
| 120 | + """Not used — gnomAD enriches, does not annotate. Always returns [].""" |
| 121 | + return [] |
| 122 | + |
| 123 | + def lookup(self, rsid: str) -> float | None: |
| 124 | + """Return global allele frequency for a single rsID, or None.""" |
| 125 | + conn = self._connection() |
| 126 | + row = conn.execute( |
| 127 | + "SELECT MAX(af) FROM gnomad_frequencies WHERE rsid = ?", (rsid,) |
| 128 | + ).fetchone() |
| 129 | + return row[0] if row else None |
| 130 | + |
| 131 | + def bulk_lookup(self, rsids: set[str]) -> dict[str, float]: |
| 132 | + """Return ``{rsid: af}`` for all rsIDs found in the cache. |
| 133 | +
|
| 134 | + Batches into chunks of 900 to stay within SQLite's variable limit. |
| 135 | + """ |
| 136 | + if not rsids: |
| 137 | + return {} |
| 138 | + conn = self._connection() |
| 139 | + result: dict[str, float] = {} |
| 140 | + rsid_list = list(rsids) |
| 141 | + for i in range(0, len(rsid_list), _BULK_BATCH_SIZE): |
| 142 | + batch = rsid_list[i : i + _BULK_BATCH_SIZE] |
| 143 | + placeholders = ",".join("?" * len(batch)) |
| 144 | + rows = conn.execute( |
| 145 | + f"SELECT rsid, MAX(af) FROM gnomad_frequencies" |
| 146 | + f" WHERE rsid IN ({placeholders}) GROUP BY rsid", |
| 147 | + batch, |
| 148 | + ).fetchall() |
| 149 | + for rsid, af in rows: |
| 150 | + if af is not None: |
| 151 | + result[rsid] = af |
| 152 | + return result |
0 commit comments