diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..6b969d3eb7c621785db931f9305cf830e15a3918 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,35 +1,57 @@ *.7z filter=lfs diff=lfs merge=lfs -text *.arrow filter=lfs diff=lfs merge=lfs -text *.bin filter=lfs diff=lfs merge=lfs -text +*.bin.* filter=lfs diff=lfs merge=lfs -text *.bz2 filter=lfs diff=lfs merge=lfs -text -*.ckpt filter=lfs diff=lfs merge=lfs -text *.ftz filter=lfs diff=lfs merge=lfs -text *.gz filter=lfs diff=lfs merge=lfs -text *.h5 filter=lfs diff=lfs merge=lfs -text *.joblib filter=lfs diff=lfs merge=lfs -text *.lfs.* filter=lfs diff=lfs merge=lfs -text -*.mlmodel filter=lfs diff=lfs merge=lfs -text *.model filter=lfs diff=lfs merge=lfs -text *.msgpack filter=lfs diff=lfs merge=lfs -text -*.npy filter=lfs diff=lfs merge=lfs -text -*.npz filter=lfs diff=lfs merge=lfs -text *.onnx filter=lfs diff=lfs merge=lfs -text *.ot filter=lfs diff=lfs merge=lfs -text *.parquet filter=lfs diff=lfs merge=lfs -text *.pb filter=lfs diff=lfs merge=lfs -text -*.pickle filter=lfs diff=lfs merge=lfs -text -*.pkl filter=lfs diff=lfs merge=lfs -text *.pt filter=lfs diff=lfs merge=lfs -text *.pth filter=lfs diff=lfs merge=lfs -text *.rar filter=lfs diff=lfs merge=lfs -text -*.safetensors filter=lfs diff=lfs merge=lfs -text saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.tar.* filter=lfs diff=lfs merge=lfs -text -*.tar filter=lfs diff=lfs merge=lfs -text *.tflite filter=lfs diff=lfs merge=lfs -text *.tgz filter=lfs diff=lfs merge=lfs -text -*.wasm filter=lfs diff=lfs merge=lfs -text *.xz filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text +*.zstandard filter=lfs diff=lfs merge=lfs -text +*.tfevents* filter=lfs diff=lfs merge=lfs -text + +*.ark* filter=lfs diff=lfs merge=lfs -text +**/*ckpt*data* filter=lfs diff=lfs merge=lfs -text +**/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text +**/*ckpt*.index filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.gguf* filter=lfs diff=lfs merge=lfs -text +*.ggml filter=lfs diff=lfs merge=lfs -text +*.llamafile* filter=lfs diff=lfs merge=lfs -text +*.pt2 filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text + +checkpoints/alphagenome-all-folds/ocdbt.process_0/d/48900811ab32b5ad3873d40e96d63846 filter=lfs diff=lfs merge=lfs -text + +checkpoints/alphagenome-all-folds/ocdbt.process_0/d/bda173d4f00d3afcef0a043614df05a6 filter=lfs diff=lfs merge=lfs -text +checkpoints/alphagenome-all-folds/ocdbt.process_0/d/6b08a83c9d6a2ade925dbcdd91299ce2 filter=lfs diff=lfs merge=lfs -text + +flax_model/alphagenome/model/metadata/OutputMetadataResponse_ORGANISM_HOMO_SAPIENS.textproto filter=lfs diff=lfs merge=lfs -text +weight/alphagenome-all-folds/ocdbt.process_0/d/48900811ab32b5ad3873d40e96d63846 filter=lfs diff=lfs merge=lfs -text +weight/alphagenome-all-folds/ocdbt.process_0/d/6b08a83c9d6a2ade925dbcdd91299ce2 filter=lfs diff=lfs merge=lfs -text +weight/alphagenome-all-folds/ocdbt.process_0/d/bda173d4f00d3afcef0a043614df05a6 filter=lfs diff=lfs merge=lfs -text \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..82699b13247f9e7114768dd2dfe83823832d4374 --- /dev/null +++ b/LICENSE @@ -0,0 +1,203 @@ +Copyright 2025 Onescience Authors. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Onescience Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bd395b074c3c1d7b7bb601e64dbbc58edce5031e --- /dev/null +++ b/README.md @@ -0,0 +1,248 @@ +--- +license: apache-2.0 +tasks: + - genomic-sequence-modeling +frameworks: + - jax +language: + - en + - zh +tags: + - OneScience + - Life Sciences + - Genomics + - DNA Sequence Model + - Variant Effect Prediction + - AlphaGenome +datasets: + - OneScience-Sugon/alphagenome_dataset +--- + +

+ + AlphaGenome + +

+ +# Model Introduction + +AlphaGenome is a DNA sequence model developed by Google DeepMind. It accepts DNA intervals of up to 1 Mbp as input and predicts a range of functional genomic signals for genomic track prediction and regulatory variant-effect scoring. + +Paper: Advancing regulatory variant effect prediction with AlphaGenome +https://www.nature.com/articles/s41586-025-10014-0 + +# Model Description + +AlphaGenome is implemented in JAX / Flax and supports genomic interval inference, variant effect scoring, track evaluation, and example fine-tuning workflows. This model package is accompanied by the Hugging Face dataset `OneScience-Sugon/alphagenome_dataset`, which enables rapid local validation. + +# Use Cases + +| Scenario | Description | +| :---: | :--- | +| Genomic interval prediction | Takes a reference-genome FASTA file, a chromosome, and genomic interval coordinates as input and outputs predicted tracks such as ATAC, DNase, CAGE, RNA-seq, and ChIP | +| Variant effect scoring | Takes either a VCF file or built-in example variants as input, compares predictions for the reference and variant sequences, and produces a variant scoring table | +| Track prediction evaluation | Uses validation data from the AlphaGenome dataset to compute regression evaluation metrics across different assay bundles | +| Fine-tuning experiments | Validates a fine-tuning workflow using custom reference genomes, interval CSVs, and BigWig signal files | +| Hugging Face / OneCode execution | After downloading the model project and accompanying dataset, quickly verifies that the scripts run correctly in a life-sciences runtime environment | + + + +# Usage Guide + +## 1. OneCode Usage + +Try one-click AI4S development in the OneCode online environment: + +[Try one-click AI4S development](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home) + +## 2. Manual Installation and Usage + +**Hardware Requirements** + +- GPU or DCU is recommended. +- A CPU can be used for import checks and lightweight configuration tests; full training and inference will be slow. +- DCU users must install DTK in advance. DTK 25.04.2 or later is recommended, or a OneScience-recommended version matching the current cluster. + + + + + +**Environment Check** + +- NVIDIA GPU: + +```bash +nvidia-smi +``` + +- Hygon DCU: + +```bash +hy-smi +``` + +### Download the Model Package + +```bash +hf download --model OneScience-Sugon/alphagenome --local-dir ./alphagenome +cd alphagenome +``` + +### Install the Runtime Environment + +**DCU Environment** + +```bash +# Activate DTK and CONDA first +conda create -n onescience311 python=3.11 -y +conda activate onescience311 +# uv installation supported +pip install onescience[bio-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai +``` + +After installation, return to the model package directory: + +```bash +cd ./alphagenome +``` + +### Data for Inference, Evaluation, and Fine-Tuning + +The OneScience community has uploaded the data required for AlphaGenome inference, evaluation, and fine-tuning to Hugging Face: [OneScience-Sugon/alphagenome_dataset](https://huggingface.co/datasets/OneScience-Sugon/alphagenome_dataset). After downloading, place the data in the `data/` directory under the model package. + +```bash +hf download --dataset OneScience-Sugon/alphagenome_dataset --local-dir ./data +``` + +### Model Weights + +The repository already includes `weight/alphagenome-all-folds`, and all scripts allow the model weights directory to be specified via `--model_dir`. + +### Preparing Weights + +If using local weights, place the AlphaGenome Orbax checkpoint in the following directory: + +```text +weight/ + alphagenome-all-folds/ + _CHECKPOINT_METADATA + _METADATA + ... +``` + +When running in a shared environment, you can also reuse centrally managed model and dataset directories via environment variables: + +```bash +export ONESCIENCE_MODELS_DIR=/path/to/onescience/models +export ONESCIENCE_DATASETS_DIR=/path/to/onescience/datasets +``` + +Scripts look in the following locations first: + +- `${ONESCIENCE_MODELS_DIR}/AlphaGenome/alphagenome-all-folds` +- `${ONESCIENCE_DATASETS_DIR}/AlphaGenome` + +If the above environment variables are not set, the scripts fall back to the following paths under the current model package: + +- `weight/alphagenome-all-folds` +- `data/` + +### Interval Inference + +```bash +bash scripts/inference.sh +``` + +Equivalent Python command example: + +```bash +python scripts/run_inference.py \ + --fasta_path ./data/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa \ + --model_dir ./weight/alphagenome-all-folds \ + --chromosome chr19 \ + --start 10587331 \ + --end 11635907 \ + --output_dir ./outputs +``` + +Inference results are saved to `outputs/`. + +### Variant Effect Scoring + +```bash +bash scripts/run_variant.sh +``` + +To specify a VCF input: + +```bash +python scripts/run_variant_scoring.py \ + --vcf_path ./data/example.vcf \ + --fasta_path ./data/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa \ + --model_dir ./weight/alphagenome-all-folds \ + --output_dir ./outputs_variant +``` + +Scoring results are saved as a CSV file. + +### Track Prediction Evaluation + +```bash +bash scripts/run_track.sh +``` + +You can also explicitly specify data and output paths: + +```bash +python scripts/run_track_prediction_eval.py \ + --model_dir ./weight/alphagenome-all-folds \ + --model_version ALL_FOLDS \ + --data_dir ./data/v1/train \ + --output_path ./outputs_track/eval_results.csv +``` + +### Fine-Tuning Example + +```bash +python scripts/run_finetuning.py \ + --fasta_path ./data/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa \ + --regions_csv ./data/finetune_regions.csv \ + --bigwig_paths ./data/sample_atac.bw \ + --output_dir ./finetuned_model \ + --num_steps 1000 \ + --batch_size 2 +``` + +# Data Format + +It is recommended to download the Hugging Face dataset `OneScience-Sugon/alphagenome_dataset` to `data/` under the model package. The default directory structure is as follows: + +```text +data/ + reference/ + HOMO_SAPIENS/ + GRCh38.p13.genome.fa + GRCh38.p13.genome.fa.fai + v1/ + train/ + ... +``` + +In this structure: + +- `reference/HOMO_SAPIENS/GRCh38.p13.genome.fa` is the human reference genome FASTA. +- `.fai` is the FASTA index file. +- `v1/train/` is the data directory used for track prediction evaluation. +- Custom fine-tuning also requires an interval CSV file with column names `chromosome,start,end`, as well as one or more BigWig signal files. + +# OneScience Official Information + +| Platform | OneScience Main Repository | Skills Repository | +| --- | --- | --- | +| Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills | +| GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills | + +# Citation & License + +- This repository is adapted from the open-source AlphaGenome model to support DCUs. The source code is licensed under Apache License 2.0. +- For scientific use, please cite the original paper: [Advancing regulatory variant effect prediction with AlphaGenome](https://www.nature.com/articles/s41586-025-10014-0). diff --git a/flax_model/__init__.py b/flax_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e6dbcfd0f531f21bc89b511afe8c039b35ea2abc --- /dev/null +++ b/flax_model/__init__.py @@ -0,0 +1 @@ +"""Local flax_models copied from OneScience for this standalone package.""" diff --git a/flax_model/alphagenome/__init__.py b/flax_model/alphagenome/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..47379dd9b6801a986d4e5e22d7d5c8e59981c95e --- /dev/null +++ b/flax_model/alphagenome/__init__.py @@ -0,0 +1,39 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome - 统一DNA序列基因组模型,已集成至OneScience。 + +AlphaGenome 是 Google DeepMind 发布的统一DNA序列模型,能够分析最长100万碱基对的 +DNA序列,以单碱基对分辨率预测基因表达、剪接模式、染色质特征和接触图谱。 + +模块结构: + model/ - 核心模型组件 (AlphaGenome, SequenceEncoder, 各类Head) + io/ - 数据输入输出 (BundleName, Dataset, Fasta) + finetuning/ - 微调工具 (训练步骤、数据管道) + evals/ - 评估指标 (track预测、回归指标) + _sdk/ - AlphaGenome SDK (vendored alphagenome v0.6.1) + 包含数据类型、gRPC客户端、变异/区间评分、可视化和ISM解释工具 + +使用方式: + from flax_model.alphagenome.model import model as alphagenome_model + from flax_model.alphagenome.io import dataset + from flax_model.alphagenome.finetuning import finetune + + # SDK 数据类型 (原 from alphagenome.data import genome): + from flax_model.alphagenome._sdk.data import genome + from flax_model.alphagenome._sdk.models import dna_model + from flax_model.alphagenome._sdk.models import dna_output +""" + +__version__ = '0.1.0' diff --git a/flax_model/alphagenome/_sdk/__init__.py b/flax_model/alphagenome/_sdk/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e32e0e966d502b11bda7201e4debd2a4ca7d9bf --- /dev/null +++ b/flax_model/alphagenome/_sdk/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2024 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome Python SDK (vendored into OneScience). + +Original package: alphagenome v0.6.1 +Provides data types, gRPC client, variant/interval scoring, +visualization, and ISM interpretation utilities for genomic models. + +This is a vendored copy integrated into OneScience to avoid requiring +a separate alphagenome package installation. +""" + +__version__ = '0.6.1' diff --git a/flax_model/alphagenome/_sdk/data/__init__.py b/flax_model/alphagenome/_sdk/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1bb78fc624ebb702acc55c87c095170a4bc4570 --- /dev/null +++ b/flax_model/alphagenome/_sdk/data/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2024 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Data classes for interacting and visualizing genomic models.""" diff --git a/flax_model/alphagenome/_sdk/data/genome.py b/flax_model/alphagenome/_sdk/data/genome.py new file mode 100644 index 0000000000000000000000000000000000000000..5de418b2283f5b53dbc395c445dd181387886a63 --- /dev/null +++ b/flax_model/alphagenome/_sdk/data/genome.py @@ -0,0 +1,1181 @@ +# Copyright 2024 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for working with genome-related objects such as intervals.""" + +import collections +from collections.abc import Iterable, Iterator, Mapping, Sequence +import copy +import dataclasses +import enum +import re +import sys +from typing import Any, Protocol + +from flax_model.alphagenome._sdk.protos import dna_model_pb2 +import numpy as np +from typing_extensions import Self + +STRAND_POSITIVE = '+' # Also called forward strand, 5'->3' direction. +STRAND_NEGATIVE = '-' # Also called negative strand, 3'->5' direction. +STRAND_UNSTRANDED = '.' +STRAND_OPTIONS = (STRAND_POSITIVE, STRAND_NEGATIVE, STRAND_UNSTRANDED) +_INTERVAL_START_END_REGEX = re.compile(r'(-?\d+)-(-?\d+)') +VALID_VARIANT_BASES = frozenset('ACGTN') + + +class Strand(enum.IntEnum): + """Represents the strand of a DNA sequence. + + This enum defines the possible strands for a DNA sequence: + + * `POSITIVE`: The forward strand (5' to 3'). + * `NEGATIVE`: The reverse strand (3' to 5'). + * `UNSTRANDED`: The strand is not specified. + """ + + POSITIVE = enum.auto() + NEGATIVE = enum.auto() + UNSTRANDED = enum.auto() + + def __str__(self): + match self: + case Strand.POSITIVE: + return STRAND_POSITIVE + case Strand.NEGATIVE: + return STRAND_NEGATIVE + case Strand.UNSTRANDED: + return STRAND_UNSTRANDED + + @classmethod + def from_str(cls, strand: str) -> Self: + match strand: + case '+': + return cls.POSITIVE + case '-': + return cls.NEGATIVE + case '.': + return cls.UNSTRANDED + case _: + raise ValueError(f'Strand needs to be in {STRAND_OPTIONS}') + + def to_proto(self) -> dna_model_pb2.Strand: + match self: + case Strand.POSITIVE: + return dna_model_pb2.Strand.STRAND_POSITIVE + case Strand.NEGATIVE: + return dna_model_pb2.Strand.STRAND_NEGATIVE + case Strand.UNSTRANDED: + return dna_model_pb2.Strand.STRAND_UNSTRANDED + + @classmethod + def from_proto(cls, strand: dna_model_pb2.Strand) -> Self: + match strand: + case dna_model_pb2.Strand.STRAND_POSITIVE: + return cls.POSITIVE + case dna_model_pb2.Strand.STRAND_NEGATIVE: + return cls.NEGATIVE + case dna_model_pb2.Strand.STRAND_UNSTRANDED: + return cls.UNSTRANDED + case _: + raise ValueError(f'Strand needs to be in {STRAND_OPTIONS}') + + +PYRANGES_INTERVAL_COLUMNS = ('Chromosome', 'Start', 'End', 'Strand', 'Name') + + +@dataclasses.dataclass(order=True) +class Interval: + """Represents a genomic interval. + + A genomic interval is a region on a chromosome defined by a start and end + position. This class provides methods for manipulating and comparing + intervals, and for calculating coverage and overlap. + + Attributes: + chromosome: The chromosome name (e.g., 'chr1', '1'). + start: The 0-based start position. + end: The 0-based end position (must be greater than or equal to start). + strand: The strand of the interval ('+', '-', or '.'). Defaults to '.' + (unstranded). + name: An optional name for the interval. + info: An optional dictionary to store additional information. + negative_strand: True if the interval is on the negative strand, False + otherwise. + width: The width of the interval (end - start). + """ + + chromosome: str + start: int + end: int + strand: str = STRAND_UNSTRANDED + name: str = dataclasses.field(default='', compare=False, hash=False) + info: dict[str, Any] = dataclasses.field( + default_factory=dict, repr=False, compare=False, hash=False + ) + + def __post_init__(self): + if self.end < self.start: + raise ValueError('end < start. Interval: ' + str(self)) + if self.strand not in STRAND_OPTIONS: + raise ValueError( + f'Strand needs to be in {STRAND_OPTIONS}, found {self.strand}.' + ) + + @property + def negative_strand(self) -> bool: + """Returns True if interval is on the negative strand, False otherwise.""" + return self.strand == STRAND_NEGATIVE + + @property + def width(self) -> int: + """Returns the width of the interval.""" + return self.end - self.start + + def copy(self) -> Self: + """Returns a deep copy of the interval.""" + return copy.deepcopy(self) + + def __str__(self) -> str: + """Returns a string representation of the interval.""" + return f'{self.chromosome}:{self.start}-{self.end}:{self.strand}' + + @classmethod + def from_str(cls, string: str) -> Self: + """Creates an Interval from a string (e.g., 'chr1:100-200:+').""" + chromosome, interval, *strand = string.split(':', maxsplit=2) + if strand: + strand = strand[0] + else: + strand = STRAND_UNSTRANDED + # Get start and end from the interval string. + match = _INTERVAL_START_END_REGEX.fullmatch(interval) + if match: + start, end = int(match.group(1)), int(match.group(2)) + else: + raise ValueError(f'Invalid interval: {string}') + return cls( + chromosome=chromosome, start=int(start), end=int(end), strand=strand + ) + + def to_proto(self) -> dna_model_pb2.Interval: + """Converts the interval to a protobuf message.""" + return dna_model_pb2.Interval( + chromosome=self.chromosome, + start=self.start, + end=self.end, + strand=Strand.from_str(self.strand).to_proto(), + ) + + @classmethod + def from_proto(cls, proto: dna_model_pb2.Interval) -> Self: + """Creates an Interval from a protobuf message.""" + return cls( + chromosome=proto.chromosome, + start=proto.start, + end=proto.end, + strand=str(Strand.from_proto(proto.strand)), + ) + + def to_interval_dict(self) -> dict[str, str | int]: + """Converts the interval to a dictionary.""" + return dict( + chrom=self.chromosome, + start=self.start, + end=self.end, + strand=self.strand, + ) + + @classmethod + def from_interval_dict(cls, interval: Mapping[str, str | int]) -> Self: + """Creates an Interval from a dictionary.""" + return cls( + chromosome=str(interval['chrom']), + start=int(interval['start']), + end=int(interval['end']), + strand=str(interval.get('strand', STRAND_UNSTRANDED)), + ) + + @classmethod + def from_pyranges_dict( + cls, row: Mapping[str, Any], ignore_info: bool = False + ) -> 'Interval': + """Creates an Interval from a pyranges-like dictionary. + + This method constructs an `Interval` object from a dictionary that follows + the pyranges format, such as a row from a :class:`pandas.DataFrame` + converted to a dict. + + The dictionary should have the following keys: + + * 'Chromosome': The chromosome name. + * 'Start': The start position. + * 'End': The end position. + * 'Strand': The strand (optional, defaults to unstranded). + * 'Name': The interval name (optional). + + Any other keys in the dictionary will be added to the `info` attribute of + the `Interval` object, unless `ignore_info` is set to True. + + Args: + row: A dictionary containing interval data. + ignore_info: If True, any keys in the dictionary that are not part of the + standard pyranges columns ('Chromosome', 'Start', 'End', 'Strand', + 'Name') will not be added to the `info` attribute. + + Returns: + An `Interval` object created from the input dictionary. + """ + if ignore_info: + info = {} + else: + info = { + k: v for k, v in row.items() if k not in PYRANGES_INTERVAL_COLUMNS + } + + return cls( + chromosome=str(row['Chromosome']), + start=int(row['Start']), + end=int(row['End']), + strand=str(row.get('Strand', STRAND_UNSTRANDED)), + name=str(row.get('Name', '')), + info=info, + ) + + def to_pyranges_dict(self) -> dict[str, int | str]: + """Converts the interval to a pyranges-like dictionary.""" + return { + 'Chromosome': self.chromosome, + 'Start': self.start, + 'End': self.end, + 'Name': self.name, + 'Strand': self.strand, + **self.info, + } + + def swap_strand(self) -> Self: + """Swaps the strand of the interval.""" + obj = self.copy() + if obj.strand == STRAND_POSITIVE: + obj.strand = STRAND_NEGATIVE + elif obj.strand == STRAND_NEGATIVE: + obj.strand = STRAND_POSITIVE + elif obj.strand == STRAND_UNSTRANDED: + raise ValueError('Cannot swap unstranded intervals.') + return obj + + def as_unstranded(self) -> Self: + """Returns an unstranded copy of the interval.""" + obj = self.copy() + obj.strand = STRAND_UNSTRANDED + return obj + + def within_reference(self, reference_length: int = sys.maxsize) -> bool: + """Checks if the interval is within the valid reference range.""" + return self.start >= 0 and self.end <= reference_length + + def truncate(self, reference_length: int = sys.maxsize) -> Self: + """Truncates the interval to fit within the valid reference range.""" + obj = self.copy() + if reference_length <= 0: + raise ValueError('Reference length should be larger than 0.') + if self.within_reference(reference_length): + return obj + else: + obj.start = max(self.start, 0) + obj.end = min(self.end, reference_length) + return obj + + def center(self, use_strand: bool = True) -> int: + """Computes the center of the interval. + + For intervals with an odd width, the center is rounded up for + positive/unstranded intervals and rounded down for negative strand + intervals. + + If `use_strand` is True and the interval is on the negative strand, the + center is calculated differently to maintain consistency when stacking + sequences from different intervals oriented in the forward strand direction. + This ensures that the relative distance between the interval's upstream + boundary and its center is preserved. + + Args: + use_strand: If True, the strand of the interval is considered when + calculating the center. + + Returns: + The integer representing the center position of the interval. + + Examples: + >>> Interval('1', 1, 3, '+').center() + 2 + >>> Interval('1', 1, 3, '-').center() # Strand doesn't matter. + 2 + >>> Interval('1', 1, 4, '+').center() + 3 + >>> Interval('1', 1, 4, '-').center() + 2 + >>> Interval('1', 1, 4, '-').center() + 2 + >>> Interval('1', 1, 4, '+').center(use_strand=False) + 3 + >>> Interval('1', 1, 2, '-').center() + 1 + """ + center = (self.start + self.end) // 2 + if use_strand and self.negative_strand: + return center + else: + return center + self.width % 2 + + def shift(self, offset: int, use_strand: bool = True) -> Self: + """Shifts the interval by the given offset. + + Args: + offset: The amount to shift the interval. + use_strand: If True, the shift direction is reversed for negative strand + intervals. + + Returns: + A new shifted interval. + """ + obj = self.copy() + if use_strand and self.negative_strand: + offset = -offset + obj.start = self.start + offset + obj.end = self.end + offset + return obj + + def boundary_shift( + self, start_offset: int = 0, end_offset: int = 0, use_strand: bool = True + ) -> Self: + """Extends or shrinks the interval by adjusting the positions with padding. + + Args: + start_offset: The amount to shift the start position. + end_offset: The amount to shift the end position. + use_strand: If True, the offsets are applied in reverse for negative + strand intervals. + + Returns: + A new interval with adjusted boundaries. + """ + return self.pad(-start_offset, end_offset, use_strand=use_strand) + + def pad( + self, start_pad: int, end_pad: int, *, use_strand: bool = True + ) -> Self: + """Pads the interval by adding the specified padding to the start and end. + + Args: + start_pad: The amount of padding to add to the start. + end_pad: The amount of padding to add to the end. + use_strand: If True, padding is applied in reverse for negative strand + intervals. + + Returns: + A new padded interval. + """ + obj = self.copy() + obj.pad_inplace(start_pad, end_pad, use_strand=use_strand) + return obj + + def pad_inplace( + self, start_pad: int, end_pad: int, *, use_strand: bool = True + ): + """Pads the interval in place by adding padding to the start and end. + + Args: + start_pad: The amount of padding to add to the start. + end_pad: The amount of padding to add to the end. + use_strand: If True, padding is applied in reverse for negative strand + intervals. + """ + if use_strand and self.strand == '-': + start_pad, end_pad = end_pad, start_pad + self.start -= start_pad + self.end += end_pad + if self.width < 0: + raise ValueError('Resulting interval has negative length') + + def resize(self, width: int, use_strand: bool = True) -> Self: + """Resizes the interval to a new width, centered around the original center. + + Args: + width: The new width of the interval. + use_strand: If True, resizing considers the strand orientation. + + Returns: + A new resized interval. + """ + obj = self.copy() + obj.resize_inplace(width, use_strand) + return obj + + def resize_inplace(self, width: int, use_strand: bool = True) -> None: + """Resizes the interval in place, centered around the original center. + + Args: + width: The new width of the interval. + use_strand: If True, resizing considers the strand orientation. + """ + if width < 0: + raise ValueError(f'Width needs to be > 0. Found: {width}.') + + if width is None or self.width == width: + return + + center = self.center() + if use_strand and self.negative_strand: + self.start = center - width // 2 + self.end = center + (width + 1) // 2 + else: + self.start = center - (width + 1) // 2 + self.end = center + width // 2 + assert self.width == width + + def overlaps(self, interval: Self) -> bool: + """Checks if this interval overlaps with another interval.""" + return ( + self.chromosome == interval.chromosome + and self.start < interval.end + and interval.start < self.end + ) + + def contains(self, interval: Self) -> bool: + """Checks if this interval completely contains another interval.""" + return ( + self.chromosome == interval.chromosome + and self.start <= interval.start + and self.end >= interval.end + ) + + def intersect(self, interval: Self) -> Self | None: + """Returns the intersection of this interval with another interval.""" + output = self.copy() + if not self.overlaps(interval): + return None + output.start = max(self.start, interval.start) + output.end = min(self.end, interval.end) + return output + + def coverage( + self, intervals: Sequence[Self], *, bin_size: int = 1 + ) -> np.ndarray: + """Computes coverage track from sequence of intervals overlapping interval. + + This method calculates the coverage of this interval by a set of other + intervals. The coverage is defined as the number of intervals that overlap + each position within this interval. + + The `bin_size` parameter allows you to bin the coverage into equal-sized + windows. This can be useful for summarizing coverage over larger regions. + If `bin_size` is 1, the coverage is calculated at single-base resolution. + + Args: + intervals: A sequence of `Interval` objects that may overlap this + interval. + bin_size: The size of the bins used to calculate coverage. Must be a + positive integer that divides the width of the interval. + + Returns: + A 1D numpy array representing the coverage track. The length of the array + is `self.width // bin_size`. Each element in the array represents the + summed coverage within the corresponding bin. + + Raises: + ValueError: If `bin_size` is not a positive integer or if the interval + width is not divisible by `bin_size`. + """ + if bin_size <= 0: + raise ValueError('bin_size needs to be larger or equal to 1.') + if self.width % bin_size != 0: + raise ValueError( + f'interval width {self.width} needs to be divisible ' + f'by bin_size {bin_size}.' + ) + output = np.zeros((self.width,), dtype=np.int32) + for interval in intervals: + if not self.overlaps(interval): + continue + relative_start = max(interval.start - self.start, 0) + relative_end = min(interval.end - self.start, self.width) + output[relative_start:relative_end] += 1 + if bin_size > 1: + return output.reshape((self.width // bin_size, bin_size)).sum(axis=-1) + else: + return output + + def overlap_ranges( + self, + intervals: Sequence[Self], + ) -> np.ndarray: + """Returns overlapping ranges from intervals overlapping this interval. + + Args: + intervals: Sequence of candidate intervals to test for overlap. + + Returns: + 2D numpy array indicating the start and end of the overlapping ranges. + """ + output = [] + for interval in intervals: + if not self.overlaps(interval): + continue + relative_start = max(interval.start - self.start, 0) + relative_end = min(interval.end - self.start, self.width) + output.append([relative_start, relative_end]) + + return ( + np.asarray(output, dtype=np.int32) + if output + else np.empty((0, 2), dtype=np.int32) + ) + + def binary_mask( + self, intervals: Sequence[Self], bin_size: int = 1 + ) -> np.ndarray: + """Boolean mask True if any interval overlaps the bin: coverage > 0.""" + return self.coverage(intervals, bin_size=bin_size) > 0 + + def coverage_stranded( + self, intervals: Sequence[Self], *, bin_size: int = 1 + ) -> np.ndarray: + """Computes a coverage track from intervals overlapping this interval. + + This method considers the strand information of both self and intervals. + + Args: + intervals: Sequence of intervals possibly overlapping self. + bin_size: Resolution at which to bin the output coverage track. Coverage + within each bin (if larger than 1) will be summarized using sum(). + + Returns: + Numpy array of shape (self.width // bin_size, 2) where output[:, 0] + represents coverage for intervals on the same strand as self and + output[:, 1] represents coverage of intervals on the opposite strand. + """ + # Split intervals based on strand. + forward_intervals = [] + reverse_intervals = [] + for interval in intervals: + if interval.negative_strand: + reverse_intervals.append(interval) + else: + forward_intervals.append(interval) + + coverage = np.stack( + [ + self.coverage(forward_intervals, bin_size=bin_size), + self.coverage(reverse_intervals, bin_size=bin_size), + ], + axis=-1, + ) + if self.negative_strand: + return coverage[::-1, ::-1] + else: + return coverage + + def binary_mask_stranded( + self, intervals: Sequence[Self], bin_size: int = 1 + ) -> np.ndarray: + """Boolean mask True if any interval overlaps the bin: coverage > 0.""" + return self.coverage_stranded(intervals, bin_size=bin_size) > 0 + + +_DEFAULT_REGEX = re.compile(r'(chr(?:X|Y|M|\d+)):(\d+):([ACGTN]*)>([ACGTN]*)') +_GTEX_REGEX = re.compile( + r'(chr(?:X|Y|M|\d+))_(\d+)_([ACGTN]*)_([ACGTN]*)_?[a-zA-Z0-9]*' +) +_OPEN_TARGETS_REGEX = re.compile(r'((?:X|Y|M|\d+))_(\d+)_([ACGTN]*)_([ACGTN]*)') +_OPEN_TARGETS_BIGQUERY_REGEX = re.compile( + r'((?:X|Y|M|\d+)):(\d+):([ACGTN]*):([ACGTN]*)' +) +_GNOMAD_REGEX = re.compile(r'((?:X|Y|M|\d+))-(\d+)-([ACGTN]*)-([ACGTN]*)') + + +class VariantFormat(enum.Enum): + """A format for parsing a string into a Variant object. + + This is used to convert from a string to a formal Variant object. + Note that it does not perform any validation (e.g. it does not verify that the + reference allele corresponds to the reference genome or that the + position is valid). + + Example formats: + DEFAULT: chr22:1024:A>C + GTEX: chr22_1024_A_C_b38 (build suffix is optional) + OPEN_TARGETS: 22_1024_A_C (chr prefix is omitted) + OPEN_TARGETS_BIGQUERY: 22:1024:A:C (chr prefix is omitted) + GNOMAD: 22-1024-A-C (chr prefix is omitted) + """ + + DEFAULT = 'default' + GTEX = 'gtex' + OPEN_TARGETS = 'open_targets' + OPEN_TARGETS_BIGQUERY = 'open_targets_bigquery' + GNOMAD = 'gnomad' + + def to_regex(self) -> re.Pattern[str]: + """Returns a regular expression for the variant format.""" + match self: + case VariantFormat.DEFAULT: + return _DEFAULT_REGEX + case VariantFormat.GTEX: + return _GTEX_REGEX + case VariantFormat.OPEN_TARGETS: + return _OPEN_TARGETS_REGEX + case VariantFormat.OPEN_TARGETS_BIGQUERY: + return _OPEN_TARGETS_BIGQUERY_REGEX + case VariantFormat.GNOMAD: + return _GNOMAD_REGEX + + +@dataclasses.dataclass +class Variant: + """Represents a genomic variant/mutation. + + Differs from the Variant definition in a VCF file, which allows + for multiple alternative bases and contains sample information. This + `Variant` class does not include sample information or variant call + quality information. + + Attributes: + chromosome: The chromosome name (e.g., 'chr1', '1'). + position: The 1-based position of the variant on the chromosome. + reference_bases: The reference base(s) at the variant position. Most + frequently (not always!), these correspond to the sequence in the + reference genome at positions: [position, ..., position + + len(reference_bases) - 1] + alternate_bases: The alternate base(s) that replace the reference. For + example, if sequence='ACT', position=2, reference_bases='C', + alternate_bases='TG', then the actual (alternate) sequence would be ATGT. + name: An optional name for the variant (e.g., a dbSNP ID like rs206437). + info: An optional dictionary for additional variant information. + """ + + chromosome: str + position: int + reference_bases: str + alternate_bases: str + name: str = dataclasses.field(default='', compare=False, hash=False) + info: dict[str, Any] = dataclasses.field( + default_factory=dict, repr=False, compare=False, hash=False + ) + + def __post_init__(self): + """Validates the variant's position.""" + if self.position < 1: + raise ValueError(f'Position has to be >=1. Found: {self.position}.') + if not set(self.reference_bases).issubset(VALID_VARIANT_BASES): + raise ValueError( + f'Invalid reference bases: "{self.reference_bases}". Must only' + ' contain "ACGTN".' + ) + if not set(self.alternate_bases).issubset(VALID_VARIANT_BASES): + raise ValueError( + f'Invalid alternate bases: "{self.alternate_bases}". Must only' + ' contain "ACGTN".' + ) + + def __str__(self): + """Returns a string representation of the variant.""" + ref_alt = f'{self.reference_bases}>{self.alternate_bases}' + return f'{self.chromosome}:{self.position}:{ref_alt}' + + def as_truncated_str(self, max_length: int = 50): + """Truncates the variant str's ref and alt bases to the given max length.""" + + def _truncate(s: str): + if len(s) <= max_length: + return s + else: + return s[: max_length // 2] + '...' + s[-max_length // 2 :] + + return ( + f'{self.chromosome}:{self.position}:' + f'{_truncate(self.reference_bases)}>{_truncate(self.alternate_bases)}' + ) + + @property + def start(self) -> int: + """Returns the 0-based start position of the variant.""" + return self.position - 1 + + @property + def end(self) -> int: + """Returns the 0-based end position of the variant.""" + return self.start + len(self.reference_bases) + + @property + def reference_interval(self) -> Interval: + """Returns an `Interval` for the variant's reference sequence.""" + return Interval(self.chromosome, self.start, self.end) + + def reference_overlaps(self, interval: Interval) -> bool: + """Checks if the variant's reference overlaps with the interval.""" + return interval.overlaps(Interval(self.chromosome, self.start, self.end)) + + def alternate_overlaps(self, interval: Interval) -> bool: + """Checks if the variant's alternate overlaps with the interval.""" + return interval.overlaps( + Interval( + self.chromosome, self.start, self.start + len(self.alternate_bases) + ) + ) + + @property + def is_snv(self) -> bool: + """Return if the variant is a Single Nucleotide Variant (SNV).""" + return len(self.reference_bases) == 1 and len(self.alternate_bases) == 1 + + @property + def is_deletion(self) -> bool: + """Return if the variant is a deletion.""" + return len(self.reference_bases) > len(self.alternate_bases) + + @property + def is_insertion(self) -> bool: + """Return if the variant is an insertion.""" + return len(self.reference_bases) < len(self.alternate_bases) + + @property + def is_frameshift(self) -> bool: + """Return if the variant is a frameshift.""" + indel_size = abs(len(self.reference_bases) - len(self.alternate_bases)) + return indel_size > 0 and indel_size % 3 != 0 + + @property + def is_indel(self) -> bool: + """Return if the variant is an insertion or deletion.""" + return self.is_insertion or self.is_deletion + + @property + def is_structural(self) -> bool: + """Return if the variant is a structural variant.""" + indel_size = abs(len(self.reference_bases) - len(self.alternate_bases)) + return indel_size >= 50 + + def copy(self) -> Self: + """Returns a deep copy of the variant.""" + return copy.deepcopy(self) + + @classmethod + def from_str( + cls, string: str, variant_format: VariantFormat = VariantFormat.DEFAULT + ) -> Self: + """Creates a `Variant` from a string representation. + + Args: + string: The string representation. + variant_format: The format of the variant string. By default, this uses + "chromosome:position:ref>alt" (for example, "chr1:1024:A>C"). See + VariantFormat for alternate formatting options. + + Returns: + A `Variant` object. + """ + result = re.fullmatch(variant_format.to_regex(), string) + if result is None: + raise ValueError(f'Invalid format for variant string: {string}') + + chromosome, position, reference, alternate = result.groups() + # Add chr prefix if not already present. + if not chromosome.startswith('chr'): + chromosome = f'chr{chromosome}' + return cls( + chromosome=chromosome, + position=int(position), + reference_bases=reference, + alternate_bases=alternate, + ) + + def to_dict(self) -> dict[str, Any]: + """Converts the variant to a dictionary.""" + return dataclasses.asdict(self) + + @classmethod + def from_dict(cls, dictionary: Mapping[str, Any] | Self) -> Self: + """Creates a `Variant` from a dictionary.""" + return cls(**dictionary) # pytype: disable=bad-return-type + + def to_proto(self) -> dna_model_pb2.Variant: + """Converts the variant to a protobuf message.""" + return dna_model_pb2.Variant( + chromosome=self.chromosome, + position=self.position, + reference_bases=self.reference_bases, + alternate_bases=self.alternate_bases, + ) + + @classmethod + def from_proto(cls, variant: dna_model_pb2.Variant) -> Self: + """Creates a `Variant` from a protobuf message.""" + return cls( + chromosome=variant.chromosome, + position=variant.position, + reference_bases=variant.reference_bases, + alternate_bases=variant.alternate_bases, + ) + + def split(self, anchor: int) -> tuple[Self | None, Self | None]: + """Splits the variant into two at the anchor point. + + If the anchor point falls within the variant's reference sequence, the + variant is split into two new variants: one upstream of the anchor and one + downstream. If the anchor is outside the variant's reference sequence, + the original variant is returned on the appropriate side, and None on the + other. + + Example: + position= 3 + ref: ...[ A C ]... + alt: .....T G T C + anchor=3 | + returns: (chr1:3:A>T, chr1:4:C>GTC) + + Args: + anchor: The 0-based anchor point to split the variant. + + Returns: + A tuple of the upstream and downstream variants. If the variant is only + on one side of the anchorpoint, then None is returned. + """ + if anchor <= self.start: + return None, self.copy() + elif anchor >= self.end: + return self.copy(), None + else: + mid = anchor - self.start + upstream, downstream = self.copy(), self.copy() + upstream.reference_bases = self.reference_bases[:mid] + upstream.alternate_bases = self.alternate_bases[:mid] + + downstream.position = anchor + 1 + downstream.reference_bases = self.reference_bases[mid:] + downstream.alternate_bases = self.alternate_bases[mid:] + return upstream, downstream + + +@dataclasses.dataclass +class Junction(Interval): + """Represents a splice junction. + + A splice junction is a point in a pre-mRNA transcript where an intron is + removed and exons are joined during RNA splicing. This class inherits from + `Interval` and adds properties and methods specific to splice junctions. + + Attributes: + chromosome: The chromosome name. + start: The 0-based start position of the junction. + end: The 0-based end position of the junction. + strand: The strand of the junction ('+' or '-'). + name: An optional name for the junction. + info: An optional dictionary to store additional information. + k: An optional integer representing the number of reads supporting the + splice junction. + + Raises: + ValueError: If the strand is unstranded. + """ + + k: int | None = None + + def __post_init__(self): + """Validates that the junction is stranded.""" + super().__post_init__() + if self.strand == STRAND_UNSTRANDED: + raise ValueError('Junctions must be stranded.') + + @property + def acceptor(self) -> int: + """Returns the acceptor site position.""" + return self.start if self.strand == STRAND_NEGATIVE else self.end + + @property + def donor(self) -> int: + """Returns the donor site position.""" + return self.end if self.strand == STRAND_NEGATIVE else self.start + + def dinucleotide_region(self) -> tuple[Interval, Interval]: + """Returns the dinucleotide regions around acceptor and donor sites.""" + return ( + Interval( + self.chromosome, self.start, self.start + 2, strand=self.strand + ), + Interval(self.chromosome, self.end - 2, self.end, strand=self.strand), + ) + + def acceptor_region(self, overhang: tuple[int, int] = (250, 250)) -> Interval: + """Returns the region around the acceptor site with overhang.""" + return Interval( + self.chromosome, self.acceptor, self.acceptor, strand=self.strand + ).pad(start_pad=overhang[0], end_pad=overhang[1]) + + def donor_region(self, overhang: tuple[int, int] = (250, 250)) -> Interval: + """Returns the region around the donor site with overhang.""" + return Interval( + self.chromosome, self.donor, self.donor, strand=self.strand + ).pad(start_pad=overhang[0], end_pad=overhang[1]) + + +class _FastaExtractorType(Protocol): + """Protocol definition for extracting intervals from a Fasta file.""" + + def extract(self, interval: Interval) -> str: + """Extract and return the DNA sequence for a given interval.""" + + +def _prefix_length(*sequences) -> int: + """Returns the length of the common prefix for a sequence of strings.""" + i = 0 + for chars in zip(*sequences, strict=False): + if all(c == chars[0] for c in chars): + i += 1 + else: + break + return i + + +def normalize_variant( + variant: Variant, extractor: _FastaExtractorType +) -> Variant: + """Normalize a Variant by left-aligning the reference and alternate bases. + + Normalization applied following algorithm described in + https://doi.org/10.1093/bioinformatics/btv112. + + Args: + variant: The Variant to normalize. + extractor: The FastaExtractor to use for extracting the reference sequence. + + Returns: + The normalized Variant. + """ + if variant.is_snv: + return variant + + chromosome = variant.chromosome + genome_sequence = extractor.extract( + Interval( + chromosome, + variant.start, + variant.start + + max(len(variant.reference_bases), len(variant.alternate_bases)), + ) + ) + + position = variant.position + alleles = [genome_sequence, variant.reference_bases, variant.alternate_bases] + + # Remove any common suffix from the alleles. + finished = False + while not finished: + suffix_length = _prefix_length(*[reversed(a) for a in alleles]) + if suffix_length > 0: + alleles = [a[:-suffix_length] for a in alleles] + + # If any alleles are empty, extend all alleles by 1 nucleotide to the left. + if not all(alleles): + position -= 1 + base = extractor.extract(Interval(chromosome, position - 1, position))[0] + alleles = [base + a for a in alleles] + else: + # Finished iff we haven't shifted alleles and don't have a common suffix. + finished = suffix_length == 0 + + # Left-align the variant to the genome, ensuring at least 1 bp of context. + max_prefix_length = len(min(alleles)) - 1 + prefix_length = _prefix_length(*alleles) + i = min(max_prefix_length, prefix_length) + + _, reference_bases, alternate_bases = alleles + return Variant( + chromosome=chromosome, + position=position + i, + reference_bases=reference_bases[i:], + alternate_bases=alternate_bases[i:], + ) + + +def _split_intervals( + intervals: Iterable[Interval], marker: int, bounds: list[tuple[int, int]] +): + """Splits intervals into start and end points with markers.""" + for i in intervals: + bounds.append((i.start, +marker)) + bounds.append((i.end, -marker)) + + +def _group_by_chromosome( + intervals: Iterable[Interval], +) -> dict[str, list[Interval]]: + """Groups intervals by chromosome.""" + interval_map = collections.defaultdict(list) + for i in intervals: + interval_map[i.chromosome].append(i) + return dict(interval_map) + + +def intersect_intervals( + lhs: Iterable[Interval], + rhs: Iterable[Interval], + *, + result_strand: str = '.', +) -> Iterator[Interval]: + """Generates the intersection of two interval sets. + + Point ranges (width == 0) are considered to intersect any range which contains + them. + + In these examples, the intersection is a point range (2,2) + ``` + 1 2 3 4 + ..|..|..|..|.. + <> (start=2, end=2) + -------> (..., end=2) + ``` + + ``` + 1 2 3 4 + ..|..|..|..|.. + <> (start=2, end=2) + <------- (start=2, end=...) + ``` + + For consistency, this means that the following results in a point + intersection: + + ``` + 1 2 3 4 + ..|..|..|..|.. + -------> (start=..., end=2) + <------- (start=2, end=...) + ``` + + Args: + lhs: A set of intervals. + rhs: A set of intervals. + result_strand: The strand for the resulting intervals. + + Yields: + The intersection of intervals. Overlapping intervals within either `lhs` + or `rhs` are implicitly unioned. + """ + + def _intersect(lhs, rhs, chrom): + """Calculates the intersection for a specific chromosome. + + Deconstructs two sets of intervals into (start, +k) and (end, -k) positions, + where k is different for each set, then sorts all interval endpoints. By + walking the sorted endpoints and accumulating the k's, we can work out when + we enter or exit an interval from either set. + + This allows emitting intervals corresponding to the intersection, and with + appropriate k's, detecting when we enter an interval in either set before + exiting the previous. + + Args: + lhs: The first list of `Interval` objects. + rhs: The second list of `Interval` objects. + chrom: The chromosome name. + + Yields: + `Interval` objects representing the intersections. + """ + bounds = [] + _split_intervals(lhs, 0x00001, bounds) + _split_intervals(rhs, 0x10000, bounds) + accum = 0 + start = None + for pos, delta in sorted(bounds, key=lambda x: (x[0], -x[1])): + old_accum = accum + accum += delta + if accum & 0xFFFF and accum & 0xFFFF0000: + if start is None: + start = pos + elif old_accum & 0xFFFF and old_accum & 0xFFFF0000: + yield Interval(chrom, start, pos, result_strand) + start = None + + lhs = _group_by_chromosome(lhs) + rhs = _group_by_chromosome(rhs) + for chromosome in set(lhs) & set(rhs): + yield from _intersect(lhs[chromosome], rhs[chromosome], chromosome) + + +def union_intervals( + lhs: Iterable[Interval], + rhs: Iterable[Interval], + *, + result_strand: str = '.', +) -> Iterator[Interval]: + """Generates the union of two interval sets. + + Args: + lhs: A non-overlapping set of intervals. + rhs: A non-overlapping set of intervals. + result_strand: The strand for the resulting intervals. + + Yields: + The union of intervals. Any position covered by an interval in `lhs` or + `rhs` is covered in the result. + """ + + def _union(lhs, rhs, chrom): + """Calculates the union for a specific chromosome, analog of _intersect.""" + bounds = [] + _split_intervals(lhs, 0x00001, bounds) + _split_intervals(rhs, 0x10000, bounds) + accum = 0 + start = end = None + for pos, delta in sorted(bounds, key=lambda x: (x[0], -x[1])): + if accum == 0 and end is not None and end < pos: + # Delay generating an interval until after the observed end point. + # This merges abutting ranges. + yield Interval(chrom, start, end, result_strand) + start = end = None + accum += delta + if accum: + if start is None: + start = pos + else: + assert start is not None + end = pos + if end is not None: + yield Interval(chrom, start, end, result_strand) + + lhs = _group_by_chromosome(lhs) + rhs = _group_by_chromosome(rhs) + for chromosome in set(lhs) | set(rhs): + yield from _union( + lhs.get(chromosome, []), rhs.get(chromosome, []), chromosome + ) + + +def merge_overlapping_intervals( + intervals: Sequence[Interval], +) -> list[Interval]: + """Merges overlapping intervals and returns a sorted list. + + Args: + intervals: A sequence of intervals with the same strand. + + Returns: + A new sorted list of merged intervals. + """ + if not intervals: + return [] + assert all(i.strand == intervals[0].strand for i in intervals) + return list(union_intervals(intervals, [], result_strand=intervals[0].strand)) diff --git a/flax_model/alphagenome/_sdk/models/interval_scorers.py b/flax_model/alphagenome/_sdk/models/interval_scorers.py new file mode 100644 index 0000000000000000000000000000000000000000..30dd858cc1fda3cf616a36c9d979a2d04ff620b1 --- /dev/null +++ b/flax_model/alphagenome/_sdk/models/interval_scorers.py @@ -0,0 +1,145 @@ +# Copyright 2024 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module containing interval scorer dataclasses for interval scoring.""" + +import dataclasses +import enum +from typing import TypeVar + +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.protos import dna_model_pb2 +import immutabledict + + +class IntervalAggregationType(enum.Enum): + """Enum indicating the type of interval scorer aggregation. + + Attributes: + MEAN: Mean across positions. + SUM: Sum across positions. + + Methods: + to_proto: Converts the aggregation type to its corresponding proto enum. + """ + + MEAN = dna_model_pb2.IntervalAggregationType.INTERVAL_AGGREGATION_TYPE_MEAN + SUM = dna_model_pb2.IntervalAggregationType.INTERVAL_AGGREGATION_TYPE_SUM + + def to_proto(self) -> dna_model_pb2.IntervalAggregationType: + return self.value + + def __repr__(self) -> str: + return self.name + + +class BaseIntervalScorer(enum.Enum): + """Enum indicating the type of interval scoring. + + Attributes: + GENE_MASK: Gene-mask scoring (e.g., aggregation of predictions within genes) + """ + + GENE_MASK = enum.auto() + + +SUPPORTED_OUTPUT_TYPES = immutabledict.immutabledict({ + BaseIntervalScorer.GENE_MASK: [ + dna_output.OutputType.ATAC, + dna_output.OutputType.CAGE, + dna_output.OutputType.CHIP_HISTONE, + dna_output.OutputType.CHIP_TF, + dna_output.OutputType.DNASE, + dna_output.OutputType.RNA_SEQ, + dna_output.OutputType.SPLICE_SITES, + dna_output.OutputType.SPLICE_SITE_USAGE, + ], +}) + +SUPPORTED_WIDTHS = immutabledict.immutabledict({ + BaseIntervalScorer.GENE_MASK: [None, 501, 2001, 10_001, 100_001, 200_001], +}) + + +@dataclasses.dataclass(frozen=True) +class GeneMaskScorer: + """Interval scorer for gene-mask scoring. + + Attributes: + requested_output: The requested output type (e.g. ATAC, DNASE, etc.) + width: The width of the target interval to include in the aggregation. + aggregation_type: The type of aggregation to perform. + base_interval_scorer: The base interval scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + + Raises: + ValueError: If the requested output is not supported. + """ + + requested_output: dna_output.OutputType + width: int | None + aggregation_type: IntervalAggregationType + + @property + def base_interval_scorer(self) -> BaseIntervalScorer: + return BaseIntervalScorer.GENE_MASK + + @property + def name(self) -> str: + return str(self) + + def __post_init__(self): + if ( + self.requested_output + not in SUPPORTED_OUTPUT_TYPES[self.base_interval_scorer] + ): + raise ValueError( + f'Unsupported requested output: {self.requested_output}. Supported' + f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_interval_scorer]}' + ) + if self.width not in SUPPORTED_WIDTHS[self.base_interval_scorer]: + raise ValueError( + f'Unsupported width: {self.width}. Supported widths:' + f' {SUPPORTED_WIDTHS[self.base_interval_scorer]}' + ) + + def to_proto(self) -> dna_model_pb2.IntervalScorer: + return dna_model_pb2.IntervalScorer( + gene_mask=dna_model_pb2.GeneMaskIntervalScorer( + requested_output=self.requested_output.to_proto(), + width=self.width, + aggregation_type=self.aggregation_type.to_proto(), + ) + ) + + +# TypeVar for all interval scorer types. +IntervalScorerTypes = TypeVar( + 'IntervalScorerTypes', + bound=GeneMaskScorer, +) + +# A dict of interval scorers, with our recommended settings for a wide range +# of different use cases and settings. +RECOMMENDED_INTERVAL_SCORERS = { + 'RNA_SEQ': GeneMaskScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + width=200_001, + aggregation_type=IntervalAggregationType.MEAN, + ), +} diff --git a/flax_model/alphagenome/_sdk/models/variant_scorers.py b/flax_model/alphagenome/_sdk/models/variant_scorers.py new file mode 100644 index 0000000000000000000000000000000000000000..6536ae4a695f3b3c3f1b068e70989c6795a3a2b9 --- /dev/null +++ b/flax_model/alphagenome/_sdk/models/variant_scorers.py @@ -0,0 +1,878 @@ +# Copyright 2024 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Module containing variant scorer dataclasses for variant scoring.""" + +from collections.abc import Sequence +import dataclasses +import enum +import itertools +import math +from typing import TypeVar + +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.protos import dna_model_pb2 +import anndata +import immutabledict +import pandas as pd + + +class AggregationType(enum.Enum): + """Enum indicating the type of variant scorer aggregation. + + Attributes: + DIFF_MEAN: Difference of means, i.e., mean(`ALT`) - mean(`REF`). + DIFF_SUM: Difference of sums, i.e., sum(`ALT`) - sum(`REF`). + DIFF_SUM_LOG2: Log scales predictions, then takes the sum and then the + difference, i.e., sum(log2(`ALT`)) - sum(log2(`REF`)). + DIFF_LOG2_SUM: Takes the sum of predictions, applies a log transform, then + takes the difference between predictions, i.e., log2(sum(`ALT`)) - + log2(sum(`REF`)). + L2_DIFF: Takes the difference of `ALT` and `REF` predictions, then computes + the L2 norm, i.e., l2_norm(`ALT` - `REF`). + L2_DIFF_LOG1P: Log scales the predictions + 1, takes the difference of `ALT` + and `REF` predictions, then computes the L2 norm, i.e., + l2_norm(log1p(`ALT`) - log1p(`REF`)). + ACTIVE_MEAN: Maximum of means, i.e., max(mean(`ALT`), mean(`REF`)). + ACTIVE_SUM: Maximum of sums, i.e., max(sum(`ALT), sum(`REF`)). + + Methods: + to_proto: Converts the aggregation type to its corresponding proto enum. + """ + + DIFF_MEAN = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_MEAN + DIFF_SUM = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_SUM + DIFF_SUM_LOG2 = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_SUM_LOG2 + DIFF_LOG2_SUM = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_LOG2_SUM + L2_DIFF = dna_model_pb2.AggregationType.AGGREGATION_TYPE_L2_DIFF + L2_DIFF_LOG1P = dna_model_pb2.AggregationType.AGGREGATION_TYPE_L2_DIFF_LOG1P + ACTIVE_MEAN = dna_model_pb2.AggregationType.AGGREGATION_TYPE_ACTIVE_MEAN + ACTIVE_SUM = dna_model_pb2.AggregationType.AGGREGATION_TYPE_ACTIVE_SUM + + def to_proto(self) -> dna_model_pb2.AggregationType: + return self.value + + def __repr__(self) -> str: + return self.name + + +class BaseVariantScorer(enum.Enum): + """Enum indicating the type of variant scoring. + + Attributes: + CENTER_MASK: Center mask scorer. + CONTACT_MAP: Contact map scorer, a center mask scorer that handles 2D + tensors. + GENE_MASK_LFC: Gene-mask scoring based on log fold change. + GENE_MASK_ACTIVE: Gene-mask scoring based on active allele. + GENE_MASK_SPLICING: Gene-mask scoring for splicing. + PA_QTL: Polyadenylation QTL scoring. + SPLICE_JUNCTION: Splice junction scoring. + """ + + CENTER_MASK = enum.auto() + CONTACT_MAP = enum.auto() + GENE_MASK_LFC = enum.auto() + GENE_MASK_ACTIVE = enum.auto() + GENE_MASK_SPLICING = enum.auto() + PA_QTL = enum.auto() + SPLICE_JUNCTION = enum.auto() + + +SUPPORTED_ORGANISMS = immutabledict.immutabledict({ + BaseVariantScorer.CENTER_MASK: dna_model_pb2.Organism.values(), + BaseVariantScorer.CONTACT_MAP: dna_model_pb2.Organism.values(), + BaseVariantScorer.GENE_MASK_LFC: dna_model_pb2.Organism.values(), + BaseVariantScorer.GENE_MASK_ACTIVE: dna_model_pb2.Organism.values(), + BaseVariantScorer.GENE_MASK_SPLICING: dna_model_pb2.Organism.values(), + BaseVariantScorer.PA_QTL: [dna_model_pb2.Organism.ORGANISM_HOMO_SAPIENS], + BaseVariantScorer.SPLICE_JUNCTION: dna_model_pb2.Organism.values(), +}) + +SUPPORTED_OUTPUT_TYPES = immutabledict.immutabledict({ + BaseVariantScorer.CENTER_MASK: [ + dna_output.OutputType.ATAC, + dna_output.OutputType.CAGE, + dna_output.OutputType.DNASE, + dna_output.OutputType.PROCAP, + dna_output.OutputType.RNA_SEQ, + dna_output.OutputType.CHIP_HISTONE, + dna_output.OutputType.CHIP_TF, + dna_output.OutputType.SPLICE_SITES, + dna_output.OutputType.SPLICE_SITE_USAGE, + ], + BaseVariantScorer.CONTACT_MAP: [dna_output.OutputType.CONTACT_MAPS], + BaseVariantScorer.GENE_MASK_LFC: [ + dna_output.OutputType.ATAC, + dna_output.OutputType.CAGE, + dna_output.OutputType.DNASE, + dna_output.OutputType.PROCAP, + dna_output.OutputType.RNA_SEQ, + dna_output.OutputType.SPLICE_SITES, + dna_output.OutputType.SPLICE_SITE_USAGE, + ], + BaseVariantScorer.GENE_MASK_ACTIVE: [ + dna_output.OutputType.ATAC, + dna_output.OutputType.CAGE, + dna_output.OutputType.DNASE, + dna_output.OutputType.PROCAP, + dna_output.OutputType.RNA_SEQ, + dna_output.OutputType.SPLICE_SITES, + dna_output.OutputType.SPLICE_SITE_USAGE, + ], + BaseVariantScorer.GENE_MASK_SPLICING: [ + dna_output.OutputType.SPLICE_SITES, + dna_output.OutputType.SPLICE_SITE_USAGE, + ], +}) + +SUPPORTED_WIDTHS = immutabledict.immutabledict({ + BaseVariantScorer.CENTER_MASK: [None, 501, 2001, 10_001, 100_001, 200_001], + BaseVariantScorer.GENE_MASK_SPLICING: [None, 101, 1_001, 10_001], +}) + +SUPPORTED_AGGREGATIONS = immutabledict.immutabledict({ + BaseVariantScorer.CENTER_MASK: [ + AggregationType.DIFF_MEAN, + AggregationType.DIFF_SUM, + AggregationType.DIFF_SUM_LOG2, + AggregationType.DIFF_LOG2_SUM, + AggregationType.L2_DIFF, + AggregationType.L2_DIFF_LOG1P, + AggregationType.ACTIVE_MEAN, + AggregationType.ACTIVE_SUM, + ], +}) + + +@dataclasses.dataclass(frozen=True) +class CenterMaskScorer: + """Variant scorer for center mask scorers. + + Variant scorer that aggregates ALT and REF values using a spatial mask + centered around the variant before computing the difference. This scorer + aggregates over the spatial axis and returns one score per output track. + + Attributes: + requested_output: The requested output type (e.g., ATAC, DNASE, etc.) + width: The width of the mask around the variant. If None, the score is + computed over the entire sequence. + aggregation_type: The aggregation type. + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + + Raises: + ValueError: If the requested output, width, or aggregation type is not + supported. + """ + + requested_output: dna_output.OutputType + width: int | None + aggregation_type: AggregationType + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.CENTER_MASK + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + # The 'active' scorers track the maximum of the ALT and REF, and are + # non-directional. All other scorers track ALT - REF, with L2_DIFF + # nondirectional and the remaining directional. + return self.aggregation_type in [ + AggregationType.DIFF_MEAN, + AggregationType.DIFF_SUM, + AggregationType.DIFF_SUM_LOG2, + AggregationType.DIFF_LOG2_SUM, + ] + + def __post_init__(self): + if ( + self.requested_output + not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer] + ): + raise ValueError( + f'Unsupported requested output: {self.requested_output}. Supported' + f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}' + ) + if self.width not in SUPPORTED_WIDTHS[self.base_variant_scorer]: + raise ValueError( + f'Unsupported width: {self.width}. Supported widths:' + f' {SUPPORTED_WIDTHS[self.base_variant_scorer]}' + ) + if ( + self.aggregation_type + not in SUPPORTED_AGGREGATIONS[self.base_variant_scorer] + ): + raise ValueError( + f'Unsupported aggregation type: {self.aggregation_type}. Supported' + ' aggregation types:' + f' {SUPPORTED_AGGREGATIONS[self.base_variant_scorer]}' + ) + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + center_mask=dna_model_pb2.CenterMaskScorer( + requested_output=self.requested_output.to_proto(), + width=self.width, + aggregation_type=self.aggregation_type.to_proto(), + ) + ) + + +@dataclasses.dataclass(frozen=True) +class ContactMapScorer: + """Variant scorer for contact map scorers. + + Variant scorer that quantifies local contact disruption between ALT and REF + alleles. Uses a 1MB window centered around the variant to calculate the + mean absolute difference of contact frequencies, for all interactions + involving the variant-containing bin. + + Attributes: + requested_output: The requested output type (e.g., CONTACT_MAPS). + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + """ + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.CONTACT_MAP + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + return False + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + contact_map=dna_model_pb2.ContactMapScorer() + ) + + @property + def requested_output(self) -> dna_output.OutputType: + return dna_output.OutputType.CONTACT_MAPS + + +@dataclasses.dataclass(frozen=True) +class GeneMaskLFCScorer: + """Variant scorer for gene-mask log fold change scoring. + + Variant scorer that quantifies impact on overall gene transcript abundance. + Calculates the log fold change of gene expression level between ALT and REF + alleles using a gene exon mask. + + Attributes: + requested_output: The requested output type (e.g. ATAC, DNASE, etc.) + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + + Raises: + ValueError: If the requested output is not supported. + """ + + requested_output: dna_output.OutputType + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.GENE_MASK_LFC + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + return True + + def __post_init__(self): + if ( + self.requested_output + not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer] + ): + raise ValueError( + f'Unsupported requested output: {self.requested_output}. Supported' + f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}' + ) + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + gene_mask=dna_model_pb2.GeneMaskLFCScorer( + requested_output=self.requested_output.to_proto(), + ) + ) + + +@dataclasses.dataclass(frozen=True) +class GeneMaskActiveScorer: + """Variant scorer for gene-mask active allele scoring. + + Variant scorer that captures absolute activity level associated with one of + the alleles, rather than quantifying the difference between the ALT and REF. + Active allele gene scores are calculated by taking the maximum of the + aggregated ALT and REF signals across exons for a gene of interest. + + Attributes: + requested_output: The requested output type (e.g. ATAC, DNASE, etc.) + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + + Raises: + ValueError: If the requested output is not supported. + """ + + requested_output: dna_output.OutputType + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.GENE_MASK_ACTIVE + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + return False + + def __post_init__(self): + if ( + self.requested_output + not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer] + ): + raise ValueError( + f'Unsupported requested output: {self.requested_output}. Supported' + f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}' + ) + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + gene_mask_active=dna_model_pb2.GeneMaskActiveScorer( + requested_output=self.requested_output.to_proto(), + ) + ) + + +@dataclasses.dataclass(frozen=True) +class GeneMaskSplicingScorer: + """Variant scorer for gene-mask scoring for splicing. + + Variant scorer that quantifies changes in class assignment probabilties + (dna_output.OutputType.SPLICE_SITES) or changes in the usage of splice sites + (dna_output.OutputType.SPLICE_SITE_USAGE) between ALT and REF alleles using + a gene exon mask. + + Attributes: + requested_output: The requested output type (e.g. ATAC, DNASE, etc.) + width: The width of the mask around the variant. + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + + Raises: + ValueError: If the requested output or width is not supported. + """ + + requested_output: dna_output.OutputType + width: int | None + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.GENE_MASK_SPLICING + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + return False + + def __post_init__(self): + if ( + self.requested_output + not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer] + ): + raise ValueError( + f'Unsupported requested output: {self.requested_output}. Supported' + f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}' + ) + if self.width not in SUPPORTED_WIDTHS[self.base_variant_scorer]: + raise ValueError( + f'Unsupported width: {self.width}. Supported widths:' + f' {SUPPORTED_WIDTHS[self.base_variant_scorer]}' + ) + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + gene_mask_splicing=dna_model_pb2.GeneMaskSplicingScorer( + requested_output=self.requested_output.to_proto(), + width=self.width, + ) + ) + + +@dataclasses.dataclass(frozen=True) +class PolyadenylationScorer: + """Variant scorer for polyadenylation QTLs (paQTLs). + + Variant scorer for polyadenylation quantitative trait loci (paQTLs) to capture + a variant's impact on RNA isoform production. + + The scoring approach quantifies the maximum log fold change in expression + between the set of proximal polyadenylation sites (PAS)s vs. the set of + distal PASs, where the sets of proximal and distal PASs are the PASs upstream + or downstream of any given 3' cleavage site respectively. + + Attributes: + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + """ + + @property + def requested_output(self) -> dna_output.OutputType: + """Returns the scorer's underlying output type.""" + return dna_output.OutputType.RNA_SEQ + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.PA_QTL + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + return False + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + pa_qtl=dna_model_pb2.PolyadenylationScorer() + ) + + +@dataclasses.dataclass(frozen=True) +class SpliceJunctionScorer: + """Variant scorer for splice junction scoring. + + Attributes: + base_variant_scorer: The base variant scorer. + name: The name of the scorer (a composite of the above attributes that + uniquely identifies a scorer combination). + is_signed: Whether this variant scorer is directional (such that scores may + be negative or positive) or non-directional (scores are always positive). + + Methods: + to_proto: Converts the scorer to its corresponding proto message. + """ + + @property + def requested_output(self) -> dna_output.OutputType: + """Returns the scorer's underlying output type.""" + return dna_output.OutputType.SPLICE_JUNCTIONS + + @property + def base_variant_scorer(self) -> BaseVariantScorer: + return BaseVariantScorer.SPLICE_JUNCTION + + @property + def name(self) -> str: + return str(self) + + @property + def is_signed(self) -> bool: + return False + + def to_proto(self) -> dna_model_pb2.VariantScorer: + return dna_model_pb2.VariantScorer( + splice_junction=dna_model_pb2.SpliceJunctionScorer() + ) + + +# TypeVar for all variant scorer types. +VariantScorerTypes = TypeVar( + 'VariantScorerTypes', + CenterMaskScorer, + ContactMapScorer, + GeneMaskLFCScorer, + GeneMaskActiveScorer, + GeneMaskSplicingScorer, + PolyadenylationScorer, + SpliceJunctionScorer, +) + +# A dict of variant scorers, with our recommended settings for a wide range +# of different use cases and settings. +RECOMMENDED_VARIANT_SCORERS = immutabledict.immutabledict({ + 'ATAC': CenterMaskScorer( + requested_output=dna_output.OutputType.ATAC, + width=501, + aggregation_type=AggregationType.DIFF_LOG2_SUM, + ), + 'CONTACT_MAPS': ContactMapScorer(), + 'DNASE': CenterMaskScorer( + requested_output=dna_output.OutputType.DNASE, + width=501, + aggregation_type=AggregationType.DIFF_LOG2_SUM, + ), + 'CHIP_TF': CenterMaskScorer( + requested_output=dna_output.OutputType.CHIP_TF, + width=501, + aggregation_type=AggregationType.DIFF_LOG2_SUM, + ), + 'CHIP_HISTONE': CenterMaskScorer( + requested_output=dna_output.OutputType.CHIP_HISTONE, + width=2001, + aggregation_type=AggregationType.DIFF_LOG2_SUM, + ), + 'CAGE': CenterMaskScorer( + requested_output=dna_output.OutputType.CAGE, + width=501, + aggregation_type=AggregationType.DIFF_LOG2_SUM, + ), + 'PROCAP': CenterMaskScorer( + requested_output=dna_output.OutputType.PROCAP, + width=501, + aggregation_type=AggregationType.DIFF_LOG2_SUM, + ), + # Expression log fold change. + 'RNA_SEQ': GeneMaskLFCScorer( + requested_output=dna_output.OutputType.RNA_SEQ + ), + 'RNA_SEQ_ACTIVE': GeneMaskActiveScorer( + requested_output=dna_output.OutputType.RNA_SEQ + ), + 'SPLICE_SITES': GeneMaskSplicingScorer( + requested_output=dna_output.OutputType.SPLICE_SITES, + width=None, + ), + 'SPLICE_SITE_USAGE': GeneMaskSplicingScorer( + requested_output=dna_output.OutputType.SPLICE_SITE_USAGE, + width=None, + ), + 'SPLICE_JUNCTIONS': SpliceJunctionScorer(), + 'POLYADENYLATION': PolyadenylationScorer(), + 'ATAC_ACTIVE': CenterMaskScorer( + requested_output=dna_output.OutputType.ATAC, + width=501, + aggregation_type=AggregationType.ACTIVE_SUM, + ), + 'DNASE_ACTIVE': CenterMaskScorer( + requested_output=dna_output.OutputType.DNASE, + width=501, + aggregation_type=AggregationType.ACTIVE_SUM, + ), + 'CHIP_TF_ACTIVE': CenterMaskScorer( + requested_output=dna_output.OutputType.CHIP_TF, + width=501, + aggregation_type=AggregationType.ACTIVE_SUM, + ), + 'CHIP_HISTONE_ACTIVE': CenterMaskScorer( + requested_output=dna_output.OutputType.CHIP_HISTONE, + width=2001, + aggregation_type=AggregationType.ACTIVE_SUM, + ), + 'CAGE_ACTIVE': CenterMaskScorer( + requested_output=dna_output.OutputType.CAGE, + width=501, + aggregation_type=AggregationType.ACTIVE_SUM, + ), + 'PROCAP_ACTIVE': CenterMaskScorer( + requested_output=dna_output.OutputType.PROCAP, + width=501, + aggregation_type=AggregationType.ACTIVE_SUM, + ), +}) + + +def get_recommended_scorers( + organism: dna_model_pb2.Organism, +) -> list[VariantScorerTypes]: + """Returns the recommended variant scorers for a given organism.""" + return [ + scorer + for scorer in RECOMMENDED_VARIANT_SCORERS.values() + if organism in SUPPORTED_ORGANISMS[scorer.base_variant_scorer] + ] + + +def tidy_anndata( + adata: anndata.AnnData, + match_gene_strand: bool = True, + include_extended_metadata: bool = True, +) -> pd.DataFrame: + """Formats an :class:`~anndata.AnnData` score as a tidy DataFrame. + + This function converts the score output from an AnnData object into a + long-format pandas DataFrame, where each row represents: + + - For non-gene-centric variant scorers: Score for a variant-track pair. + - For non-gene-centric interval scorers: Score for an interval-track pair. + - For gene-centric variant/interval scoring: Score for a + variant/interval-gene-track combination. + + Args: + adata: An AnnData object containing scores. + match_gene_strand: If True (and using gene-centric scoring), rows with + mismatched gene and track strands are removed. + include_extended_metadata: If True, includes additional columns derived from + metadata specific to the output type, such as biosample name and type, + gtex tissue, transcription factor, and histone mark, if available. If + False, only includes minimal metadata columns required to unique identify + a track withing a given output type: track_name and track_strand. + + Returns: + A pandas DataFrame with one score per row. The DataFrame includes + columns for variant ID (if applicable), scored interval, gene information + (if applicable), output type, variant/interval scorer, track name, + ontology term, assay type, track strand, and raw score. Additional metadata + such as biosample name and type, gtex tissue are also returned (where + available). See :func:`full_path_to.tidy_scores` for more details on the + returned columns. + + Raises: + ValueError: If the input is not an AnnData object. + """ + if not isinstance(adata, anndata.AnnData): + raise ValueError('Invalid input type. Must be an AnnData object.') + + # Columns to include from the gene metadata. If the column did not + # exist in the original metadata (or if the scores do not have a concept + # of a gene), a column of all Nones is added. + gene_columns = [ + 'gene_id', + 'gene_name', + 'gene_type', + 'gene_strand', + 'junction_Start', + 'junction_End', + ] + if math.prod(adata.X.shape) == 0: + # Scores are empty, so we return an empty dataframe. + return pd.DataFrame() + elif 'gene_id' in adata.obs and 'strand' in adata.obs: + # Scores are for a gene-based scorer. + obs = adata.obs.rename({'strand': 'gene_strand'}, axis=1) + + # Remove patch number from gene_id. + obs['gene_id'] = obs['gene_id'].str.split('.', expand=True).get(0) + for col in gene_columns: + if col not in obs: + obs[col] = None + elif adata.X.shape[0] == 1 and adata.obs.empty: + # Scores are for a non-gene-based scorer. + obs = pd.DataFrame([[None] * len(gene_columns)], columns=gene_columns) + else: + raise ValueError('Scores contain gene metadata but no gene_id/strand.') + + # Columns to include from the track metadata. Only added if the column + # appears in the original metadata. + var = adata.var.rename( + {'strand': 'track_strand', 'name': 'track_name'}, axis=1 + ) + track_columns = ['track_name', 'track_strand'] + if include_extended_metadata: + extended_metadata_columns = [ + 'Assay title', + 'ontology_curie', + 'biosample_name', + 'biosample_type', + 'biosample_life_stage', + 'gtex_tissue', + 'data_source', + 'endedness', + 'genetically_modified', + 'transcription_factor', + 'histone_mark', + ] + track_columns.extend([c for c in extended_metadata_columns if c in var]) + + # Construct score dataframe. + df = pd.merge(var, obs, how='cross') + df['scored_interval'] = adata.uns['interval'] + + # Add id and scorer information depending on the type of score. + if 'variant_scorer' in adata.uns: + df['variant_id'] = adata.uns['variant'] + df['output_type'] = adata.uns['variant_scorer'].requested_output.name + df['variant_scorer'] = str(adata.uns['variant_scorer']) + id_columns = ['variant_id', 'scored_interval'] + scorer_columns = ['output_type', 'variant_scorer'] + elif 'interval_scorer' in adata.uns: + df['output_type'] = adata.uns['interval_scorer'].requested_output.name + df['interval_scorer'] = str(adata.uns['interval_scorer']) + id_columns = ['scored_interval'] + scorer_columns = ['output_type', 'interval_scorer'] + else: + raise ValueError( + 'Invalid scores, expected either variant_scorer or interval_scorer.' + ) + + # Formatting final touches. + df = df.loc[:, id_columns + gene_columns + scorer_columns + track_columns] + df['raw_score'] = adata.X.T.reshape((-1,)) + if 'quantiles' in adata.layers: + df['quantile_score'] = adata.layers['quantiles'].T.reshape((-1,)) + + # Remove entries where DNA strands are mismatched. Note that we still retain + # all tracks that have strand '.' which indicates the data is unstranded. + if match_gene_strand: + mismatched_strands = (df['gene_strand'] == '+') & ( + df['track_strand'] == '-' + ) | (df['gene_strand'] == '-') & (df['track_strand'] == '+') + df = df[~mismatched_strands].reset_index(drop=True) + return df.reset_index(drop=True) + + +def tidy_scores( + scores: Sequence[anndata.AnnData] | Sequence[Sequence[anndata.AnnData]], + match_gene_strand: bool = True, + include_extended_metadata: bool = True, +) -> pd.DataFrame | None: + """Formats scores into a tidy (long) pandas DataFrame. + + This function reformats variant scores into a more readable DataFrame with one + score per row. This function supports both scores generated from variant + scorers (e.g., the output of `score_variant` or `score_variants`) or interval + scorers (e.g., the output of `score_interval` or `score_intervals`). + + It handles both variant/interval-centric scoring (producing one score row per + variant/interval-track pair) and gene-centric scoring (one score row per + variant/interval-gene-track combination). + + The function accepts these score input types: + + - A sequence of AnnData objects (e.g., output of `score_variant` with one or + more scorers). + - A nested sequence of AnnData objects (e.g., output of `score_variants` + with multiple variants). + + Scores from multiple scorers or multiple variants/intervals are concatenated + together into a single pandas DataFrame, containing the union of all + applicable columns across scorers. + + Args: + scores: Scoring output as either a sequence of AnnData objects, or a nested + sequence of AnnData objects (for example, the outputs of `score_variant` + and `score_variants`, respectively). + match_gene_strand: If True (and using gene-centric scoring), rows with + mismatched gene and track strands are removed. + include_extended_metadata: Argument passed to `tidy_anndata` to include + additional metadata columns where available. + + Returns: + pd.DataFrame with columns: + + - variant_id (when applicable): Variant of interest (e.g. + chr22:36201698:A>C). + - scored_interval: Genomic interval scored (e.g. chr22:36100000-36300000). + - gene_id: ENSEMBL gene identifier without version number. + (e.g. ENSG00000100342), or None if not applicable. + - gene_name: HGNC gene symbol (e.g. APOL1), or None if not applicable. + - gene_type: Gene biotype (e.g. protein_coding, lncRNA), or None if not + applicable. + - gene_strand: Strand of the gene ('+', '-', '.'), or None if not + applicable. + - output_type: Type of the output from the model (e.g. RNA_SEQ, DNASE). + - interval_scorer (when applicable): Name of the interval scorer used. + - variant_scorer (when applicable): Name of the variant scorer used. + - track_name: Name of the output track (e.g. UBERON:0036149 total + RNA-seq). + - track_strand: Strand of the track ('+', '-', or '.'). + - ontology_curie: Ontology term for the cell type or tissue of the track + (e.g. UBERON:0036149), or NaN if not applicable. + - gtex_tissue: Name of the gtex tissue (e.g. Liver), or NaN if not + applicable. + - Assay title: Subtype of the assay (e.g., total RNA-seq), or NaN if not + applicable. + - biosample_name: Name of the biosample (e.g. liver), or NaN if not + applicable. + - biosample_type: Type of biosample (e.g. 'tissue' or 'primary cell'), or + NaN if not applicable. + - transcription_factor: Name of the transcription factor (e.g. 'CTCF'), or + NaN if not applicable. + - histone_mark: Name of the histological mark (e.g. 'H3K4ME3'), or NaN if + not applicable. + - raw_score: Raw variant score. + - quantile_score (when applicable): Quantile score. + + Raises: + ValueError: If the input is not a valid type (sequence of AnnData or nested + sequence of AnnDatas). + """ + if isinstance(scores, Sequence): + tidied_anndata = [ + tidy_anndata(adata, match_gene_strand, include_extended_metadata) + for adata in itertools.chain.from_iterable(scores) + ] + if not tidied_anndata: + return None + + concatenated_df = pd.concat(tidied_anndata, axis=0, ignore_index=True) + # Put the raw_score (and quantile_score when applicable) columns last. + last_columns = ['raw_score'] + if 'quantile_score' in concatenated_df.columns: + last_columns.append('quantile_score') + return concatenated_df[ + [col for col in concatenated_df.columns if col not in last_columns] + + last_columns + ] + else: + raise ValueError( + 'Invalid input type. Must be sequence of AnnDatas or nested sequence of' + ' AnnDatas.' + ) diff --git a/flax_model/alphagenome/_sdk/typing.py b/flax_model/alphagenome/_sdk/typing.py new file mode 100644 index 0000000000000000000000000000000000000000..ac4c0c8ffbfce58a9b6fd95bae0636aeb06b4c3b --- /dev/null +++ b/flax_model/alphagenome/_sdk/typing.py @@ -0,0 +1,39 @@ +# Copyright 2025 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utility functions for type annotations.""" + +import importlib.metadata +from typing import TypeVar + +import jaxtyping +import typeguard + +_T = TypeVar('_T') + + +def jaxtyped(fn: _T) -> _T: + """Wrapper around jaxtyping.jaxtyped that uses typeguard iff typeguard < 3.""" + try: + major, *_ = importlib.metadata.version('typeguard').split('.') + except importlib.metadata.PackageNotFoundError: + major = -1 + + # Only use jaxtyping if typeguard is < 3. See + # https://docs.kidger.site/jaxtyping/api/runtime-type-checking/#runtime-type-checking + # for more details. + if int(major) < 3: + return jaxtyping.jaxtyped(fn, typechecker=typeguard.typechecked) + else: + return fn diff --git a/flax_model/alphagenome/_sdk/visualization/__init__.py b/flax_model/alphagenome/_sdk/visualization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..602823a26de43a59ecbc53130824f87f82ebd5bc --- /dev/null +++ b/flax_model/alphagenome/_sdk/visualization/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2024 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Library of tools for visualizing with genomic model predictions.""" diff --git a/flax_model/alphagenome/evals/__init__.py b/flax_model/alphagenome/evals/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..65cb18306da0ba67bfb07b23f1f7299ce70e84a1 --- /dev/null +++ b/flax_model/alphagenome/evals/__init__.py @@ -0,0 +1,14 @@ +# Copyright 2025 DeepMind Technologies Limited +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""AlphaGenome Evaluation Utilities.""" diff --git a/flax_model/alphagenome/evals/regression_metrics.py b/flax_model/alphagenome/evals/regression_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c2428d48b7e26b069b7b4dc59aa05763bd53c9 --- /dev/null +++ b/flax_model/alphagenome/evals/regression_metrics.py @@ -0,0 +1,204 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utility functions for experiments.""" + +from typing import Sequence +from flax_model.alphagenome._sdk import typing +import chex +import jax +import jax.numpy as jnp +from jaxtyping import ArrayLike, Float, PyTree # pylint: disable=g-importing-member, g-multiple-import +import numpy as np + + +@chex.dataclass +class _PearsonRState: + """State to compute PearsonR correlation coefficient.""" + + xy_sum: jax.Array + x_sum: jax.Array + xx_sum: jax.Array + y_sum: jax.Array + yy_sum: jax.Array + count: jax.Array + + def __add__(self, other: '_PearsonRState') -> '_PearsonRState': + return jax.tree.map(lambda x, y: x + y, self, other) + + +def _pearsonr_initialize() -> '_PearsonRState': + """Initialize PearsonrState with zeros.""" + return _PearsonRState( + xy_sum=np.zeros(()), + x_sum=np.zeros(()), + xx_sum=np.zeros(()), + y_sum=np.zeros(()), + yy_sum=np.zeros(()), + count=np.zeros(()), + ) + + +def _pearsonr_update( + x: jax.Array, + y: jax.Array, + axis: Sequence[int] | int | None = None, + mask: jax.Array | None = None, +) -> _PearsonRState: + """Construct PearsonrState by correlating two arrays.""" + if mask is not None: + mask = jnp.astype(mask, bool) + return _PearsonRState( + xy_sum=jnp.sum(x * y, axis=axis, where=mask, dtype=jnp.float32), + x_sum=jnp.sum(x, axis=axis, where=mask, dtype=jnp.float32), + xx_sum=jnp.sum(jnp.square(x), axis=axis, where=mask, dtype=jnp.float32), + y_sum=jnp.sum(y, axis=axis, where=mask, dtype=jnp.float32), + yy_sum=jnp.sum(jnp.square(y), axis=axis, where=mask, dtype=jnp.float32), + count=jnp.sum(jnp.ones_like(x), axis=axis, where=mask, dtype=jnp.float32), + ) + + +def _pearsonr_result(state: _PearsonRState) -> jax.Array: + """Get PearsonR correlation coeficient.""" + x_mean = state.x_sum / state.count + y_mean = state.y_sum / state.count + + covariance = state.xy_sum - state.count * x_mean * y_mean + + x_var = state.xx_sum - state.count * x_mean * x_mean + y_var = state.yy_sum - state.count * y_mean * y_mean + variance = x_var**0.5 * y_var**0.5 + eps = jnp.finfo(variance.dtype).eps # Avoid division by zero. + return covariance / (variance + eps) + + +@chex.dataclass +class RegressionState: + """State for accumulating regression statistics.""" + + pearsonr: _PearsonRState + pearsonr_log1p: _PearsonRState + sq_error: jax.Array + abs_error: jax.Array + count: jax.Array + + def __add__(self, other: 'RegressionState') -> 'RegressionState': + return jax.tree.map( + lambda a, b: a + b, + self, + other, + ) + + +def initialize_regression_metrics() -> RegressionState: + """Initialize metric state.""" + return RegressionState( + pearsonr=_pearsonr_initialize(), + pearsonr_log1p=_pearsonr_initialize(), + sq_error=np.zeros(()), + abs_error=np.zeros(()), + count=np.zeros(()), + ) + + +def update_regression_metrics( + y_true: jax.Array, + y_pred: jax.Array, + mask: jax.Array | None = None, +) -> RegressionState: + y_true = jnp.astype(y_true, jnp.float32) + y_pred = jnp.astype(y_pred, jnp.float32) + return RegressionState( + pearsonr=_pearsonr_update(y_true, y_pred, mask=mask, axis=(-2, -3)), + pearsonr_log1p=_pearsonr_update( + jnp.log1p(y_true), jnp.log1p(y_pred), mask=mask, axis=(-2, -3) + ), + sq_error=jnp.sum( + jnp.square(y_true - y_pred), + axis=(-2, -3), + where=mask, + dtype=jnp.float32, + ), + abs_error=jnp.sum( + jnp.abs(y_true - y_pred), + axis=(-2, -3), + where=mask, + dtype=jnp.float32, + ), + count=jnp.sum( + jnp.ones_like(y_true), axis=(-2, -3), where=mask, dtype=jnp.float32 + ), + ) + + +def finalize_regression_metrics( + state: PyTree[RegressionState], +) -> PyTree[jax.Array]: + """Compute final metrics from accumulated state.""" + + def _finalize(state: RegressionState) -> PyTree[jax.Array]: + return { + 'pearsonr': ( + _pearsonr_result(state.pearsonr).mean( + where=state.pearsonr.count > 0 + ) + ), + 'pearsonr_log1p': ( + _pearsonr_result(state.pearsonr_log1p).mean( + where=state.pearsonr_log1p.count > 0 + ) + ), + 'mse': jnp.mean(state.sq_error / state.count, where=state.count > 0), + 'mae': jnp.mean(state.abs_error / state.count, where=state.count > 0), + } + + return jax.tree.map( + _finalize, state, is_leaf=lambda x: isinstance(x, RegressionState) + ) + + +def reduce_regression_metrics( + previous_metrics: PyTree[RegressionState], + current_metrics: PyTree[RegressionState], +) -> RegressionState: + """Reduce metrics from a single device to a single scalar.""" + return jax.tree.map( + lambda x, y: x + y, + previous_metrics, + current_metrics, + is_leaf=lambda x: isinstance(x, RegressionState), + ) + + +@typing.jaxtyped +def crop_sequence_length( + x: Float[ArrayLike, '... S D'], *, target_length: int +) -> Float[ArrayLike, '... {target_length} D']: + """Crops an array to match the target length along the sequence dimension.""" + sequence_axis = -2 + if x.shape[sequence_axis] < target_length: + raise ValueError( + f'Input length {x.shape[sequence_axis]} is shorter than the requested' + f' cropped length of {target_length}.' + ) + elif x.shape[sequence_axis] == target_length: + return x + else: + ltrim = (x.shape[sequence_axis] - target_length) // 2 + rtrim = x.shape[sequence_axis] - target_length - ltrim + slices = [ + slice(None), + ] * len(x.shape) + slices[sequence_axis] = slice(ltrim, -rtrim) + return x[tuple(slices)] diff --git a/flax_model/alphagenome/evals/track_prediction.py b/flax_model/alphagenome/evals/track_prediction.py new file mode 100644 index 0000000000000000000000000000000000000000..b835e9635c454c5858ed5adb88e4e8532749f069 --- /dev/null +++ b/flax_model/alphagenome/evals/track_prediction.py @@ -0,0 +1,202 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Evaluates AlphaGenome track prediction performance.""" + +from collections.abc import Iterator +import pprint +from typing import Callable, Sequence +from absl import app +from absl import logging +from flax_model.alphagenome._sdk.data import fold_intervals +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome.evals import regression_metrics +from flax_model.alphagenome.io import bundles as bundles_lib +from flax_model.alphagenome.io import dataset +from flax_model.alphagenome.model import dna_model +from flax_model.alphagenome.model import model as model_lib +from flax_model.alphagenome.model import schemas +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +import haiku as hk +import jax +from jax import sharding +from jax.experimental import mesh_utils +from jaxtyping import PyTree # pylint: disable=g-importing-member +import jmp +import kagglehub +import orbax.checkpoint as ocp +import pandas as pd +import tensorflow as tf + + +PS = sharding.PartitionSpec +PredictFn = Callable[ + [ + hk.Params, + hk.State, + jax.Array, + jax.Array, + ], + PyTree[jax.Array], +] + +_SUBSET = fold_intervals.Subset.VALID +_LOG_FREQUENCY = 5 +_EVAL_BUNDLES = [ + bundles_lib.BundleName.ATAC, + bundles_lib.BundleName.CAGE, + bundles_lib.BundleName.CHIP_HISTONE, + bundles_lib.BundleName.CHIP_TF, + bundles_lib.BundleName.DNASE, + bundles_lib.BundleName.PROCAP, + bundles_lib.BundleName.RNA_SEQ, +] + + +def load_model( + model_version: dna_model.ModelVersion = dna_model.ModelVersion.FOLD_0, +) -> tuple[hk.Params, hk.State, PredictFn]: + """Loads the model consiting of params, state and predict function.""" + checkpoint_path = kagglehub.model_download( + f'google/alphagenome/jax/{model_version.name.lower()}' + ) + params, state = ocp.StandardCheckpointer().restore(checkpoint_path) + metadata = { + organism: metadata_lib.load(organism) for organism in dna_model.Organism + } + + @hk.transform_with_state + def forward(dna_sequence, organism_index): + policy = jmp.get_policy('params=float32,compute=bfloat16,output=bfloat16') + with hk.mixed_precision.push_policy(model_lib.AlphaGenome, policy): + return model_lib.AlphaGenome(metadata)(dna_sequence, organism_index) + + @jax.jit( + in_shardings=(PS(), PS(), PS('data'), PS('data')), + out_shardings=PS('data'), + ) + def predict(params, state, dna_sequence, organism_index) -> PyTree[jax.Array]: + (predictions, _), _ = forward.apply( + params, state, None, dna_sequence, organism_index + ) + predictions = dna_model.extract_predictions(predictions) + return predictions + + return params, state, predict + + +def create_eval_step( + predict_fn: PredictFn, bundles: Sequence[bundles_lib.BundleName] +): + """Returns the eval step function.""" + + @jax.jit( + in_shardings=(PS(), PS(), PS('data')), + out_shardings=PS(), + ) + def eval_step(params, state, batch: schemas.DataBatch): + predictions = predict_fn( + params, state, batch.dna_sequence, batch.organism_index + ) + metrics_step = {} + for bundle in bundles: + targets_true, mask = batch.get_genome_tracks(bundle) + targets_pred = predictions[dna_output.OutputType[bundle.name]] + targets_pred = regression_metrics.crop_sequence_length( + targets_pred, target_length=targets_true.shape[-2] + ) + metrics_step[bundle.name] = regression_metrics.update_regression_metrics( + targets_true, targets_pred, mask + ) + return metrics_step + + return eval_step + + +def evaluate( + params: hk.Params, + state: hk.State, + predict_fn: PredictFn, + bundles: Sequence[bundles_lib.BundleName], + dataset_iterator: Iterator[tuple[schemas.DataBatch, dataset.BatchMetadata]], +): + """Evaluates the model.""" + # Setup Mesh. + devices = mesh_utils.create_device_mesh((jax.local_device_count(),)) + mesh = jax.sharding.Mesh(devices, axis_names=('data',)) + sharding_rep = sharding.NamedSharding(mesh, PS()) + sharding_data = sharding.NamedSharding(mesh, PS('data')) + + # Replicate params and state. + params = jax.device_put(params, sharding_rep) + state = jax.device_put(state, sharding_rep) + + eval_step = create_eval_step(predict_fn, bundles) + metrics = { + b.name: regression_metrics.initialize_regression_metrics() + for b in bundles + } + num_elements = 0 + + for i, (batch, _) in enumerate(dataset_iterator): + num_elements += batch.dna_sequence.shape[0] + if i % _LOG_FREQUENCY == 1: + m = pprint.pformat( + regression_metrics.finalize_regression_metrics(metrics) + ) + logging.info('step %d: %s', i, m) + + with jax.set_mesh(mesh): + batch = jax.device_put(batch, sharding_data) + step_metrics = eval_step(params, state, batch) + + # Accumulate metrics. + step_metrics = jax.device_get(step_metrics) + metrics = regression_metrics.reduce_regression_metrics( + metrics, step_metrics + ) + logging.info('num_elements: %d', num_elements) + return regression_metrics.finalize_regression_metrics(metrics) + + +def run( + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + model_version: dna_model.ModelVersion = dna_model.ModelVersion.FOLD_0, +) -> pd.DataFrame: + """Runs the track prediction experiment.""" + logging.info('Starting track prediction experiment.') + params, state, predict_fn = load_model(model_version) + dataset_iterator = dataset.get_numpy_dataset_iterator( + batch_size=jax.local_device_count(), + organism=organism, + model_version=model_version, + bundles=_EVAL_BUNDLES, + subset=_SUBSET, + ) + results = evaluate(params, state, predict_fn, _EVAL_BUNDLES, dataset_iterator) + flattened_results = {} + for bundle, result in results.items(): + for metric, value in result.items(): + logging.info('bundle: %s, metric: %s, value: %s', bundle, metric, value) + flattened_results[f'{bundle}_{metric}'] = value + df = pd.DataFrame( + {'metric': flattened_results.keys(), 'value': flattened_results.values()} + ) + return df + + +if __name__ == '__main__': + # Hide local GPUs from TF. TF is only used for data loading. + tf.config.set_visible_devices([], 'GPU') + app.run(lambda _: run()) diff --git a/flax_model/alphagenome/io/__init__.py b/flax_model/alphagenome/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..742f89aa058f809017fa691ed903899d8188ab64 --- /dev/null +++ b/flax_model/alphagenome/io/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for reading and writing data.""" diff --git a/flax_model/alphagenome/io/bundles.py b/flax_model/alphagenome/io/bundles.py new file mode 100644 index 0000000000000000000000000000000000000000..d40424058457ad1195fb0237413a8e87f666b740 --- /dev/null +++ b/flax_model/alphagenome/io/bundles.py @@ -0,0 +1,91 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Bundle names and their associated keys and resolutions.""" + +import enum +import tensorflow as tf + + +class BundleName(enum.Enum): + """Bundle names.""" + + ATAC = 'atac' + DNASE = 'dnase' + PROCAP = 'procap' + CAGE = 'cage' + RNA_SEQ = 'rna_seq' + CHIP_TF = 'chip_tf' + CHIP_HISTONE = 'chip_histone' + CONTACT_MAPS = 'contact_maps' + SPLICE_SITES_CLASSIFICATION = 'splice_sites' + SPLICE_SITES_USAGE = 'splice_site_usage' + SPLICE_SITES_JUNCTION = 'splice_junctions' + SPLICE_SITES_POSITIONS = 'splice_site_positions' + + def get_dtypes(self) -> dict[str, tf.DType]: + """Returns the keys and dtypes for the given bundle.""" + match self: + case BundleName.ATAC: + return {'atac': tf.bfloat16, 'atac_mask': tf.bool} + case BundleName.DNASE: + return {'dnase': tf.bfloat16, 'dnase_mask': tf.bool} + case BundleName.PROCAP: + return {'procap': tf.bfloat16, 'procap_mask': tf.bool} + case BundleName.CAGE: + return {'cage': tf.bfloat16, 'cage_mask': tf.bool} + case BundleName.RNA_SEQ: + return { + 'rna_seq': tf.bfloat16, + 'rna_seq_mask': tf.bool, + 'rna_seq_strand': tf.int32, + } + case BundleName.CHIP_TF: + return {'chip_tf': tf.float32, 'chip_tf_mask': tf.bool} + case BundleName.CHIP_HISTONE: + return {'chip_histone': tf.float32, 'chip_histone_mask': tf.bool} + case BundleName.CONTACT_MAPS: + return {'contact_maps': tf.float32} + case BundleName.SPLICE_SITES_CLASSIFICATION: + return {'splice_sites': tf.bool} + case BundleName.SPLICE_SITES_USAGE: + return {'splice_site_usage': tf.float16} + case BundleName.SPLICE_SITES_JUNCTION: + return {'splice_junctions': tf.float32} + case BundleName.SPLICE_SITES_POSITIONS: + return {'splice_site_positions': tf.int32} + case _: + raise ValueError(f'Unknown bundle name: {self}') + + def get_resolution(self) -> int: + """Returns the resolutions for the given bundle.""" + match self: + case ( + BundleName.ATAC + | BundleName.DNASE + | BundleName.PROCAP + | BundleName.CAGE + | BundleName.RNA_SEQ + | BundleName.SPLICE_SITES_CLASSIFICATION + | BundleName.SPLICE_SITES_USAGE + | BundleName.SPLICE_SITES_JUNCTION + | BundleName.SPLICE_SITES_POSITIONS + ): + return 1 + case BundleName.CHIP_TF | BundleName.CHIP_HISTONE: + return 128 + case BundleName.CONTACT_MAPS: + return 2_048 + case _: + raise ValueError(f'Unknown bundle name: {self}') diff --git a/flax_model/alphagenome/io/dataset.py b/flax_model/alphagenome/io/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..5229862cfc10c4d6ba5e2f4755808c8bd839e943 --- /dev/null +++ b/flax_model/alphagenome/io/dataset.py @@ -0,0 +1,255 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Reading AlphaGenome data from TFRecords. + +This module provides functions to load AlphaGenome datasets from TFRecord files. +Each TFRecord file contains data from a particular bundle (see `bundles.py`) +for a set of intervals. + +We recommend using `get_numpy_dataset_iterator` to load the data for a +particular organism, fold split, and subset. The iterator yields batches of +data, where each batch is a tuple of `schemas.DataBatch` and a metadata +dictionary containing the chromosome, start, and end of each interval. +""" + +from collections.abc import Iterator, Mapping +import functools +import os +import re +from typing import Any, Sequence + +from flax_model.alphagenome._sdk.data import fold_intervals +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome.io import bundles as bundles_lib +from flax_model.alphagenome.model import dna_model as research_dna_model +from flax_model.alphagenome.model import schemas +from etils import epath +import numpy as np +import pandas as pd +import tensorflow as tf + +_DEFAULT_PATH = 'gs:///alphagenome-datasets/v1/train/' + +BatchMetadata = Mapping[str, Any] + +_DNA_SEQUENCE_DTYPE = tf.float32 +_DNA_SEQUENCE_FEATURE_SPEC = { + 'dna_sequence': tf.io.FixedLenFeature([], tf.string) +} +_INTERVAL_FEATURE_SPEC = { + 'interval/chromosome': tf.io.FixedLenFeature([], tf.string), + 'interval/start': tf.io.FixedLenFeature([], tf.int64), + 'interval/end': tf.io.FixedLenFeature([], tf.int64), +} +_FILENAME_REGEX = re.compile( + r'data_(?P.+)_(?P\d+)-(?P\d+)\.gz\.tfrecord' +) + + +def get_tfrecords_df( + *, + organism: dna_model.Organism | None = None, + bundle: bundles_lib.BundleName | None = None, + fold_split: dna_model.ModelVersion | None = None, + subset: fold_intervals.Subset | None = None, + chromosome: str | None = None, + path: str | os.PathLike[str] | None = None, +) -> pd.DataFrame: + """Return a dataframe with metadata about the TFRecord files. + + Args: + organism: The organism to load. If None, all organisms are loaded. + bundle: The bundle to load. If None, all bundles are loaded. + fold_split: The fold split to load. If None, all fold splits are loaded. + subset: The subset to load. If None, all subsets are loaded. + chromosome: The chromosome to load. If None, all chromosomes are loaded. + path: The path to the TFRecord files. If None, the default path is used. + """ + organism_pattern = organism.name if organism is not None else '*' + fold_split_pattern = fold_split.name if fold_split is not None else '*' + subset_pattern = subset.name if subset is not None else '*' + chromosome_pattern = chromosome if chromosome is not None else '*' + bundle_pattern = bundle.value.upper() if bundle is not None else '*' + glob_pattern = '/'.join([ + fold_split_pattern, + organism_pattern, + subset_pattern, + bundle_pattern, + f'data_{chromosome_pattern}_*-*.gz.tfrecord', + ]) + tfrecord_paths = epath.Path(path or _DEFAULT_PATH).glob(glob_pattern) + + def _parse_path(tfrecord_path: epath.Path): + base_name = tfrecord_path.name + match_ = _FILENAME_REGEX.match(base_name) + if not match_: + raise ValueError(f'Could not parse metadata for file: {base_name}') + + parsed = match_.groupdict() + metadata = { + 'organism': tfrecord_path.parts[-4], + 'bundle': tfrecord_path.parts[-2], + 'fold_split': tfrecord_path.parts[-5], + 'subset': tfrecord_path.parts[-3], + 'chromosome': parsed['chr'], + 'shard': int(parsed['shard']), + 'num_shards': int(parsed['num_shards']), + 'path': str(tfrecord_path), + } + return pd.DataFrame(metadata, index=[0]) + + if not tfrecord_paths: + return pd.DataFrame() + + return pd.concat( + [_parse_path(epath.Path(p)) for p in tfrecord_paths] + ).reset_index(drop=True) + + +def _get_parse_function(bundle: bundles_lib.BundleName): + """Get parse function for a given output type.""" + feature_spec = ( + _DNA_SEQUENCE_FEATURE_SPEC + | _INTERVAL_FEATURE_SPEC + | { + key: tf.io.FixedLenFeature([], tf.string) + for key in bundle.get_dtypes().keys() + } + ) + output_dtypes = bundle.get_dtypes() | {'dna_sequence': _DNA_SEQUENCE_DTYPE} + + def _parse(proto): + example = tf.io.parse_single_example(proto, feature_spec) + for key, dtype in output_dtypes.items(): + example[key] = tf.io.parse_tensor(example[key], dtype) + return example + + return _parse + + +def _get_tfrecords_dataset( + paths: Sequence[str | os.PathLike[str]], bundle: bundles_lib.BundleName +) -> tf.data.Dataset: + """Returns a dataset for a given output type from a sequence of paths.""" + parser = _get_parse_function(bundle) + + def _get(p): + ds = tf.data.TFRecordDataset(p, compression_type='GZIP') + ds = ds.map(parser, num_parallel_calls=tf.data.AUTOTUNE) + return ds + + ds = _get(paths[0]) + for p in paths[1:]: + ds_next = _get(p) + ds = ds.concatenate(ds_next) + return ds + + +def create_dataset( + *, + organism: dna_model.Organism, + fold_split: dna_model.ModelVersion, + subset: fold_intervals.Subset, + bundles: Sequence[bundles_lib.BundleName] | None = None, + path: str | os.PathLike[str] | None = None, +) -> tf.data.Dataset: + """Returns AlphaGenome dataset for a given organism, fold and subset. + + Args: + organism: The organism to load. + fold_split: The fold split to load. + subset: The subset to load. + bundles: The bundles to load. If None, all bundles are loaded. + path: The path to the TFRecord files. If None, the default path is used. + """ + bundles = bundles or [None] + records = [] + for bundle in bundles: + records.append( + get_tfrecords_df( + organism=organism, + bundle=bundle, + fold_split=fold_split, + subset=subset, + path=path, + ) + ) + df = pd.concat(records) + num_paths = df.groupby('bundle').agg('path').count() + if num_paths.nunique() != 1: + raise ValueError( + f'Number of TFRecord files per bundle is not the same: {num_paths}' + ) + dataset_per_bundle = [] + bundles = df['bundle'].unique() + for bundle in bundles: + dft = df[df['bundle'] == bundle].sort_values('shard') + if dft.empty: + raise ValueError(f'No data found for {bundle=}.') + dataset_per_bundle.append( + _get_tfrecords_dataset( + dft['path'].tolist(), bundles_lib.BundleName(bundle.lower()) + ) + ) + + # Zip datasets across bundles. + return tf.data.Dataset.zip(*dataset_per_bundle) + + +def _parse_batch( + element, + bundles: Sequence[bundles_lib.BundleName] | None, + organism_index: int, + batch_size: int, +) -> tuple[schemas.DataBatch, BatchMetadata]: + """Parses a raw dataset element into Input and Target schemas.""" + + if bundles is None: + bundles = list(bundles_lib.BundleName) + if len(bundles) == 1: + element = (element,) + + merged_data = functools.reduce(lambda x, y: x | y, element) + organism_index = np.full((batch_size,), organism_index, dtype=np.int32) + metadata = { + 'interval/chromosome': merged_data.pop('interval/chromosome'), + 'interval/start': merged_data.pop('interval/start'), + 'interval/end': merged_data.pop('interval/end'), + } + batch = schemas.DataBatch(organism_index=organism_index, **merged_data) + return batch, metadata + + +def get_numpy_dataset_iterator( + *, + batch_size: int, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + model_version: dna_model.ModelVersion = dna_model.ModelVersion.FOLD_0, + subset: fold_intervals.Subset = fold_intervals.Subset.VALID, + bundles: Sequence[bundles_lib.BundleName] | None = None, + path: str | os.PathLike[str] | None = None, +) -> Iterator[tuple[schemas.DataBatch, BatchMetadata]]: + """Yields numpy batches of data from the dataset.""" + ds = create_dataset( + organism=organism, + fold_split=model_version, + subset=subset, + bundles=bundles, + path=path, + ) + organism_index = research_dna_model.convert_to_organism_index(organism) + ds = ds.batch(batch_size, drop_remainder=True).prefetch(tf.data.AUTOTUNE) + for element in ds.as_numpy_iterator(): + yield _parse_batch(element, bundles, organism_index, batch_size) diff --git a/flax_model/alphagenome/io/dataset_test.py b/flax_model/alphagenome/io/dataset_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d728711e7b1a2f8cf084a482161f5875177350 --- /dev/null +++ b/flax_model/alphagenome/io/dataset_test.py @@ -0,0 +1,254 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import pathlib + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import fold_intervals +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome.io import bundles +from flax_model.alphagenome.io import dataset +from flax_model.alphagenome.model import schemas +import jax +import jax.numpy as jnp +import numpy as np +import tensorflow as tf + + +def _bytes_feature(value): + """Returns a bytes_list from a string / byte.""" + if isinstance(value, type(tf.constant(0))): + value = value.numpy() + return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) + + +def _int64_feature(value): + """Returns an int64_list from a bool / enum / int / uint.""" + return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) + + +def to_tf_example(data): + """Creates a tf.train.Example message from a data dictionary.""" + features = {} + for key, value in data.items(): + if isinstance(value, int): + features[key] = _int64_feature(value) + elif isinstance(value, str): + features[key] = _bytes_feature(value.encode('utf-8')) + elif isinstance(value, np.ndarray): + features[key] = _bytes_feature(tf.io.serialize_tensor(value).numpy()) + else: + raise ValueError(f'Unsupported data type for key {key}: {type(value)}') + return tf.train.Example( + features=tf.train.Features(feature=features) + ).SerializeToString() + + +def _write_tfrecord(path: pathlib.Path, data_list): + """Writes a list of data to a TFRecord file.""" + path.parent.mkdir(parents=True, exist_ok=True) + options = tf.io.TFRecordOptions(compression_type='GZIP') + with tf.io.TFRecordWriter(str(path), options=options) as writer: + for data in data_list: + writer.write(to_tf_example(data)) + + +class LoadDataTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.tmpdir = self.create_tempdir().full_path + self._num_channels = 7 + self._seq_len = int(2**5) + self._num_shards = 2 + self._intervals = { + 'chr1': { + '1': [ + genome.Interval( + start=10, end=10 + self._seq_len, chromosome='chr1' + ), + genome.Interval( + start=100, end=100 + self._seq_len, chromosome='chr1' + ), + ], + '2': [ + genome.Interval( + start=200, end=200 + self._seq_len, chromosome='chr1' + ), + ], + }, + 'chr3': { + '1': [ + genome.Interval( + start=30, end=30 + self._seq_len, chromosome='chr3' + ), + ], + '2': [ + genome.Interval( + start=130, end=130 + self._seq_len, chromosome='chr3' + ), + genome.Interval( + start=230, end=230 + self._seq_len, chromosome='chr3' + ), + ], + }, + } + self._organism = dna_model.Organism.HOMO_SAPIENS + self._fold_split = dna_model.ModelVersion.FOLD_0 + self._subset = fold_intervals.Subset.TRAIN + self._bundles = [ + bundles.BundleName.ATAC, + bundles.BundleName.RNA_SEQ, + ] + self._create_dummy_files() + + def _create_dummy_files(self): + """Creates data for two bundles in two chromosomes.""" + for bundle in self._bundles: + for chromosome, shard_intervals_map in self._intervals.items(): + for shard_idx, intervals in shard_intervals_map.items(): + data_list = [] + for interval in intervals: + data = { + 'dna_sequence': np.zeros((self._seq_len, 4), dtype=np.float32), + 'interval/chromosome': interval.chromosome, + 'interval/start': interval.start, + 'interval/end': interval.end, + f'{bundle.value}': np.zeros( + (self._seq_len, self._num_channels), dtype=jnp.bfloat16 + ), + f'{bundle.value}_mask': np.ones( + (1, self._num_channels), dtype=bool + ), + } + if bundle == bundles.BundleName.RNA_SEQ: + data['rna_seq_strand'] = np.zeros( + (1, self._num_channels), dtype=np.int32 + ) + data_list.append(data) + + path = ( + pathlib.Path(self.tmpdir) + / self._fold_split.name + / self._organism.name + / self._subset.name + / bundle.name + / f'data_{chromosome}_{shard_idx}-{self._num_shards}.gz.tfrecord' + ) + _write_tfrecord(path, data_list) + + def test_get_tfrecords_df(self): + df = dataset.get_tfrecords_df(path=self.tmpdir) + self.assertLen(df, 8) + self.assertSameElements(df.organism, ['HOMO_SAPIENS']) + self.assertSameElements(df.bundle, ['ATAC', 'RNA_SEQ']) + self.assertSameElements(df.fold_split, ['FOLD_0']) + self.assertSameElements(df.subset, ['TRAIN']) + self.assertSameElements(df.chromosome, ['chr1', 'chr3']) + self.assertSameElements(df.shard, [1, 2]) + + @parameterized.parameters(True, False) + def test_create_dataset(self, shuffle_dataset: bool): + ds = dataset.create_dataset( + organism=self._organism, + fold_split=self._fold_split, + subset=self._subset, + bundles=self._bundles, + path=self.tmpdir, + ) + if shuffle_dataset: + ds = ds.shuffle(buffer_size=100) + ds_iterator = ds.as_numpy_iterator() + intervals = [] + + # 6 intervals in total: 3 in chr1, 3 in chr3 + for _ in range(6): + data = next(ds_iterator) + self.assertLen(data, 2) # 2 bundles + data_atac, data_rna_seq = ( + (data[0], data[1]) + if bundles.BundleName.ATAC.value in data[0] + else (data[1], data[0]) + ) + + self.assertIn('atac', data_atac) + self.assertIn('rna_seq', data_rna_seq) + self.assertEqual( + data_atac['interval/chromosome'], data_rna_seq['interval/chromosome'] + ) + self.assertEqual( + data_atac['interval/start'], data_rna_seq['interval/start'] + ) + self.assertEqual(data_atac['interval/end'], data_rna_seq['interval/end']) + intervals.append( + genome.Interval( + start=data_atac['interval/start'], + end=data_atac['interval/end'], + chromosome=data_atac['interval/chromosome'].decode('utf-8'), + ) + ) + self.assertEqual(data_atac['atac'].dtype, tf.bfloat16) + self.assertEqual(data_rna_seq['rna_seq'].dtype, tf.bfloat16) + + def _interval_to_tuple(interval): + # Convert interval to tuple to check equality. + return (interval.chromosome, interval.start, interval.end) + + all_intervals = jax.tree.reduce( + lambda x, y: x + y, + self._intervals, + is_leaf=lambda x: isinstance(x, list), + ) + self.assertEqual( + set(_interval_to_tuple(i) for i in intervals), + set(_interval_to_tuple(i) for i in all_intervals), + ) + + with self.subTest('Dataset length is correct'): + with self.assertRaises(StopIteration): + next(ds_iterator) + + @parameterized.parameters( + ([bundles.BundleName.ATAC],), + ([bundles.BundleName.ATAC, bundles.BundleName.RNA_SEQ],), + ) + def test_get_numpy_dataset_iterator(self, requested_bundles): + batch_size = 2 + ds_iterator = dataset.get_numpy_dataset_iterator( + batch_size=batch_size, + organism=self._organism, + model_version=self._fold_split, + subset=self._subset, + bundles=requested_bundles, + path=self.tmpdir, + ) + + num_batches = 0 + for batch, metadata in ds_iterator: + self.assertIsInstance(batch, schemas.DataBatch) + self.assertEqual(batch.dna_sequence.shape[0], batch_size) + self.assertEqual(batch.organism_index.shape[0], batch_size) + for bundle in requested_bundles: + self.assertIsNotNone(getattr(batch, bundle.value)) + self.assertIsNotNone(getattr(batch, f'{bundle.value}_mask')) + self.assertLen(metadata, 3) + self.assertEqual(metadata['interval/start'].shape[0], batch_size) + num_batches += 1 + + self.assertEqual(num_batches, 6 // batch_size) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/io/fasta.py b/flax_model/alphagenome/io/fasta.py new file mode 100644 index 0000000000000000000000000000000000000000..2b80dc3f69f9bbca5dbbd7ef26392cc956f477f9 --- /dev/null +++ b/flax_model/alphagenome/io/fasta.py @@ -0,0 +1,75 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Extractors for working with FASTA files.""" + +import os + +from flax_model.alphagenome._sdk.data import genome +import fsspec +import pyfaidx + +_REVERSE_COMPLEMENT_TRANSLATION = str.maketrans('ATCGN', 'TAGCN') + + +def reverse_complement(sequence: str) -> str: + """Returns the reverse complement of a DNA sequence string.""" + return sequence.translate(_REVERSE_COMPLEMENT_TRANSLATION)[::-1] + + +class FastaExtractor: + """FASTA file extractor.""" + + def __init__(self, fasta_path: str | os.PathLike[str]): + self._faidx = pyfaidx.Faidx( + fsspec.open(fasta_path), + as_raw=True, + mutable=False, + build_index=False, + sequence_always_upper=True, + ) + + def extract(self, interval: genome.Interval) -> str: + """Returns the FASTA sequence in some given interval as a string. + + Args: + interval: the interval to query. + + Returns: + sequence of requested interval. + """ + if (chromosome := self._faidx.index.get(interval.chromosome)) is None: + raise ValueError(f'Chromosome "{interval.chromosome}" not found.') + + chromosome_length = chromosome.rlen + + if interval.start >= chromosome_length or interval.end < 0: + raise ValueError(f'Interval fully out of bounds. {interval=}') + elif interval.within_reference(chromosome_length): + sequence = self._faidx.fetch( + interval.chromosome, interval.start + 1, interval.end + ) + else: + start_padding = 'N' * max(-interval.start, 0) + end_padding = 'N' * max(interval.end - chromosome_length, 0) + trimmed_interval = interval.truncate(chromosome_length) + sequence = self._faidx.fetch( + interval.chromosome, trimmed_interval.start + 1, trimmed_interval.end + ) + sequence = start_padding + sequence + end_padding + + if interval.negative_strand: + return reverse_complement(sequence) + else: + return sequence diff --git a/flax_model/alphagenome/io/fasta_test.py b/flax_model/alphagenome/io/fasta_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f212517b90e8f8240945d95d936de7f2ac91862a --- /dev/null +++ b/flax_model/alphagenome/io/fasta_test.py @@ -0,0 +1,55 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import pathlib + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome.io import fasta + + +def _get_test_fasta_path() -> str | os.PathLike[str]: + return pathlib.Path(__file__).parent / 'testdata' / 'example.fa' + + +class FastaExtractorTest(parameterized.TestCase): + + @parameterized.parameters([ + dict(interval='chr1:0-9:+', expected='TAATATGCT'), + dict(interval='chr1:0-9:-', expected='AGCATATTA'), + dict(interval='chr2:70-78', expected='CAGATACA'), + dict(interval='chr1:-10-1', expected='NNNNNNNNNNT'), + dict(interval='chr1:50-55:.', expected='ANNNN'), + dict(interval='chr1:50-55:-', expected='NNNNT'), + ]) + def test_extract(self, interval: str, expected: str): + extractor = fasta.FastaExtractor(_get_test_fasta_path()) + interval = genome.Interval.from_str(interval) + self.assertEqual(extractor.extract(interval), expected) + + def test_extract_fully_out_of_bounds_raises(self): + extractor = fasta.FastaExtractor(_get_test_fasta_path()) + with self.assertRaisesRegex(ValueError, 'Interval fully out of bounds.'): + extractor.extract(genome.Interval('chr1', 100, 1000)) + + def test_invalid_chromosome_raises(self): + extractor = fasta.FastaExtractor(_get_test_fasta_path()) + with self.assertRaisesRegex(ValueError, 'Chromosome "foo" not found.'): + extractor.extract(genome.Interval('foo', 0, 10)) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/io/genome.py b/flax_model/alphagenome/io/genome.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ee9cfbe3f08fbc82ea50540ec8a180baa06f7a --- /dev/null +++ b/flax_model/alphagenome/io/genome.py @@ -0,0 +1,139 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for working with genome-related objects such as intervals.""" + +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome.io import fasta + + +def insert_reference_variant( + sequence: str, + interval: genome.Interval, + variant: genome.Variant, +) -> str: + """Replace reference genome sequence with variant REF sequences. + + Args: + sequence: Reference genome DNA sequence. + interval: Interval from which the reference genome sequence was extracted. + variant: A variant. + + Returns: + Sequence of the same length as input `sequence`, but with variant.REF + integrated in case it mismatches it. + """ + if interval.negative_strand: + raise ValueError('Interval must not be on the negative strand.') + + if not variant.reference_overlaps(interval): + return sequence + + # Relative start/end must be within the interval boundaries. + relative_start = max(variant.start - interval.start, 0) + relative_end = min(variant.end - interval.start, interval.width) + + # Remove reference bases outside the interval. + clip_start = max(interval.start - variant.start, 0) + clip_end = min(interval.end - variant.start, variant.end - variant.start) + variant_reference_bases = variant.reference_bases[clip_start:clip_end] + + return ( + sequence[:relative_start] + + variant_reference_bases + + sequence[relative_end:] + ) + + +def insert_alternate_variant( + sequence: str, interval: genome.Interval, variant: genome.Variant +) -> str: + """Replace reference genome sequence with a single variant ALT sequence. + + Args: + sequence: Reference genome DNA sequence. + interval: Interval corresponding to reference sequence. + variant: Variant to integrate. + + Returns: + DNA sequence with integrated variant. Length of the sequence might be + be different from the input sequence. + """ + if interval.negative_strand: + raise ValueError('Interval must not be on the negative strand.') + + if not ( + variant.reference_overlaps(interval) + or (not variant.reference_bases and variant.alternate_overlaps(interval)) + ): + return sequence + + if variant.end > interval.end: + # Variant reference is partially outside of the interval at the end. + variant, _ = variant.split(interval.end) + assert isinstance(variant, genome.Variant) + + if variant.start < interval.start: + # Variant reference is partially outside of the interval at the start. + _, variant = variant.split(interval.start) + assert isinstance(variant, genome.Variant) + + relative_start = variant.start - interval.start + relative_end = relative_start + len(variant.reference_bases) + return ( + sequence[:relative_start] + + variant.alternate_bases + + sequence[relative_end:] + ) + + +def extract_variant_sequences( + interval: genome.Interval, + variant: genome.Variant, + extractor: fasta.FastaExtractor, +) -> tuple[str, str]: + """Extracts the interval and inserts variant to generate ref/alt sequences. + + Args: + interval: Interval of interest from which to query the sequence. + variant: Variant to insert. + extractor: FASTA extractor for extracting the sequence. + + Returns: + Tuple of reference and alternate sequences. + """ + + # If the variant is a deletion, extend the interval to account for the + # shrinking sequence. + interval_length = interval.width + extended_length = max( + 0, len(variant.reference_bases) - len(variant.alternate_bases) + ) + extended_unstranded_interval = interval.as_unstranded().boundary_shift( + end_offset=extended_length + ) + + sequence = extractor.extract(extended_unstranded_interval) + reference_sequence = insert_reference_variant( + sequence, extended_unstranded_interval, variant + )[:interval_length] + alternate_sequence = insert_alternate_variant( + sequence, extended_unstranded_interval, variant + )[:interval_length] + + if interval.negative_strand: + reference_sequence = fasta.reverse_complement(reference_sequence) + alternate_sequence = fasta.reverse_complement(alternate_sequence) + + return reference_sequence, alternate_sequence diff --git a/flax_model/alphagenome/io/genome_test.py b/flax_model/alphagenome/io/genome_test.py new file mode 100644 index 0000000000000000000000000000000000000000..80add4f3a1c4de33e36a359ce678c401a926f04c --- /dev/null +++ b/flax_model/alphagenome/io/genome_test.py @@ -0,0 +1,239 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome.io import fasta +from flax_model.alphagenome.io import genome as genome_io + + +class VariantTest(parameterized.TestCase): + + @parameterized.named_parameters([ + dict( + testcase_name='Modification', + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4), + variant=genome.Variant('chr1', 3, 'A', 'G'), + expected='AAGA', + ), + dict( + testcase_name='Insertion', + sequence='AAAA', + interval=genome.Interval('chr2', 0, 4), + variant=genome.Variant('chr2', 2, 'A', 'GGGG'), + expected='AGGGGAA', + ), + dict( + testcase_name='Deletion', + sequence='AAAA', + interval=genome.Interval('chr3', 0, 4), + variant=genome.Variant('chr3', 2, 'AA', ''), + expected='AA', + ), + dict( + testcase_name='NoOverlap', + sequence='AAAA', + interval=genome.Interval('chr4', 0, 4), + variant=genome.Variant('chr4', 6, 'A', 'G'), + expected='AAAA', + ), + dict( + testcase_name='OverlapStart', + sequence='AAAA', + interval=genome.Interval('chr4', 4, 8), + variant=genome.Variant('chr4', 1, 'TTTTT', 'GGGGG'), + expected='GAAA', + ), + dict( + testcase_name='OverlapEnd', + sequence='AAAA', + interval=genome.Interval('chr4', 0, 4), + variant=genome.Variant('chr4', 4, 'TTTTTT', 'GG'), + expected='AAAG', + ), + dict( + testcase_name='DifferentChromosomes', + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4), + variant=genome.Variant('chr2', 1, 'A', 'G'), + expected='AAAA', + ), + ]) + def test_insert_alternate_variant( + self, + sequence: str, + interval: genome.Interval, + variant: genome.Variant, + expected: str, + ): + alternate_sequence = genome_io.insert_alternate_variant( + sequence, interval, variant + ) + self.assertEqual(alternate_sequence, expected) + + def test_insert_alternate_variant_negative_strand_raises(self): + with self.assertRaisesRegex( + ValueError, 'Interval must not be on the negative strand.' + ): + _ = genome_io.insert_alternate_variant( + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4, '-'), + variant=genome.Variant('chr1', 2, 'A', 'G'), + ) + + @parameterized.named_parameters([ + dict( + testcase_name='Normal', + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4), + variant=genome.Variant('chr1', 2, 'A', 'G'), + expected='AAAA', + ), + dict( + testcase_name='ModifiedReference', + sequence='AAAA', + interval=genome.Interval('chr2', 0, 4), + variant=genome.Variant('chr2', 2, 'GGG', ''), + expected='AGGG', + ), + dict( + testcase_name='NoOverlap', + sequence='AAAA', + interval=genome.Interval('chr4', 0, 4), + variant=genome.Variant('chr4', 6, 'G', ''), + expected='AAAA', + ), + dict( + testcase_name='OverlapStart', + sequence='AAAA', + interval=genome.Interval('chr4', 4, 8), + variant=genome.Variant('chr4', 1, 'GGGGG', ''), + expected='GAAA', + ), + dict( + testcase_name='OverlapEnd', + sequence='AAAA', + interval=genome.Interval('chr4', 0, 4), + variant=genome.Variant('chr4', 4, 'GGG', ''), + expected='AAAG', + ), + dict( + testcase_name='DifferentChromosomes', + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4), + variant=genome.Variant('chr2', 1, 'G', ''), + expected='AAAA', + ), + ]) + def test_insert_reference_variant( + self, + sequence: str, + interval: genome.Interval, + variant: genome.Variant, + expected: str, + ): + reference_sequence = genome_io.insert_reference_variant( + sequence, interval, variant + ) + self.assertEqual(reference_sequence, expected) + + def test_insert_reference_variant_negative_strand_raises(self): + with self.assertRaisesRegex( + ValueError, 'Interval must not be on the negative strand.' + ): + _ = genome_io.insert_reference_variant( + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4, '-'), + variant=genome.Variant('chr1', 2, 'A', 'G'), + ) + + @parameterized.named_parameters([ + dict( + testcase_name='Normal', + sequence='AAAA', + interval=genome.Interval('chr1', 0, 4), + variant=genome.Variant('chr1', 2, 'A', 'G'), + expected_reference='AAAA', + expected_alternate='AGAA', + ), + dict( + testcase_name='ModifiedReference', + sequence='AAAA', + interval=genome.Interval('chr2', 0, 4), + variant=genome.Variant('chr2', 2, 'G', 'G'), + expected_reference='AGAA', + expected_alternate='AGAA', + ), + dict( + testcase_name='Insertion', + sequence='AAAA', + interval=genome.Interval('chr3', 0, 4), + variant=genome.Variant('chr3', 2, 'A', 'GGGG'), + expected_reference='AAAA', + expected_alternate='AGGG', + ), + dict( + testcase_name='Deletion', + sequence='GATACA', + interval=genome.Interval('chr3', 0, 4), + variant=genome.Variant('chr3', 2, 'AT', ''), + expected_reference='GATA', + expected_alternate='GACA', + ), + dict( + testcase_name='NoOverlap', + sequence='GGGG', + interval=genome.Interval('chr4', 0, 4), + variant=genome.Variant('chr4', 6, 'T', 'T'), + expected_reference='GGGG', + expected_alternate='GGGG', + ), + dict( + testcase_name='NegativeStrand', + sequence='AAAAA', + interval=genome.Interval('chr1', 0, 5, '-'), + variant=genome.Variant('chr1', 2, 'A', 'G'), + expected_reference='TTTTT', + expected_alternate='TTTCT', + ), + ]) + def test_extract_variant_sequences( + self, + sequence: str, + interval: genome.Interval, + variant: genome.Variant, + expected_reference: str, + expected_alternate: str, + ): + def _extract(interval: genome.Interval) -> str: + self.assertLen(sequence, interval.width, f'{interval=}') + return sequence + + extractor = mock.create_autospec(fasta.FastaExtractor) + extractor.extract.side_effect = _extract + reference_sequence, alternate_sequence = ( + genome_io.extract_variant_sequences(interval, variant, extractor) + ) + self.assertLen(reference_sequence, interval.width) + self.assertLen(alternate_sequence, interval.width) + self.assertEqual(reference_sequence, expected_reference) + self.assertEqual(alternate_sequence, expected_alternate) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/io/splicing.py b/flax_model/alphagenome/io/splicing.py new file mode 100644 index 0000000000000000000000000000000000000000..d532282972606ae8674c895cfe07f730f24ce366 --- /dev/null +++ b/flax_model/alphagenome/io/splicing.py @@ -0,0 +1,153 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Extractors for working with splicing data.""" + +from flax_model.alphagenome._sdk.data import genome +import numpy as np +import pandas as pd + + +class PositionExtractor: + """Extractor focused on single position, rather than an interval. + + Interval is considered semi-open [start, end) rows where: + - chromosome == interval.chromosome, + - position >= interval.start, + - position < interval.end, + are returned. + + Note: This code doesn't consider stand information. + """ + + def __init__( + self, + df: pd.DataFrame, + position_column: str, + chromosome_column: str = 'Chromosome', + ): + """Init. + + Args: + df: dataframe to query with `position_column` and `chromosome_column`. + position_column: Which column in the dataframe to use as 0-based position. + chromosome_column: Which column in the dataframe to use as chromosome. + """ + self._positions = { + chromosome: (values, values[position_column].values) + for chromosome, values in df.groupby(chromosome_column, observed=False) + } + + self._empty = df.iloc[:0] + + def extract(self, interval: genome.Interval) -> pd.DataFrame: + if interval.chromosome not in self._positions: + return self._empty + else: + dfc, position = self._positions[interval.chromosome] + return dfc[(position >= interval.start) & (position < interval.end)] + + +class SpliceSiteAnnotationExtractor: + """Generate binary masks of overlapping splice sites.""" + + def __init__( + self, + junction_starts: pd.DataFrame, + junction_ends: pd.DataFrame, + ): + """Init. + + Args: + junction_starts: DataFrame of splice junctions starts with columns: + Chromosome, Start, Strand and an optional set of tissue columns. The + `Start` column must be 0-based position of the first nucleotide of the + intron. + junction_ends: DataFrame of splice junctions ends with columns: + Chromosome, End, Strand and an optional set of tissue columns. The `End` + column must be the 1-based position of the last nucleotide of the + intron. + """ + self._tissues = [ + c for c in junction_starts if c not in ['Chromosome', 'Strand', 'Start'] + ] + ends_tissues = [ + c for c in junction_ends if c not in ['Chromosome', 'Strand', 'End'] + ] + if self._tissues != ends_tissues: + raise ValueError('Tissues mismatch:', self._tissues, ends_tissues) + + # Junctions describe intron intervals as [Start, End). Start point to the + # first nucleotide of the intron and End point to the fist nucleotide of the + # the next exon. We label DONOR the last nucleotide of the exon before the + # intron (so we move Start back by 1) and ACCEPTOR the first nucleotide of + # the exon after the intron (so End are not moved). + junction_starts.update(junction_starts['Start'] - 1) + + self._start_position_extractor = PositionExtractor(junction_starts, 'Start') + self._end_position_extractor = PositionExtractor(junction_ends, 'End') + + def extract(self, interval: genome.Interval) -> np.ndarray: + """Extract splice site masks.""" + splice_junctions_starts = self._start_position_extractor.extract(interval) + splice_junctions_ends = self._end_position_extractor.extract(interval) + tissues = self._tissues + splice_junctions_starts = splice_junctions_starts[ + ['Chromosome', 'Strand', 'Start'] + tissues + ] + splice_junctions_ends = splice_junctions_ends[ + ['Chromosome', 'Strand', 'End'] + tissues + ] + + donors_fw = splice_junctions_starts[splice_junctions_starts.Strand == '+'] + accept_fw = splice_junctions_ends[splice_junctions_ends.Strand == '+'] + donors_rw = splice_junctions_ends[splice_junctions_ends.Strand == '-'] + accept_rw = splice_junctions_starts[splice_junctions_starts.Strand == '-'] + + donor_idx_fw = (donors_fw.Start.values - interval.start).astype(np.int32) + accept_idx_fw = (accept_fw.End.values - interval.start).astype(np.int32) + donor_idx_rw = (donors_rw.End.values - interval.start).astype(np.int32) + accept_idx_rw = (accept_rw.Start.values - interval.start).astype(np.int32) + + if tissues: + donor_theta_fw = donors_fw[tissues].to_numpy() + accept_theta_fw = accept_fw[tissues].to_numpy() + donor_theta_rw = donors_rw[tissues].to_numpy() + accept_theta_rw = accept_rw[tissues].to_numpy() + else: + donor_theta_fw = True + accept_theta_fw = True + donor_theta_rw = True + accept_theta_rw = True + + if interval.negative_strand: + # Then model sees negative strand data as positive strand, swap arrays. + donor_idx_fw, donor_idx_rw = donor_idx_rw, donor_idx_fw + accept_idx_fw, accept_idx_rw = accept_idx_rw, accept_idx_fw + donor_theta_fw, donor_theta_rw = donor_theta_rw, donor_theta_fw + accept_theta_fw, accept_theta_rw = accept_theta_rw, accept_theta_fw + # Sequence is flipped, so indices must start at end of sequence. + donor_idx_fw = interval.width - 1 - donor_idx_fw + accept_idx_fw = interval.width - 1 - accept_idx_fw + donor_idx_rw = interval.width - 1 - donor_idx_rw + accept_idx_rw = interval.width - 1 - accept_idx_rw + + splice_sites = np.zeros((interval.width, 5), dtype=bool) + splice_sites[donor_idx_fw, 0] = np.any(donor_theta_fw > 0) + splice_sites[accept_idx_fw, 1] = np.any(accept_theta_fw > 0) + splice_sites[donor_idx_rw, 2] = np.any(donor_theta_rw > 0) + splice_sites[accept_idx_rw, 3] = np.any(accept_theta_rw > 0) + splice_sites[:, 4] = np.logical_not(np.any(splice_sites[:, :4], axis=1)) + + return splice_sites diff --git a/flax_model/alphagenome/io/splicing_test.py b/flax_model/alphagenome/io/splicing_test.py new file mode 100644 index 0000000000000000000000000000000000000000..70d734a6627eb2bcf832b5c219d2e75809d74eb7 --- /dev/null +++ b/flax_model/alphagenome/io/splicing_test.py @@ -0,0 +1,115 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome.io import splicing +import numpy as np +import pandas as pd + + +class SpliceSiteAnnotationExtractorTest(parameterized.TestCase): + + @parameterized.product(interval_strand=['+', '-'], with_tissues=[True, False]) + def test_extract(self, interval_strand, with_tissues): + interval_start = 100 + interval_end = 116 + + pos_first_bp_intron_0based = np.asarray([101, 106, 107]) + neg_first_bp_intron_0based = np.asarray([101, 106, 107]) + pos_last_bp_intron_1based = np.asarray([104, 109, 115]) + neg_last_bp_intron_1based = np.asarray([104, 109, 115]) + junction_starts = pd.DataFrame({ + 'Chromosome': 'chr1', + 'Start': [*pos_first_bp_intron_0based, *neg_first_bp_intron_0based], + 'Strand': ['+', '+', '+', '-', '-', '-'], + }) + junction_ends = pd.DataFrame({ + 'Chromosome': 'chr1', + 'End': [*pos_last_bp_intron_1based, *neg_last_bp_intron_1based], + 'Strand': ['+', '+', '+', '-', '-', '-'], + }) + if with_tissues: + junction_starts['Tissue_0'] = [1, 3, 5, 2, 4, 6] + junction_starts['Tissue_1'] = [2, 4, 6, 3, 5, 7] + junction_ends['Tissue_0'] = [1, 3, 5, 2, 4, 6] + junction_ends['Tissue_1'] = [2, 4, 6, 3, 5, 7] + + interval = genome.Interval( + 'chr1', interval_start, interval_end, interval_strand + ) + extractor = splicing.SpliceSiteAnnotationExtractor( + junction_starts, junction_ends + ) + result = extractor.extract(interval) + + expected_sites = np.zeros((interval.width, 5), dtype=bool) + + # Move all to the exon bp, and to 0-based coordinates within the interval. + pos_last_exon_before = pos_first_bp_intron_0based - interval_start - 1 + pos_first_exon_after = pos_last_bp_intron_1based - interval_start + neg_first_exon_after = neg_last_bp_intron_1based - interval_start + neg_last_exon_before = neg_first_bp_intron_0based - interval_start - 1 + if interval_strand == '+': + expected_sites[pos_last_exon_before, 0] = True + expected_sites[pos_first_exon_after, 1] = True + expected_sites[neg_first_exon_after, 2] = True + expected_sites[neg_last_exon_before, 3] = True + elif interval_strand == '-': + pos_last_exon_before = interval.width - 1 - pos_last_exon_before + pos_first_exon_after = interval.width - 1 - pos_first_exon_after + neg_last_exon_before = interval.width - 1 - neg_last_exon_before + neg_first_exon_after = interval.width - 1 - neg_first_exon_after + expected_sites[neg_first_exon_after, 0] = True + expected_sites[neg_last_exon_before, 1] = True + expected_sites[pos_last_exon_before, 2] = True + expected_sites[pos_first_exon_after, 3] = True + expected_sites[:, 4] = np.logical_not(np.any(expected_sites, axis=1)) + + np.testing.assert_array_equal(result, expected_sites) + + def test_tissue_mismatch_raises(self): + junction_starts = pd.DataFrame({ + 'Chromosome': 'chr1', + 'Start': [101, 106, 107], + 'Strand': ['+', '+', '+'], + 'Tissue_0': [1, 3, 5], + }) + junction_ends = pd.DataFrame({ + 'Chromosome': 'chr1', + 'End': [104, 109, 115], + 'Strand': ['+', '+', '+'], + 'Tissue_1': [1, 3, 5], + }) + with self.assertRaisesRegex(ValueError, 'Tissues mismatch'): + _ = splicing.SpliceSiteAnnotationExtractor(junction_starts, junction_ends) + + +class PositionExtractorTest(parameterized.TestCase): + + def test_extract(self): + df = pd.DataFrame({'Chromosome': ['chr1'], 'position': [1]}) + ex = splicing.PositionExtractor(df, position_column='position') + # Inside. + self.assertLen(ex.extract(genome.Interval('chr1', 0, 2)), 1) + self.assertLen(ex.extract(genome.Interval('chr1', 1, 2)), 1) + # Outside. + self.assertEmpty(ex.extract(genome.Interval('chr2', 0, 2))) + self.assertEmpty(ex.extract(genome.Interval('chr1', 0, 1))) + self.assertEmpty(ex.extract(genome.Interval('chr1', 2, 3))) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/io/testdata/example.fa b/flax_model/alphagenome/io/testdata/example.fa new file mode 100644 index 0000000000000000000000000000000000000000..5749f6dbe712dfb34091d117e61238f5bdd53c13 --- /dev/null +++ b/flax_model/alphagenome/io/testdata/example.fa @@ -0,0 +1,4 @@ +>chr1 +TAATATGCTATATATGATACAGATACAGATACAGATACAGATACAAAAAAA +>chr2 +GATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACA diff --git a/flax_model/alphagenome/io/testdata/example.fa.fai b/flax_model/alphagenome/io/testdata/example.fa.fai new file mode 100644 index 0000000000000000000000000000000000000000..ac37ccd191379748be3a808d957c9e28255f534a --- /dev/null +++ b/flax_model/alphagenome/io/testdata/example.fa.fai @@ -0,0 +1,2 @@ +chr1 51 6 51 52 +chr2 78 64 78 79 diff --git a/flax_model/alphagenome/model/__init__.py b/flax_model/alphagenome/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d498393731fba16d4e87d90cf5a91feb70d8e059 --- /dev/null +++ b/flax_model/alphagenome/model/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome Model.""" diff --git a/flax_model/alphagenome/model/attention.py b/flax_model/alphagenome/model/attention.py new file mode 100644 index 0000000000000000000000000000000000000000..c29a4cd94620777d1618b485da3389195fa4f8cc --- /dev/null +++ b/flax_model/alphagenome/model/attention.py @@ -0,0 +1,283 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Attention layers.""" + +import math +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome.model import layers +import chex +from einshape import jax_einshape as einshape # pylint: disable=g-importing-member +import haiku as hk +import jax +import jax.numpy as jnp +from jaxtyping import Array, Float, Int # pylint: disable=g-importing-member, g-multiple-import + + +_MAX_RELATIVE_DISTANCE = 8192 # 1Mb / 128bp. + + +def _shift( + x: jnp.ndarray, + query_length: int, + key_length: int, +) -> jnp.ndarray: + """Shifts the diagonal of a 2D array.""" + chex.assert_axis_dimension(x, -2, query_length) + chex.assert_axis_dimension(x, -1, query_length + key_length) + *batch_shapes, n_rows, n_diags = x.shape + x = x.reshape(batch_shapes + [n_diags, n_rows]) + x = x[..., 1:, :] + x = x.reshape(batch_shapes + [n_rows, n_diags - 1]) + return x[..., :key_length] + + +def _central_mask_features( + *, distances: jnp.ndarray, feature_size: int, seq_length: int +) -> jnp.ndarray: + """Positional features using exponentially-spaced central mask.""" + if feature_size > seq_length: + raise ValueError(f'{feature_size=} must be <= than {seq_length=}. ') + center_widths = jnp.arange(feature_size) + jnp.geomspace( + 1, seq_length - feature_size + 1, feature_size, endpoint=False + ) + center_widths = jax.lax.broadcast_to_rank(center_widths, distances.ndim) + outputs = (center_widths > distances[..., None]).astype(distances.dtype) + chex.assert_shape(outputs, expected_shapes=distances.shape + (feature_size,)) + return outputs + + +def apply_rope( + x: Float[Array, 'B S H C'], + positions: Int[Array, 'B S'] | None, + max_position: int, +) -> Float[Array, 'B S H C']: + """Applies Rotary Position Embeddings to the input tensor.""" + if positions is None: + positions = jnp.arange(x.shape[1]).astype(x.dtype).reshape(1, x.shape[1]) + num_freq = x.shape[-1] // 2 + inv_freq = 1.0 / ( + jnp.arange(num_freq) + + jnp.geomspace(1, max_position - num_freq + 1, num_freq) + ).astype(x.dtype) + theta = jnp.einsum('bs,f->bsf', positions, inv_freq) + theta = jnp.repeat(theta, 2, axis=-1)[..., None, :] # [b, s, 1, c] + x_rotated = jnp.stack([-x[..., 1::2], x[..., ::2]], axis=-1).reshape( + x.shape + ) # [b, s, h, c] + return x * jnp.cos(theta) + x_rotated * jnp.sin(theta) + + +class MLPBlock(hk.Module): + """MLP block for sequence representations.""" + + @typing.jaxtyped + def __call__(self, x: Float[Array, 'B S D']) -> Float[Array, 'B S D']: + h = layers.RMSBatchNorm()(x) + h = hk.Linear(x.shape[-1] * 2)(h) + h = jax.nn.relu(h) + h = hk.Linear(x.shape[-1])(h) + return layers.RMSBatchNorm()(h) + + +class PairMLPBlock(hk.Module): + """MLP block for pairwise representations.""" + + @typing.jaxtyped + def __call__( + self, pair_input: Float[Array, 'B S S F'] + ) -> Float[Array, 'B S S F']: + x = layers.LayerNorm(rms_norm=True)(pair_input) + hidden_channels = 2 * pair_input.shape[-1] + x = hk.Linear(hidden_channels)(x) + x = jax.nn.relu(x) + x = hk.Linear(pair_input.shape[-1])(x) + return x + + +class MHABlock(hk.Module): + """Multi-Head Attention block with residual connection.""" + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S D'], attention_bias: Float[Array, 'B H S S'] + ) -> Float[Array, 'B S D']: + batch_size, seq_len, _ = x.shape + h = layers.RMSBatchNorm()(x) + q = layers.LayerNorm(name='norm_q')( + hk.Linear(8 * 128, with_bias=False, name='q_layer')(h).reshape( + batch_size, seq_len, 8, 128 + ) + ) + k = layers.LayerNorm(name='norm_k')( + hk.Linear(128, with_bias=False, name='k_layer')(h).reshape( + batch_size, seq_len, 1, 128 + ) + ) + v = layers.LayerNorm(name='norm_v')( + hk.Linear(192, with_bias=False, name='v_layer')(h).reshape( + batch_size, seq_len, 1, 192 + ) + ) + q = apply_rope(q, None, max_position=_MAX_RELATIVE_DISTANCE) + k = apply_rope(k, None, max_position=_MAX_RELATIVE_DISTANCE) + + logits_dtype = jnp.float32 + attention_logits = jnp.einsum( + 'bshc,bS1c->bhsS', + q, + k, + precision=jax.lax.Precision.DEFAULT, + # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32, + preferred_element_type=logits_dtype, + ) + attention_logits = attention_logits / math.sqrt(128.0) + attention_logits = (attention_logits + attention_bias).astype(logits_dtype) + logits_soft_cap = 5.0 + attention_logits = ( + jnp.tanh(attention_logits / logits_soft_cap) * logits_soft_cap + ) + attention_weights = jax.nn.softmax(attention_logits, axis=-1) + + y = jnp.einsum( + 'bhsS,bS1c->bshc', + attention_weights, + v, + # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32, + precision=jax.lax.Precision.DEFAULT, + ).astype(q.dtype) + y = hk.Linear(x.shape[-1], name='linear_embedding')( + y.reshape(batch_size, seq_len, -1) + ) + return layers.RMSBatchNorm()(y) + + +class AttentionBiasBlock(hk.Module): + """Generates attention bias for Multi-Head Attention.""" + + @typing.jaxtyped + def __call__(self, x: Float[Array, 'B s s D']) -> Float[Array, 'B H S S']: + x = jax.nn.gelu(layers.RMSBatchNorm()(x)) + # 8 = number of heads in sequence MHA. + x = hk.Linear(8, with_bias=False)(x) + for axis in [1, 2]: + x = jnp.repeat(x, repeats=16, axis=axis) # [B S S H] + return jnp.moveaxis(x, 3, 1) + + +class RowAttentionBlock(hk.Module): + """Self-attention block applied along rows of pairwise representations.""" + + @typing.jaxtyped + def __call__( + self, pair_input: Float[Array, 'B s s F'] + ) -> Float[Array, 'B s s F']: + x = layers.LayerNorm(rms_norm=True)(pair_input) + k = hk.Linear(128, with_bias=False, name='linear_k')(x) + q = hk.Linear(128, with_bias=False, name='linear_q')(x) + v = hk.Linear(128, name='linear_v')(x) + x = jnp.einsum( + 'bpqf,bpkf->bpqk', + q, + k, + # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32, + precision=jax.lax.Precision.DEFAULT, + preferred_element_type=jnp.float32, + ) / math.sqrt(128) + x = jax.nn.softmax(x, axis=-1) + x = jnp.einsum( + 'bpqk,bpkf->bpqf', + x, + v, + # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32, + precision=jax.lax.Precision.DEFAULT, + ).astype(q.dtype) + return x + + +class SequenceToPairBlock(hk.Module): + """Converts sequence representations to pairwise representations.""" + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S D'] + ) -> Float[Array, 'B S//16 S//16 F']: + x = layers.LayerNorm(rms_norm=True, name='norm_seq2pair')( + layers.pool(x, by=16, reduce='mean') + ) + batch_size, seq_len = x.shape[0], x.shape[1] + q = hk.Linear(32 * 128, with_bias=False, name='linear_q')(x).reshape( + batch_size, seq_len, 32, 128 + ) + k = hk.Linear(32 * 128, with_bias=False, name='linear_k')(x).reshape( + batch_size, seq_len, 32, 128 + ) + + relative_positions = jnp.arange(-seq_len, seq_len).astype(jnp.float32) + pos_features = _central_mask_features( + distances=jnp.abs(relative_positions), + feature_size=32, + seq_length=_MAX_RELATIVE_DISTANCE // 16, + ).astype(x.dtype) + pos_features = jnp.concatenate( + [pos_features, jnp.sign(relative_positions)[..., None] * pos_features], + axis=-1, + ).astype(x.dtype) + pos_encoding = hk.Linear(32 * 128, name='linear_pos_features')( + pos_features + ).reshape(2 * seq_len, 32, 128) + + q_bias = hk.get_parameter( + 'q_r_bias', (1, 1, 32, 128), init=jnp.zeros + ).astype(x.dtype) + k_bias = hk.get_parameter( + 'k_r_bias', (1, 1, 32, 128), init=jnp.zeros + ).astype(x.dtype) + + rel_q_a = _shift( + jnp.einsum('bqhc,phc->bhqp', q + q_bias, pos_encoding), seq_len, seq_len + ) + rel_k_a = _shift( + jnp.einsum('bkhc,phc->bhkp', k + k_bias, pos_encoding), seq_len, seq_len + ) + + a = jnp.einsum('bqhc,bkhc->bqkh', q, k) + a += 0.5 * ( + einshape('bhqp->bqph', rel_q_a) + einshape('bhkp->bpkh', rel_k_a) + ) + + y_q = hk.Linear(128, with_bias=False, name='linear_y_q')(jax.nn.gelu(x)) + y_k = hk.Linear(128, with_bias=False, name='linear_y_k')(jax.nn.gelu(x)) + pair_act = ( + hk.Linear(128, name='linear_pair')(a) + + y_q[:, :, None, :] + + y_k[:, None, :, :] + ) + return pair_act + + +class PairUpdateBlock(hk.Module): + """Updates pairwise representations.""" + + @typing.jaxtyped + def __call__( + self, + sequence_input: Float[Array, 'B S C'], + pair_input: Float[Array, 'B S//16 S//16 F'] | None, + ): + y = SequenceToPairBlock()(sequence_input) + x = y if pair_input is None else (pair_input + y) + x += RowAttentionBlock()(x) + x += PairMLPBlock()(x) + return x diff --git a/flax_model/alphagenome/model/attention_test.py b/flax_model/alphagenome/model/attention_test.py new file mode 100644 index 0000000000000000000000000000000000000000..19fba85012c9bfb7d3553532ff924796fa144792 --- /dev/null +++ b/flax_model/alphagenome/model/attention_test.py @@ -0,0 +1,78 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome.model import attention +import chex +import haiku as hk +import jax +import jax.numpy as jnp + + +class ConvolutionsTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self._batch_size = 4 + self._sequence_length = 4096 + self._pair_sequence_length = self._sequence_length // 16 + self._hidden_size = 64 + + def test_mlp_block_output_shape(self): + """Tests that MLPBlock produces the expected output shape.""" + rng = jax.random.PRNGKey(42) + + def _forward(x): + module = attention.MLPBlock() + return module(x) + + init, apply = hk.transform_with_state(_forward) + x = jnp.zeros((self._batch_size, self._sequence_length, self._hidden_size)) + params, state = init(rng, x) + output, _ = apply(params, state, rng, x) + chex.assert_shape( + output, (self._batch_size, self._sequence_length, self._hidden_size) + ) + + def test_pair_mlp_block_output_shape(self): + """Tests that PairMLPBlock produces the expected output shape.""" + rng = jax.random.PRNGKey(42) + + def _forward(x): + module = attention.PairMLPBlock() + return module(x) + + init, apply = hk.transform_with_state(_forward) + x = jnp.zeros(( + self._batch_size, + self._pair_sequence_length, + self._pair_sequence_length, + self._hidden_size, + )) + params, state = init(rng, x) + output, _ = apply(params, state, rng, x) + chex.assert_shape( + output, + ( + self._batch_size, + self._pair_sequence_length, + self._pair_sequence_length, + self._hidden_size, + ), + ) + + +if __name__ == "__main__": + absltest.main() diff --git a/flax_model/alphagenome/model/augmentation.py b/flax_model/alphagenome/model/augmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..43ad3f3dc262fa8784509c6720ac1f5c3ddb7ae0 --- /dev/null +++ b/flax_model/alphagenome/model/augmentation.py @@ -0,0 +1,122 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utilities for augmenting predictions, e.g. reverse complementation.""" + +from collections.abc import Mapping +from typing import TypeAlias + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.models import dna_output +import chex +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float, Int32, PyTree # pylint: disable=g-importing-member, g-multiple-import + +_Predictions: TypeAlias = PyTree[Float[Array, 'B ...'] | Int32[Array, 'B ...']] + + +@typing.jaxtyped +def reverse_complement_output_type( + predictions: _Predictions, + *, + output_type: dna_output.OutputType, + strand_reindexing: Int32[Array, '_'] | None, + sequence_length: Int32[Array, ''] | int, +) -> _Predictions: + """Reverse complement predictions for a given output type.""" + match output_type: # pytype: disable=incomplete-match + case dna_output.OutputType.SPLICE_JUNCTIONS: + splice_junction_predictions = predictions['predictions'] + chex.assert_rank(splice_junction_predictions, 4) + # Only need to strand flip for junction outputs. Index flipping is done + # with splice_site_positions. + chex.assert_equal_shape( + (splice_junction_predictions, strand_reindexing), dims=-1 + ) + predictions['predictions'] = splice_junction_predictions[ + ..., strand_reindexing + ] + + splice_site_positions = predictions['splice_site_positions'] + chex.assert_rank(splice_site_positions, 3) + padding_predictions = splice_site_positions < 0 + splice_site_positions = sequence_length - 1 - splice_site_positions + splice_site_positions = jnp.where( + padding_predictions, -1, splice_site_positions + ) + splice_site_positions = splice_site_positions[:, jnp.array([2, 3, 0, 1])] + + predictions['splice_site_positions'] = splice_site_positions + case dna_output.OutputType.CONTACT_MAPS: + chex.assert_rank(predictions, 4) + # Contact maps are unstranded, so no need to strand flip. + return predictions[:, ::-1, ::-1] + case _: + chex.assert_rank(predictions, 3) + predictions = predictions[:, ::-1] + if strand_reindexing is not None: + predictions = predictions[..., strand_reindexing] + # For DNASE, +ve strand predictions are not aligned with -ve strand + # predictions after reverse-complementation: + # Input positions: + # [ 0 ][ 1 ][ 2 ] + # Track values: + # [ A ][ B ][ C ][ D ] + # In this example, output predictions are determined by the track value + # at the start of the position. Thus, when read forwards, the + strand + # will give ABC and the - strand will give DCB. If we want predictions to + # align after reverse-complementation (for example, to perform TTA or to + # return aligned, unstranded predictions for both + and -), we need to + # shift predictions by 1 after rc. + if output_type == dna_output.OutputType.DNASE: + predictions = jnp.roll(predictions, 1, axis=1) + predictions = predictions.at[:, 0].set(0) + + return predictions + + +@typing.jaxtyped +def reverse_complement( + predictions: Mapping[dna_output.OutputType, _Predictions], + reverse_complement_mask: Bool[Array, 'B'], + *, + strand_reindexing: Mapping[dna_output.OutputType, Int32[Array, '_']], + sequence_length: int, +) -> Mapping[dna_output.OutputType, _Predictions]: + """Reverse complement predictions.""" + + def _reverse_complement(predictions: _Predictions): + result = {} + for output_type in dna_output.OutputType: + if (prediction := predictions.get(output_type)) is not None: + result[output_type] = reverse_complement_output_type( + prediction, + output_type=output_type, + strand_reindexing=strand_reindexing.get(output_type), + sequence_length=sequence_length, + ) + return result + + # Add single batch dimension to vmap over. + predictions = jax.tree.map(lambda x: jnp.expand_dims(x, axis=1), predictions) + predictions = jax.vmap( + lambda prediction, should_reverse: jax.lax.cond( + should_reverse, + _reverse_complement, + lambda prediction: prediction, + prediction, + ) + )(predictions, reverse_complement_mask) + return jax.tree.map(lambda x: jnp.squeeze(x, axis=1), predictions) diff --git a/flax_model/alphagenome/model/augmentation_test.py b/flax_model/alphagenome/model/augmentation_test.py new file mode 100644 index 0000000000000000000000000000000000000000..074c287cd99f4364be7e5ef507a163b0b628d274 --- /dev/null +++ b/flax_model/alphagenome/model/augmentation_test.py @@ -0,0 +1,232 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections.abc import Sequence +import functools + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome.model import augmentation +import chex +import jax +from jax import numpy as jnp +from jaxtyping import PyTree # pylint: disable=g-importing-member +import ml_dtypes +import numpy as np + + +class AugmentationTest(chex.TestCase, parameterized.TestCase): + + @chex.variants(with_jit=True, without_jit=True) + @parameterized.parameters( + dict( + output_type=dna_output.OutputType.SPLICE_JUNCTIONS, + predictions={ + 'predictions': np.array( + [[ + [[0, 1, 2, 3], [4, 5, 6, 7]], + [[8, 9, 10, 11], [12, 13, 14, 15]], + ]], + dtype=np.float32, + ), + 'splice_site_positions': np.array( + [[[0, 1], [-1, 3], [4, -1], [6, 7]]], + dtype=np.int32, + ), + }, + strand_reindexing=np.array([3, 2, 1, 0], dtype=np.int32), + expected={ + 'predictions': np.array( + [[ + [[3, 2, 1, 0], [7, 6, 5, 4]], + [[11, 10, 9, 8], [15, 14, 13, 12]], + ]], + dtype=np.float32, + ), + 'splice_site_positions': np.array( + [[[-1, -1], [-3, -4], [3, 2], [-1, 0]]], + dtype=np.int32, + ), + }, + sequence_length=4, + ), + dict( + output_type=dna_output.OutputType.CONTACT_MAPS, + predictions=np.array( + [[ + [[0, 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]], + ]], + dtype=ml_dtypes.bfloat16, + ), + strand_reindexing=None, + expected=np.array( + [[ + [[30, 31], [28, 29], [26, 27], [24, 25]], + [[22, 23], [20, 21], [18, 19], [16, 17]], + [[14, 15], [12, 13], [10, 11], [8, 9]], + [[6, 7], [4, 5], [2, 3], [0, 1]], + ]], + dtype=ml_dtypes.bfloat16, + ), + sequence_length=-1, # Unused. + ), + dict( + output_type=dna_output.OutputType.RNA_SEQ, + predictions=np.array( + [[[0, 1], [2, 3], [4, 5], [6, 7]]], + dtype=ml_dtypes.bfloat16, + ), + strand_reindexing=np.array([1, 0], dtype=np.int32), + expected=np.array( + [[[7, 6], [5, 4], [3, 2], [1, 0]]], + dtype=ml_dtypes.bfloat16, + ), + sequence_length=-1, # Unused. + ), + dict( + output_type=dna_output.OutputType.DNASE, + predictions=np.array( + [[[0, 1], [2, 3], [4, 5], [6, 7]]], + dtype=ml_dtypes.bfloat16, + ), + strand_reindexing=np.array([1, 0], dtype=np.int32), + expected=np.array( + [[[0, 0], [7, 6], [5, 4], [3, 2]]], + dtype=ml_dtypes.bfloat16, + ), + sequence_length=-1, # Unused. + ), + ) + def test_reverse_complement_output_type( + self, + output_type: dna_output.OutputType, + predictions: PyTree[np.ndarray], + strand_reindexing: np.ndarray, + expected: PyTree[np.ndarray], + sequence_length: int, + ): + output = self.variant( + augmentation.reverse_complement_output_type, + static_argnames=['output_type'], + )( + jax.tree.map(jnp.asarray, predictions), + output_type=output_type, + strand_reindexing=jnp.asarray(strand_reindexing) + if strand_reindexing is not None + else None, + sequence_length=sequence_length, + ) + jax.tree.map(np.testing.assert_array_equal, output, expected) + + @chex.variants(with_jit=True, without_jit=True) + @parameterized.product( + mask=[[True, False], [False, False], [True, True]], + ) + def test_reverse_complement(self, mask: Sequence[bool]): + sequence_length = 64 + example = { + dna_output.OutputType.ATAC: ( + jnp.arange(sequence_length * 2, dtype=jnp.bfloat16).reshape( + 1, sequence_length, 2 + ) + ), + dna_output.OutputType.DNASE: ( + jnp.arange(sequence_length * 2, dtype=jnp.bfloat16).reshape( + 1, sequence_length, 2 + ) + ), + dna_output.OutputType.SPLICE_JUNCTIONS: { + 'predictions': ( + jnp.arange(32, dtype=jnp.bfloat16).reshape(1, 4, 4, 2) + ), + 'splice_site_positions': ( + jnp.arange(16, dtype=jnp.int32).reshape(1, 4, 4) + ), + }, + dna_output.OutputType.CONTACT_MAPS: ( + jnp.arange(400, dtype=jnp.bfloat16).reshape(1, 10, 10, 4) + ), + } + strand_reindexing = { + dna_output.OutputType.ATAC: jnp.array([1, 0], dtype=jnp.int32), + dna_output.OutputType.DNASE: jnp.array([1, 0], dtype=jnp.int32), + dna_output.OutputType.SPLICE_JUNCTIONS: jnp.array( + [0, 1], dtype=jnp.int32 + ), + } + splice_site_positions_reversed = ( + sequence_length + - 1 + - example[dna_output.OutputType.SPLICE_JUNCTIONS][ + 'splice_site_positions' + ] + ) + expected_reversed = { + dna_output.OutputType.ATAC: example[dna_output.OutputType.ATAC][ + :, ::-1, strand_reindexing[dna_output.OutputType.ATAC] + ], + dna_output.OutputType.DNASE: jnp.pad( + example[dna_output.OutputType.DNASE][ + :, :0:-1, strand_reindexing[dna_output.OutputType.DNASE] + ], + ((0, 0), (1, 0), (0, 0)), + ), + dna_output.OutputType.SPLICE_JUNCTIONS: { + 'predictions': example[dna_output.OutputType.SPLICE_JUNCTIONS][ + 'predictions' + ], + 'splice_site_positions': splice_site_positions_reversed[ + :, + (2, 3, 0, 1), + ], + }, + dna_output.OutputType.CONTACT_MAPS: example[ + dna_output.OutputType.CONTACT_MAPS + ][:, ::-1, ::-1], + } + batched_example = jax.tree.map( + lambda x: jnp.repeat(x, len(mask), axis=0), example + ) + expected = jax.tree.map( + lambda *x: jnp.concatenate(x, axis=0), + *[expected_reversed if m else example for m in mask], + ) + + result = self.variant( + augmentation.reverse_complement, + static_argnames=['sequence_length'], + )( + batched_example, + jnp.asarray(mask, dtype=bool), + strand_reindexing=strand_reindexing, + sequence_length=sequence_length, + ) + + for output_type in dna_output.OutputType: + if (prediction := result.get(output_type)) is not None: + jax.tree.map( + functools.partial( + np.testing.assert_array_equal, err_msg=f'{output_type=}' + ), + prediction, + expected.get(output_type), + ) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/convolutions.py b/flax_model/alphagenome/model/convolutions.py new file mode 100644 index 0000000000000000000000000000000000000000..711f63f275038ff5693f95bf44da3729e3979a09 --- /dev/null +++ b/flax_model/alphagenome/model/convolutions.py @@ -0,0 +1,152 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Convolutional layers.""" + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome.model import layers +import chex +import haiku as hk +import jax +import jax.numpy as jnp +from jaxtyping import Array, Float # pylint: disable=g-importing-member, g-multiple-import + + +class ConvBlock(hk.Module): + """A convolutional block with GELU activation and RMS Batch Normalization.""" + + def __init__(self, num_channels: int, width: int, name: str | None = None): + """Initializes the convolutional block. + + Args: + num_channels: The number of output channels. + width: The width of the convolution. If 1, a linear layer is used instead. + name: The name of the module. + """ + super().__init__(name=name) + self._num_channels = num_channels + self._width = width + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S D'] + ) -> Float[Array, 'B S {self._num_channels}']: + x = layers.gelu(layers.RMSBatchNorm()(x)) + if self._width == 1: + return hk.Linear(self._num_channels)(x) + else: + return StandardizedConv1D( + num_channels=self._num_channels, width=self._width + )(x) + + +class StandardizedConv1D(hk.Module): + """Standardized 1D Convolution with scaled weight standardization.""" + + def __init__( + self, + num_channels: int, + width: int, + name: str | None = None, + ): + super().__init__(name=name) + self._num_channels = num_channels + self._width = width + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S D'] + ) -> Float[Array, 'B S {self._num_channels}']: + input_channels = x.shape[-1] + fan_in = self._width * input_channels + kernel_shape = (self._width, input_channels, self._num_channels) + w = hk.get_parameter('w', shape=kernel_shape, dtype=x.dtype, init=jnp.zeros) + + # Weight standardization + w -= jnp.mean(w, axis=(0, 1), keepdims=True) + var_w = jnp.var(w, axis=(0, 1), keepdims=True) + scale = hk.get_parameter( + 'scale', + shape=[1, 1, self._num_channels], + init=jnp.ones, + dtype=w.dtype, + ) + scale = scale * jax.lax.rsqrt(jnp.maximum(fan_in * var_w, 1e-4)) + w_standardized = w * scale + + out = jax.lax.conv_general_dilated( + lhs=x, + rhs=w_standardized, + window_strides=[1], + padding='SAME', + dimension_numbers=jax.lax.ConvDimensionNumbers( + lhs_spec=(0, 2, 1), rhs_spec=(2, 1, 0), out_spec=(0, 2, 1) + ), + ) + bias = hk.get_parameter( + 'bias', shape=(self._num_channels,), dtype=x.dtype, init=jnp.zeros + ) + bias = jnp.broadcast_to(bias, out.shape) + return out + bias + + +class DnaEmbedder(hk.Module): + """Encodes one-hot encoded DNA sequences into a fixed-length embedding.""" + + @typing.jaxtyped + def __call__( + self, dna_sequence: Float[Array, 'B S 4'] + ) -> Float[Array, 'B S 768']: + x = hk.Conv1D(output_channels=768, kernel_shape=15)(dna_sequence) + return x + ConvBlock(num_channels=768, width=5)(x) + + +class DownResBlock(hk.Module): + """Down resolution convolution.""" + + @typing.jaxtyped + def __call__(self, x: Float[Array, 'B S D']) -> Float[Array, 'B S D+128']: + num_out_channels = x.shape[-1] + 128 + out = ConvBlock(num_channels=num_out_channels, width=5)(x) + out = out + jnp.pad( + x, [(0, 0), (0, 0), (0, 128)] + ) # Padding for residual connection + return out + ConvBlock(num_channels=out.shape[-1], width=5)(out) + + +class UpResBlock(hk.Module): + """Upsampling residual block.""" + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S D'], unet_skip: Float[Array, 'B S_skip D_skip'] + ) -> Float[Array, 'B S_up D_skip']: + chex.assert_rank(x, 3) + chex.assert_rank(unet_skip, 3) + num_channels = unet_skip.shape[-1] + out = ( + ConvBlock(num_channels=num_channels, width=5, name='conv_in')(x) + + x[:, :, :num_channels] + ) + out = jnp.repeat(out, 2, axis=1) # Upsampling + residual_scale = hk.get_parameter( + 'residual_scale', (), init=jnp.ones + ).astype(out.dtype) + out *= residual_scale + out += ConvBlock( + num_channels=num_channels, width=1, name='pointwise_conv_unet_skip' + )(unet_skip) + return out + ConvBlock(num_channels=num_channels, width=5, name='conv_out')( + out + ) diff --git a/flax_model/alphagenome/model/convolutions_test.py b/flax_model/alphagenome/model/convolutions_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4412430c636da1b74c205bc0061664ba0f8caf53 --- /dev/null +++ b/flax_model/alphagenome/model/convolutions_test.py @@ -0,0 +1,137 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome.model import convolutions +import chex +import haiku as hk +import jax +import jax.numpy as jnp + + +class ConvolutionsTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self._batch_size = 4 + self._sequence_length = 200 + self._input_channels = 768 + self._output_channels = 256 + self._dna_embedder_output_channels = 768 + self._unet_skip_channels = 512 + self._down_block_added_channels = 128 + self._rng = jax.random.PRNGKey(42) + + @parameterized.named_parameters( + dict(testcase_name='width_1', width=1), + dict(testcase_name='width_5', width=5), + ) + def test_conv_block_output_shape(self, width: int): + def _conv_block(x): + return convolutions.ConvBlock( + num_channels=self._output_channels, width=width + )(x) + + conv_block = hk.transform_with_state(_conv_block) + x = jnp.zeros( + (self._batch_size, self._sequence_length, self._input_channels) + ) + params, state = conv_block.init(self._rng, x) + out, state = conv_block.apply(params, state, self._rng, x) + chex.assert_shape( + out, (self._batch_size, self._sequence_length, self._output_channels) + ) + self.assertNotEmpty(state) + + def test_standardized_conv1d_output_shape(self): + def _standardized_conv1d(x): + return convolutions.StandardizedConv1D( + num_channels=self._output_channels, width=5 + )(x) + + standardized_conv1d = hk.transform_with_state(_standardized_conv1d) + x = jnp.zeros( + (self._batch_size, self._sequence_length, self._input_channels) + ) + params, state = standardized_conv1d.init(self._rng, x) + out, state = standardized_conv1d.apply(params, state, self._rng, x) + chex.assert_shape( + out, (self._batch_size, self._sequence_length, self._output_channels) + ) + + def test_dna_embedder_output_shape(self): + def _dna_embedder(x): + return convolutions.DnaEmbedder()(x) + + dna_embedder = hk.transform_with_state(_dna_embedder) + x = jnp.zeros((self._batch_size, self._sequence_length, 4)) + params, state = dna_embedder.init(self._rng, x) + out, state = dna_embedder.apply(params, state, self._rng, x) + chex.assert_shape( + out, + ( + self._batch_size, + self._sequence_length, + self._dna_embedder_output_channels, + ), + ) + self.assertNotEmpty(state) + + def test_down_res_block_output_shape(self): + def _down_res_block(x): + return convolutions.DownResBlock()(x) + + down_res_block = hk.transform_with_state(_down_res_block) + x = jnp.zeros( + (self._batch_size, self._sequence_length, self._input_channels) + ) + params, state = down_res_block.init(self._rng, x) + out, state = down_res_block.apply(params, state, self._rng, x) + chex.assert_shape( + out, + ( + self._batch_size, + self._sequence_length, + self._input_channels + self._down_block_added_channels, + ), + ) + self.assertNotEmpty(state) + + def test_up_res_block_output_shape(self): + def _up_res_block(x, unet_skip): + return convolutions.UpResBlock()(x, unet_skip) + + up_res_block = hk.transform_with_state(_up_res_block) + x = jnp.zeros( + (self._batch_size, self._sequence_length, self._input_channels) + ) + unet_skip = jnp.zeros( + (self._batch_size, self._sequence_length * 2, self._unet_skip_channels) + ) + params, state = up_res_block.init(self._rng, x, unet_skip) + out, state = up_res_block.apply(params, state, self._rng, x, unet_skip) + chex.assert_shape( + out, + ( + self._batch_size, + self._sequence_length * 2, + self._unet_skip_channels, + ), + ) + self.assertNotEmpty(state) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/dna_model.py b/flax_model/alphagenome/model/dna_model.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe267580814d07c19c7fbd53766098ebd7dfebb --- /dev/null +++ b/flax_model/alphagenome/model/dna_model.py @@ -0,0 +1,1326 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implementation of alphagenome DNAModel interface.""" + +from collections.abc import Callable, Iterable, Mapping, Sequence +import dataclasses +import functools +import os +import threading +from typing import TypeAlias + +from flax_model.alphagenome._sdk import tensor_utils +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import junction_data +from flax_model.alphagenome._sdk.data import ontology +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.interpretation import ism +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import interval_scorers as interval_scorers_lib +from flax_model.alphagenome._sdk.models import variant_scorers as variant_scorers_lib +from flax_model.alphagenome.io import fasta +from flax_model.alphagenome.io import genome as genome_io +from flax_model.alphagenome.io import splicing as splicing_io +from flax_model.alphagenome.model import augmentation +from flax_model.alphagenome.model import model +from flax_model.alphagenome.model import one_hot_encoder +from flax_model.alphagenome.model import splicing +from flax_model.alphagenome.model.interval_scoring import gene_mask as interval_gene_mask +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +from flax_model.alphagenome.model.variant_scoring import center_mask +from flax_model.alphagenome.model.variant_scoring import contact_map +from flax_model.alphagenome.model.variant_scoring import gene_mask +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor +from flax_model.alphagenome.model.variant_scoring import polyadenylation +from flax_model.alphagenome.model.variant_scoring import splice_junction +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import chex +import haiku as hk +import huggingface_hub +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float, Float32, Int32, PyTree, Shaped # pylint: disable=g-importing-member, g-multiple-import +import jmp +import kagglehub +from kagglehub import auth as kaggle_auth +import numpy as np +import orbax.checkpoint as ocp +import pandas as pd + + +AlphaGenomeOutputMetadata: TypeAlias = metadata_lib.AlphaGenomeOutputMetadata +ModelVersion: TypeAlias = dna_model.ModelVersion +Organism: TypeAlias = dna_model.Organism +Output: TypeAlias = dna_output.Output +OutputMetadata: TypeAlias = dna_output.OutputMetadata +OutputType: TypeAlias = dna_output.OutputType +VariantOutput: TypeAlias = dna_output.VariantOutput +Organism: TypeAlias = dna_model.Organism + +BatchPrediction: TypeAlias = PyTree[ + Float[Array, 'B ...'] | Int32[Array, 'B ...'] +] + +ApplyFn = Callable[ + [ + hk.Params, + hk.State, + Float32[Array, 'B S 4'], + Int32[Array, 'B'], + ], + BatchPrediction, +] +JunctionsApplyFn = Callable[ + [ + hk.Params, + hk.State, + Float32[Array, 'B S D'], + Int32[Array, 'B 4 K'], + Int32[Array, 'B'], + ], + BatchPrediction, +] + + +def extract_predictions( + predictions: BatchPrediction, +) -> Mapping[dna_output.OutputType, BatchPrediction]: + """Extracts predictions from the model predictions.""" + results = {} + for output_type in dna_output.OutputType: + match output_type: + case dna_output.OutputType.ATAC: + prediction = predictions.get('atac', {}).get('predictions_1bp') + case dna_output.OutputType.CAGE: + prediction = predictions.get('cage', {}).get('predictions_1bp') + case dna_output.OutputType.DNASE: + prediction = predictions.get('dnase', {}).get('predictions_1bp') + case dna_output.OutputType.RNA_SEQ: + prediction = predictions.get('rna_seq', {}).get('predictions_1bp') + case dna_output.OutputType.CHIP_HISTONE: + prediction = predictions.get('chip_histone', {}).get( + 'predictions_128bp' + ) + case dna_output.OutputType.CHIP_TF: + prediction = predictions.get('chip_tf', {}).get('predictions_128bp') + case dna_output.OutputType.SPLICE_SITES: + prediction = predictions.get('splice_sites_classification', {}).get( + 'predictions' + ) + case dna_output.OutputType.SPLICE_SITE_USAGE: + prediction = predictions.get('splice_sites_usage', {}).get( + 'predictions' + ) + case dna_output.OutputType.SPLICE_JUNCTIONS: + if ( + splice_site_preds := predictions.get('splice_sites_junction') + ) is not None: + prediction = { + 'predictions': splice_site_preds.get('predictions'), + 'splice_site_positions': splice_site_preds.get( + 'splice_site_positions' + ), + } + else: + prediction = None + case dna_output.OutputType.CONTACT_MAPS: + prediction = predictions.get('contact_maps', {}).get('predictions') + case dna_output.OutputType.PROCAP: + prediction = predictions.get('procap', {}).get('predictions_1bp') + case _: + raise ValueError(f'Unsupported output type: {output_type}') + if prediction is not None: + results[output_type] = prediction + return results + + +@typing.jaxtyped +def _predict( + params: hk.Params, + state: hk.State, + sequences: Float32[Array, 'B S 4'], + organism_indices: Int32[Array, 'B'], + *, + strand_reindexing: Mapping[dna_output.OutputType, Int32[Array, '_']], + negative_strand_mask: Bool[Array, 'B'], + apply_fn: ApplyFn, +) -> Mapping[dna_output.OutputType, BatchPrediction]: + """Maps predictions to output types and optionally reverse complements.""" + predictions = apply_fn(params, state, sequences, organism_indices) + predictions = extract_predictions(predictions) + predictions = augmentation.reverse_complement( + predictions, + negative_strand_mask, + strand_reindexing=strand_reindexing, + sequence_length=sequences.shape[1], + ) + return predictions + + +@typing.jaxtyped +def _predict_variant( + params: hk.Params, + state: hk.State, + reference_sequences: Float32[Array, 'B S 4'], + alternate_sequences: Float32[Array, 'B S 4'], + splice_sites: Bool[Array, 'B S 5'] | None, + organism_indices: Int32[Array, 'B'], + strand_reindexing: Mapping[dna_output.OutputType, Int32[Array, '_']], + negative_strand_mask: Bool[Array, 'B'], + *, + apply_fn: ApplyFn, + junctions_apply_fn: JunctionsApplyFn, + num_splice_sites: int, + splice_site_threshold: float, +) -> tuple[ + Mapping[dna_output.OutputType, BatchPrediction], + Mapping[dna_output.OutputType, BatchPrediction], +]: + """Computes and reverse-complements variant predictions.""" + chex.assert_equal_shape([reference_sequences, alternate_sequences]) + sequence_length = reference_sequences.shape[1] + + reference_predictions = apply_fn( + params, + state, + reference_sequences, + organism_indices, + ) + alternate_predictions = apply_fn( + params, + state, + alternate_sequences, + organism_indices, + ) + # Get union of splice site positions across ref and alt. + ref_and_alt_splice_site_positions = splicing.generate_splice_site_positions( + ref=reference_predictions['splice_sites_classification']['predictions'], + alt=alternate_predictions['splice_sites_classification']['predictions'], + splice_sites=splice_sites, + k=num_splice_sites, + pad_to_length=num_splice_sites, + threshold=splice_site_threshold, + ) + reference_predictions['splice_sites_junction'] = junctions_apply_fn( + params, + state, + reference_predictions['embeddings_1bp'], + ref_and_alt_splice_site_positions, + organism_indices, + ) + alternate_predictions['splice_sites_junction'] = junctions_apply_fn( + params, + state, + alternate_predictions['embeddings_1bp'], + ref_and_alt_splice_site_positions, + organism_indices, + ) + + def _extract_and_rc(predictions): + return augmentation.reverse_complement( + extract_predictions(predictions), + negative_strand_mask, + strand_reindexing=strand_reindexing, + sequence_length=sequence_length, + ) + + return ( + _extract_and_rc(reference_predictions), + _extract_and_rc(alternate_predictions), + ) + + +@typing.jaxtyped +def _filter_predictions( + predictions: Mapping[dna_output.OutputType, BatchPrediction], + *, + track_masks: Mapping[dna_output.OutputType, Bool[Array, '_']], +) -> Mapping[dna_output.OutputType, BatchPrediction]: + """Filters predictions by mapping of track masks.""" + result = {} + for output_type, mask in track_masks.items(): + if (prediction := predictions.get(output_type)) is not None: + # JAX dynamic slicing does not work with transfer_guard. + with jax.transfer_guard('allow'): + if output_type == dna_output.OutputType.SPLICE_JUNCTIONS: + result[output_type] = { + 'predictions': prediction['predictions'][ + ..., jnp.tile(mask, reps=2) + ], + 'splice_site_positions': prediction['splice_site_positions'], + } + else: + result[output_type] = prediction[..., mask] + return result + + +@functools.partial(jax.jit, static_argnames=['transfer_to_host']) +@typing.jaxtyped +def _upcast_single_batch_predictions( + x: PyTree[Float[Array, '1 ...'] | Int32[Array, '1 ...']], + *, + transfer_to_host: bool = True, +) -> PyTree[ + Float32[Array | np.ndarray, '...'] | Int32[Array | np.ndarray, '...'] +]: + """Helper to upcast and optionally transfer predictions to host.""" + x = jax.tree.map(lambda x: tensor_utils.upcast_floating(x[0]), x) + # return jax.device_put(x, jax.memory.Space.Host) if transfer_to_host else x + return jax.device_put(x, jax.devices("cpu")[0]) if transfer_to_host else x + + + +@typing.jaxtyped +def _filter_variant_predictions( + reference_predictions: Mapping[dna_output.OutputType, BatchPrediction], + alternate_predictions: Mapping[dna_output.OutputType, BatchPrediction], + *, + track_masks: Mapping[dna_output.OutputType, Bool[Array, '_']], +) -> tuple[ + Mapping[dna_output.OutputType, BatchPrediction], + Mapping[dna_output.OutputType, BatchPrediction], +]: + """Filters variant predictions to a set of output types.""" + return ( + _filter_predictions(reference_predictions, track_masks=track_masks), + _filter_predictions(alternate_predictions, track_masks=track_masks), + ) + + +class _DeviceContextManager: + """Context manager for managing a jax.Device.""" + + def __init__(self, device: jax.Device): + self._device = device + self._lock = threading.Lock() + + def __enter__(self) -> jax.Device: + self._lock.acquire() + return self._device + + def __exit__(self, exc_type, exc_value, traceback): + del exc_type, exc_value, traceback + self._lock.release() + + +class AlphaGenomeModel(dna_model.DnaModel): + """Abstract class for DNA sequence models.""" + + def __init__( + self, + *, + params: hk.Params, + state: hk.State, + apply_fn: ApplyFn, + junctions_apply_fn: JunctionsApplyFn, + metadata: Mapping[dna_model.Organism, AlphaGenomeOutputMetadata], + fasta_extractors: ( + Mapping[dna_model.Organism, fasta.FastaExtractor] | None + ) = None, + splice_site_extractors: ( + Mapping[dna_model.Organism, splicing_io.SpliceSiteAnnotationExtractor] + | None + ) = None, + gtfs: Mapping[dna_model.Organism, pd.DataFrame] | None = None, + pas_gtfs: Mapping[dna_model.Organism, pd.DataFrame] | None = None, + num_splice_sites: int = 512, + splice_site_threshold: float = 0.1, + device: jax.Device | None = None, + ): + """Initializes the AlphaGenomeModel. + + Args: + params: Model parameters. + state: Model state. + apply_fn: A function that takes model parameters, state, DNA sequence and + organism index; and returns the model's predictions. + junctions_apply_fn: A function that takes model parameters, state, + embeddings and splice site positions; and returns the model's junctions + predictions. + metadata: A mapping of organism to OutputMetadata. + fasta_extractors: Optional mapping of organism to FastaExtractor. If not + provided, functions that require sequence extraction will fail. + splice_site_extractors: Optional mapping of organism to + SpliceSiteAnnotationExtractor. If not provided, reference splice sits + will not be used in variant predictions. + gtfs: Optional mapping of organism to GENCODE GTF Pandas dataframe. If not + provided, variant scorers that require GTFs will not be available. + pas_gtfs: Optional mapping of organism to polyadenylation annotation + dataframe. If not provided, variant scorers that require polyadenylation + annotations will not be available. + num_splice_sites: The maximum number of splice sites that are extracted + from the splice site classification predictions. + splice_site_threshold: The threshold to use for splice site prediction. + device: Optional device to use for model prediction. If None, the first + local device will be used. + """ + if device is None: + device = jax.default_device.value or jax.local_devices()[0] + if device.platform not in {'gpu', 'tpu'}: + raise ValueError( + 'Cannot find any GPU or TPU devices. We strondly recommend running' + ' on GPU or TPU, but if you wish to run on CPU, please explicitly' + ' pass the JAX device to run the model.' + ) + self._device_context = _DeviceContextManager(device) + self._params = jax.device_put(params, device) + self._state = jax.device_put(state, device) + self._metadata = metadata + self._one_hot_encoder = one_hot_encoder.DNAOneHotEncoder() + self._fasta_extractors = fasta_extractors or {} + self._splice_site_extractors = splice_site_extractors or {} + + self._predict = jax.jit(functools.partial(_predict, apply_fn=apply_fn)) + self._predict_variant = jax.jit( + functools.partial( + _predict_variant, + apply_fn=jax.jit(apply_fn), + junctions_apply_fn=jax.jit(junctions_apply_fn), + num_splice_sites=num_splice_sites, + splice_site_threshold=splice_site_threshold, + ) + ) + + # Metadata for each organism without padding. + self._output_metadata_by_organism = {} + + gtfs = gtfs or {} + pas_gtfs = pas_gtfs or {} + + for organism, organism_metadata in self._metadata.items(): + masks = jax.tree.map(np.logical_not, organism_metadata.padding) + output_metadata = { + output_type.name.lower(): m[masks[output_type]] + for output_type in dna_output.OutputType + if (m := organism_metadata.get(output_type)) is not None + } + self._output_metadata_by_organism[organism] = dna_output.OutputMetadata( + **output_metadata + ) + + self._variant_scorers = {} + + for organism in metadata.keys(): + self._variant_scorers[organism]: dict[ + variant_scorers_lib.BaseVariantScorer, variant_scoring.VariantScorer + ] = { + variant_scorers_lib.BaseVariantScorer.CENTER_MASK: ( + center_mask.CenterMaskVariantScorer() + ), + variant_scorers_lib.BaseVariantScorer.CONTACT_MAP: ( + contact_map.ContactMapScorer() + ), + } + if (gtf := gtfs.get(organism)) is not None: + gene_scorer = gene_mask.GeneVariantScorer( + gene_mask_extractor=gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, + gene_query_type=( + gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED + ), + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + ), + ) + self._variant_scorers[organism][ + variant_scorers_lib.BaseVariantScorer.GENE_MASK_LFC + ] = gene_scorer + self._variant_scorers[organism][ + variant_scorers_lib.BaseVariantScorer.GENE_MASK_ACTIVE + ] = gene_scorer + self._variant_scorers[organism][ + variant_scorers_lib.BaseVariantScorer.GENE_MASK_SPLICING + ] = gene_scorer + self._variant_scorers[organism][ + variant_scorers_lib.BaseVariantScorer.SPLICE_JUNCTION + ] = splice_junction.SpliceJunctionVariantScorer(gtf) + if (pas_gtf := pas_gtfs.get(organism)) is not None: + self._variant_scorers[organism][ + variant_scorers_lib.BaseVariantScorer.PA_QTL + ] = polyadenylation.PolyadenylationVariantScorer(gtf, pas_gtf) + + self._interval_scorers = {} + + for organism in metadata.keys(): + self._interval_scorers[organism] = {} + if (gtf := gtfs.get(organism)) is not None: + self._interval_scorers[organism][ + interval_scorers_lib.BaseIntervalScorer.GENE_MASK + ] = interval_gene_mask.GeneIntervalScorer( + gene_mask_extractor=gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, + gene_query_type=( + gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED + ), + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + ), + ) + + def _get_fasta_extractor( + self, organism: dna_model.Organism + ) -> fasta.FastaExtractor: + """Returns the FastaExtractor for a given organism.""" + if extractor := self._fasta_extractors.get(organism): + return extractor + else: + raise ValueError(f'FastaExtractor not found for {organism.name=}') + + def predict_sequence( + self, + sequence: str, + *, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + requested_outputs: Iterable[dna_output.OutputType], + ontology_terms: Iterable[ontology.OntologyTerm | str] | None, + interval: genome.Interval | None = None, + ) -> dna_output.Output: + """Predicts the sequence.""" + if ontology_terms is not None: + ontology_terms = set( + ontology.from_curie(o) if isinstance(o, str) else o + for o in ontology_terms + ) + metadata = self._metadata[organism] + track_masks = metadata_lib.create_track_masks( + metadata, + requested_outputs=set(requested_outputs), + requested_ontologies=ontology_terms, + ) + + with self._device_context as device, jax.transfer_guard('disallow'): + organism_index = jax.device_put( + np.full((1,), convert_to_organism_index(organism), dtype=np.int32), + device, + ) + sequence = jax.device_put( + np.asarray(self._one_hot_encoder.encode(sequence))[np.newaxis], device + ) + predictions = self._predict( + self._params, + self._state, + sequence, + organism_index, + negative_strand_mask=jax.device_put(np.asarray([False]), device), + strand_reindexing=jax.device_put(metadata.strand_reindexing, device), + ) + predictions = _filter_predictions( + predictions, track_masks=jax.device_put(track_masks, device) + ) + predictions = _upcast_single_batch_predictions(predictions) + return _construct_output_from_predictions( + predictions, + track_masks=track_masks, + metadata=metadata, + interval=interval, + ) + + def predict_interval( + self, + interval: genome.Interval, + *, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + requested_outputs: Iterable[dna_output.OutputType], + ontology_terms: Iterable[ontology.OntologyTerm | str] | None, + ) -> dna_output.Output: + if ontology_terms is not None: + ontology_terms = set( + ontology.from_curie(o) if isinstance(o, str) else o + for o in ontology_terms + ) + sequence = self._get_fasta_extractor(organism).extract(interval) + metadata = self._metadata[organism] + track_masks = metadata_lib.create_track_masks( + metadata, + requested_outputs=set(requested_outputs), + requested_ontologies=ontology_terms, + ) + + with self._device_context as device, jax.transfer_guard('disallow'): + organism_index = jax.device_put( + np.full((1,), convert_to_organism_index(organism), dtype=np.int32), + device, + ) + sequence = jax.device_put( + np.asarray(self._one_hot_encoder.encode(sequence))[np.newaxis], device + ) + predictions = self._predict( + self._params, + self._state, + sequence, + organism_index, + negative_strand_mask=jax.device_put( + np.asarray([interval.negative_strand]), device + ), + strand_reindexing=jax.device_put(metadata.strand_reindexing, device), + ) + predictions = _filter_predictions( + predictions, track_masks=jax.device_put(track_masks, device) + ) + predictions = _upcast_single_batch_predictions(predictions) + return _construct_output_from_predictions( + predictions, + track_masks=track_masks, + metadata=metadata, + interval=interval, + ) + + def predict_variant( + self, + interval: genome.Interval, + variant: genome.Variant, + *, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + requested_outputs: Iterable[dna_output.OutputType], + ontology_terms: Iterable[ontology.OntologyTerm | str] | None, + ) -> dna_output.VariantOutput: + if ontology_terms is not None: + ontology_terms = set( + ontology.from_curie(o) if isinstance(o, str) else o + for o in ontology_terms + ) + reference_sequence, alternate_sequence = ( + genome_io.extract_variant_sequences( + interval, variant, self._get_fasta_extractor(organism) + ) + ) + metadata = self._metadata[organism] + track_masks = metadata_lib.create_track_masks( + metadata, + requested_outputs=set(requested_outputs), + requested_ontologies=ontology_terms, + ) + splice_sites = None + if splice_site_extractor := self._splice_site_extractors.get(organism): + splice_sites = splice_site_extractor.extract(interval)[np.newaxis] + + with self._device_context as device, jax.transfer_guard('disallow'): + reference_sequence = jax.device_put( + np.asarray(self._one_hot_encoder.encode(reference_sequence))[ + np.newaxis + ], + device, + ) + alternate_sequence = jax.device_put( + np.asarray(self._one_hot_encoder.encode(alternate_sequence))[ + np.newaxis + ], + device, + ) + organism_indices = jax.device_put( + np.full((1,), convert_to_organism_index(organism), dtype=np.int32), + device, + ) + reference_predictions, alt_predictions = self._predict_variant( + self._params, + self._state, + reference_sequence, + alternate_sequence, + jax.device_put(splice_sites, device), + organism_indices, + negative_strand_mask=jax.device_put( + np.asarray([interval.negative_strand]), device + ), + strand_reindexing=jax.device_put(metadata.strand_reindexing, device), + ) + reference_predictions, alt_predictions = _filter_variant_predictions( + reference_predictions, + alt_predictions, + track_masks=jax.device_put(track_masks, device), + ) + reference_predictions, alt_predictions = _upcast_single_batch_predictions( + (reference_predictions, alt_predictions) + ) + + return dna_output.VariantOutput( + reference=_construct_output_from_predictions( + reference_predictions, + track_masks=track_masks, + metadata=metadata, + interval=interval, + ), + alternate=_construct_output_from_predictions( + alt_predictions, + track_masks=track_masks, + metadata=metadata, + interval=interval, + ), + ) + + def score_interval( + self, + interval: genome.Interval, + interval_scorers: Sequence[interval_scorers_lib.IntervalScorerTypes] = (), + *, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + ) -> list[anndata.AnnData]: + if not interval_scorers: + interval_scorers = list( + interval_scorers_lib.RECOMMENDED_INTERVAL_SCORERS.values() + ) + + sequence = self._get_fasta_extractor(organism).extract(interval) + sequence = np.array(self._one_hot_encoder.encode(sequence))[np.newaxis] + organism_indices = np.full( + (1,), convert_to_organism_index(organism), dtype=np.int32 + ) + + requested_outputs = set( + scorer.requested_output for scorer in interval_scorers + ) + + track_metadata = self._metadata[organism] + track_masks = metadata_lib.create_track_masks( + track_metadata, + requested_outputs=requested_outputs, + requested_ontologies=None, + ) + + with self._device_context as device, jax.transfer_guard('disallow'): + predictions = self._predict( + self._params, + self._state, + jax.device_put(sequence, device), + jax.device_put(organism_indices, device), + negative_strand_mask=jax.device_put( + np.asarray([interval.negative_strand]), device + ), + strand_reindexing=jax.device_put( + track_metadata.strand_reindexing, device + ), + ) + predictions = _filter_predictions( + predictions, + track_masks=jax.device_put(track_masks, device), + ) + predictions = _upcast_single_batch_predictions( + predictions, + transfer_to_host=False, + ) + output_metadata = self.output_metadata(organism) + + results = [] + + for scorer_settings in interval_scorers: + scorer = self._interval_scorers[organism][ + scorer_settings.base_interval_scorer + ] + masks, metadata = scorer.get_masks_and_metadata( + interval, + settings=scorer_settings, + track_metadata=output_metadata, + ) + masks = jax.device_put(masks, device) + scores = scorer.score_interval( + predictions, + masks=masks, + settings=scorer_settings, + interval=interval, + ) + result = scorer.finalize_interval( + jax.device_get(scores), + track_metadata=output_metadata, + mask_metadata=metadata, + settings=scorer_settings, + ) + result.uns['interval'] = interval + result.uns['interval_scorer'] = scorer_settings + results.append(result) + + return results + + def score_variant( + self, + interval: genome.Interval, + variant: genome.Variant, + variant_scorers: Sequence[variant_scorers_lib.VariantScorerTypes] = (), + *, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + ) -> list[anndata.AnnData]: + if not variant_scorers: + variant_scorers = variant_scorers_lib.get_recommended_scorers( + organism.to_proto() + ) + for scorer in variant_scorers: + if scorer.base_variant_scorer not in self._variant_scorers[organism]: + raise ValueError( + f"Scorer '{scorer.base_variant_scorer}' is missing for" + f' {organism.name=}. This may be due to a missing variant scorer' + ' metadata.' + ) + reference_sequence, alternate_sequence = ( + genome_io.extract_variant_sequences( + interval, variant, self._get_fasta_extractor(organism) + ) + ) + reference_sequence = np.asarray( + self._one_hot_encoder.encode(reference_sequence) + )[np.newaxis] + alternate_sequence = np.asarray( + self._one_hot_encoder.encode(alternate_sequence) + )[np.newaxis] + organism_indices = np.full( + (1,), convert_to_organism_index(organism), dtype=np.int32 + ) + splice_sites = None + if splice_site_extractor := self._splice_site_extractors.get(organism): + splice_sites = splice_site_extractor.extract(interval)[np.newaxis] + + requested_outputs = set( + scorer.requested_output for scorer in variant_scorers + ) + + track_metadata = self._metadata[organism] + track_masks = metadata_lib.create_track_masks( + track_metadata, + requested_outputs=requested_outputs, + requested_ontologies=None, + ) + + with self._device_context as device, jax.transfer_guard('disallow'): + + reference_predictions, alternate_predictions = self._predict_variant( + self._params, + self._state, + jax.device_put(reference_sequence, device), + jax.device_put(alternate_sequence, device), + jax.device_put(splice_sites, device), + jax.device_put(organism_indices, device), + negative_strand_mask=jax.device_put( + np.asarray([interval.negative_strand]), device + ), + strand_reindexing=jax.device_put( + track_metadata.strand_reindexing, device + ), + ) + reference_predictions, alternate_predictions = ( + _filter_variant_predictions( + reference_predictions, + alternate_predictions, + track_masks=jax.device_put(track_masks, device), + ) + ) + reference_predictions, alternate_predictions = ( + _upcast_single_batch_predictions( + (reference_predictions, alternate_predictions), + transfer_to_host=False, + ) + ) + output_metadata = self.output_metadata(organism) + + results = [] + + for scorer_settings in variant_scorers: + scorer = self._variant_scorers[organism][ + scorer_settings.base_variant_scorer + ] + masks, metadata = scorer.get_masks_and_metadata( + interval, + variant, + settings=scorer_settings, + track_metadata=output_metadata, + ) + masks = jax.device_put(masks, device) + scores = scorer.score_variant( + reference_predictions, + alternate_predictions, + masks=masks, + settings=scorer_settings, + variant=variant, + interval=interval, + ) + result = scorer.finalize_variant( + jax.device_get(scores), + track_metadata=output_metadata, + mask_metadata=metadata, + settings=scorer_settings, + ) + result.uns['interval'] = interval + result.uns['variant'] = variant + result.uns['variant_scorer'] = scorer_settings + results.append(result) + + return results + + def score_ism_variants( + self, + interval: genome.Interval, + ism_interval: genome.Interval, + variant_scorers: Sequence[variant_scorers_lib.VariantScorerTypes] = (), + *, + organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS, + interval_variant: genome.Variant | None = None, + ) -> list[list[anndata.AnnData]]: + """Generate in-silico mutagenesis (ISM) variant scores for a given interval. + + Args: + interval: DNA interval to make the prediction for. + ism_interval: Interval to perform ISM. + variant_scorers: Sequence of variant scorers to use for scoring each + variant. If no variant scorers are provided, the recommended variant + scorers for the organism will be used. + organism: Organism to use for the prediction. + interval_variant: Optional variant to apply to the sequence. If provided, + the alternate allele is used for in-silico mutagenesis, otherwise the + unaltered reference sequence is used. + + Returns: + List of variant scores for each variant in the ISM interval. + """ + extractor = self._get_fasta_extractor(organism) + if interval_variant is not None: + _, sequence = genome_io.extract_variant_sequences( + interval, interval_variant, extractor + ) + else: + sequence = extractor.extract(interval) + + interval_slice = interval.intersect(ism_interval) + if interval_slice is None: + raise ValueError(f'{ism_interval=} not fully contained in {interval=}.') + start = interval_slice.start - interval.start + end = interval_slice.end - interval.start + ism_sequence = sequence[start:end] + + variants = ism.ism_variants(ism_interval, ism_sequence) + return self.score_variants( + interval, variants, variant_scorers, organism=organism + ) + + def output_metadata( + self, organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS + ) -> dna_output.OutputMetadata: + """Get the metadata for a given organism. + + Args: + organism: Organism to get metadata for. + + Returns: + OutputMetadata for the provided organism. + """ + return self._output_metadata_by_organism[organism] + + +@typing.jaxtyped +def _construct_output_from_predictions( + predictions: Mapping[ + dna_output.OutputType, + PyTree[Float[Array, '...'] | Int32[Array, '...']], + ], + *, + track_masks: Mapping[dna_output.OutputType, Bool[np.ndarray, '_']], + metadata: AlphaGenomeOutputMetadata, + interval: genome.Interval | None = None, +) -> dna_output.Output: + """Returns a dna_output.Output from model predictions with data on CPU.""" + + def _convert_to_track_data( + output_type: dna_output.OutputType, + ) -> track_data.TrackData | None: + track_metadata = metadata.get(output_type) + prediction = predictions.get(output_type) + if prediction is None or track_metadata is None: + # No tracks are predicted for this head. + return None + return track_data.TrackData( + values=jax.device_get(prediction), + resolution=metadata.resolution(output_type), + metadata=track_metadata[track_masks[output_type]], + interval=interval, + ) + + def _convert_to_junction_data() -> junction_data.JunctionData | None: + """Returns a splice junction prediction.""" + output_type = dna_output.OutputType.SPLICE_JUNCTIONS + junction_metadata = metadata.get(output_type) + splice_junction_predictions = predictions.get(output_type) + if junction_metadata is None or splice_junction_predictions is None: + return None + splice_junctions = splice_junction_predictions['predictions'] + splice_site_positions = splice_junction_predictions['splice_site_positions'] + + junction_predictions, strands, starts, ends = ( + splice_junction.unstack_junction_predictions( + jax.device_get(splice_junctions), + jax.device_get(splice_site_positions), + interval, + ) + ) + chromosome = interval.chromosome if interval is not None else None + junctions = [ + genome.Junction(chromosome, start, end, strand) + for start, end, strand in zip(starts, ends, strands) + if start < end + ] + return junction_data.JunctionData( + junctions=np.asarray(junctions), + values=junction_predictions, + metadata=junction_metadata[track_masks[output_type]], + interval=interval, + ) + + return dna_output.Output( + atac=_convert_to_track_data(dna_output.OutputType.ATAC), + dnase=_convert_to_track_data(dna_output.OutputType.DNASE), + procap=_convert_to_track_data(dna_output.OutputType.PROCAP), + cage=_convert_to_track_data(dna_output.OutputType.CAGE), + rna_seq=_convert_to_track_data(dna_output.OutputType.RNA_SEQ), + chip_histone=_convert_to_track_data(dna_output.OutputType.CHIP_HISTONE), + chip_tf=_convert_to_track_data(dna_output.OutputType.CHIP_TF), + contact_maps=_convert_to_track_data(dna_output.OutputType.CONTACT_MAPS), + splice_sites=_convert_to_track_data(dna_output.OutputType.SPLICE_SITES), + splice_site_usage=_convert_to_track_data( + dna_output.OutputType.SPLICE_SITE_USAGE + ), + splice_junctions=_convert_to_junction_data(), + ) + + +def convert_to_organism_index( + organism: dna_model.Organism, +) -> int: + """Converts a dna_model.Organism to a organism index.""" + match organism: + case dna_model.Organism.HOMO_SAPIENS: + return 0 + case dna_model.Organism.MUS_MUSCULUS: + return 1 + case _: + raise ValueError(f'Unsupported organism: {organism}') + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class ModelSettings: + """Settings for the AlphaGenomeModel.""" + + # The maximum number of splice sites that are extracted from the splice site + # classification predictions. + num_splice_sites: int = 512 + # The threshold to use for splice site prediction. + splice_site_threshold: float = 0.1 + + +@dataclasses.dataclass(frozen=True, kw_only=True) +class OrganismSettings: + """Settings for a specific organism.""" + + # Optional output metadata. If None, we load the default AlphaGenome metadata + # for the organism. + metadata: AlphaGenomeOutputMetadata | None = None + + # Optional paths to the reference genome and annotation data. If None, + # functions that accept intervals or variants will fail. + fasta_path: str | os.PathLike[str] | None = None + + # Optional paths to the reference annotation data. If None, variant scorers + # that require a GTF will not be available. + gtf_feather_path: str | os.PathLike[str] | None = None + + # Optional path to reference polyadenylation annotation data. If None, + # variant scorers that require a PAS GTF will not be available. + pas_feather_path: str | os.PathLike[str] | None = None + + # Optional paths to the reference splice site data. If None, no reference + # splice sites will be used during variant predictions. + splice_site_starts_feather_path: str | os.PathLike[str] | None = None + splice_site_ends_feather_path: str | os.PathLike[str] | None = None + + +def default_organism_settings() -> ( + Mapping[dna_model.Organism, OrganismSettings] +): + """Returns the default organism settings for the AlphaGenomeModel.""" + return { + dna_model.Organism.HOMO_SAPIENS: OrganismSettings( + fasta_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'hg38/GRCh38.p13.genome.fa' + ), + gtf_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'hg38/gencode.v46.annotation.gtf.gz.feather' + ), + pas_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/exon/hg38/' + 'polyadb_human_v3_exon3_contiguous_gtfv46.feather' + ), + splice_site_starts_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'hg38/gencode.v46.splice_sites_starts.feather' + ), + splice_site_ends_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'hg38/gencode.v46.splice_sites_ends.feather' + ), + ), + dna_model.Organism.MUS_MUSCULUS: OrganismSettings( + fasta_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'mm10/GRCm38.p6.genome.fa' + ), + gtf_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'mm10/gencode.vM23.annotation.gtf.gz.feather' + ), + pas_feather_path=None, + splice_site_starts_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'mm10/gencode.vM23.splice_sites_starts.feather' + ), + splice_site_ends_feather_path=( + 'https://storage.googleapis.com/alphagenome/reference/gencode/' + 'mm10/gencode.vM23.splice_sites_ends.feather' + ), + ), + } + + +@typing.jaxtyped +def create_model( + metadata: Mapping[dna_model.Organism, AlphaGenomeOutputMetadata], + *, + num_splice_sites: int = model.DEFAULT_NUM_SPLICE_SITES, + splice_site_threshold: float = model.DEFAULT_SPLICE_SITE_THRESHOLD, +) -> tuple[ + Callable[ + [chex.PRNGKey, Float[Array, 'B S 4'], Int32[Array, 'B']], + tuple[hk.Params, hk.State], + ], + ApplyFn, + JunctionsApplyFn, +]: + """Helper to create AlphaGenome init and two apply functions.""" + + jmp_policy = jmp.get_policy('params=float32,compute=bfloat16,output=bfloat16') + + @hk.transform_with_state + def _forward( + dna_sequence: Float[Array, 'B S 4'], + organism_index: Int32[Array, 'B'], + ): + """AlphaGenome default forward pass.""" + with hk.mixed_precision.push_policy(model.AlphaGenome, jmp_policy): + return model.AlphaGenome( + metadata, + num_splice_sites=num_splice_sites, + splice_site_threshold=splice_site_threshold, + )(dna_sequence, organism_index) + + def _apply_fn( + params: hk.Params, + state: hk.State, + dna_sequence: Float[Array, 'B S 4'], + organism_index: Int32[Array, 'B'], + ) -> PyTree[Shaped[Array, 'B ...']]: + """AlphaGenome default apply function.""" + (predictions, _), _ = _forward.apply( + params, state, None, dna_sequence, organism_index + ) + return predictions + + def _junctions_apply_fn( + params: hk.Params, + state: hk.State, + trunk_embeddings: Float[Array, 'B S D'], + splice_site_positions: Int32[Array, 'B 4 K'], + organism_index: Int32[Array, 'B'], + ): + """AlphaGenome junctions apply function.""" + + @hk.transform_with_state + def _forward_junctions( + trunk_embeddings, splice_site_positions, organism_index + ): + with hk.mixed_precision.push_policy(model.AlphaGenome, jmp_policy): + return model.AlphaGenome( + metadata, + num_splice_sites=num_splice_sites, + splice_site_threshold=splice_site_threshold, + ).predict_junctions( + trunk_embeddings, splice_site_positions, organism_index + ) + + predictions, _ = _forward_junctions.apply( + params, + state, + None, + trunk_embeddings, + splice_site_positions, + organism_index, + ) + return predictions + + return _forward.init, _apply_fn, _junctions_apply_fn + + +def create( + checkpoint_path: str | os.PathLike[str], + *, + organism_settings: ( + Mapping[dna_model.Organism, OrganismSettings] | None + ) = None, + model_settings: ModelSettings = ModelSettings(), + device: jax.Device | None = None, +) -> AlphaGenomeModel: + """Returns a AlphaGenomeModel from a checkpoint stored at the given path. + + Args: + checkpoint_path: Path to the checkpoint to load. + organism_settings: Optional organism settings to use. If not set, will use + default organism settings. + model_settings: Settings for the model. If not set, will use default model + settings. + device: Optional device to use for model prediction. If None, the first + local device will be used. + """ + if organism_settings is None: + organism_settings = default_organism_settings() + + metadata = {} + fasta_extractors = {} + splice_site_extractors = {} + gtfs = {} + pas_gtfs = {} + validate_checkpoint = True + + for organism, settings in organism_settings.items(): + if settings.metadata is not None: + metadata[organism] = settings.metadata + validate_checkpoint = False + else: + metadata[organism] = metadata_lib.load(organism) + + if settings.fasta_path is not None: + fasta_extractors[organism] = fasta.FastaExtractor(settings.fasta_path) + if settings.gtf_feather_path is not None: + gtfs[organism] = pd.read_feather(settings.gtf_feather_path) + if settings.pas_feather_path is not None: + pas_gtfs[organism] = pd.read_feather(settings.pas_feather_path) + if settings.splice_site_starts_feather_path is not None: + splice_site_extractors[organism] = ( + splicing_io.SpliceSiteAnnotationExtractor( + junction_starts=pd.read_feather( + settings.splice_site_starts_feather_path + ), + junction_ends=pd.read_feather( + settings.splice_site_ends_feather_path + ), + ) + ) + + init_fn, apply_fn, junctions_apply_fn = create_model( + metadata, + num_splice_sites=model_settings.num_splice_sites, + splice_site_threshold=model_settings.splice_site_threshold, + ) + + dna_sequence_shape = jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32) + organism_index_shape = jax.ShapeDtypeStruct((1,), dtype=jnp.int32) + target_shapes = jax.eval_shape( + init_fn, jax.random.PRNGKey(0), dna_sequence_shape, organism_index_shape + ) + checkpointer = ocp.StandardCheckpointer() + params, state = checkpointer.restore( + checkpoint_path, + target=target_shapes if validate_checkpoint else None, + strict=validate_checkpoint, + ) + + return AlphaGenomeModel( + params=params, + state=state, + apply_fn=apply_fn, + junctions_apply_fn=junctions_apply_fn, + metadata=metadata, + fasta_extractors=fasta_extractors, + splice_site_extractors=splice_site_extractors, + gtfs=gtfs, + pas_gtfs=pas_gtfs, + num_splice_sites=model_settings.num_splice_sites, + splice_site_threshold=model_settings.splice_site_threshold, + device=device, + ) + + +def create_from_kaggle( + model_version: str | ModelVersion, + *, + organism_settings: ( + Mapping[dna_model.Organism, OrganismSettings] | None + ) = None, + device: jax.Device | None = None, +) -> AlphaGenomeModel: + """Helper function to create a model from Kaggle. + + Args: + model_version: The model version to use, e.g. all_folds. + organism_settings: Optional organism settings to use. If unset, will use + default organism settings. + device: Optional device to use for model prediction. If None, the first + local device will be used. + + Returns: + AlphaGenomeModel created from the Kaggle checkpoint. + """ + if kaggle_auth.get_username() is None: + kagglehub.login() + + if isinstance(model_version, ModelVersion): + model_version = model_version.name + + checkpoint_path = kagglehub.model_download( + f'google/alphagenome/jax/{model_version.lower()}' + ) + return create( + checkpoint_path, organism_settings=organism_settings, device=device + ) + + +def create_from_huggingface( + model_version: str | ModelVersion, + *, + organism_settings: ( + Mapping[dna_model.Organism, OrganismSettings] | None + ) = None, + device: jax.Device | None = None, +) -> AlphaGenomeModel: + """Helper function to create a DNA model from HuggingFace. + + Args: + model_version: The model version to use, e.g. all_folds. + organism_settings: Optional organism settings to use. If unset, will use + default organism settings. + device: Optional device to use for model prediction. If None, the first + local device will be used. + + Returns: + AlphaGenomeModel created from the Hugging Face checkpoint. + """ + + try: + huggingface_hub.whoami() + except huggingface_hub.errors.LocalTokenNotFoundError: + huggingface_hub.login() + + if isinstance(model_version, ModelVersion): + model_version = model_version.name + + checkpoint_path = huggingface_hub.snapshot_download( + repo_id=f'google/alphagenome-{model_version.replace("_", "-").lower()}' + ) + return create( + checkpoint_path, organism_settings=organism_settings, device=device + ) diff --git a/flax_model/alphagenome/model/dna_model_test.py b/flax_model/alphagenome/model/dna_model_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f1b23a5c1548bc530ea18582d51836ca5a14de --- /dev/null +++ b/flax_model/alphagenome/model/dna_model_test.py @@ -0,0 +1,872 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import pathlib +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import ontology +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import interval_scorers +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.io import fasta +from flax_model.alphagenome.io import splicing +from flax_model.alphagenome.model import dna_model +from flax_model.alphagenome.model.metadata import metadata +import chex +import huggingface_hub +import jax +import jax.numpy as jnp +import kagglehub +from kagglehub import auth as kaggle_auth +import numpy as np +import orbax.checkpoint as ocp +import pandas as pd + + +MOCK_SHAPES = ({}, {}) + + +def _create_mock_gtf() -> pd.DataFrame: + return pd.DataFrame({ + 'Chromosome': 'chr1', + 'Start': [101, 101, 102, 103, 0, 0, 0, 80], + 'End': [200, 200, 200, 200, 108, 108, 40, 108], + 'Strand': ['+', '+', '+', '+', '-', '-', '-', '-'], + 'transcript_id': [None, 'T1', 'T2', 'T2', None, 'T4', 'T4', 'T4'], + 'gene_id': ['G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2'], + 'Feature': [ + 'gene', + 'transcript', + 'transcript', + 'exon', + 'gene', + 'transcript', + 'exon', + 'exon', + ], + 'gene_type': 'protein_coding', + 'gene_name': 'GX_name', + 'transcript_type': 'protein_coding', + }) + + +def _create_mock_splice_sites() -> tuple[pd.DataFrame, pd.DataFrame]: + return pd.DataFrame( + {'Chromosome': 'chr1', 'Start': [40], 'Strand': ['-'], 'Tissue_0': [1]} + ), pd.DataFrame( + {'Chromosome': 'chr1', 'End': [80], 'Strand': ['-'], 'Tissue_0': [1]} + ) + + +def _create_polya_df_gtf() -> pd.DataFrame: + return pd.DataFrame({ + 'End': [103, 104, 1, 81], + 'Start': [102, 103, 0, 80], + 'cutmode': [102, 103, 0, 80], + 'pas_strand': ['+', '+', '-', '-'], + 'pas_id': ['P1', 'P2', 'P3', 'P4'], + 'gene_id': ['G1', 'G1', 'G2', 'G2'], + 'pas_gene_id': ['G1', 'G1', 'G2', 'G2'], + 'Chromosome': 'chr1', + }) + + +def _get_test_fasta_path() -> str | os.PathLike[str]: + root_dir = pathlib.Path(__file__).parent.parent + return root_dir / 'io' / 'testdata' / 'example.fa' + + +class DnaModelTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + + self._num_tissues = 10 + self._num_splice_sites = 100 + self._metadata = metadata.AlphaGenomeOutputMetadata( + atac=pd.DataFrame({ + 'name': ['atac1', 'atac1'], + 'strand': ['+', '-'], + 'ontology_curie': ['CL:0000001', 'CL:0000001'], + 'nonzero_mean': [1.0, 1.0], + }), + dnase=pd.DataFrame({ + 'name': ['acc_1'], + 'strand': ['.'], + 'ontology_curie': ['UBERON:0000001'], + 'nonzero_mean': [1.0], + }), + contact_maps=pd.DataFrame({ + 'name': ['hic_1', 'hic_2'], + 'ontology_curie': ['UBERON:0000001', 'UBERON:0000002'], + 'strand': '.', + }), + splice_sites=pd.DataFrame({ + 'name': ['donor', 'acceptor', 'donor', 'acceptor', 'padding'], + 'strand': ['+', '+', '-', '-', '.'], + }), + splice_junctions=pd.DataFrame({ + 'name': ( + [f'tissue_{i}' for i in range(self._num_tissues)] + + ['Padding'] * 2 + ), + 'ontology_curie': ['UBERON:0000001'] * (self._num_tissues + 2), + }), + chip_tf=pd.DataFrame({ + 'name': ['chip_1', 'chip_2'], + 'strand': ['+', '-'], + 'ontology_curie': 'UBERON:0000001', + 'nonzero_mean': 1.0, + }), + ) + + def _apply_fn(params, state, dna_sequence, organism_index): + del params, state, organism_index + batch_size, sequence_length = dna_sequence.shape[0], dna_sequence.shape[1] + splice_site_positions = ( + np.ones((batch_size, 4, self._num_splice_sites), dtype=np.int32) * -1 + ) + splice_site_positions[:, 0, 0] = 100 # pos donor + splice_site_positions[:, 1, 0] = 200 # pos acceptor + splice_site_positions[:, 2, 0] = 300 # neg donor + splice_site_positions[:, 3, 0] = 50 # neg acceptor + return { + 'atac': { + 'predictions_1bp': jnp.zeros( + (batch_size, sequence_length, len(self._metadata.atac)), + dtype=jnp.bfloat16, + ) + }, + 'dnase': { + 'predictions_1bp': jnp.zeros( + (batch_size, sequence_length, len(self._metadata.dnase)) + ) + }, + 'contact_maps': { + 'predictions': jnp.zeros(( + batch_size, + sequence_length // 2048, + sequence_length // 2048, + len(self._metadata.contact_maps), + )) + }, + 'splice_sites_classification': { + 'predictions': jnp.ones( + ( + batch_size, + sequence_length, + 5, + ), + dtype=jnp.bfloat16, + ), + }, + 'splice_sites_junction': { + 'predictions': jnp.ones( + ( + batch_size, + self._num_splice_sites, + self._num_splice_sites, + 2 * self._num_tissues + 4, # Add 4 to mimic padding. + ), + dtype=jnp.bfloat16, + ), + 'splice_site_positions': jnp.array(splice_site_positions), + }, + 'embeddings_1bp': jnp.zeros( + (batch_size, sequence_length, 1536), dtype=jnp.bfloat16 + ), + 'chip_tf': { + 'predictions_128bp': jnp.zeros( + (batch_size, sequence_length // 128, 2), dtype=jnp.bfloat16 + ) + }, + } + + self._mock_model = _apply_fn + + def _apply_fn_junctions( + params, state, trunk_embeddings, splice_site_positions, organism_index + ): + del params, state, trunk_embeddings, organism_index + batch_size, _, num_splice_sites = splice_site_positions.shape + return { + 'predictions': jnp.ones( + ( + batch_size, + num_splice_sites, + num_splice_sites, + 2 * self._num_tissues + 4, # Add 4 to mimic padding. + ), + dtype=jnp.bfloat16, + ), + 'splice_site_positions': jnp.array(splice_site_positions), + } + + self._mock_model_junctions = _apply_fn_junctions + + @parameterized.parameters([ + dict(organism=dna_model.Organism.HOMO_SAPIENS, expected_index=0), + dict(organism=dna_model.Organism.MUS_MUSCULUS, expected_index=1), + ]) + def test_convert_to_organism_index(self, organism, expected_index): + self.assertEqual( + dna_model.convert_to_organism_index(organism), + expected_index, + ) + + @parameterized.parameters([ + dict( + requested_outputs=[ + dna_output.OutputType.ATAC, + dna_output.OutputType.DNASE, + ], + requested_ontologies=None, + expected_shapes={ + dna_output.OutputType.ATAC: (65_536, 2), + dna_output.OutputType.DNASE: (65_536, 1), + }, + ), + dict( + requested_outputs=[ + dna_output.OutputType.ATAC, + dna_output.OutputType.DNASE, + ], + requested_ontologies=[ontology.from_curie('CL:0000001')], + expected_shapes={ + dna_output.OutputType.ATAC: (65_536, 2), + dna_output.OutputType.DNASE: (65_536, 0), + }, + ), + ]) + def test_predict_sequence( + self, requested_outputs, requested_ontologies, expected_shapes + ): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + device=jax.local_devices()[0], + ) + seq = 'ATGC' * int(2**14) + predictions = model.predict_sequence( + seq, + requested_outputs=requested_outputs, + ontology_terms=requested_ontologies, + ) + for output_type, expected_shape in expected_shapes.items(): + output = predictions.get(output_type) + self.assertIsNotNone(output) + chex.assert_shape(output.values, expected_shape) + + @parameterized.parameters([ + dict( + requested_outputs=[dna_output.OutputType.ATAC], + requested_ontologies=None, + expected_shapes={dna_output.OutputType.ATAC: (2048, 2)}, + ), + dict( + requested_outputs=[dna_output.OutputType.DNASE], + requested_ontologies=[ontology.from_curie('UBERON:0000001')], + expected_shapes={dna_output.OutputType.DNASE: (2048, 1)}, + ), + ]) + def test_predict_interval( + self, requested_outputs, requested_ontologies, expected_shapes + ): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + device=jax.local_devices()[0], + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + output = model.predict_interval( + interval, + requested_outputs=requested_outputs, + ontology_terms=requested_ontologies, + ) + for output_type, expected_shape in expected_shapes.items(): + output = output.get(output_type) + self.assertIsNotNone(output) + chex.assert_shape(output.values, expected_shape) + + def test_predict_interval_with_splicing(self): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + device=jax.local_devices()[0], + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + output = model.predict_interval( + interval, + requested_outputs=[ + dna_output.OutputType.ATAC, + dna_output.OutputType.SPLICE_JUNCTIONS, + ], + ontology_terms=None, + ) + atac_output = output.atac + self.assertIsNotNone(atac_output) + chex.assert_shape(atac_output.values, (interval.width, 2)) + + splice_junctions_output = output.splice_junctions + self.assertIsNotNone(splice_junctions_output) + self.assertLen(splice_junctions_output.junctions, 2) + chex.assert_shape(splice_junctions_output.values, (2, self._num_tissues)) + self.assertEqual( + splice_junctions_output.junctions[0], + genome.Junction('chr1', 101, 200, '+'), + ) + self.assertEqual( + splice_junctions_output.junctions[1], + genome.Junction('chr1', 51, 300, '-'), + ) + + def test_predict_interval_missing_fasta_raises_error(self): + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + device=jax.local_devices()[0], + ) + with self.assertRaisesRegex( + ValueError, "FastaExtractor not found for organism.name='HOMO_SAPIENS'" + ): + model.predict_interval( + genome.Interval.from_str('chr1:0-2048:.'), + requested_outputs=[dna_output.OutputType.ATAC], + ontology_terms=None, + ) + + @parameterized.parameters([ + dict( + requested_outputs=[ + dna_output.OutputType.ATAC, + dna_output.OutputType.DNASE, + ], + requested_ontologies=None, + expected_shapes={ + dna_output.OutputType.ATAC: (2048, 2), + dna_output.OutputType.DNASE: (2048, 1), + }, + ), + dict( + requested_outputs=[ + dna_output.OutputType.ATAC, + dna_output.OutputType.DNASE, + ], + requested_ontologies=[ontology.from_curie('CL:0000001')], + expected_shapes={ + dna_output.OutputType.ATAC: (2048, 2), + dna_output.OutputType.DNASE: (2048, 0), + }, + ), + ]) + def test_predict_variant( + self, requested_outputs, requested_ontologies, expected_shapes + ): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + + mock_splice_sites_extractor = mock.create_autospec( + splicing.SpliceSiteAnnotationExtractor, instance=True + ) + mock_splice_sites_extractor.extract.side_effect = lambda x: np.zeros( + (x.width, 5), dtype=bool + ) + + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + device=jax.local_devices()[0], + splice_site_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_splice_sites_extractor + }, + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + predictions = model.predict_variant( + interval, + variant=genome.Variant.from_str('chr1:1024:A>C'), + requested_outputs=requested_outputs, + ontology_terms=requested_ontologies, + ) + for output_type, expected_shape in expected_shapes.items(): + output = predictions.reference.get(output_type) + self.assertIsNotNone(output) + chex.assert_shape(output.values, expected_shape) + for output_type, expected_shape in expected_shapes.items(): + output = predictions.alternate.get(output_type) + self.assertIsNotNone(output) + chex.assert_shape(output.values, expected_shape) + + def test_score_variant(self): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + + mock_splice_sites_extractor = mock.create_autospec( + splicing.SpliceSiteAnnotationExtractor, instance=True + ) + mock_splice_sites_extractor.extract.side_effect = lambda x: np.zeros( + (x.width, 5), dtype=bool + ) + + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()}, + device=jax.local_devices()[0], + splice_site_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_splice_sites_extractor + }, + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + variant = genome.Variant.from_str('chr1:1024:A>C') + scorers = [ + variant_scorers.CenterMaskScorer( + aggregation_type=variant_scorers.AggregationType.DIFF_MEAN, + requested_output=dna_output.OutputType.ATAC, + width=501, + ), + variant_scorers.CenterMaskScorer( + requested_output=dna_output.OutputType.CHIP_TF, + width=501, + aggregation_type=variant_scorers.AggregationType.DIFF_LOG2_SUM, + ), + variant_scorers.ContactMapScorer(), + variant_scorers.GeneMaskLFCScorer( + requested_output=dna_output.OutputType.ATAC + ), + variant_scorers.SpliceJunctionScorer(), + ] + output = model.score_variant(interval, variant, variant_scorers=scorers) + self.assertLen(output, len(scorers)) + for result, scorer in zip(output, scorers): + self.assertEqual(result.uns['interval'], interval) + self.assertEqual(result.uns['variant'], variant) + self.assertEqual(result.uns['variant_scorer'], scorer) + + df = variant_scorers.tidy_scores(output) + self.assertCountEqual( + [ + 'variant_id', + 'scored_interval', + 'gene_id', + 'gene_name', + 'gene_type', + 'gene_strand', + 'junction_Start', + 'junction_End', + 'output_type', + 'variant_scorer', + 'track_name', + 'track_strand', + 'ontology_curie', + 'raw_score', + ], + df.columns, + ) + + def test_missing_gtf_raises_scorer_missing_error(self): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + device=jax.local_devices()[0], + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + variant = genome.Variant.from_str('chr1:1024:A>C') + scorers = [ + variant_scorers.GeneMaskLFCScorer( + requested_output=dna_output.OutputType.ATAC + ) + ] + with self.assertRaisesRegex( + ValueError, "Scorer 'BaseVariantScorer.GENE_MASK_LFC' is missing" + ): + model.score_variant(interval, variant, variant_scorers=scorers) + + def test_missing_pas_raises_scorer_missing_error(self): + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()}, + device=jax.local_devices()[0], + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + variant = genome.Variant.from_str('chr1:1024:A>C') + scorers = [variant_scorers.PolyadenylationScorer()] + with self.assertRaisesRegex( + ValueError, "Scorer 'BaseVariantScorer.PA_QTL' is missing" + ): + model.score_variant(interval, variant, variant_scorers=scorers) + + def test_score_interval(self): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()}, + device=jax.local_devices()[0], + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + scorers = [ + interval_scorers.GeneMaskScorer( + aggregation_type=interval_scorers.IntervalAggregationType.MEAN, + requested_output=dna_output.OutputType.ATAC, + width=501, + ) + ] + output = model.score_interval(interval, interval_scorers=scorers) + self.assertLen(output, len(scorers)) + for result, scorer in zip(output, scorers): + self.assertEqual(result.uns['interval'], interval) + self.assertEqual(result.uns['interval_scorer'], scorer) + + @parameterized.parameters([ + dict( + ism_interval=genome.Interval.from_str('chr1:10-11:.'), + interval_variant=None, + expected_variants=[ + genome.Variant('chr1', 11, 'A', 'C'), + genome.Variant('chr1', 11, 'A', 'G'), + genome.Variant('chr1', 11, 'A', 'T'), + ], + ), + dict( + ism_interval=genome.Interval.from_str('chr1:10-11:.'), + interval_variant=genome.Variant.from_str('chr1:11:A>C'), + expected_variants=[ + genome.Variant('chr1', 11, 'C', 'A'), + genome.Variant('chr1', 11, 'C', 'G'), + genome.Variant('chr1', 11, 'C', 'T'), + ], + ), + ]) + def test_score_ism_variants( + self, + ism_interval: genome.Interval, + interval_variant: genome.Variant | None, + expected_variants: list[genome.Variant], + ): + mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor) + mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width + + mock_splice_sites_extractor = mock.create_autospec( + splicing.SpliceSiteAnnotationExtractor, instance=True + ) + mock_splice_sites_extractor.extract.side_effect = lambda x: np.zeros( + (x.width, 5), dtype=bool + ) + + model = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata}, + fasta_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor + }, + gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()}, + pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()}, + device=jax.local_devices()[0], + splice_site_extractors={ + dna_model.Organism.HOMO_SAPIENS: mock_splice_sites_extractor + }, + ) + interval = genome.Interval.from_str('chr1:0-2048:.') + + scores = model.score_ism_variants( + interval, + ism_interval, + interval_variant=interval_variant, + variant_scorers=[ + variant_scorers.CenterMaskScorer( + aggregation_type=variant_scorers.AggregationType.DIFF_MEAN, + requested_output=dna_output.OutputType.ATAC, + width=501, + ) + ], + ) + scores = sorted(scores, key=lambda x: str(x[0].uns['variant'])) + self.assertLen(scores, len(expected_variants)) + for expected, scores in zip(expected_variants, scores, strict=True): + self.assertEqual(expected, scores[0].uns['variant']) + + @parameterized.parameters( + dict(model_metadata=None), + dict( + model_metadata=metadata.AlphaGenomeOutputMetadata( + atac=metadata.load(dna_model.Organism.HOMO_SAPIENS).atac, + dnase=metadata.load(dna_model.Organism.HOMO_SAPIENS).dnase, + ) + ), + ) + def test_create( + self, model_metadata: metadata.AlphaGenomeOutputMetadata | None + ): + init_fn, _, _ = dna_model.create_model( + {o: metadata.load(o) for o in dna_model.Organism} + ) + params, state = jax.jit(init_fn)( + jax.random.PRNGKey(0), + jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32), + jax.ShapeDtypeStruct((1,), dtype=jnp.int32), + ) + checkpointer = ocp.StandardCheckpointer() + checkpoint_dir = os.path.join(self.create_tempdir().full_path, 'ckpt') + checkpointer.save(checkpoint_dir, (params, state)) + gtf_path = os.path.join(self.create_tempdir().full_path, 'hg38.feather') + _create_mock_gtf().to_feather(gtf_path) + polya_gtf_path = os.path.join( + self.create_tempdir().full_path, 'polya_gtf.feather' + ) + _create_polya_df_gtf().to_feather(polya_gtf_path) + splice_starts, splice_ends = _create_mock_splice_sites() + splice_starts_path = os.path.join( + self.create_tempdir().full_path, 'splice_starts.feather' + ) + splice_ends_path = os.path.join( + self.create_tempdir().full_path, 'splice_ends.feather' + ) + splice_starts.to_feather(splice_starts_path) + splice_ends.to_feather(splice_ends_path) + checkpointer.wait_until_finished() + + model = dna_model.create( + checkpoint_dir, + organism_settings={ + dna_model.Organism.HOMO_SAPIENS: dna_model.OrganismSettings( + fasta_path=_get_test_fasta_path(), + gtf_feather_path=gtf_path, + pas_feather_path=polya_gtf_path, + splice_site_starts_feather_path=splice_starts_path, + splice_site_ends_feather_path=splice_ends_path, + metadata=model_metadata, + ) + }, + device=jax.local_devices()[0], + ) + self.assertIsInstance(model, dna_model.AlphaGenomeModel) + + def test_default_organism_settings(self): + organism_settings = dna_model.default_organism_settings() + self.assertContainsSubset( + [ + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ], + organism_settings.keys(), + ) + + def test_create_model(self): + init, apply, apply_junctions = dna_model.create_model( + {dna_model.Organism.HOMO_SAPIENS: self._metadata} + ) + + dna_sequence_shape = jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32) + organism_index_shape = jax.ShapeDtypeStruct((1,), dtype=jnp.int32) + + params, state = jax.eval_shape( + init, jax.random.PRNGKey(0), dna_sequence_shape, organism_index_shape + ) + + predictions = jax.eval_shape( + apply, params, state, dna_sequence_shape, organism_index_shape + ) + expected_predictions = { + dna_output.OutputType.ATAC: jax.ShapeDtypeStruct( + (1, 2048, 2), dtype=jnp.bfloat16 + ), + dna_output.OutputType.DNASE: jax.ShapeDtypeStruct( + (1, 2048, 1), dtype=jnp.bfloat16 + ), + dna_output.OutputType.CHIP_TF: jax.ShapeDtypeStruct( + (1, 16, 2), dtype=jnp.bfloat16 + ), + dna_output.OutputType.SPLICE_SITES: jax.ShapeDtypeStruct( + (1, 2048, 5), dtype=jnp.bfloat16 + ), + dna_output.OutputType.SPLICE_JUNCTIONS: { + 'predictions': jax.ShapeDtypeStruct( + (1, 512, 512, 24), dtype=jnp.bfloat16 + ), + 'splice_site_positions': jax.ShapeDtypeStruct( + (1, 4, 512), dtype=jnp.int32 + ), + }, + dna_output.OutputType.CONTACT_MAPS: jax.ShapeDtypeStruct( + (1, 1, 1, 2), dtype=jnp.bfloat16 + ), + } + chex.assert_trees_all_equal_shapes_and_dtypes( + dna_model.extract_predictions(predictions), expected_predictions + ) + + junction_predictions = jax.eval_shape( + apply_junctions, + params, + state, + predictions['embeddings_1bp'], + predictions['splice_sites_junction']['splice_site_positions'], + organism_index_shape, + ) + expected_junction_predictions = { + 'predictions': jax.ShapeDtypeStruct( + (1, 512, 512, 24), dtype=jnp.bfloat16 + ), + 'splice_junction_mask': jax.ShapeDtypeStruct( + (1, 512, 512, 24), dtype=jnp.bool + ), + 'splice_site_positions': jax.ShapeDtypeStruct( + (1, 4, 512), dtype=jnp.int32 + ), + } + chex.assert_trees_all_equal_shapes_and_dtypes( + junction_predictions, expected_junction_predictions + ) + + @parameterized.parameters(('all_folds',), (dna_model.ModelVersion.ALL_FOLDS,)) + @mock.patch.object(jax, 'eval_shape', return_value=MOCK_SHAPES, autospec=True) + def test_create_from_kaggle(self, version, mock_eval_shape): + del mock_eval_shape + checkpointer = ocp.StandardCheckpointer() + checkpoint_dir = os.path.join(self.create_tempdir().full_path, 'ckpt') + checkpointer.save(checkpoint_dir, ({}, {})) + checkpointer.wait_until_finished() + with ( + mock.patch.object(kagglehub, 'model_download') as mock_model_download, + mock.patch.object(kaggle_auth, 'get_username') as mock_get_username, + mock.patch.object(kagglehub, 'login') as mock_login, + ): + mock_get_username.return_value = None + mock_model_download.return_value = checkpoint_dir + model = dna_model.create_from_kaggle( + version, organism_settings={}, device=jax.local_devices()[0] + ) + + self.assertIsInstance(model, dna_model.AlphaGenomeModel) + mock_get_username.assert_called_once() + mock_login.assert_called_once() + mock_model_download.assert_called_once_with( + 'google/alphagenome/jax/all_folds' + ) + + @parameterized.parameters(('fold_0',), (dna_model.ModelVersion.FOLD_0,)) + @mock.patch.object(jax, 'eval_shape', return_value=MOCK_SHAPES, autospec=True) + def test_create_from_huggingface(self, version, mock_eval_shape): + del mock_eval_shape + checkpointer = ocp.StandardCheckpointer() + checkpoint_dir = os.path.join(self.create_tempdir().full_path, 'ckpt') + checkpointer.save(checkpoint_dir, ({}, {})) + checkpointer.wait_until_finished() + with ( + mock.patch.object( + huggingface_hub, 'snapshot_download' + ) as mock_snapshot_download, + mock.patch.object(huggingface_hub, 'login') as mock_login, + mock.patch.object(huggingface_hub, 'whoami') as mock_whoami, + ): + mock_snapshot_download.return_value = checkpoint_dir + mock_whoami.side_effect = huggingface_hub.errors.LocalTokenNotFoundError() + model = dna_model.create_from_huggingface( + version, organism_settings={}, device=jax.local_devices()[0] + ) + + self.assertIsInstance(model, dna_model.AlphaGenomeModel) + mock_login.assert_called_once() + mock_whoami.assert_called_once() + mock_snapshot_download.assert_called_once_with( + repo_id='google/alphagenome-fold-0' + ) + + def test_default_create_with_cpu_raises_error(self): + with jax.default_device(jax.devices(backend='cpu')[0]): + with self.assertRaisesRegex( + ValueError, 'Cannot find any GPU or TPU devices' + ): + _ = dna_model.AlphaGenomeModel( + params={}, + state={}, + apply_fn=self._mock_model, + junctions_apply_fn=self._mock_model_junctions, + metadata={}, + ) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/embeddings.py b/flax_model/alphagenome/model/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..66cccd2559b5175ba074d1667b9768b5cbd4b624 --- /dev/null +++ b/flax_model/alphagenome/model/embeddings.py @@ -0,0 +1,102 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Embeddings for AlphaGenome.""" + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome.model import layers +import chex +import haiku as hk +import jax.numpy as jnp +from jaxtyping import Array, Float, Int # pylint: disable=g-importing-member, g-multiple-import + + +@typing.jaxtyped +@chex.dataclass(frozen=True, kw_only=True) +class Embeddings: + """AlphaGenome embeddings.""" + + embeddings_1bp: Float[Array, 'B S 1536'] | None = None + embeddings_128bp: Float[Array, 'B S//128 3072'] | None = None + embeddings_pair: Float[Array, 'B S//2048 S//2048 128'] | None = None + + def get_sequence_embeddings(self, resolution: int) -> Float[Array, 'B S D']: + if resolution == 128: + return self.embeddings_128bp + elif resolution == 1: + return self.embeddings_1bp + else: + raise ValueError(f'Unsupported resolution: {resolution}') + + +class OutputEmbedder(hk.Module): + """Generates output embeddings with organism-specific adjustments.""" + + def __init__(self, num_organisms: int, name: str | None = None): + """Initializes the OutputEmbedder module. + + Args: + num_organisms: The number of organisms to embed. Typically 2 (human and + mouse). + name: The name of the module. + """ + super().__init__(name=name) + self._num_organisms = num_organisms + + @typing.jaxtyped + def __call__( + self, + x: Float[Array, 'B S D'], + organism_index: Int[Array, 'B'], + skip_x: Float[Array, 'B S_skip D_skip'] | None = None, + ) -> Float[Array, 'B S D_out']: + x = hk.Linear(2 * x.shape[-1])(x) + if skip_x is not None: + # Assumes skip_x needs to be upsampled to match x's sequence length + skip_x = hk.Linear(x.shape[-1], with_bias=False)(skip_x) + x += jnp.repeat(skip_x, x.shape[1] // skip_x.shape[1], axis=1) + + x = layers.RMSBatchNorm()(x) + if self._num_organisms >= 1: + organism_embedding = hk.Embed(self._num_organisms, x.shape[-1])( + organism_index + )[:, None, :] + x += organism_embedding + return layers.gelu(x) + + +class OutputPair(hk.Module): + """Generates output pairwise embeddings with organism-specific adjustments.""" + + def __init__(self, num_organisms: int, name: str | None = None): + """Initializes the OutputPair module. + + Args: + num_organisms: The number of organisms to embed. Typically 2 (human and + mouse). + name: The name of the module. + """ + super().__init__(name=name) + self._num_organisms = num_organisms + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S S F'], organism_index: Int[Array, 'B'] + ) -> Float[Array, 'B S S 128']: + x = (x + jnp.swapaxes(x, 1, 2)) / 2.0 # Symmetrize. + x = layers.LayerNorm(rms_norm=True)(x) + if self._num_organisms >= 1: + organism_embedding = hk.Embed(self._num_organisms, 128)(organism_index) + x += organism_embedding[:, None, None, :] + return layers.gelu(x) diff --git a/flax_model/alphagenome/model/heads.py b/flax_model/alphagenome/model/heads.py new file mode 100644 index 0000000000000000000000000000000000000000..5d16167885e1bea0bc181a8c5f27c426118af41d --- /dev/null +++ b/flax_model/alphagenome/model/heads.py @@ -0,0 +1,1055 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Heads for AlphaGenome.""" + +import abc +from collections.abc import Mapping, Sequence +import dataclasses +import enum +import functools +import math +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import junction_data +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome.io import bundles +from flax_model.alphagenome.model import attention +from flax_model.alphagenome.model import embeddings as embeddings_module +from flax_model.alphagenome.model import losses +from flax_model.alphagenome.model import schemas +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +import chex +import haiku as hk +import jax +import jax.numpy as jnp +from jaxtyping import Array, ArrayLike, Bool, Float, Int, PyTree, Shaped # pylint: disable=g-importing-member, g-multiple-import +import numpy as np + +_SOFT_CLIP_VALUE = 10.0 + + +class HeadType(enum.Enum): + """Head types.""" + + GENOME_TRACKS = 'genome_tracks' + CONTACT_MAPS = 'contact_maps' + SPLICE_SITES_CLASSIFICATION = 'splice_sites_classification' + SPLICE_SITES_USAGE = 'splice_sites_usage' + SPLICE_SITES_JUNCTION = 'splice_sites_junction' + + +class HeadName(enum.Enum): + """Output heads.""" + + ATAC = 'atac' + DNASE = 'dnase' + PROCAP = 'procap' + CAGE = 'cage' + RNA_SEQ = 'rna_seq' + CHIP_TF = 'chip_tf' + CHIP_HISTONE = 'chip_histone' + CONTACT_MAPS = 'contact_maps' + SPLICE_SITES_CLASSIFICATION = 'splice_sites_classification' + SPLICE_SITES_USAGE = 'splice_sites_usage' + SPLICE_SITES_JUNCTION = 'splice_sites_junction' + + +@dataclasses.dataclass +class HeadConfig: + type: HeadType + name: str + output_type: dna_output.OutputType + + +@dataclasses.dataclass +class GenomeTracksHeadConfig(HeadConfig): + resolutions: Sequence[int] + apply_squashing: bool + bundle: bundles.BundleName + + +def create_head( + config: HeadConfig, + metadata: Mapping[ + dna_model.Organism, metadata_lib.AlphaGenomeOutputMetadata + ], + *, + num_organisms: int | None = None, +) -> 'Head': + match config.type: + case HeadType.GENOME_TRACKS: + assert isinstance(config, GenomeTracksHeadConfig) + return GenomeTracksHead( + name=config.name, + output_type=config.output_type, + metadata=metadata, + resolutions=config.resolutions, + apply_squashing=config.apply_squashing, + bundle=config.bundle, + num_organisms=num_organisms, + ) + case HeadType.CONTACT_MAPS: + return ContactMapsHead( + name=config.name, + output_type=config.output_type, + metadata=metadata, + num_organisms=num_organisms, + ) + case HeadType.SPLICE_SITES_CLASSIFICATION: + return SpliceSitesClassificationHead( + name=config.name, + output_type=config.output_type, + metadata=metadata, + num_organisms=num_organisms, + ) + case HeadType.SPLICE_SITES_USAGE: + return SpliceSitesUsageHead( + name=config.name, + output_type=config.output_type, + metadata=metadata, + num_organisms=num_organisms, + ) + case HeadType.SPLICE_SITES_JUNCTION: + return SpliceSitesJunctionHead( + name=config.name, + output_type=config.output_type, + metadata=metadata, + num_organisms=num_organisms, + ) + case _: + raise ValueError(f'Unknown head type: {config.type}') + + +def get_head_config(head_name: HeadName) -> HeadConfig: + """Returns a head for the given head name.""" + match head_name: + case HeadName.ATAC: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.ATAC.value, + output_type=dna_output.OutputType.ATAC, + resolutions=[1, 128], + apply_squashing=False, + bundle=bundles.BundleName.ATAC, + ) + case HeadName.DNASE: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.DNASE.value, + output_type=dna_output.OutputType.DNASE, + resolutions=[1, 128], + apply_squashing=False, + bundle=bundles.BundleName.DNASE, + ) + case HeadName.PROCAP: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.PROCAP.value, + output_type=dna_output.OutputType.PROCAP, + resolutions=[1, 128], + apply_squashing=False, + bundle=bundles.BundleName.PROCAP, + ) + case HeadName.CAGE: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.CAGE.value, + output_type=dna_output.OutputType.CAGE, + resolutions=[1, 128], + apply_squashing=False, + bundle=bundles.BundleName.CAGE, + ) + case HeadName.RNA_SEQ: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.RNA_SEQ.value, + output_type=dna_output.OutputType.RNA_SEQ, + resolutions=[1, 128], + apply_squashing=True, + bundle=bundles.BundleName.RNA_SEQ, + ) + case HeadName.CHIP_TF: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.CHIP_TF.value, + output_type=dna_output.OutputType.CHIP_TF, + resolutions=[128], + apply_squashing=False, + bundle=bundles.BundleName.CHIP_TF, + ) + case HeadName.CHIP_HISTONE: + return GenomeTracksHeadConfig( + type=HeadType.GENOME_TRACKS, + name=HeadName.CHIP_HISTONE.value, + output_type=dna_output.OutputType.CHIP_HISTONE, + resolutions=[128], + apply_squashing=False, + bundle=bundles.BundleName.CHIP_HISTONE, + ) + case HeadName.CONTACT_MAPS: + return HeadConfig( + type=HeadType.CONTACT_MAPS, + name=HeadName.CONTACT_MAPS.value, + output_type=dna_output.OutputType.CONTACT_MAPS, + ) + case HeadName.SPLICE_SITES_CLASSIFICATION: + return HeadConfig( + type=HeadType.SPLICE_SITES_CLASSIFICATION, + name=HeadName.SPLICE_SITES_CLASSIFICATION.value, + output_type=dna_output.OutputType.SPLICE_SITES, + ) + case HeadName.SPLICE_SITES_USAGE: + return HeadConfig( + type=HeadType.SPLICE_SITES_USAGE, + name=HeadName.SPLICE_SITES_USAGE.value, + output_type=dna_output.OutputType.SPLICE_SITE_USAGE, + ) + case HeadName.SPLICE_SITES_JUNCTION: + return HeadConfig( + type=HeadType.SPLICE_SITES_JUNCTION, + name=HeadName.SPLICE_SITES_JUNCTION.value, + output_type=dna_output.OutputType.SPLICE_JUNCTIONS, + ) + case _: + raise ValueError(f'Unknown head name: {head_name}') + + +@typing.jaxtyped +def _sum_pool( + x: Float[Array, 'B S C'], width: int +) -> Float[Array, 'B S//{width} C']: + return x.reshape((x.shape[0], x.shape[1] // width, width, x.shape[2])).sum( + axis=-2, dtype=jnp.float32 + ) + + +@typing.jaxtyped +def _get_param_for_index( + params: Float[ArrayLike, 'P ...'], index: Int[Array, 'B'] +) -> Float[ArrayLike, 'B ...']: + """Returns a parameter for a specific index. + + Embeds the params into the graph. + + Args: + params: The parameters to embed. + index: The index to get the parameter for. + """ + return jnp.asarray(params)[(index,)] + + +class _MultiOrganismLinear(hk.Module): + """A linear layer with organism-specific weights and biases.""" + + def __init__( + self, + output_size: int, + num_organisms: int, + name: str | None = 'multi_organism_linear', + ): + super().__init__(name=name) + self._output_size = output_size + self._num_organisms = num_organisms + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B *S D'], organism_index: Int[Array, 'B'] + ) -> Float[Array, 'B *S {self._output_size}']: + w_shape = (self._num_organisms, x.shape[-1], self._output_size) + stddev = 1.0 / np.sqrt(x.shape[-1]) + w_init = hk.initializers.TruncatedNormal(stddev=stddev) + w = hk.get_parameter('w', w_shape, init=w_init).astype(x.dtype) + w = _get_param_for_index(w, organism_index) + b_shape = (self._num_organisms, self._output_size) + b = hk.get_parameter('b', b_shape, init=jnp.zeros).astype(x.dtype) + b = _get_param_for_index(b, organism_index) + num_inner_dims = len(x.shape) - 2 + target_b_shape = (b.shape[0],) + (1,) * num_inner_dims + (b.shape[1],) + return jnp.einsum( + 'b...i,bij->b...j', x, w, preferred_element_type=jnp.float32 + ) + b.reshape(target_b_shape) + + +def predictions_scaling( + x: Float[ArrayLike, 'B S C'], + track_means: Float[ArrayLike, 'B C'], + resolution: int, + apply_squashing: bool, + soft_clip_value: float = _SOFT_CLIP_VALUE, +) -> Float[ArrayLike, 'S C']: + """Scales predictions to experimental data scale. + + Args: + x: Experimental target counts. + track_means: Mean values per track (broadcastable). + resolution: The bin resolution of the targets (e.g., 1 or 128). + apply_squashing: Whether to apply power law compression (for RNA-seq). + soft_clip_value: The value to soft clip the predictions to. + + Returns: + Scaled predictions. + """ + xnp = jnp if isinstance(x, jnp.ndarray) else np + x = xnp.where( + x > soft_clip_value, + (x + soft_clip_value) ** 2 / (4 * soft_clip_value), + x, + ) + if apply_squashing: + x = xnp.power(x, 1.0 / 0.75) + x = x * (track_means[:, None] * resolution).astype(x.dtype) + return x + + +@typing.jaxtyped +def targets_scaling( + targets: Float[ArrayLike, 'B S C'], + track_means: Float[ArrayLike, 'B C'], + resolution: int, + apply_squashing: bool, + soft_clip_value: float = _SOFT_CLIP_VALUE, +) -> Float[Array, 'B S C']: + """Scales experimental targets to the model prediction space. + + Args: + targets: Experimental target counts. + track_means: Mean values per track. + resolution: The bin resolution of the targets (e.g., 1 or 128). + apply_squashing: Whether to apply power law compression (for RNA-seq). + soft_clip_value: The value to soft clip the targets to. + + Returns: + Scaled targets ready for loss calculation. + """ + xnp = jnp if isinstance(targets, jnp.ndarray) else np + targets = targets / (track_means[:, None] * resolution).astype(targets.dtype) + + if apply_squashing: + targets = xnp.power(targets, 0.75) + + # Where(targets > 10.0, 2 * Sqrt(x * 10.0) - 10.0, targets) + return xnp.where( + targets > soft_clip_value, + 2.0 * jnp.sqrt(targets * soft_clip_value) - soft_clip_value, + targets, + ) + + +class Head(metaclass=abc.ABCMeta): + """Abstract class for a model head.""" + + def __init__( + self, + *, + name: str, + output_type: dna_output.OutputType, + metadata: Mapping[ + dna_model.Organism, + metadata_lib.AlphaGenomeOutputMetadata, + ], + num_organisms: int | None = None, + ): + """Initializes the Head class. + + Args: + name: The name of the head. + output_type: The type of output to predict. + metadata: A dictionary of track metadata for each organism. The metadata + should be a ordered aligned with the organism index. E.g., + organism_index=0 should correspond to the first organism in the metadata + dictionary. + num_organisms: Optional number of organisms. If not provided, the number + of organisms will be inferred from the metadata. + """ + + self._name = name + self._output_type = output_type + self._metadata = metadata + self._num_organisms = ( + num_organisms if num_organisms is not None else len(metadata) + ) + if not self._metadata: + raise ValueError('No metadata provided for any organism.') + self._num_tracks = self._get_num_tracks() + + @property + def name(self) -> str: + return self._name + + @property + def num_tracks(self) -> int: + """Returns the maximum number of tracks for the head across all organisms.""" + return self._num_tracks + + def _get_num_tracks(self) -> int: + """Returns the number of tracks for the head.""" + num_tracks = [] + for organism in self._metadata.keys(): + if (track_metadata := self.get_metadata(organism)) is not None: + num_tracks.append(len(track_metadata)) + + if not num_tracks: + raise ValueError( + f'No metadata found for any organism for {self._output_type=}.' + ) + + if len(set(num_tracks)) > 1: + raise ValueError( + 'Number of tracks is not the same for all organisms. Please pad the' + ' metadata to have the same number of tracks for all organisms.' + ) + return num_tracks[0] + + @typing.jaxtyped + def get_multi_organism_track_mask( + self, + ) -> Bool[Array, '{len(self._metadata)} {self.num_tracks}']: + """Returns the track mask for all organisms.""" + track_masks = [] + for organism in self._metadata.keys(): + padding = self._metadata[organism].padding[self._output_type] + chex.assert_shape(padding, (self.num_tracks,)) + track_masks.append(np.logical_not(padding)) + return jnp.stack(track_masks).astype(bool) + + def get_metadata( + self, organism: dna_model.Organism + ) -> track_data.TrackMetadata | junction_data.JunctionMetadata | None: + return self._metadata.get(organism, {}).get(self._output_type) + + def __call__( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Shaped[Array, 'B ...'] | None]: + """Calls the head's predict function as a module.""" + return hk.to_module(self.predict)(self._name)( + embeddings, organism_index, **kwargs + ) + + @abc.abstractmethod + def predict( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Shaped[Array, 'B ...'] | None]: + """Returns the predictions for the head.""" + + @abc.abstractmethod + def loss( + self, + predictions: PyTree[Shaped[Array, 'B ...']], + batch: schemas.DataBatch, + ) -> PyTree[Float[Array, '']]: + """Returns the loss for the head.""" + + +class GenomeTracksHead(Head): + """A model head that predicts at multiple resolutions. + + This module takes embeddings at different resolutions and produces predictions + for a specified number of tracks. It uses organism-specific linear layers and + learnt scales to generate the predictions. + """ + + def __init__( + self, + *, + name: str, + output_type: dna_output.OutputType, + apply_squashing: bool, + resolutions: Sequence[int], + bundle: bundles.BundleName | None = None, + metadata: Mapping[ + dna_model.Organism, + metadata_lib.AlphaGenomeOutputMetadata, + ], + num_organisms: int | None = None, + ): + """Initializes the BaseResolutionHead module. + + Args: + name: The name of the head. + output_type: The type of output to predict. + apply_squashing: Whether to apply squashing to the predictions. + resolutions: The resolutions to predict. + bundle: The name of the dataset bundle associated with this head. This is + required to fetch the target tracks for loss computation. If None, the + `loss` method will not be functional. + metadata: A dictionary mapping each organism to its track metadata. The + order of organisms in the dictionary is important, as it must align with + the organism index provided in the data batches (e.g., organism_index=0 + corresponds to the first organism in `metadata`). For each organism, the + metadata for `output_type` should contain the same number of rows + (tracks), padded if necessary. If the metadata includes a 'nonzero_mean' + column, these values are used to scale predictions and targets. + Otherwise, scaling is omitted. Note that squashing is only applied if + `apply_squashing` is True. + num_organisms: Optional number of organisms. If not provided, the number + of organisms will be inferred from the metadata. + """ + + super().__init__( + name=name, + output_type=output_type, + metadata=metadata, + num_organisms=num_organisms, + ) + self._apply_squashing = apply_squashing + self._resolutions = sorted(resolutions) + self._bundle = bundle + + def _get_track_means(organism: dna_model.Organism) -> Float[Array, 'C']: + metadata = self.get_metadata(organism) + if metadata is None or metadata.get('nonzero_mean') is None: + return jnp.ones((self.num_tracks,)) + else: + return metadata['nonzero_mean'].values + + self._track_means = jnp.stack( + [_get_track_means(organism) for organism in self._metadata.keys()] + ) + + @typing.jaxtyped + def unscale( + self, + x: Float[Array, 'B S C'], + organism_index: Int[Array, 'B'], + resolution: int, + ) -> Float[Array, 'B S C'] | None: + """Unscales predictions to experimental data scale. + + Requires the column `nonzero_mean` to be present in the metadata to result + in valid scaling. + + Args: + x: The predictions to unscale. + organism_index: The organism index. + resolution: The resolution of the predictions. + """ + track_means = _get_param_for_index(self._track_means, organism_index) + return predictions_scaling( + x, + track_means=track_means, + resolution=resolution, + apply_squashing=self._apply_squashing, + ) + + @typing.jaxtyped + def scale( + self, + x: Float[Array, 'B S C'], + organism_index: Int[Array, 'B'], + resolution: int, + ) -> Float[Array, 'B S C']: + """Scales targets to model predictions scale.""" + track_means = _get_param_for_index(self._track_means, organism_index) + return targets_scaling( + x, + track_means=track_means, + resolution=resolution, + apply_squashing=self._apply_squashing, + ) + + @hk.transparent + @typing.jaxtyped + def _predict( + self, x: Float[Array, 'B S D'], organism_index: Int[Array, 'B'] + ) -> Float[Array, 'B S {self.num_tracks}']: + """Predicts genome tracks.""" + x = _MultiOrganismLinear(self.num_tracks, self._num_organisms)( + x, organism_index + ) + residual_scales = hk.get_parameter( + 'learnt_scale', (self._num_organisms, self.num_tracks), init=jnp.ones + ).astype(x.dtype) + residual_scale = _get_param_for_index(residual_scales, organism_index) + return jax.nn.softplus(x) * jax.nn.softplus(residual_scale[:, None, :]) + + def predict( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Float[Array, 'B ...'] | None]: + predictions = {} + for resolution in self._resolutions: + with hk.name_scope(f'resolution_{resolution}'): + scaled_predictions = self._predict( + embeddings.get_sequence_embeddings(resolution), organism_index + ) + predictions[f'scaled_predictions_{resolution}bp'] = scaled_predictions + predictions[f'predictions_{resolution}bp'] = self.unscale( + scaled_predictions, organism_index, resolution + ) + return predictions + + @typing.jaxtyped + def _compute_loss( + self, + *, + organism_index: Int[Array, 'B'], + predictions: Float[Array, 'B S C'], + targets: Float[Array, 'B S C'], + targets_mask: Bool[Array, 'B 1 C'] | None, + resolution: int, + ) -> PyTree[Float[Array, '']]: + """Computes the loss for the head at a given resolution.""" + chex.assert_equal_shape([predictions, targets]) + scaled_targets = self.scale(targets, organism_index, resolution) + all_losses = losses.multinomial_loss( + y_pred=predictions, + y_true=scaled_targets, + mask=targets_mask, + positional_weight=5.0, + multinomial_resolution=int(2**17) // resolution, + ) + return all_losses + + @typing.jaxtyped + def loss( + self, + predictions: PyTree[Float[Array, 'B ...']], + batch: schemas.DataBatch, + ) -> PyTree[Float[Array, '']]: + """Returns the loss for the head.""" + if self._bundle is None: + raise ValueError('Bundle is required for loss computation.') + + tracks, mask = batch.get_genome_tracks(self._bundle) + + if mask.shape[-2] != 1: + raise ValueError( + 'We assume the mask to broadcast over the sequence length.' + ) + + bundle_resolution = self._bundle.get_resolution() + loss_sum, scalars = 0.0, {} + + for resolution in self._resolutions: + predictions_for_resolution = predictions[ + f'scaled_predictions_{resolution}bp' + ] + if resolution == bundle_resolution: + targets = tracks + else: + targets = _sum_pool(tracks, resolution) + + all_losses = self._compute_loss( + organism_index=batch.get_organism_index(), + predictions=predictions_for_resolution, + targets=targets, + targets_mask=mask, + resolution=resolution, + ) + for k, v in all_losses.items(): + scalars[f'{k}_{resolution}bp'] = v + loss_sum += all_losses['loss'] + + scalars['loss'] = loss_sum + return scalars + + +class ContactMapsHead(Head): + """A model head that predicts contact maps from pairwise embeddings.""" + + @typing.jaxtyped + @hk.transparent + def _predict( + self, + pair_embeddings: Float[Array, 'B S S D'], + organism_index: Int[Array, 'B'], + ) -> Float[Array, 'B S S {self.num_tracks}']: + """Predicts contact maps from pairwise embeddings.""" + return _MultiOrganismLinear(self.num_tracks, self._num_organisms)( + pair_embeddings, organism_index + ) + + def predict( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Float[Array, 'B ...'] | None]: + """Predicts contact maps from embeddings.""" + return { + 'predictions': self._predict(embeddings.embeddings_pair, organism_index) + } + + def _get_targets_mask( + self, + organism_index: Int[Array, 'B'], + ) -> Bool[Array, 'B 1 1 {self.num_tracks}']: + """Returns a mask for padding channels.""" + track_mask = self.get_multi_organism_track_mask()[(organism_index,)] + return track_mask[:, None, None, :] + + def loss( + self, + predictions: PyTree[Float[Array, 'B ...']], + batch: schemas.DataBatch, + ) -> PyTree[Float[Array, '']]: + """Returns the loss for the head.""" + if (targets := batch.contact_maps) is None: + raise ValueError('contact_maps target not in batch.') + + contact_predictions = predictions['predictions'] + chex.assert_equal_shape([contact_predictions, targets]) + + # Mask out NaN targets (which happens when balancing a missing slice). + targets_mask = self._get_targets_mask(batch.get_organism_index()) + targets_mask = jnp.where(jnp.isnan(targets), False, targets_mask) + targets = jnp.where(jnp.isnan(targets), 0.0, targets) + + loss = losses.mse( + y_pred=contact_predictions, y_true=targets, mask=targets_mask + ) + return {'loss': loss} + + +class SpliceSitesClassificationHead(Head): + """A model head that predicts splice site classification.""" + + @typing.jaxtyped + @hk.transparent + def _predict_logits( + self, x: Float[Array, 'B S D'], organism_index: Int[Array, 'B'] + ) -> Float[Array, 'B S {self.num_tracks}']: + """Splice site classification.""" + return _MultiOrganismLinear(self.num_tracks, self._num_organisms)( + x, organism_index + ) + + def predict( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Float[Array, 'B ...'] | None]: + """Predicts splice site classification from embeddings.""" + embeddings_1bp = embeddings.get_sequence_embeddings(1) + logits = self._predict_logits(embeddings_1bp, organism_index) + probs = jax.nn.softmax(logits.astype(jnp.float32), axis=-1) + return {'logits': logits, 'predictions': probs} + + def loss( + self, + predictions: PyTree[Float[Array, 'B ...']], + batch: schemas.DataBatch, + ) -> PyTree[Float[Array, '']]: + """Returns the loss for the head.""" + if (splice_sites := batch.splice_sites) is None: + raise ValueError('splice_sites target not in batch.') + logits = predictions['logits'] + chex.assert_equal_shape([splice_sites, logits]) + + classification_mask = jnp.any(splice_sites, axis=-1, keepdims=True) + loss = losses.cross_entropy_loss_from_logits( + y_pred_logits=logits, + # Label smoothing with FP32 machine precision (~1e-7) for 5 classes. + y_true=(1.0 - 1e-7) * splice_sites.astype(jnp.float32) + + 1e-7 / self.num_tracks, + mask=classification_mask, + axis=-1, + ) + return {'loss': loss} + + +class SpliceSitesUsageHead(Head): + """A model head that predicts splice site usage.""" + + @typing.jaxtyped + @hk.transparent + def _predict_logits( + self, x: Float[Array, 'B S D'], organism_index: Int[Array, 'B'] + ) -> Float[Array, 'B S {self.num_tracks}']: + """Splice site usage.""" + return _MultiOrganismLinear(self.num_tracks, self._num_organisms)( + x, organism_index + ) + + def predict( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Float[Array, 'B ...'] | None]: + """Predicts splice site usage from embeddings.""" + embeddings_1bp = embeddings.get_sequence_embeddings(1) + logits = self._predict_logits(embeddings_1bp, organism_index) + splice_site_usage = jax.nn.sigmoid(logits.astype(jnp.float32)).astype( + jnp.float16 + ) + return {'logits': logits, 'predictions': splice_site_usage} + + @typing.jaxtyped + def _get_targets_mask( + self, + organism_index: Int[Array, 'B'], + ) -> Bool[Array, 'B 1 {self.num_tracks}']: + """Returns a mask for padding channels.""" + track_mask = self.get_multi_organism_track_mask()[(organism_index,)] + return track_mask[:, None, :] + + def loss( + self, + predictions: PyTree[Float[Array, 'B ...']], + batch: schemas.DataBatch, + ) -> PyTree[Float[Array, '']]: + """Returns the loss for the head.""" + if (splice_site_usage := batch.splice_site_usage) is None: + raise ValueError('splice_site_usage target not in batch.') + logits = predictions['logits'] + chex.assert_equal_shape([splice_site_usage, logits]) + loss = losses.binary_crossentropy_from_logits( + y_pred=logits, + y_true=jnp.clip(splice_site_usage, 1e-7, 1.0 - 1e-7), + mask=self._get_targets_mask(batch.get_organism_index()), + ) + return {'loss': loss} + + +class SpliceSitesJunctionHead(Head): + """A model head that predicts splice site junctions.""" + + def __init__( + self, + *, + name: str, + output_type: dna_output.OutputType, + metadata: Mapping[ + dna_model.Organism, + metadata_lib.AlphaGenomeOutputMetadata, + ], + num_organisms: int | None = None, + ): + """Initializes the SpliceSitesJunctionHead module.""" + super().__init__( + name=name, + output_type=output_type, + metadata=metadata, + num_organisms=num_organisms, + ) + self._hidden_dim = 768 + self._max_position_encoding_distance = int(2**20) + + def get_num_tissues(self, organism: dna_model.Organism) -> int: + """Returns the number of tissues for the given organism.""" + metadata = self.get_metadata(organism) + if metadata is None: + raise ValueError(f'Metadata not found for organism {organism}.') + return len(metadata) + + @property + def max_num_tissues(self) -> int: + """Returns the maximum number of tissues across all organisms from the metadata.""" + + return max(self.get_num_tissues(organism) for organism in self._metadata) + + def _get_num_tracks(self) -> int: + """Returns the number of tracks. + + Splice junctions metadata contains the tissues per organism, rather than the + tracks. The number of tracks is twice the number of tissues accounting for + the two strands. + """ + return 2 * self.max_num_tissues + + def get_multi_organism_track_mask( + self, + ) -> Bool[Array, '{self._num_organisms} {self.num_tracks}']: + """Returns the track mask for the head for human and mouse. + + Splice junctions metadata contains the tissues per organism, rather than the + tracks. + """ + track_masks = [] + for organism in self._metadata: + num_tissues = self.get_num_tissues(organism) + tissue_mask = np.arange(self.max_num_tissues) < num_tissues + # Repeat the mask for the two strands. + track_mask = np.concatenate([tissue_mask, tissue_mask]) + track_masks.append(track_mask) + return jnp.stack(track_masks).astype(bool) + + @typing.jaxtyped + @hk.transparent + def _predict( + self, + x: Float[Array, 'B S D'], + splice_site_positions: Int[Array, 'B 4 P'], + organism_index: Int[Array, 'B'], + ) -> tuple[ + Float[Array, 'B P P {self.num_tracks}'], + Bool[Array, 'B P P {self.num_tracks}'], + ]: + """Splice site junctions.""" + + chex.assert_shape(splice_site_positions, (None, 4, None)) + pos_donor_idx = splice_site_positions[:, 0, :] + pos_accept_idx = splice_site_positions[:, 1, :] + neg_donor_idx = splice_site_positions[:, 2, :] + neg_accept_idx = splice_site_positions[:, 3, :] + + def _index_embedding(embedding, indices): + return jax.vmap(functools.partial(jnp.take, axis=0))(embedding, indices) + + shape = (self._num_organisms, 2, self.max_num_tissues, self._hidden_dim) + + def _apply_rope(x, indices): + x = _index_embedding(x, indices).astype(jnp.float32) + params = hk.get_parameter( + 'embeddings', + (shape[0], math.prod(shape[1:])), + dtype=x.dtype, + init=jnp.zeros, + ).reshape(*shape) + params = _get_param_for_index(params, organism_index) + # scale and offset have shape [B, 1, num_tissues, C]. + scale, offset = params[:, [0], :, :], params[:, [1], :, :] + x = scale * x[:, :, None, :] + offset # [B, num_indices, num_tissues, C] + return attention.apply_rope( + x, indices, self._max_position_encoding_distance + ) + + splice_site_logits = _MultiOrganismLinear( + self._hidden_dim, self._num_organisms + )(x, organism_index) + + with hk.name_scope('pos_acceptor_logits'): + pos_accept_logits = _apply_rope(splice_site_logits, pos_accept_idx) + with hk.name_scope('pos_donor_logits'): + pos_donor_logits = _apply_rope(splice_site_logits, pos_donor_idx) + with hk.name_scope('neg_acceptor_logits'): + neg_accept_logits = _apply_rope(splice_site_logits, neg_accept_idx) + with hk.name_scope('neg_donor_logits'): + neg_donor_logits = _apply_rope(splice_site_logits, neg_donor_idx) + pos_counts = jax.nn.softplus( + jnp.einsum( + 'bdtc,batc->bdat', + pos_donor_logits, + pos_accept_logits, + # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32, + precision=jax.lax.Precision.DEFAULT, + ) + ) + neg_counts = jax.nn.softplus( + jnp.einsum( + 'bdtc,batc->bdat', + neg_donor_logits, + neg_accept_logits, + # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32, + precision=jax.lax.Precision.DEFAULT, + ) + ) + pos_mask = jnp.einsum('bd,ba->bda', pos_donor_idx >= 0, pos_accept_idx >= 0) + neg_mask = jnp.einsum('bd,ba->bda', neg_donor_idx >= 0, neg_accept_idx >= 0) + track_mask = self.get_multi_organism_track_mask()[( + organism_index, + )] # [B, 2 * num_tissues] + pos_mask = ( + pos_mask[:, :, :, None] + * track_mask[:, None, None, : self.max_num_tissues] + ) + neg_mask = ( + neg_mask[:, :, :, None] + * track_mask[:, None, None, self.max_num_tissues :] + ) + # Shape [B, D, A, 2 * num_tissues] + splice_junction_mask = jnp.concatenate([pos_mask, neg_mask], axis=-1) + pred_counts = jnp.concatenate((pos_counts, neg_counts), axis=-1) + pred_counts = jnp.where(splice_junction_mask, pred_counts, 0) + return pred_counts, splice_junction_mask + + def predict( + self, + embeddings: embeddings_module.Embeddings, + organism_index: Int[Array, 'B'], + **kwargs, + ) -> PyTree[Shaped[Array, 'B ...'] | None]: + """Predicts splice site junctions from embeddings.""" + if (splice_site_positions := kwargs.get('splice_site_positions')) is None: + raise ValueError( + 'splice_site_positions is required for junctions predictions.' + ) + embeddings_1bp = embeddings.get_sequence_embeddings(1) + splice_site_junction, splice_junction_mask = self._predict( + embeddings_1bp, splice_site_positions, organism_index + ) + return { + 'predictions': splice_site_junction, + 'splice_site_positions': splice_site_positions, + 'splice_junction_mask': splice_junction_mask, + } + + def loss( + self, + predictions: PyTree[Shaped[Array, 'B ...']], + batch: schemas.DataBatch, + ) -> PyTree[Float[Array, '']]: + """Returns the loss for the head.""" + if (count_target := batch.splice_junctions) is None: + raise ValueError('splice_junctions target not in batch.') + + pred_pair = predictions['predictions'] + pairs_mask = predictions['splice_junction_mask'] + # Junctions shape is [batch, donors, acceptors, 2 * num_tissues]. + chex.assert_equal_shape([pred_pair, count_target, pairs_mask]) + chex.assert_rank(pred_pair, 4) + + def _scale_junction_counts(counts): + return jnp.where( + counts > _SOFT_CLIP_VALUE, + 2.0 * jnp.sqrt(counts * _SOFT_CLIP_VALUE) - _SOFT_CLIP_VALUE, + counts, + ) + + accept_total_loss = losses.poisson_loss( + y_true=_scale_junction_counts( + count_target.sum(axis=-2, dtype=jnp.float32, where=pairs_mask) + ), + y_pred=pred_pair.sum(axis=-2, dtype=jnp.float32, where=pairs_mask), + mask=jnp.any(pairs_mask, axis=-2), + ) + donor_total_loss = losses.poisson_loss( + y_true=_scale_junction_counts( + count_target.sum(axis=-3, dtype=jnp.float32, where=pairs_mask) + ), + y_pred=pred_pair.sum(axis=-3, dtype=jnp.float32, where=pairs_mask), + mask=jnp.any(pairs_mask, axis=-3), + ) + + # Ratios with cross entropy loss. + donor_ratios_loss = losses.cross_entropy_loss( + y_true=count_target, + y_pred=pred_pair, + mask=pairs_mask, + axis=-3, + ) + acceptor_ratios_loss = losses.cross_entropy_loss( + y_true=count_target, + y_pred=pred_pair, + mask=pairs_mask, + axis=-2, + ) + loss = ( + donor_ratios_loss + + acceptor_ratios_loss + + 0.2 * (accept_total_loss + donor_total_loss) + ) + return {'loss': loss} diff --git a/flax_model/alphagenome/model/heads_test.py b/flax_model/alphagenome/model/heads_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4543befd414cb7780f7dbe2be5d593e61cc5d2b7 --- /dev/null +++ b/flax_model/alphagenome/model/heads_test.py @@ -0,0 +1,677 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import junction_data +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome.io import bundles +from flax_model.alphagenome.model import embeddings +from flax_model.alphagenome.model import heads +from flax_model.alphagenome.model import schemas +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +import chex +import haiku as hk +import jax +import jax.numpy as jnp +import numpy as np +import pandas as pd + + +_EMBEDDING_DIM_PAIR = 128 +_EMBEDDING_DIM_1BP = 1536 +_EMBEDDING_DIM_128BP = 3072 + +# Number of tracks for human and mouse. +_MOCK_ATAC_NUM_TRACKS = (9, 7) +_MOCK_CHIP_TF_NUM_TRACKS = (11, 10) +_MOCK_CONTACT_MAPS_NUM_TRACKS = (8, 7) +_MOCK_SPLICE_SITES_NUM_TRACKS = (5, 5) +_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS = (10, 9) +_MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES = (15, 12) # Tissues, not tracks. + + +_ORGANSIM_INDEX = { + dna_model.Organism.HOMO_SAPIENS: 0, + dna_model.Organism.MUS_MUSCULUS: 1, +} + + +def get_mock_output_metadata( + organism: dna_model.Organism, +) -> metadata_lib.AlphaGenomeOutputMetadata: + """Returns mock output metadata for the given organisms.""" + + def _make_metadata_df(total_tracks, num_tracks) -> track_data.TrackMetadata: + df_tracks = pd.DataFrame({ + 'name': [f'track_{i}' for i in range(num_tracks)], + 'nonzero_mean': [1.0] * num_tracks, + }) + df_padding = pd.DataFrame({ + 'name': ['padding'] * (total_tracks - num_tracks), + 'nonzero_mean': [0.0] * (total_tracks - num_tracks), + }) + return pd.concat([df_tracks, df_padding], ignore_index=True) + + def _make_junction_metadata_df(num_tissues) -> junction_data.JunctionMetadata: + return pd.DataFrame({ + 'name': [f'tissue_{i}' for i in range(num_tissues)], + }) + + organism_idx = _ORGANSIM_INDEX[organism] + return metadata_lib.AlphaGenomeOutputMetadata( + atac=_make_metadata_df( + max(_MOCK_ATAC_NUM_TRACKS), _MOCK_ATAC_NUM_TRACKS[organism_idx] + ), + chip_tf=_make_metadata_df( + max(_MOCK_CHIP_TF_NUM_TRACKS), + _MOCK_CHIP_TF_NUM_TRACKS[organism_idx], + ), + contact_maps=_make_metadata_df( + max(_MOCK_CONTACT_MAPS_NUM_TRACKS), + _MOCK_CONTACT_MAPS_NUM_TRACKS[organism_idx], + ), + splice_sites=_make_metadata_df( + max(_MOCK_SPLICE_SITES_NUM_TRACKS), + _MOCK_SPLICE_SITES_NUM_TRACKS[organism_idx], + ), + splice_site_usage=_make_metadata_df( + max(_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS), + _MOCK_SPLICE_SITES_USAGE_NUM_TRACKS[organism_idx], + ), + splice_junctions=_make_junction_metadata_df( + _MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES[organism_idx], + ), + ) + + +@typing.jaxtyped +def get_mock_embeddings( + batch_size: int, + sequence_length: int, +) -> embeddings.Embeddings: + """Returns mock embeddings for testing.""" + return embeddings.Embeddings( + embeddings_pair=jnp.zeros( + ( + batch_size, + sequence_length // 2048, + sequence_length // 2048, + _EMBEDDING_DIM_PAIR, + ), + dtype=jnp.bfloat16, + ), + embeddings_1bp=jnp.zeros( + (batch_size, sequence_length, _EMBEDDING_DIM_1BP), dtype=jnp.bfloat16 + ), + embeddings_128bp=jnp.zeros( + (batch_size, sequence_length // 128, _EMBEDDING_DIM_128BP), + dtype=jnp.bfloat16, + ), + ) + + +@typing.jaxtyped +def get_mock_batch( + batch_size: int, + sequence_length: int, + num_splice_sites: int, + organism_index: int = 0, +) -> schemas.DataBatch: + """Returns mock target data for testing.""" + return schemas.DataBatch( + organism_index=jnp.ones((batch_size,), dtype=jnp.int32) * organism_index, + atac=jnp.zeros( + (batch_size, sequence_length, max(_MOCK_ATAC_NUM_TRACKS)), + dtype=jnp.float32, + ), + atac_mask=jnp.ones( + (batch_size, 1, max(_MOCK_ATAC_NUM_TRACKS)), + dtype=bool, + ), + chip_tf=jnp.zeros( + (batch_size, sequence_length // 128, max(_MOCK_CHIP_TF_NUM_TRACKS)), + dtype=jnp.float32, + ), + chip_tf_mask=jnp.ones( + (batch_size, 1, max(_MOCK_CHIP_TF_NUM_TRACKS)), + dtype=bool, + ), + contact_maps=jnp.zeros( + ( + batch_size, + sequence_length // 16 // 128, + sequence_length // 16 // 128, + max(_MOCK_CONTACT_MAPS_NUM_TRACKS), + ), + dtype=jnp.float32, + ), + splice_junctions=jnp.zeros( + ( + batch_size, + num_splice_sites, + num_splice_sites, + max(_MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES) * 2, + ), + dtype=jnp.float32, + ), + splice_site_positions=jnp.zeros( + (batch_size, 4, num_splice_sites), dtype=jnp.int32 + ), + splice_site_usage=jnp.zeros( + ( + batch_size, + sequence_length, + max(_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS), + ), + dtype=jnp.float32, + ), + splice_sites=jnp.ones( + (batch_size, sequence_length, max(_MOCK_SPLICE_SITES_NUM_TRACKS)), + dtype=bool, + ), + ) + + +class HeadsTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self.batch_size = 1 + # Set >= multinomial resolution of 2^17. + self.sequence_length = int(2**17) + self.num_splice_sites = 128 + + def test_head_num_tracks_with_default_metadata(self): + metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.load( + dna_model.Organism.HOMO_SAPIENS + ), + dna_model.Organism.MUS_MUSCULUS: metadata_lib.load( + dna_model.Organism.MUS_MUSCULUS + ), + } + expected_num_tracks = { + heads.HeadName.ATAC: 256, + heads.HeadName.DNASE: 384, + heads.HeadName.PROCAP: 128, + heads.HeadName.CAGE: 640, + heads.HeadName.RNA_SEQ: 768, + heads.HeadName.CHIP_TF: 1664, + heads.HeadName.CHIP_HISTONE: 1152, + heads.HeadName.CONTACT_MAPS: 28, + heads.HeadName.SPLICE_SITES_CLASSIFICATION: 5, + heads.HeadName.SPLICE_SITES_USAGE: 734, + heads.HeadName.SPLICE_SITES_JUNCTION: 734, + } + for head_name in heads.HeadName: + with self.subTest(head_name.value): + config = heads.get_head_config(head_name) + head = heads.create_head(config, metadata) + self.assertEqual(head.num_tracks, expected_num_tracks[head_name]) + + def test_genome_tracks_head_no_metadata_raises_error(self): + metadata = { + dna_model.Organism.HOMO_SAPIENS: ( + metadata_lib.AlphaGenomeOutputMetadata() + ), + } + with self.assertRaisesRegex( + ValueError, 'No metadata found for any organism' + ): + _ = heads.GenomeTracksHead( + name='test_head', + output_type=dna_output.OutputType.ATAC, + apply_squashing=True, + resolutions=[1], + bundle=bundles.BundleName.ATAC, + metadata=metadata, + ) + + def test_genome_tracks_head_inconsistent_num_tracks_raises_error(self): + def _make_metadata_df(num_tracks) -> track_data.TrackMetadata: + return pd.DataFrame({ + 'name': [f'track_{i}' for i in range(num_tracks)], + 'nonzero_mean': [1.0] * num_tracks, + }) + + metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_make_metadata_df(10) + ), + dna_model.Organism.MUS_MUSCULUS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_make_metadata_df(11) + ), + } + with self.assertRaisesRegex( + ValueError, + 'Number of tracks is not the same for all organisms', + ): + _ = heads.GenomeTracksHead( + name='test_head', + output_type=dna_output.OutputType.ATAC, + apply_squashing=True, + resolutions=[1], + bundle=bundles.BundleName.ATAC, + metadata=metadata, + ) + + def _test_head( + self, + head: heads.Head, + expected_params_shape: Any, + expected_output_shape: Any, + ): + @hk.transform + def forward(embeddings_input, batch): + kwargs = {} + if isinstance(head, heads.SpliceSitesJunctionHead): + kwargs['splice_site_positions'] = batch.splice_site_positions + output = head(embeddings_input, batch.organism_index, **kwargs) + loss = head.loss(output, batch) + return output, loss + + rng = jax.random.PRNGKey(42) + embeddings_input = get_mock_embeddings( + self.batch_size, self.sequence_length + ) + batch = get_mock_batch( + self.batch_size, self.sequence_length, self.num_splice_sites + ) + + params = forward.init(rng, embeddings_input, batch) + output, loss = forward.apply(params, rng, embeddings_input, batch) + + to_shape = lambda t: jax.tree.map(lambda x: x.shape, t) + chex.assert_trees_all_equal(to_shape(params), expected_params_shape) + chex.assert_trees_all_equal(to_shape(output), expected_output_shape) + self.assertTrue(np.isfinite(loss['loss']).all()) + + @parameterized.named_parameters( + dict( + testcase_name='one_organism', + organisms=(dna_model.Organism.HOMO_SAPIENS,), + ), + dict( + testcase_name='two_organisms', + organisms=( + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ), + ), + ) + def test_genome_tracks_head(self, organisms: tuple[dna_model.Organism, ...]): + metadata = { + organism: get_mock_output_metadata(organism) for organism in organisms + } + head = heads.GenomeTracksHead( + name='test_head', + output_type=dna_output.OutputType.ATAC, + apply_squashing=True, + resolutions=[1, 128], + bundle=bundles.BundleName.ATAC, + metadata=metadata, + ) + with self.subTest('num_organisms'): + self.assertLen(head.get_multi_organism_track_mask(), len(metadata)) + with self.subTest('num_tracks'): + self.assertEqual(head.num_tracks, max(_MOCK_ATAC_NUM_TRACKS)) + with self.subTest('track_mask'): + for i, organism in enumerate(organisms): + organism_idx = _ORGANSIM_INDEX[organism] + self.assertEqual( + np.sum(head.get_multi_organism_track_mask()[i]), + _MOCK_ATAC_NUM_TRACKS[organism_idx], + ) + + num_organisms = len(metadata) + num_tracks = head.num_tracks + expected_params_shape = { + 'test_head/resolution_1': {'learnt_scale': (num_organisms, num_tracks)}, + 'test_head/resolution_1/multi_organism_linear': { + 'b': (num_organisms, num_tracks), + 'w': (num_organisms, _EMBEDDING_DIM_1BP, num_tracks), + }, + 'test_head/resolution_128': { + 'learnt_scale': (num_organisms, num_tracks) + }, + 'test_head/resolution_128/multi_organism_linear': { + 'b': (num_organisms, num_tracks), + 'w': (num_organisms, _EMBEDDING_DIM_128BP, num_tracks), + }, + } + expected_output_shape = { + 'scaled_predictions_1bp': ( + self.batch_size, + self.sequence_length, + num_tracks, + ), + 'predictions_1bp': (self.batch_size, self.sequence_length, num_tracks), + 'scaled_predictions_128bp': ( + self.batch_size, + self.sequence_length // 128, + num_tracks, + ), + 'predictions_128bp': ( + self.batch_size, + self.sequence_length // 128, + num_tracks, + ), + } + with self.subTest('params_shape'): + self._test_head( + head, + expected_params_shape, + expected_output_shape, + ) + + @parameterized.named_parameters( + dict( + testcase_name='one_organism', + organisms=(dna_model.Organism.HOMO_SAPIENS,), + ), + dict( + testcase_name='two_organisms', + organisms=( + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ), + ), + ) + def test_contact_maps_head(self, organisms: tuple[dna_model.Organism, ...]): + metadata = { + organism: get_mock_output_metadata(organism) for organism in organisms + } + config = heads.get_head_config(heads.HeadName.CONTACT_MAPS) + head = heads.create_head(config, metadata) + + with self.subTest('num_organisms'): + self.assertLen(head.get_multi_organism_track_mask(), len(metadata)) + with self.subTest('num_tracks'): + self.assertEqual(head.num_tracks, max(_MOCK_CONTACT_MAPS_NUM_TRACKS)) + with self.subTest('track_mask'): + for i, organism in enumerate(organisms): + organism_idx = _ORGANSIM_INDEX[organism] + self.assertEqual( + np.sum(head.get_multi_organism_track_mask()[i]), + _MOCK_CONTACT_MAPS_NUM_TRACKS[organism_idx], + ) + + num_organisms = len(metadata) + num_tracks = head.num_tracks + prefix = config.name + expected_params_shape = { + f'{prefix}/multi_organism_linear': { + 'b': (num_organisms, num_tracks), + 'w': (num_organisms, _EMBEDDING_DIM_PAIR, num_tracks), + }, + } + expected_output_shape = { + 'predictions': ( + self.batch_size, + self.sequence_length // 2048, + self.sequence_length // 2048, + num_tracks, + ), + } + with self.subTest('params_shape'): + self._test_head( + head, + expected_params_shape, + expected_output_shape, + ) + + @parameterized.named_parameters( + dict( + testcase_name='one_organism', + organisms=(dna_model.Organism.HOMO_SAPIENS,), + ), + dict( + testcase_name='two_organisms', + organisms=( + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ), + ), + ) + def test_splice_sites_classification_head( + self, organisms: tuple[dna_model.Organism, ...] + ): + metadata = { + organism: get_mock_output_metadata(organism) for organism in organisms + } + config = heads.get_head_config(heads.HeadName.SPLICE_SITES_CLASSIFICATION) + head = heads.create_head(config, metadata) + + with self.subTest('num_organisms'): + self.assertLen(head.get_multi_organism_track_mask(), len(metadata)) + with self.subTest('num_tracks'): + self.assertEqual(head.num_tracks, max(_MOCK_SPLICE_SITES_NUM_TRACKS)) + with self.subTest('track_mask'): + for i, organism in enumerate(organisms): + organism_idx = _ORGANSIM_INDEX[organism] + self.assertEqual( + np.sum(head.get_multi_organism_track_mask()[i]), + _MOCK_SPLICE_SITES_NUM_TRACKS[organism_idx], + ) + + num_organisms = len(metadata) + num_tracks = head.num_tracks + prefix = config.name + expected_params_shape = { + f'{prefix}/multi_organism_linear': { + 'b': (num_organisms, num_tracks), + 'w': (num_organisms, _EMBEDDING_DIM_1BP, num_tracks), + }, + } + expected_output_shape = { + 'predictions': ( + self.batch_size, + self.sequence_length, + num_tracks, + ), + 'logits': ( + self.batch_size, + self.sequence_length, + num_tracks, + ), + } + self._test_head( + head, + expected_params_shape, + expected_output_shape, + ) + + @parameterized.named_parameters( + dict( + testcase_name='one_organism', + organisms=(dna_model.Organism.HOMO_SAPIENS,), + ), + dict( + testcase_name='two_organisms', + organisms=( + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ), + ), + ) + def test_splice_sites_usage_head( + self, organisms: tuple[dna_model.Organism, ...] + ): + metadata = { + organism: get_mock_output_metadata(organism) for organism in organisms + } + config = heads.get_head_config(heads.HeadName.SPLICE_SITES_USAGE) + head = heads.create_head(config, metadata) + + with self.subTest('num_organisms'): + self.assertLen(head.get_multi_organism_track_mask(), len(metadata)) + with self.subTest('num_tracks'): + self.assertEqual( + head.num_tracks, max(_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS) + ) + with self.subTest('track_mask'): + for i, organism in enumerate(organisms): + organism_idx = _ORGANSIM_INDEX[organism] + self.assertEqual( + np.sum(head.get_multi_organism_track_mask()[i]), + _MOCK_SPLICE_SITES_USAGE_NUM_TRACKS[organism_idx], + ) + + num_organisms = len(metadata) + num_tracks = head.num_tracks + prefix = config.name + expected_params_shape = { + f'{prefix}/multi_organism_linear': { + 'b': (num_organisms, num_tracks), + 'w': (num_organisms, _EMBEDDING_DIM_1BP, num_tracks), + }, + } + expected_output_shape = { + 'predictions': ( + self.batch_size, + self.sequence_length, + num_tracks, + ), + 'logits': ( + self.batch_size, + self.sequence_length, + num_tracks, + ), + } + self._test_head( + head, + expected_params_shape, + expected_output_shape, + ) + + @parameterized.named_parameters( + dict( + testcase_name='one_organism', + organisms=(dna_model.Organism.HOMO_SAPIENS,), + ), + dict( + testcase_name='two_organisms', + organisms=( + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ), + ), + ) + def test_splice_sites_junction_head( + self, organisms: tuple[dna_model.Organism, ...] + ): + metadata = { + organism: get_mock_output_metadata(organism) for organism in organisms + } + config = heads.get_head_config(heads.HeadName.SPLICE_SITES_JUNCTION) + head = heads.create_head(config, metadata) + assert isinstance(head, heads.SpliceSitesJunctionHead) + + with self.subTest('num_organisms'): + self.assertLen(head.get_multi_organism_track_mask(), len(metadata)) + with self.subTest('num_tracks'): + self.assertEqual( + head.num_tracks, 2 * max(_MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES) + ) + with self.subTest('track_mask'): + for i, organism in enumerate(organisms): + organism_idx = _ORGANSIM_INDEX[organism] + self.assertEqual( + np.sum(head.get_multi_organism_track_mask()[i]), + 2 * _MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES[organism_idx], + ) + + num_organisms = len(metadata) + num_tracks = head.num_tracks + num_tissues = head.max_num_tissues + hidden_dim = 768 + prefix = config.name + expected_params_shape = { + f'{prefix}/pos_acceptor_logits': { + 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim), + }, + f'{prefix}/pos_donor_logits': { + 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim), + }, + f'{prefix}/neg_acceptor_logits': { + 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim), + }, + f'{prefix}/neg_donor_logits': { + 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim), + }, + f'{prefix}/multi_organism_linear': { + 'b': (num_organisms, hidden_dim), + 'w': (num_organisms, _EMBEDDING_DIM_1BP, hidden_dim), + }, + } + expected_output_shape = { + 'predictions': ( + self.batch_size, + self.num_splice_sites, + self.num_splice_sites, + num_tracks, + ), + 'splice_site_positions': ( + self.batch_size, + 4, + self.num_splice_sites, + ), + 'splice_junction_mask': ( + self.batch_size, + self.num_splice_sites, + self.num_splice_sites, + num_tracks, + ), + } + self._test_head( + head, + expected_params_shape, + expected_output_shape, + ) + + @parameterized.named_parameters( + dict(testcase_name='with_squashing', apply_squashing=True), + dict(testcase_name='without_squashing', apply_squashing=False), + ) + def test_scaling_and_unscaling(self, apply_squashing: bool): + batch_size, sequence_length, num_tracks, resolution = 3, 2048, 10, 1 + key = jax.random.PRNGKey(42) + key_data, key_means = jax.random.split(key) + track_means = jax.random.uniform(key_means, (batch_size, num_tracks)) + 0.01 + input_data = jax.random.uniform( + key_data, (batch_size, sequence_length, num_tracks), minval=0, maxval=99 + ) + scaled_data = heads.targets_scaling( + input_data, + track_means=track_means, + resolution=resolution, + apply_squashing=apply_squashing, + ) + unscaled_data = heads.predictions_scaling( + scaled_data, + track_means=track_means, + resolution=resolution, + apply_squashing=apply_squashing, + ) + chex.assert_trees_all_close(input_data, unscaled_data, rtol=1e-5, atol=1e-5) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/interval_scoring/__init__.py b/flax_model/alphagenome/model/interval_scoring/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a14856a0caa4b98b6df7ed5a4868434153023a19 --- /dev/null +++ b/flax_model/alphagenome/model/interval_scoring/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome Interval Scoring.""" diff --git a/flax_model/alphagenome/model/interval_scoring/gene_mask.py b/flax_model/alphagenome/model/interval_scoring/gene_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..b932d34404bb5c2f2308a5a213645e68d5fd13bc --- /dev/null +++ b/flax_model/alphagenome/model/interval_scoring/gene_mask.py @@ -0,0 +1,142 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implementation of gene mask interval scoring.""" + +from collections.abc import Mapping + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import interval_scorers +from flax_model.alphagenome.model.interval_scoring import interval_scoring +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor as gene_mask_extractor_lib +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float32 # pylint: disable=g-multiple-import, g-importing-member +import numpy as np +import pandas as pd + + +class GeneIntervalScorer( + interval_scoring.IntervalScorer[ + Bool[np.ndarray | Array, 'M G'], + pd.DataFrame, + interval_scorers.GeneMaskScorer, + ] +): + """Interval scorer that aggregates intervals across different genes.""" + + def __init__( + self, gene_mask_extractor: gene_mask_extractor_lib.GeneMaskExtractor + ): + """Initializes the GeneIntervalScorer. + + Args: + gene_mask_extractor: Gene mask extractor to use. + """ + self._gene_mask_extractor = gene_mask_extractor + + def get_masks_and_metadata( + self, + interval: genome.Interval, + *, + settings: interval_scorers.GeneMaskScorer, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[Bool[np.ndarray | Array, 'S G'], pd.DataFrame]: + """Get gene masks and metadata for the given interval. + + Args: + interval: Genomic interval to extract gene masks for. + settings: The variant scorer settings. + track_metadata: Track metadata for the variant. + + Returns: + Tuple of (gene variant masks, mask metadata). The mask metadata is the + part of the GTF pandas dataframe that was used to construct the gene + masks. + """ + del track_metadata + if interval.negative_strand: + raise ValueError( + 'IntervalScorers do not support negative strands (negative strand' + ' predictions should already be reverse-complemented prior to' + ' scoring and thus masks should be generated on the positive strand).' + ) + if settings.width is not None and settings.width > interval.width: + raise ValueError('Interval width must be >= the center mask width.') + resolution = variant_scoring.get_resolution(settings.requested_output) + target_interval = ( + interval.resize(width=settings.width) + if settings.width is not None + else interval + ) + + gene_mask, metadata = self._gene_mask_extractor.extract(target_interval) + interval_padding = interval.width - target_interval.width + gene_mask = np.pad( + gene_mask, + ((interval_padding // 2, (interval_padding + 1) // 2), (0, 0)), + ) + if resolution > 1: + gene_mask = gene_mask.reshape( + (gene_mask.shape[0] // resolution, resolution, -1) + ).max(axis=1) + return gene_mask, metadata + + @typing.jaxtyped + def score_interval( + self, + predictions: Mapping[dna_output.OutputType, Float32[Array, 'S T']], + *, + masks: Bool[Array | np.ndarray, 'M G'], + settings: interval_scorers.GeneMaskScorer, + interval: genome.Interval | None = None, + ) -> interval_scoring.ScoreIntervalOutput: + """See base class.""" + del interval + tracks = predictions[settings.requested_output] + + match settings.aggregation_type: + case interval_scorers.IntervalAggregationType.MEAN: + output = jnp.einsum('lt,lg->gt', tracks, masks) / jnp.expand_dims( + masks.sum(axis=0), axis=-1 + ) + case interval_scorers.IntervalAggregationType.SUM: + output = jnp.einsum('lt,lg->gt', tracks, masks) + case _: + raise ValueError( + f'Unsupported aggregation type: {self._aggregation_type}.' + ) + + return {'score': output} + + def finalize_interval( + self, + scores: interval_scoring.ScoreIntervalResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: pd.DataFrame, + settings: interval_scorers.GeneMaskScorer, + ) -> anndata.AnnData: + """Returns summarized scores for the given scores and metadata.""" + output_metadata = track_metadata.get(settings.requested_output) + assert isinstance(output_metadata, track_data.TrackMetadata) + return variant_scoring.create_anndata( + scores['score'], + obs=mask_metadata, + var=output_metadata, + ) diff --git a/flax_model/alphagenome/model/interval_scoring/gene_mask_test.py b/flax_model/alphagenome/model/interval_scoring/gene_mask_test.py new file mode 100644 index 0000000000000000000000000000000000000000..dd6589975c50fb9c6b56d443cc0e064c99c44baf --- /dev/null +++ b/flax_model/alphagenome/model/interval_scoring/gene_mask_test.py @@ -0,0 +1,266 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import interval_scorers +from flax_model.alphagenome.model.interval_scoring import gene_mask +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import jax.numpy as jnp +import numpy as np +import pandas as pd + + +def _load_gtf(): + return pd.DataFrame({ + 'End': [306, 303, 305, 138, 15], + 'Start': [301, 302, 303, 0, 5], + 'Strand': ['+', '+', '+', '-', '-'], + 'transcript_id': ['', 'T1', 'T2', '', 'T3'], + 'gene_id': ['G1', 'G1', 'G1', 'G2', 'G2'], + 'Feature': [ + 'gene', + 'transcript', + 'transcript', + 'gene', + 'transcript', + ], + # Fixed Fields + 'Chromosome': 'chr1', + 'Score': '.', + 'Frame': '.', + 'Source': 'ENSEMBL', + 'gene_type': 'protein_coding', + 'gene_name': 'GX_name', + 'transcript_type': 'protein_coding', + }) + + +class GeneIntervalScorerTest(parameterized.TestCase): + + @parameterized.product( + aggregation_type=[ + interval_scorers.IntervalAggregationType.SUM, + interval_scorers.IntervalAggregationType.MEAN, + ], + output_type=[dna_output.OutputType.RNA_SEQ, dna_output.OutputType.DNASE], + ) + def test_gene_scorer_get_masks_and_metadata( + self, aggregation_type, output_type + ): + gtf = _load_gtf() + + settings = interval_scorers.GeneMaskScorer( + requested_output=output_type, + aggregation_type=aggregation_type, + width=501, + ) + + interval = genome.Interval('chr1', 0, 2048) + interval_scorer = gene_mask.GeneIntervalScorer( + gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + ) + ) + + track_metadata = dna_output.OutputMetadata(**{ + output_type.name.lower(): pd.DataFrame({ + 'name': np.arange(9).astype(str), + 'strand': '.', + }) + }) + masks, metadata = interval_scorer.get_masks_and_metadata( + interval, settings=settings, track_metadata=track_metadata + ) + self.assertIsInstance(metadata, pd.DataFrame) + self.assertContainsSubset( + ['strand', 'gene_name', 'gene_id', 'gene_type'], metadata.columns + ) + + self.assertEqual(masks.shape[0], interval.width) + + def test_gene_scorer_get_masks_and_metadata_negative_strand(self): + gtf = _load_gtf() + interval_scorer = gene_mask.GeneIntervalScorer( + gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + ) + ) + settings = interval_scorers.GeneMaskScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + aggregation_type=interval_scorers.IntervalAggregationType.SUM, + width=501, + ) + with self.assertRaisesRegex( + ValueError, 'IntervalScorers do not support negative strands' + ): + _ = interval_scorer.get_masks_and_metadata( + genome.Interval('chr1', 0, 2048, strand='-'), + settings=settings, + track_metadata=dna_output.OutputMetadata(), + ) + + @parameterized.product( + aggregation_type=[ + interval_scorers.IntervalAggregationType.SUM, + interval_scorers.IntervalAggregationType.MEAN, + ], + output_type=[dna_output.OutputType.RNA_SEQ, dna_output.OutputType.DNASE], + ) + def test_gene_scorer_score_interval( + self, + aggregation_type, + output_type, + ): + # Score a simple example for an interval of length 10, consisting of 100 + # tracks, all of values 0..9 depending on the position. The mask + # includes positions 4-6. + tracks = jnp.arange(10, dtype=jnp.float32).repeat(100).reshape((10, 100)) + mask = np.zeros((10, 3), dtype=bool) + mask[4:7] = True + + gtf = _load_gtf() + settings = interval_scorers.GeneMaskScorer( + requested_output=output_type, + aggregation_type=aggregation_type, + width=501, + ) + interval_scorer = gene_mask.GeneIntervalScorer( + gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, gene_mask_type=gene_mask_extractor.GeneMaskType.BODY + ), + ) + scores = interval_scorer.score_interval( + {output_type: tracks}, settings=settings, masks=mask + ) + + expected_num_tracks = 100 + match aggregation_type: + case interval_scorers.IntervalAggregationType.SUM: + expected_score = 15.0 + case interval_scorers.IntervalAggregationType.MEAN: + expected_score = 5.0 + case _: + raise ValueError(f'Unknown aggregation type: {aggregation_type}') + + np.testing.assert_almost_equal( + scores['score'][0], + np.full((expected_num_tracks,), expected_score, dtype=jnp.float32), + ) + + @parameterized.product( + center_mask_width=[501], + output_type=[ + dna_output.OutputType.RNA_SEQ, + dna_output.OutputType.CHIP_TF, + ], + ) + def test_gene_scorer_with_center_mask_width( + self, + center_mask_width, + output_type, + ): + gtf = _load_gtf() + interval = genome.Interval('chr1', 0, 1024) + interval_scorer = gene_mask.GeneIntervalScorer( + gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + ), + ) + settings = interval_scorers.GeneMaskScorer( + requested_output=output_type, + aggregation_type=interval_scorers.IntervalAggregationType.MEAN, + width=center_mask_width, + ) + resolution = variant_scoring.get_resolution(output_type) + num_bins = interval.width // resolution + tracks = ( + jnp.arange(num_bins, dtype=jnp.float32).repeat(4).reshape((num_bins, 4)) + ) + + track_metadata = dna_output.OutputMetadata(**{ + output_type.name.lower(): pd.DataFrame( + {'name': np.arange(4).astype(str), 'strand': '.'} + ) + }) + masks, metadata = interval_scorer.get_masks_and_metadata( + interval, settings=settings, track_metadata=track_metadata + ) + scores = interval_scorer.score_interval( + {output_type: tracks}, settings=settings, masks=masks + ) + + expected_genes = ['G1'] + expected_mask = np.zeros([num_bins, len(expected_genes)], dtype=bool) + expected_scores = np.full( + (len(expected_genes), 4), np.nan, dtype=jnp.float32 + ) + + if resolution == 1: + expected_mask[301:306, 0] = True # G1 + expected_scores[0] = 303.0 + else: + expected_mask[2, 0] = True # G1 + expected_scores[0] = 2.0 + np.testing.assert_array_equal(masks, expected_mask) + np.testing.assert_almost_equal(scores['score'], expected_scores) + np.testing.assert_array_equal(metadata['gene_id'].values, expected_genes) + + def test_gene_scorer_finalize(self): + interval = genome.Interval('chr1', 0, 2048) + track_metadata = dna_output.OutputMetadata( + rna_seq=pd.DataFrame({ + 'name': np.arange(9).astype(str), + 'strand': '.', + }) + ) + expected_scores = np.full((1, 9), 15.0, dtype=jnp.float32) + scores = {'score': expected_scores} + + gtf = _load_gtf() + interval_scorer = gene_mask.GeneIntervalScorer( + gene_mask_extractor.GeneMaskExtractor( + gtf=gtf, gene_mask_type=gene_mask_extractor.GeneMaskType.BODY + ) + ) + + settings = interval_scorers.GeneMaskScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + aggregation_type=interval_scorers.IntervalAggregationType.SUM, + width=2001, + ) + + _, mask_metadata = interval_scorer.get_masks_and_metadata( + interval, track_metadata=track_metadata, settings=settings + ) + finalized_score = interval_scorer.finalize_interval( + scores, + track_metadata=track_metadata, + mask_metadata=mask_metadata, + settings=settings, + ) + + self.assertIsInstance(finalized_score, anndata.AnnData) + np.testing.assert_array_almost_equal(finalized_score.X, expected_scores) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/interval_scoring/interval_scoring.py b/flax_model/alphagenome/model/interval_scoring/interval_scoring.py new file mode 100644 index 0000000000000000000000000000000000000000..a156e7adeb58da1903316305623db4cc1c0dbe17 --- /dev/null +++ b/flax_model/alphagenome/model/interval_scoring/interval_scoring.py @@ -0,0 +1,113 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Base class for interval scorers.""" + +import abc +from collections.abc import Mapping +from typing import Generic, TypeVar + +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +import anndata +import jax +from jaxtyping import Array, Float32 # pylint: disable=g-multiple-import, g-importing-member +import numpy as np + +IntervalMaskT = TypeVar('IntervalMaskT') +IntervalMetadataT = TypeVar('IntervalMetadataT') +IntervalSettingsT = TypeVar('IntervalSettingsT') + +ScoreIntervalOutput = Mapping[str, jax.Array | np.ndarray] +ScoreIntervalResult = Mapping[str, np.ndarray] + + +class IntervalScorer( + Generic[IntervalMaskT, IntervalMetadataT, IntervalSettingsT], + metaclass=abc.ABCMeta, +): + """Abstract class for interval scorers.""" + + @abc.abstractmethod + def get_masks_and_metadata( + self, + interval: genome.Interval, + *, + settings: IntervalSettingsT, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[IntervalMaskT, IntervalMetadataT]: + """Returns masks and metadata for the given interval and metadata. + + The generated masks and metadata will be passed to `score_interval` and + `finalize_interval` respectively. + + Args: + interval: The interval to score. + settings: The interval scorer settings. + track_metadata: The model's track metadata. + + Returns: + A tuple of (masks, metadata), where: + masks: The masks required to score the interval, such as gene or TSS or + strand masks. These will be passed into the jitted `score_interval` + function. + metadata: The metadata required to finalize the interval. These will + be passed into the `finalize_interval` function. + + The formats/shapes of masks and metadata will vary across interval scorers + depending on their individual needs. + """ + + @abc.abstractmethod + def score_interval( + self, + predictions: Mapping[dna_output.OutputType, Float32[Array, 'S T']], + *, + masks: IntervalMaskT, + settings: IntervalSettingsT, + interval: genome.Interval | None = None, + ) -> ScoreIntervalOutput: + """Generates a score per track for the provided predictions. + + Args: + predictions: Model predictions for the interval. + masks: The masks for scoring the interval. + settings: The interval scorer settings. + interval: The interval to score. + + Returns: + Dictionary of scores to be passed to `finalize_interval`. + """ + + @abc.abstractmethod + def finalize_interval( + self, + scores: ScoreIntervalResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: IntervalMetadataT, + settings: IntervalSettingsT, + ) -> anndata.AnnData: + """Returns finalized scores for the given scores and metadata. + + Args: + scores: Dictionary of scores generated from `score_interval` function. + track_metadata: Metadata describing the tracks for each output_type. + mask_metadata: Metadata describing the masks. + settings: The interval scorer settings. + + Returns: + An AnnData object containing the final interval outputs. The entries will + vary across scorers depending on their individual needs. + """ diff --git a/flax_model/alphagenome/model/layers.py b/flax_model/alphagenome/model/layers.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf5667be0a51ca276344d00463764ec70cfc2bc --- /dev/null +++ b/flax_model/alphagenome/model/layers.py @@ -0,0 +1,123 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common layers.""" + +from flax_model.alphagenome._sdk import typing +import haiku as hk +import jax +import jax.numpy as jnp +from jaxtyping import Array, Float # pylint: disable=g-importing-member, g-multiple-import + + +def gelu(x: jax.Array) -> jax.Array: + """Gaussian Error Linear Unit activation function.""" + coef = jax.lax.convert_element_type(1.702, x.dtype) + return jax.nn.sigmoid(coef * x) * x + + +@typing.jaxtyped +def pool( + x: Float[Array, '... S D'], by: int = 2, reduce: str = 'max' +) -> Float[Array, '... S/{by} D']: + """Applies pooling to the sequence dimension of the input. + + Args: + x: The input sequence, where the second to last dimension is the sequence + dimension. + by: The pooling window size. + reduce: The pooling reduction method. + + Returns: + The pooled sequence. + Raises: + NotImplementedError: If the reduce method is not supported. + """ + if reduce == 'max': + return hk.MaxPool(window_shape=(by, 1), strides=(by, 1), padding='SAME')(x) + elif reduce in ['avg', 'mean']: + return hk.AvgPool(window_shape=(by, 1), strides=(by, 1), padding='SAME')(x) + else: + raise NotImplementedError(f'Reduce method={reduce} unknown.') + + +class RMSBatchNorm(hk.Module): + r"""Root Mean Square Batch Normalization. + + Normalization is applied to the last dimension of the input as + `x -> x * scale / sqrt(var + epsilon) + offset`. + The scale and offset are learned parameters. The variance is tracked + as an exponential moving average. + + Variance is computed across the batch and sequence dimension. + + Note: only support inference mode (i.e. no training). + """ + + def __call__(self, x: Float[Array, '... D']) -> Float[Array, '... D']: + param_shape = (1,) * (x.ndim - 1) + (x.shape[-1],) + variance = hk.get_state( + 'var_ema', param_shape, dtype=jnp.float32, init=jnp.ones + ) + scale = hk.get_parameter( + 'scale', param_shape, dtype=x.dtype, init=jnp.ones + ).astype(x.dtype) + offset = hk.get_parameter( + 'offset', param_shape, dtype=x.dtype, init=jnp.zeros + ) + inv = scale * jax.lax.rsqrt(variance + 1e-5).astype(x.dtype) + return x * inv + offset + + +class LayerNorm(hk.Module): + """Layer Normalization.""" + + def __init__( + self, rms_norm: bool = False, axis: int = -1, name: str | None = None + ) -> None: + """Initializes the LayerNorm module. + + Args: + rms_norm: If False, the input is centered before computing the + mean-squared for normalization. If True, the mean-squared is computed + directly on the uncentered input. + axis: The axis to apply the normalization to. + name: The name of the module. + """ + super().__init__(name=name) + self._rms_norm = rms_norm + self._axis = axis + + def __call__(self, x: Float[Array, '... D']) -> Float[Array, '... D']: + dtype = x.dtype + scale = hk.get_parameter( + 'scale', (x.shape[-1],), dtype, init=jnp.ones + ).astype(dtype) + offset = hk.get_parameter( + 'offset', (x.shape[-1],), dtype, init=jnp.zeros + ).astype(dtype) + scale = jax.lax.broadcast_to_rank(scale, x.ndim) + offset = jax.lax.broadcast_to_rank(offset, x.ndim) + + if not self._rms_norm: + mean = jnp.mean( + x, axis=self._axis, dtype=jnp.float32, keepdims=True + ).astype(dtype) + x = x - mean + + variance = jnp.mean( + jnp.square(x), axis=self._axis, dtype=jnp.float32, keepdims=True + ) + inv = scale * jax.lax.rsqrt(variance + 1e-5).astype(dtype) + return inv * x + offset diff --git a/flax_model/alphagenome/model/layers_test.py b/flax_model/alphagenome/model/layers_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2104eabc66cf4217244e7d79d3a446059862f11a --- /dev/null +++ b/flax_model/alphagenome/model/layers_test.py @@ -0,0 +1,71 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome.model import layers +import chex +import haiku as hk +import jax.numpy as jnp + + +def _get_pool_layer(by: int): + """Helper function to create the pool layer.""" + + def pool_fn(x): + return layers.pool(x, by=by) + + pool_mod = hk.transform(pool_fn) + return pool_mod + + +class LayersTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self._batch_size = 4 + self._sequence_length = 16 + self._num_channels = 8 + self._by = 2 + + def test_pool_shape(self): + """Tests that the pool layer returns the expected shape.""" + x = jnp.ones((self._batch_size, self._sequence_length, self._num_channels)) + pool_mod = _get_pool_layer(by=self._by) + params = pool_mod.init(None, x) + out = pool_mod.apply(params, None, x) + chex.assert_shape( + out, + ( + self._batch_size, + self._sequence_length // self._by, + self._num_channels, + ), + ) + + def test_pool_type_error(self): + """Tests that the pool layer raises a type error with invalid input.""" + with self.subTest('wrong_dtype'): + x = jnp.ones( + (self._batch_size, self._sequence_length, self._num_channels), + dtype=jnp.int32, # Provide wrong type. + ) + with self.assertRaises(TypeError): + pool_mod = _get_pool_layer(by=self._by) + params = pool_mod.init(None, x) + pool_mod.apply(params, None, x) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/losses.py b/flax_model/alphagenome/model/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..f1981e5793c111b45bb0d29cdd65220f93d54e2f --- /dev/null +++ b/flax_model/alphagenome/model/losses.py @@ -0,0 +1,184 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Losses for AlphaGenome.""" + +from flax_model.alphagenome._sdk import typing +import chex +from einshape import jax_einshape as einshape # pylint: disable=g-importing-member +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float, PyTree # pylint: disable=g-importing-member, g-multiple-import + + +@typing.jaxtyped +def _safe_masked_mean( + x: Float[Array, '*dims'], + mask: Bool[Array, '#*dims'] | None = None, +) -> Float[Array, '']: + """Safe jnp.mean that handles completely masked arrays.""" + if mask is None: + masked = x + mask = jnp.ones_like(x) + else: + # We need to broadcast mask to compute correct mean. + mask = jnp.broadcast_to(mask, x.shape) + masked = x * mask + + return jnp.sum(jnp.asarray(masked), dtype=jnp.float32) / jnp.maximum( + 1.0, jnp.sum(mask, dtype=jnp.float32) + ) + + +@typing.jaxtyped +def poisson_loss( + *, + y_true: Float[Array, '*dims'], + y_pred: Float[Array, '*dims'], + mask: Bool[Array, '#*dims'], +) -> Float[Array, '']: + """Poisson loss.""" + y_true = jnp.abs(y_true).astype(jnp.float32) + y_pred = y_pred.astype(jnp.float32) + y_pred_logits = jnp.log(y_pred + 1e-7) + # Substract the minimum value such that loss is zero at optimal prediction. + min_value = y_true - y_true * jnp.log(y_true + 1e-7) + loss = (y_pred - y_true * y_pred_logits) - min_value + return _safe_masked_mean(loss, mask) + + +@typing.jaxtyped +def multinomial_loss( + *, + y_true: Float[Array, '... S C'], + y_pred: Float[Array, '... S C'], + mask: Bool[Array, '... 1 C'], + multinomial_resolution: int, + positional_weight: float, +) -> PyTree[Float[Array, '']]: + """Returns sum of multinomial losses and Poison loss on total count. + + Args: + y_true: Target values. + y_pred: Model predictions. + mask: Array of bools. + multinomial_resolution: We split the input into sub-sequences and compute a + separate multinomial loss over each sub-sequence. + positional_weight: Weight of the positional loss. + """ + chex.assert_equal_shape([y_true, y_pred]) + if y_pred.shape[-2] % multinomial_resolution != 0: + raise ValueError( + f'{y_pred.shape[-2]=} must be divisible by {multinomial_resolution=}.' + ) + + num_segments = y_pred.shape[-2] // multinomial_resolution + + # Remove the masked out bins from the totals sum. + y_true = jnp.maximum(y_true, 0) * mask + y_pred = y_pred * mask + + # Split sequence into n sub-sequences of size multinomial_resolution. + y_true = einshape('...(ns)c->...nsc', y_true, n=num_segments) + y_pred = einshape('...(ns)c->...nsc', y_pred, n=num_segments) + + total_pred = jnp.sum(y_pred, axis=-2, keepdims=True, dtype=jnp.float32) + total_true = jnp.sum(y_true, axis=-2, keepdims=True, dtype=jnp.float32) + mask = mask[..., None, :] # broadcast over segments. + + loss_total_count = poisson_loss( + y_true=total_true, + y_pred=total_pred, + mask=mask, + ) + # Magnitude of poisson loss is linear with the number of bins involved in the + # `total_count` prediction/target window. Normalization keeps overall loss + # magnitude invariant to input `multinomial_resolution`. + loss_total_count /= multinomial_resolution + + prob_predictions = y_pred.astype(jnp.float32) / (total_pred + 1e-7) + loss_positional = -y_true * jnp.log(prob_predictions + 1e-7) + loss_positional = _safe_masked_mean(loss_positional, mask=mask) + + return { + 'loss': loss_total_count + positional_weight * loss_positional, + 'loss_total': loss_total_count, + 'loss_positional': loss_positional, + 'max_sum_preds': jnp.max(total_pred), + 'max_preds': jnp.max(y_pred), + 'max_targets': jnp.max(y_true).astype(jnp.float32), + } + + +def mse( + y_pred: Float[Array, '*dims'], + y_true: Float[Array, '*dims'], + mask: Bool[Array, '#*dims'], +) -> Float[Array, '']: + """Mean squared error.""" + return _safe_masked_mean(jnp.square(y_pred - y_true), mask) + + +@typing.jaxtyped +def cross_entropy_loss_from_logits( + *, + y_pred_logits: Float[Array, '*dims'], + y_true: Float[Array, '*dims'], + mask: Bool[Array, '#*dims'], + axis: int, +) -> Float[Array, '']: + """Cross-entropy loss from logits.""" + log_softmax_preds = jax.nn.log_softmax( + y_pred_logits.astype(jnp.float32), axis=axis + ) + loss = -jnp.sum(y_true.astype(jnp.float32) * log_softmax_preds, axis=axis) + mask = jnp.any(mask, axis=axis) + return _safe_masked_mean(loss, mask) + + +@typing.jaxtyped +def binary_crossentropy_from_logits( + *, + y_pred: Float[Array, '*dims'], + y_true: Float[Array, '*dims'], + mask: Bool[Array, '#*dims'], +) -> Float[Array, '']: + """Binary cross-entropy loss from sigmoid logits.""" + loss = ( + jnp.maximum(y_pred, 0) + - y_pred * y_true + + jnp.log1p(jnp.exp(-jnp.abs(y_pred))) + ) + return _safe_masked_mean(loss, mask) + + +@typing.jaxtyped +def cross_entropy_loss( + *, + y_true: Float[Array, '*dims'], + y_pred: Float[Array, '*dims'], + mask: Bool[Array, '#*dims'], + axis: int, + eps: float = 1e-7, +) -> Float[Array, '']: + """Cross entropy loss on counts.""" + mask = jnp.broadcast_to(mask, y_true.shape) + chex.assert_equal_shape([y_true, y_pred, mask]) + y_true = jnp.where(mask, y_true.astype(jnp.float32), 0) + p_true = y_true / jnp.maximum(y_true.sum(axis=axis, keepdims=True), eps) + + log_normalizer = jnp.log((jnp.where(mask, y_pred, 0) + eps).sum(axis=axis)) + log_likelihood = (p_true * jnp.log(y_pred + eps)).sum(axis=axis) + log_loss = log_normalizer - log_likelihood + return _safe_masked_mean(log_loss, mask.any(axis=axis)) diff --git a/flax_model/alphagenome/model/losses_test.py b/flax_model/alphagenome/model/losses_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f411b524698ec39fc276805f94d6d60dc0bf483c --- /dev/null +++ b/flax_model/alphagenome/model/losses_test.py @@ -0,0 +1,81 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome.model import losses +import jax.numpy as jnp +import numpy as np + + +class LossesTest(parameterized.TestCase): + + def test_multinomial_loss_masking(self): + """Tests that masking correctly zeros out predictions and targets.""" + y_true = jnp.array([[[10.0, 1.0, 3.0], [5.0, 2.0, 20.0]]]) + y_pred = jnp.array([[[0.5, 2.5, 1.0], [2.5, 0.5, 1.0]]]) + loss_full = losses.multinomial_loss( + y_true=y_true, + y_pred=y_pred, + mask=jnp.array([[[True, True, True]]]), + multinomial_resolution=1, + positional_weight=1.0, + )['loss'] + loss_masked = losses.multinomial_loss( + y_true=y_true, + y_pred=y_pred, + mask=jnp.array([[[True, True, False]]]), + multinomial_resolution=1, + positional_weight=1.0, + )['loss'] + y_true_zero = jnp.array([[[10.0, 1.0], [5.0, 2.0]]]) + y_pred_zero = jnp.array([[[0.5, 2.5], [2.5, 0.5]]]) + loss_truncated = losses.multinomial_loss( + y_true=y_true_zero, + y_pred=y_pred_zero, + mask=jnp.array([[[True, True]]]), + multinomial_resolution=1, + positional_weight=1.0, + )['loss'] + np.testing.assert_almost_equal(loss_masked, loss_truncated, decimal=5) + np.testing.assert_array_less(loss_masked, loss_full) + + def test_multinomial_loss_resolution_aggregation(self): + """Tests the resolution aggregation logic.""" + # Seq length 4, all 1s. + y_true = jnp.ones((1, 4, 1)) + y_pred = jnp.ones((1, 4, 1)) + mask = jnp.ones((1, 1, 1), dtype=bool) + out_res1 = losses.multinomial_loss( + y_true=y_true, + y_pred=y_pred, + mask=mask, + multinomial_resolution=1, + positional_weight=1.0, + ) + out_res4 = losses.multinomial_loss( + y_true=y_true, + y_pred=y_pred, + mask=mask, + multinomial_resolution=4, + positional_weight=1.0, + ) + self.assertTrue(np.all(np.isfinite(out_res1['loss']))) + self.assertTrue(np.all(np.isfinite(out_res4['loss']))) + np.testing.assert_almost_equal(out_res1['max_sum_preds'], 1.0) + np.testing.assert_almost_equal(out_res4['max_sum_preds'], 4.0) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/metadata/__init__.py b/flax_model/alphagenome/model/metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ac91ecd062eee536567baa42db67767038a0cff --- /dev/null +++ b/flax_model/alphagenome/model/metadata/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome Model Metadata.""" diff --git a/flax_model/alphagenome/model/metadata/metadata.py b/flax_model/alphagenome/model/metadata/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..1112c5f1c80dd04fabd8648164610dfe24429c41 --- /dev/null +++ b/flax_model/alphagenome/model/metadata/metadata.py @@ -0,0 +1,159 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome output metadata.""" + +from importlib import resources +from collections.abc import Collection, Mapping +import dataclasses +import functools +import pathlib + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import ontology +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_client +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.protos import dna_model_service_pb2 +from google.protobuf import text_format +from jaxtyping import Bool, Int32 # pylint: disable=g-importing-member, g-multiple-import +import numpy as np + +_PATH_METADATA = 'model/metadata/' +_PADDING_TRACK_NAME = 'padding' + + +def _create_output_strand_reindexing( + metadata: track_data.TrackMetadata, + num_tracks: int, +) -> Int32[np.ndarray, '_']: + """Creates the strand reindexing for a given output type's track metadata.""" + strands = metadata['strand'].values + reindex_array = np.arange(num_tracks, dtype=np.int32) + positive_indices = np.flatnonzero(strands == '+') + negative_indices = np.flatnonzero(strands == '-') + reindex_array[positive_indices] = negative_indices + reindex_array[negative_indices] = positive_indices + return reindex_array + + +@typing.jaxtyped +@dataclasses.dataclass(frozen=True, kw_only=True) +class AlphaGenomeOutputMetadata(dna_output.OutputMetadata): + """AlphaGenome output metadata.""" + + def resolution(self, output: dna_output.OutputType) -> int: + """Returns the resolution of the given output type.""" + match output: + case dna_output.OutputType.ATAC: + return 1 + case dna_output.OutputType.CAGE: + return 1 + case dna_output.OutputType.DNASE: + return 1 + case dna_output.OutputType.RNA_SEQ: + return 1 + case dna_output.OutputType.CHIP_HISTONE: + return 128 + case dna_output.OutputType.CHIP_TF: + return 128 + case dna_output.OutputType.SPLICE_SITES: + return 1 + case dna_output.OutputType.SPLICE_SITE_USAGE: + return 1 + case dna_output.OutputType.SPLICE_JUNCTIONS: + return 1 + case dna_output.OutputType.CONTACT_MAPS: + return 2048 + case dna_output.OutputType.PROCAP: + return 1 + case _: + raise ValueError(f'Unknown {output=}') + + @functools.cached_property + def padding(self) -> Mapping[dna_output.OutputType, Bool[np.ndarray, '_']]: + """Returns mapping of output type to padding mask.""" + padding = {} + for output_type in dna_output.OutputType: + if (metadata := self.get(output_type)) is not None: + padding[output_type] = ( + metadata['name'].str.lower() == _PADDING_TRACK_NAME + ).values + return padding + + @functools.cached_property + def strand_reindexing( + self, + ) -> Mapping[dna_output.OutputType, Int32[np.ndarray, '_']]: + """Return mapping of output type to negative strand reindexing.""" + result = {} + for output_type in dna_output.OutputType: + if (metadata := self.get(output_type)) is not None: + num_tracks = len(metadata) + if output_type == dna_output.OutputType.SPLICE_JUNCTIONS: + # Splice junction metadata is strand agnostic, but predictions are + # structured as all positive followed by all negative strands. + result[output_type] = np.concatenate(( + np.arange(num_tracks, num_tracks * 2), + np.arange(num_tracks), + )) + else: + result[output_type] = _create_output_strand_reindexing( + metadata, num_tracks + ) + return result + + +@typing.jaxtyped +def create_track_masks( + metadata: AlphaGenomeOutputMetadata, + *, + requested_outputs: Collection[dna_output.OutputType], + requested_ontologies: Collection[ontology.OntologyTerm] | None, +) -> Mapping[dna_output.OutputType, Bool[np.ndarray, '_']]: + """Creates track masks for the requested output types and ontologies.""" + track_masks = {} + for output_type in requested_outputs: + if (output_metadata := metadata.get(output_type)) is None: + continue + + if ( + requested_ontologies is not None + # Splice sites are tissue agnostic. + and output_type != dna_output.OutputType.SPLICE_SITES + ): + ontology_curies = {o.ontology_curie for o in requested_ontologies} + mask = np.asarray( + [o in ontology_curies for o in output_metadata['ontology_curie']] + ) + else: + mask = ~np.array(metadata.padding[output_type]) + + track_masks[output_type] = mask + + return track_masks + + +def load(organism: dna_model.Organism) -> AlphaGenomeOutputMetadata: + """Loads the metadata for a given organism.""" + file_name = f'OutputMetadataResponse_ORGANISM_{organism.name}.textproto' + path = pathlib.Path(_PATH_METADATA, file_name) + content = resources.files('flax_model.alphagenome').joinpath(path).read_text() + metadata_response = text_format.Parse( + content, dna_model_service_pb2.MetadataResponse() + ) + return AlphaGenomeOutputMetadata( + **vars(dna_client.construct_output_metadata(iter((metadata_response,)))) + ) diff --git a/flax_model/alphagenome/model/model.py b/flax_model/alphagenome/model/model.py new file mode 100644 index 0000000000000000000000000000000000000000..36bf968730421a556d8f2ac28f07d30e50aa6265 --- /dev/null +++ b/flax_model/alphagenome/model/model.py @@ -0,0 +1,282 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome model.""" + +from collections.abc import Mapping + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome.model import attention +from flax_model.alphagenome.model import convolutions +from flax_model.alphagenome.model import embeddings as embeddings_module +from flax_model.alphagenome.model import heads as heads_module +from flax_model.alphagenome.model import layers +from flax_model.alphagenome.model import schemas +from flax_model.alphagenome.model import splicing +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +import haiku as hk +import jax +from jaxtyping import Array, Float, Int, PyTree, Shaped # pylint: disable=g-importing-member, g-multiple-import + + +DEFAULT_NUM_SPLICE_SITES = 512 +DEFAULT_SPLICE_SITE_THRESHOLD = 0.1 + + +class SequenceEncoder(hk.Module): + """Encodes a sequence of DNA into embeddings.""" + + @typing.jaxtyped + def __call__( + self, dna_sequence: Float[Array, 'B S 4'] + ) -> tuple[Float[Array, 'B S//128 D'], dict[str, Array]]: + intermediates = {} + x = convolutions.DnaEmbedder()(dna_sequence) + intermediates['bin_size_1'] = x + x = layers.pool(x) + for block_idx, bin_size in enumerate([2, 4, 8, 16, 32, 64]): + x = convolutions.DownResBlock(f'downres_block_{block_idx}')(x) + intermediates[f'bin_size_{bin_size}'] = x + x = layers.pool(x) + return x, intermediates + + +class SequenceDecoder(hk.Module): + """Decodes a sequence of embeddings.""" + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S D'], intermediates: dict[str, Array] + ) -> Float[Array, 'B S_final D_final']: + for bin_size in [64, 32, 16, 8, 4, 2, 1]: + x = convolutions.UpResBlock()(x, intermediates[f'bin_size_{bin_size}']) + return x + + +class TransformerTower(hk.Module): + """Transformer tower with interleaved pairwise updates.""" + + @typing.jaxtyped + def __call__( + self, x: Float[Array, 'B S C'] + ) -> tuple[Float[Array, 'B S C'], Float[Array, 'B S//16 S//16 F'] | None]: + pair_x = None + for i in range(9): + if i % 2 == 0: + pair_x = attention.PairUpdateBlock()(x, pair_x) + mha_bias = attention.AttentionBiasBlock()(pair_x) + x += attention.MHABlock()(x, mha_bias) + x += attention.MLPBlock()(x) + return x, pair_x + + +class AlphaGenome(hk.Module): + """Main AlphaGenome model. + + The model architecture consists of a sequence encoder, a transformer tower, + and a sequence decoder. The output of the decoder is used to generate + embeddings at 1bp resolution, while the output of the transformer tower + is used to generate embeddings at 128bp resolution and pair embeddings. + These embeddings are then passed to various heads to make predictions. + """ + + def __init__( + self, + output_metadata: Mapping[ + dna_model.Organism, metadata_lib.AlphaGenomeOutputMetadata + ], + *, + num_splice_sites: int = DEFAULT_NUM_SPLICE_SITES, + splice_site_threshold: float = DEFAULT_SPLICE_SITE_THRESHOLD, + freeze_trunk_embeddings: bool = False, + num_organisms: int = 2, + name: str | None = None, + ): + """Initializes the AlphaGenome model. + + Args: + output_metadata: Metadata for the output tracks for each organism. + num_splice_sites: The maximum number of splice sites that are extracted + from the splice site classification predictions. + splice_site_threshold: The threshold to use for splice site prediction. + freeze_trunk_embeddings: Whether to stop the gradient to the embeddings. + This is useful for training only the heads in fine-tuning. + num_organisms: The number of organisms. This is used to initialize the + organism embedding layer. Default is 2, for human and mouse. Leave at 2 + to load pre-trained weights. + name: The name of the module. + """ + + super().__init__(name=name or 'alphagenome') + self._output_metadata = output_metadata + self._num_splice_sites = num_splice_sites + self._splice_site_threshold = splice_site_threshold + self._freeze_trunk_embeddings = freeze_trunk_embeddings + self._num_organisms = num_organisms + self._heads: dict[heads_module.HeadName, heads_module.Head] = {} + for head in heads_module.HeadName: + output_type = heads_module.get_head_config(head).output_type + organisms_with_metadata = [ + organism + for organism, metadata in output_metadata.items() + if metadata.get(output_type) is not None + ] + if not organisms_with_metadata: + # None of the organisms have metadata for this output type. Skip. + continue + missing_organisms = set(self._output_metadata.keys()) - set( + organisms_with_metadata + ) + if missing_organisms: + raise ValueError( + f'No metadata found for output type "{output_type.name}" for the' + f' following organisms: {missing_organisms}. We expect the same set' + ' of output types for all organisms. Use padding to account for' + ' missing tracks.' + ) + self._heads[head] = heads_module.create_head( + heads_module.get_head_config(head), + self._output_metadata, + num_organisms=num_organisms, + ) + + @hk.name_like('__call__') + def predict_junctions( + self, + trunk_embeddings: Float[Array, 'B S D'], + splice_site_positions: Int[Array, 'B 4 K'], + organism_index: Int[Array, 'B'], + ) -> PyTree[Float[Array, 'B ...'] | None]: + """Predicts splice site junctions from embeddings and splice site positions. + + Args: + trunk_embeddings: The trunk embeddings to use for predictions. + splice_site_positions: The splice site positions. Format: [batch, 4, + num_splice_sites] with order: [donor_pos_idx, accept_pos_idx, + donor_neg_idx, accept_neg_idx] + organism_index: The organism index. + + Returns: + The predictions for splice site junctions. + """ + junction_head = self._heads.get(heads_module.HeadName.SPLICE_SITES_JUNCTION) + if junction_head is None: + raise ValueError('Junction head is not supported by this model.') + with hk.name_scope('head'): + return junction_head( + embeddings_module.Embeddings(embeddings_1bp=trunk_embeddings), + organism_index, + splice_site_positions=splice_site_positions, + ) + + @typing.jaxtyped + def __call__( + self, + dna_sequence: Float[Array, 'B S 4'], + organism_index: Int[Array, 'B'], + ) -> tuple[PyTree[Shaped[Array, 'B ...']], embeddings_module.Embeddings]: + """Encodes a sequence of DNA and makes predictions for various heads. + + Args: + dna_sequence: The sequence of DNA to encode. + organism_index: The organism index. + + Returns: + A tuple of (predictions, embeddings), where predictions is a dictionary + of predictions for various heads. + """ + trunk, intermediates = SequenceEncoder()(dna_sequence) + if self._num_organisms >= 1: + organism_embedding_trunk = hk.Embed(self._num_organisms, trunk.shape[-1])( + organism_index + ) + trunk += organism_embedding_trunk[:, None, :] + trunk, pair_activations = TransformerTower()(trunk) + + x = SequenceDecoder()(trunk, intermediates) + + embeddings_128bp = embeddings_module.OutputEmbedder(self._num_organisms)( + trunk, organism_index + ) + embeddings_1bp = embeddings_module.OutputEmbedder(self._num_organisms)( + x, organism_index, embeddings_128bp + ) + embeddings_pair = embeddings_module.OutputPair(self._num_organisms)( + pair_activations, organism_index + ) + + embeddings = embeddings_module.Embeddings( + embeddings_1bp=embeddings_1bp, + embeddings_128bp=embeddings_128bp, + embeddings_pair=embeddings_pair, + ) + if self._freeze_trunk_embeddings: + embeddings = jax.lax.stop_gradient(embeddings) + predictions = { + 'embeddings_1bp': embeddings_1bp, + } + with hk.name_scope('head'): + for head_name, head_fn in self._heads.items(): + if head_name == heads_module.HeadName.SPLICE_SITES_JUNCTION: + # This head is handled separately (see below). + continue + predictions[head_name.value] = head_fn( + embeddings, + organism_index, + ) + + # Handle the splice junction head separately. It requires splice site + # positions as input, which are derived from the splice site + # classification predictions. + if ( + junction_head := heads_module.HeadName.SPLICE_SITES_JUNCTION + ) in self._heads: + if heads_module.HeadName.SPLICE_SITES_CLASSIFICATION not in self._heads: + raise ValueError( + 'SPLICE_SITES_CLASSIFICATION head is required for junctions' + ' predictions.' + ) + splice_sites_probabilities = predictions[ + heads_module.HeadName.SPLICE_SITES_CLASSIFICATION.value + ]['predictions'] + splice_site_positions = splicing.generate_splice_site_positions( + splice_sites_probabilities, + alt=None, + splice_sites=None, + k=self._num_splice_sites, + pad_to_length=self._num_splice_sites, + threshold=self._splice_site_threshold, + ) + predictions[junction_head.value] = self.predict_junctions( + embeddings.embeddings_1bp, splice_site_positions, organism_index + ) + return predictions, embeddings + + @typing.jaxtyped + def loss( + self, batch: schemas.DataBatch + ) -> tuple[ + Float[Array, ''], PyTree[Float[Array, '']], PyTree[Shaped[Array, 'B ...']] + ]: + """Returns the loss for the model.""" + predictions, _ = self(batch.dna_sequence, batch.get_organism_index()) + total_loss, all_scalars = 0.0, {} + for head_name, head_fn in self._heads.items(): + scalars = head_fn.loss(predictions[head_name.value], batch) + all_scalars.update( + {f'{head_name.value}_{k}': v for k, v in scalars.items()} + ) + total_loss += scalars['loss'] + return total_loss, all_scalars, predictions diff --git a/flax_model/alphagenome/model/model_test.py b/flax_model/alphagenome/model/model_test.py new file mode 100644 index 0000000000000000000000000000000000000000..815623c0de2aaaba7551a8ec39551ddcb332cdef --- /dev/null +++ b/flax_model/alphagenome/model/model_test.py @@ -0,0 +1,491 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import junction_data +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_model +from flax_model.alphagenome.model import embeddings as embeddings_lib +from flax_model.alphagenome.model import model as model_lib +from flax_model.alphagenome.model import schemas +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +import chex +import haiku as hk +import jax +import jax.numpy as jnp +from jaxtyping import Array, Float, Int # pylint: disable=g-importing-member, g-multiple-import +import numpy as np +import pandas as pd + + +def _mock_track_metadata( + num_tracks: int, num_padding: int = 0 +) -> track_data.TrackMetadata: + return pd.DataFrame({ + 'name': ( + [f'track_{i}' for i in range(num_tracks)] + ['padding'] * num_padding + ), + 'nonzero_mean': [1.0] * num_tracks + [0.0] * num_padding, + }) + + +def _mock_junction_metadata( + num_tissues: int, num_padding: int = 0 +) -> junction_data.JunctionMetadata: + return pd.DataFrame({ + 'tissue': ( + [f'tissue_{i}' for i in range(num_tissues)] + + ['padding'] * num_padding + ), + 'name': ( + [f'tissue_{i}' for i in range(num_tissues)] + + ['padding'] * num_padding + ), + }) + + +class ModelTest(parameterized.TestCase): + + def test_create_model_metadata_consistency(self): + """Tests that the model raises an error if the metadata is inconsistent.""" + output_metadata_missing = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=13) + ), + dna_model.Organism.MUS_MUSCULUS: ( + metadata_lib.AlphaGenomeOutputMetadata() + ), + } + + @hk.transform_with_state + def forward(dna_sequence, organism_index): + return model_lib.AlphaGenome(output_metadata_missing)( + dna_sequence, organism_index + ) + + with self.assertRaisesRegex( + ValueError, + r'No metadata found for output type "ATAC" for the following organisms:' + r'.*MUS_MUSCULUS.*', + ): + jax.eval_shape( + forward.init, + jax.random.key(0), + jax.ShapeDtypeStruct((1, 2048, 4), jnp.float32), + jax.ShapeDtypeStruct((1,), jnp.int32), + ) + + @parameterized.named_parameters( + dict( + testcase_name='no_organisms', + organisms=(), + ), + dict( + testcase_name='one_organism', + organisms=(dna_model.Organism.HOMO_SAPIENS,), + ), + dict( + testcase_name='two_organisms', + organisms=( + dna_model.Organism.HOMO_SAPIENS, + dna_model.Organism.MUS_MUSCULUS, + ), + ), + ) + def test_create_headless_model( + self, organisms: tuple[dna_model.Organism, ...] + ): + """Tests that the model can be created without any heads.""" + output_metadata = { + organism: metadata_lib.AlphaGenomeOutputMetadata() + for organism in organisms + } + + @hk.transform_with_state + def forward(dna_sequence, organism_index): + return model_lib.AlphaGenome(output_metadata)( + dna_sequence, organism_index + ) + + params_shape, state_shape = jax.eval_shape( + forward.init, + jax.random.key(0), + seq_input := jax.ShapeDtypeStruct((1, 2048, 4), jnp.float32), + organism_index := jax.ShapeDtypeStruct((1,), jnp.int32), + ) + (predictions_shape, embeddings_shape), _ = jax.eval_shape( + forward.apply, + params_shape, + state_shape, + jax.random.key(0), + seq_input, + organism_index, + ) + # Predictions are only the embeddings in this case. + chex.assert_trees_all_equal_shapes( + predictions_shape, + {'embeddings_1bp': jnp.zeros((1, 2048, 1536))}, + ) + chex.assert_trees_all_equal_shapes( + embeddings_shape, + embeddings_lib.Embeddings( + embeddings_1bp=jnp.zeros((1, 2048, 1536)), + embeddings_128bp=jnp.zeros((1, 16, 3072), jnp.float32), + embeddings_pair=jnp.zeros((1, 1, 1, 128), jnp.float32), + ), + ) + + def test_create_model(self): + num_tracks = 13 + output_metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=num_tracks) + ), + dna_model.Organism.MUS_MUSCULUS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=7, num_padding=num_tracks - 7) + ), + } + + @hk.transform_with_state + def forward( + dna_sequence: Float[Array, 'B S 4'], organism_index: Int[Array, 'B'] + ): + return model_lib.AlphaGenome(output_metadata)( + dna_sequence, organism_index + ) + + seq_length = int(2**14) + key = jax.random.PRNGKey(42) + dna_sequence = jnp.zeros((1, seq_length, 4)) + organism_index = jnp.zeros((1,), dtype=jnp.int32) + + params, state = forward.init(key, dna_sequence, organism_index) + + (predictions, embeddings), _ = forward.apply( + params, state, key, dna_sequence, organism_index + ) + self.assertEqual(embeddings.embeddings_1bp.shape, (1, seq_length, 1536)) + self.assertEqual( + embeddings.embeddings_128bp.shape, (1, seq_length // 128, 3072) + ) + self.assertEqual( + embeddings.embeddings_pair.shape, + (1, seq_length // 128 // 16, seq_length // 128 // 16, 128), + ) + self.assertEqual( + predictions['atac']['scaled_predictions_1bp'].shape, + (1, seq_length, num_tracks), + ) + self.assertEqual( + predictions['atac']['scaled_predictions_128bp'].shape, + (1, seq_length // 128, num_tracks), + ) + + def test_predict_junctions_with_same_params(self): + seq_length = 2048 + num_tissues = 15 + num_splice_sites = 17 + output_metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + splice_sites=_mock_track_metadata(5), + splice_junctions=_mock_junction_metadata(num_tissues), + ), + } + + @hk.transform_with_state + def forward( + dna_sequence: Float[Array, 'B S 4'], organism_index: Int[Array, 'B'] + ): + return model_lib.AlphaGenome( + output_metadata, num_splice_sites=num_splice_sites + )(dna_sequence, organism_index) + + key = jax.random.PRNGKey(42) + dna_sequence = jax.ShapeDtypeStruct((1, seq_length, 4), jnp.float32) + organism_index = jax.ShapeDtypeStruct((1,), jnp.int32) + + params, state = jax.eval_shape( + forward.init, key, dna_sequence, organism_index + ) + + (predictions, embeddings), _ = jax.eval_shape( + forward.apply, params, state, key, dna_sequence, organism_index + ) + + @hk.transform_with_state + def predict_junctions_fn(embeddings, splice_site_positions, organism_index): + return model_lib.AlphaGenome( + output_metadata, num_splice_sites=num_splice_sites + ).predict_junctions(embeddings, splice_site_positions, organism_index) + + splice_site_positions = predictions['splice_sites_junction'][ + 'splice_site_positions' + ] + self.assertEqual(splice_site_positions.shape, (1, 4, num_splice_sites)) + junction_predictions, _ = jax.eval_shape( + predict_junctions_fn.apply, + params, + state, + key, + embeddings.embeddings_1bp, + splice_site_positions, + organism_index, + ) + self.assertIsNotNone(junction_predictions) + self.assertEqual( + junction_predictions['predictions'].shape, + (1, num_splice_sites, num_splice_sites, num_tissues * 2), + ) + self.assertEqual( + junction_predictions['splice_junction_mask'].shape, + (1, num_splice_sites, num_splice_sites, num_tissues * 2), + ) + + def test_loss_and_grads(self): + seq_length = 131072 # Must be larger or equal to multinomial_resolution. + batch_size = 1 + num_splice_sites = 17 + num_tissues_junctions = 1 + output_metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=1), + contact_maps=_mock_track_metadata(num_tracks=1), + splice_sites=_mock_track_metadata(num_tracks=5), + splice_site_usage=_mock_track_metadata(num_tracks=4), + splice_junctions=_mock_junction_metadata( + num_tissues=num_tissues_junctions + ), + ) + } + + batch = schemas.DataBatch( + dna_sequence=jnp.zeros((batch_size, seq_length, 4), dtype=jnp.float32), + organism_index=jnp.zeros((batch_size,), dtype=jnp.int32), + atac=jnp.zeros((batch_size, seq_length, 1), dtype=jnp.float32), + atac_mask=jnp.ones((batch_size, 1, 1), dtype=bool), + contact_maps=jnp.zeros( + (batch_size, seq_length // 2048, seq_length // 2048, 1), + dtype=jnp.float32, + ), + splice_sites=jnp.zeros((batch_size, seq_length, 5), dtype=bool), + splice_site_usage=jnp.zeros( + (batch_size, seq_length, 4), dtype=jnp.float32 + ), + splice_junctions=jnp.zeros( + ( + batch_size, + num_splice_sites, + num_splice_sites, + num_tissues_junctions * 2, + ), + dtype=jnp.float32, + ), + ) + + @hk.transform_with_state + def forward(batch): + return model_lib.AlphaGenome( + output_metadata, num_splice_sites=num_splice_sites + ).loss(batch) + + key = jax.random.PRNGKey(42) + params, state = jax.eval_shape(forward.init, key, batch) + (loss, scalars, predictions), _ = jax.eval_shape( + forward.apply, params, state, key, batch + ) + chex.assert_shape(loss, ()) + chex.assert_tree_shape(scalars, ()) + chex.assert_tree_shape_prefix(predictions, (batch_size,)) + self.assertContainsSubset( + [ + 'atac_loss', + 'contact_maps_loss', + 'splice_sites_classification_loss', + 'splice_sites_usage_loss', + 'splice_sites_junction_loss', + ], + scalars.keys(), + ) + + def grads_fn(params, state, batch): + def _loss_fn(params): + (loss, scalars, predictions), new_state = forward.apply( + params, state, None, batch + ) + return loss, (scalars, predictions, new_state) + + (loss, (scalars, predictions, new_state)), grads = jax.value_and_grad( + _loss_fn, has_aux=True + )(params) + return loss, scalars, new_state, predictions, grads + + loss2, scalars2, state2, predictions2, grads = jax.eval_shape( + grads_fn, params, state, batch + ) + chex.assert_trees_all_equal_shapes(loss, loss2) + chex.assert_trees_all_equal_shapes(scalars, scalars2) + chex.assert_trees_all_equal_shapes(state, state2) + chex.assert_trees_all_equal_shapes(predictions, predictions2) + chex.assert_trees_all_equal_shapes(params, grads) + + def test_finetuning_weights_merging(self): + """Tests that the weights can be merged for fine-tuning. + + We test this by creating a base model and a fine-tuning model, where the + fine-tuning model has fewer heads and tracks than the base model. We then + merge the weights of the base model and the fine-tuning model, and check + that the loss can be computed with the merged weights. + """ + seq_length = 131072 + batch_size = 1 + key = jax.random.key(0) + + # Setup base model. + base_metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=(atac_tracks_base := 5)), + rna_seq=_mock_track_metadata(num_tracks=(rna_seq_tracks_base := 3)), + ), + } + + @hk.transform_with_state + def base_forward(batch: schemas.DataBatch): + return model_lib.AlphaGenome(base_metadata).loss(batch) + + base_batch = schemas.DataBatch( + dna_sequence=np.zeros((batch_size, seq_length, 4), dtype=np.float32), + organism_index=np.zeros((batch_size,), dtype=np.int32), + atac=jnp.zeros( + (batch_size, seq_length, atac_tracks_base), dtype=np.float32 + ), + atac_mask=np.ones((batch_size, 1, atac_tracks_base), dtype=bool), + rna_seq=np.zeros( + (batch_size, seq_length, rna_seq_tracks_base), dtype=np.float32 + ), + rna_seq_mask=np.ones((batch_size, 1, rna_seq_tracks_base), dtype=bool), + ) + base_params, base_state = jax.eval_shape(base_forward.init, key, base_batch) + + # 2. Setup fine-tuning model. + ft_metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=(atac_tracks_ft := 7)), + ), + } + + @hk.transform_with_state + def ft_forward(batch: schemas.DataBatch): + return model_lib.AlphaGenome(ft_metadata).loss(batch) + + ft_batch = schemas.DataBatch( + dna_sequence=np.zeros((batch_size, seq_length, 4), dtype=np.float32), + organism_index=np.zeros((batch_size,), dtype=np.int32), + atac=jnp.zeros( + (batch_size, seq_length, atac_tracks_ft), dtype=np.float32 + ), + atac_mask=np.ones((batch_size, 1, atac_tracks_ft), dtype=bool), + ) + ft_params, ft_state = jax.eval_shape(ft_forward.init, key, ft_batch) + + # 3. Merge weights: base model weights + fine-tuning model head weights. + def merge(base_weights, ft_weights): + ft_head_weights = hk.data_structures.filter( + lambda module_name, name, v: 'head' in module_name, ft_weights + ) + return hk.data_structures.merge(base_weights, ft_head_weights) + + merged_params = merge(base_params, ft_params) + merged_state = merge(base_state, ft_state) + + # 4. Check that we can compute loss with merged weights + (loss, scalars, predictions), _ = jax.eval_shape( + ft_forward.apply, merged_params, merged_state, key, ft_batch + ) + chex.assert_shape(loss, ()) + self.assertContainsSubset(['atac_loss'], scalars.keys()) + self.assertNotIn('rna_seq_loss', scalars.keys()) + chex.assert_tree_shape_prefix(predictions, (batch_size,)) + self.assertEqual( + predictions['atac']['scaled_predictions_1bp'].shape, + (batch_size, seq_length, atac_tracks_ft), + ) + + def test_freeze_trunk_embeddings(self): + if jax.local_devices()[0].platform.lower() not in {'gpu', 'tpu'}: + self.skipTest('This test requires accelerator devices.') + + seq_length, batch_size, key = 131072, 1, jax.random.key(0) + + metadata = { + dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata( + atac=_mock_track_metadata(num_tracks=(atac_tracks_base := 5)), + rna_seq=_mock_track_metadata(num_tracks=(rna_seq_tracks_base := 3)), + ), + } + + @hk.transform_with_state + def forward(batch: schemas.DataBatch): + return model_lib.AlphaGenome(metadata, freeze_trunk_embeddings=True).loss( + batch + ) + + @jax.jit + def grads_fn(params, state, batch): + def loss_fn(params, state, batch): + (loss, _, _), _ = forward.apply(params, state, None, batch) + return loss + + grads_fn = jax.grad(loss_fn) + return grads_fn(params, state, batch) + + batch = schemas.DataBatch( + dna_sequence=np.zeros((batch_size, seq_length, 4), dtype=np.float32), + organism_index=np.zeros((batch_size,), dtype=np.int32), + atac=jnp.zeros( + (batch_size, seq_length, atac_tracks_base), dtype=np.float32 + ), + atac_mask=np.ones((batch_size, 1, atac_tracks_base), dtype=bool), + rna_seq=np.zeros( + (batch_size, seq_length, rna_seq_tracks_base), dtype=np.float32 + ), + rna_seq_mask=np.ones((batch_size, 1, rna_seq_tracks_base), dtype=bool), + ) + batch = jax.device_put(batch, jax.local_devices()[0]) + + params, state = jax.jit(forward.init)(key, batch) + grads = jax.jit(grads_fn)(params, state, batch) + chex.assert_trees_all_equal_shapes(params, grads) + grads_trunk = hk.data_structures.filter( + lambda module_name, name, v: 'head' not in module_name, grads + ) + grads_head = hk.data_structures.filter( + lambda module_name, name, v: 'head' in module_name, grads + ) + # Gradients in the trunk should be zero. + chex.assert_trees_all_equal( + grads_trunk, + jax.tree.map(np.zeros_like, grads_trunk), + ) + # Gradients in the head should be non-zero. + head_grad_sq_norm = jax.tree_util.tree_reduce( + lambda acc, x: acc + jnp.sum(jnp.square(x)), + grads_head, + initializer=0.0, + ) + self.assertGreater(head_grad_sq_norm, 0.0) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/one_hot_encoder.py b/flax_model/alphagenome/model/one_hot_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a21e7fbd47fe3faa37ab3f8e706b5d28f939204b --- /dev/null +++ b/flax_model/alphagenome/model/one_hot_encoder.py @@ -0,0 +1,54 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""A one-hot encoder for DNA sequences.""" + +import numpy as np +import numpy.typing as np_typing + + +class DNAOneHotEncoder: + """A one-hot encoder for DNA sequences. + + A -> [1, 0, 0, 0] + C -> [0, 1, 0, 0] + G -> [0, 0, 1, 0] + T -> [0, 0, 0, 1] + + all other characters are encoded as zeros [0, 0, 0, 0]. + """ + + def __init__(self, dtype: np_typing.DTypeLike = np.float32): + self._lookup_table = np.zeros((256, 4), dtype=dtype) + self._lookup_table[ord('A')] = [1, 0, 0, 0] + self._lookup_table[ord('C')] = [0, 1, 0, 0] + self._lookup_table[ord('G')] = [0, 0, 1, 0] + self._lookup_table[ord('T')] = [0, 0, 0, 1] + self._lookup_table[ord('a')] = self._lookup_table[ord('A')] + self._lookup_table[ord('c')] = self._lookup_table[ord('C')] + self._lookup_table[ord('g')] = self._lookup_table[ord('G')] + self._lookup_table[ord('t')] = self._lookup_table[ord('T')] + + def encode(self, seq: str) -> np.ndarray: + """One-hot encodes a DNA sequence string. + + Args: + seq: The DNA sequence string (e.g., "AGCTNacgt"). + + Returns: + A 2D numpy array of shape (sequence_length, 4) containing the + one-hot encoded representation of the sequence. + """ + byte_values = np.frombuffer(seq.encode('latin1'), dtype=np.uint8) + return self._lookup_table[byte_values] diff --git a/flax_model/alphagenome/model/one_hot_encoder_test.py b/flax_model/alphagenome/model/one_hot_encoder_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d0e58f104df3bfb6bea387ae65a18614a2ff882d --- /dev/null +++ b/flax_model/alphagenome/model/one_hot_encoder_test.py @@ -0,0 +1,44 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome.model import one_hot_encoder +import numpy as np + + +class OneHotEncoderTest(parameterized.TestCase): + + @parameterized.product( + sequence=['AGCTN', 'agctn'], + output_type=[np.int8, np.float32], + ) + def test_encode(self, sequence: str, output_type: np.dtype): + expected = np.array( + [ + [1, 0, 0, 0], + [0, 0, 1, 0], + [0, 1, 0, 0], + [0, 0, 0, 1], + [0, 0, 0, 0], + ], + dtype=output_type, + ) + encoder = one_hot_encoder.DNAOneHotEncoder(dtype=output_type) + encoded = encoder.encode(sequence) + np.testing.assert_array_equal(encoded, expected) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/schemas.py b/flax_model/alphagenome/model/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..e106adf8ce6ca8c15c4ac9df3d566504ec3c0a00 --- /dev/null +++ b/flax_model/alphagenome/model/schemas.py @@ -0,0 +1,85 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common schemas for the model.""" + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome.io import bundles +import chex +from jaxtyping import ArrayLike, Bool, Float, Int # pylint: disable=g-importing-member, g-multiple-import + + +@typing.jaxtyped +@chex.dataclass(frozen=True) +class DataBatch: + """Input batch for the model.""" + + dna_sequence: Float[ArrayLike, 'B S_DNA 4'] | None = None + organism_index: Int[ArrayLike, 'B'] | None = None + atac: Float[ArrayLike, 'B S C_ATAC'] | None = None + atac_mask: Bool[ArrayLike, 'B #S C_ATAC'] | None = None + dnase: Float[ArrayLike, 'B S C_DNASE'] | None = None + dnase_mask: Bool[ArrayLike, 'B #S C_DNASE'] | None = None + procap: Float[ArrayLike, 'B S C_PROCAP'] | None = None + procap_mask: Bool[ArrayLike, 'B #S C_PROCAP'] | None = None + chip_histone: Float[ArrayLike, 'B S//128 C_CHIP_HISTONE'] | None = None + chip_histone_mask: Bool[ArrayLike, 'B #S//128 C_CHIP_HISTONE'] | None = None + chip_tf: Float[ArrayLike, 'B S//128 C_CHIP_TF'] | None = None + chip_tf_mask: Bool[ArrayLike, 'B #S//128 C_CHIP_TF'] | None = None + rna_seq: Float[ArrayLike, 'B S C_RNA_SEQ'] | None = None + rna_seq_mask: Bool[ArrayLike, 'B #S C_RNA_SEQ'] | None = None + rna_seq_strand: Int[ArrayLike, 'B 1 C_RNA_SEQ'] | None = None + cage: Float[ArrayLike, 'B S C_CAGE'] | None = None + cage_mask: Bool[ArrayLike, 'B #S C_CAGE'] | None = None + contact_maps: Float[ArrayLike, 'B S//2048 S//2048 C_CONTACT_MAPS'] | None = ( + None + ) + splice_junctions: Float[ArrayLike, 'B P P C_SPLICE_JUNCTIONS'] | None = None + splice_site_positions: Int[ArrayLike, 'B 4 P'] | None = None + splice_site_usage: Float[ArrayLike, 'B S C_SPLICE_SITE_USAGE'] | None = None + splice_sites: Bool[ArrayLike, 'B S C_SPLICE_SITES'] | None = None + + def get_organism_index(self) -> Int[ArrayLike, 'B']: + """Returns the organism index data.""" + if self.organism_index is None: + raise ValueError('Organism index data is not present in the batch.') + return self.organism_index + + def get_genome_tracks( + self, bundle: bundles.BundleName + ) -> tuple[Float[ArrayLike, 'B S C'], Bool[ArrayLike, 'B #S C']]: + """Returns the genome tracks data for the given bundle if present.""" + match bundle: + case bundles.BundleName.ATAC: + data, mask = self.atac, self.atac_mask + case bundles.BundleName.DNASE: + data, mask = self.dnase, self.dnase_mask + case bundles.BundleName.PROCAP: + data, mask = self.procap, self.procap_mask + case bundles.BundleName.CAGE: + data, mask = self.cage, self.cage_mask + case bundles.BundleName.RNA_SEQ: + data, mask = self.rna_seq, self.rna_seq_mask + case bundles.BundleName.CHIP_TF: + data, mask = self.chip_tf, self.chip_tf_mask + case bundles.BundleName.CHIP_HISTONE: + data, mask = self.chip_histone, self.chip_histone_mask + case _: + raise ValueError( + f'Unknown bundle name: {bundle!r}. Is it a genome tracks bundle?' + ) + + if data is None or mask is None: + raise ValueError(f'{bundle.name!r} data is not present in the batch.') + return data, mask diff --git a/flax_model/alphagenome/model/splicing.py b/flax_model/alphagenome/model/splicing.py new file mode 100644 index 0000000000000000000000000000000000000000..33a63a4b8704d0e777962396f3176f6b76f1b52b --- /dev/null +++ b/flax_model/alphagenome/model/splicing.py @@ -0,0 +1,77 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Splicing utilities.""" + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome.model.variant_scoring import splice_junction +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float, Int32 # pylint: disable=g-importing-member, g-multiple-import + + +@typing.jaxtyped +def _top_k_splice_sites( + x: Float[Array, 'B S 5'], + *, + k: int, + pad_to_length: int, + threshold: float, +) -> Int32[Array, 'B 4 K']: + """Returns the top k splice sites from the predictions. + + Args: + x: Array of shape [batch, sequence_length, 5] containing splice site + predictions (donor +ve, acceptor +ve, donor -ve, acceptor -ve, other). + k: Number of top splice sites to return. + pad_to_length: Pad the output to this length. + threshold: Threshold to filter out low confidence splice sites. + """ + batch_size = x.shape[0] + values, positions = jax.lax.approx_max_k(x[..., :4], k, reduction_dimension=1) + if threshold > 0: + positions = jnp.where(values < threshold, jnp.inf, positions) + positions = jnp.sort(positions, axis=1, descending=False) + if threshold > 0: + positions = jnp.where(positions == jnp.inf, -1, positions) + # positions shape [batch, 4 (+ve and -ve donors and acceptors), k]. + positions = positions.swapaxes(1, 2).astype(jnp.int32) + if positions.shape[2] < pad_to_length: + padding_shape = (batch_size, 4, pad_to_length - positions.shape[2]) + padding = jnp.full( + padding_shape, splice_junction.PAD_VALUE, dtype=jnp.int32 + ) + positions = jnp.concatenate([positions, padding], axis=2) + return positions + + +@typing.jaxtyped +def generate_splice_site_positions( + ref: Float[Array, 'B S 5'], + alt: Float[Array, 'B S 5'] | None, + splice_sites: Bool[Array, 'B S 5'] | None, + *, + k: int, + pad_to_length: int, + threshold: float, +) -> Int32[Array, 'B 4 K']: + """Returns the top k splice sites from predictions and (true) splice sites.""" + + if alt is not None: + ref = jnp.maximum(ref, alt) + if splice_sites is not None: + ref = jnp.maximum(ref, splice_sites) + return _top_k_splice_sites( + ref, k=k, pad_to_length=pad_to_length, threshold=threshold + ) diff --git a/flax_model/alphagenome/model/splicing_test.py b/flax_model/alphagenome/model/splicing_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f4b1f8aae39cc3367d51abb20b5ac13ed6da7909 --- /dev/null +++ b/flax_model/alphagenome/model/splicing_test.py @@ -0,0 +1,113 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome.model import splicing +import jax.numpy as jnp +import jaxtyping +import numpy as np + + +class SplicingTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + # Disable jaxtyped decorator for testing as parameterized + # test_generate_splice_site_positions test doesn't follow the jaxtyped + # annotations. + jaxtyping.config.update('jaxtyping_disable', True) + + def test_generate_splice_site_positions_no_alt_no_mask(self): + # ref probabilities not normalized but it doesn't matter for this test. + ref = jnp.array([[ + [0.09, 0.2, 0.9, 0.4, 0.0], + [0.5, 0.6, 0.7, 0.05, 0.0], + [0.05, 0.8, 0.6, 0.6, 0.0], + ]]) + k = 2 + pad_to_length = 5 + threshold = 0.1 + + result = splicing.generate_splice_site_positions( + ref, + alt=None, + splice_sites=None, + k=k, + pad_to_length=pad_to_length, + threshold=threshold, + ) + expected = jnp.array([[ + [1, -1, -1, -1, -1], # donor +ve + [1, 2, -1, -1, -1], # acceptor +ve + [0, 1, -1, -1, -1], # donor -ve + [0, 2, -1, -1, -1], # acceptor -ve + ]]) + np.testing.assert_array_equal(result, expected) + + @parameterized.parameters( + dict( + ref=np.array([[[0.1], [0.2], [0.9], [0.8], [0.0]]]), + alt=None, + splice_site_mask=None, + probability_threshold=0.0, + expected=np.array([[[2, 3]]]), + ), + dict( + ref=np.array([[[0.1], [0.2], [0.9], [0.8], [0.0]]]), + alt=np.array([[[0.9], [0.1], [0.1], [0.1], [0.0]]]), + splice_site_mask=None, + probability_threshold=0.0, + expected=np.array([[[0, 2]]]), + ), + dict( + ref=np.array([[[0.0], [0.2], [0.9], [0.8], [0.0]]]), + alt=None, + splice_site_mask=np.array([[[0.05], [0.1], [0.1], [0.1], [0.9]]]), + probability_threshold=0.1, + expected=np.array([[[2, 4]]]), + ), + dict( + ref=np.array([[[0.1], [0.2], [0.9], [0.8], [0.0]]]), + alt=None, + splice_site_mask=None, + probability_threshold=0.5, + expected=np.array([[[2, 3]]]), + ), + dict( + ref=np.array([[[0.1], [0.2], [0.3], [0.4], [0.0]]]), + alt=None, + splice_site_mask=None, + probability_threshold=0.5, + expected=np.array([[[-1, -1]]]), + ), + ) + def test_generate_splice_site_positions( + self, ref, alt, splice_site_mask, probability_threshold, expected + ): + actual = splicing.generate_splice_site_positions( + jnp.array(ref), + alt=jnp.array(alt) if alt is not None else None, + splice_sites=jnp.array(splice_site_mask) + if splice_site_mask is not None + else None, + k=2, + pad_to_length=1, + threshold=probability_threshold, + ) + np.testing.assert_array_equal(actual, expected) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/center_mask.py b/flax_model/alphagenome/model/variant_scoring/center_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6ce4dd58a4a5f519a0f58338456e59f2c24154 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/center_mask.py @@ -0,0 +1,176 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implementation of center mask variant scoring.""" + +import functools +import math + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float32 # pylint: disable=g-multiple-import, g-importing-member +import numpy as np + + +def create_center_mask( + interval: genome.Interval, + variant: genome.Variant, + *, + width: int | None, + resolution: int, +) -> Bool[np.ndarray, 'S 1']: + """Creates a mask centered on a variant for a given interval.""" + if width is None: + if interval.start <= variant.start < interval.end: + mask = np.ones([interval.width // resolution, 1], dtype=bool) + else: + mask = np.zeros([interval.width // resolution, 1], dtype=bool) + else: + target_resolution_width = math.ceil(width / resolution) + + # Determine the position of the variant in the specified resolution. + base_resolution_center = variant.position - interval.start + target_resolution_center = base_resolution_center // resolution + + # Compute start and end indices of the variant-centered mask. + target_resolution_start = max( + target_resolution_center - target_resolution_width // 2, 0 + ) + target_resolution_end = min( + (target_resolution_center - target_resolution_width // 2) + + target_resolution_width, + interval.width // resolution, + ) + + # If the variant is not within the interval, we return an empty mask. + # Otherwise, we build the mask using our target_resolution_start/end, + # taking into account the resolution. + mask = np.zeros([interval.width // resolution, 1], dtype=bool) + if interval.start <= variant.start < interval.end: + mask[target_resolution_start:target_resolution_end] = 1 + + return mask + + +@functools.partial(jax.jit, static_argnames=['aggregation_type']) +@typing.jaxtyped +def _apply_aggregation( + ref: Float32[Array, 'S T'], + alt: Float32[Array, 'S T'], + masks: Bool[Array, 'S 1'], + aggregation_type: variant_scorers.AggregationType, +): + match aggregation_type: + case variant_scorers.AggregationType.DIFF_MEAN: + return alt.mean(axis=0, where=masks) - ref.mean(axis=0, where=masks) + case variant_scorers.AggregationType.ACTIVE_MEAN: + return jnp.maximum( + alt.mean(axis=0, where=masks), + ref.mean(axis=0, where=masks), + ) + case variant_scorers.AggregationType.DIFF_SUM: + return alt.sum(axis=0, where=masks) - ref.sum(axis=0, where=masks) + case variant_scorers.AggregationType.ACTIVE_SUM: + return jnp.maximum( + alt.sum(axis=0, where=masks), + ref.sum(axis=0, where=masks), + ) + case variant_scorers.AggregationType.L2_DIFF: + return jnp.sqrt(jnp.sum((alt - ref) ** 2, axis=0, where=masks)) + case variant_scorers.AggregationType.L2_DIFF_LOG1P: + return jnp.sqrt( + jnp.sum( + (jnp.log1p(alt) - jnp.log1p(ref)) ** 2, + axis=0, + where=masks, + ) + ) + case variant_scorers.AggregationType.DIFF_SUM_LOG2: + return jnp.sum(jnp.log2(alt + 1), axis=0, where=masks) - jnp.sum( + jnp.log2(ref + 1), axis=0, where=masks + ) + case variant_scorers.AggregationType.DIFF_LOG2_SUM: + return jnp.log2(1 + jnp.sum(alt, axis=0, where=masks)) - jnp.log2( + 1 + jnp.sum(ref, axis=0, where=masks) + ) + case _: + raise ValueError(f'Unknown bin aggregation type: {aggregation_type}.') + + +class CenterMaskVariantScorer(variant_scoring.VariantScorer): + """Variant scorer that aggregates ALT - REF in a window around the variant.""" + + def get_masks_and_metadata( + self, + interval: genome.Interval, + variant: genome.Variant, + *, + settings: variant_scorers.CenterMaskScorer, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[np.ndarray, None]: + """See base class.""" + del track_metadata + + resolution = variant_scoring.get_resolution(settings.requested_output) + mask = create_center_mask( + interval, variant, width=settings.width, resolution=resolution + ) + + return mask, None + + @typing.jaxtyped + def score_variant( + self, + ref: variant_scoring.ScoreVariantInput, + alt: variant_scoring.ScoreVariantInput, + *, + masks: Bool[Array, '_ 1'], + settings: variant_scorers.CenterMaskScorer, + variant: genome.Variant | None = None, + interval: genome.Interval | None = None, + ) -> variant_scoring.ScoreVariantOutput: + """See base class.""" + del variant, interval # Unused. + alt = alt[settings.requested_output] + ref = ref[settings.requested_output] + + output = _apply_aggregation(ref, alt, masks, settings.aggregation_type) + return {'score': output} + + def finalize_variant( + self, + scores: variant_scoring.ScoreVariantResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: None, + settings: variant_scorers.CenterMaskScorer, + ) -> anndata.AnnData: + """See base class.""" + del mask_metadata # Unused. + output_metadata = track_metadata.get(settings.requested_output) + assert isinstance(output_metadata, track_data.TrackMetadata) + + num_tracks = len(output_metadata) + return variant_scoring.create_anndata( + scores['score'][np.newaxis, :num_tracks], + obs=None, + var=output_metadata, + ) diff --git a/flax_model/alphagenome/model/variant_scoring/center_mask_test.py b/flax_model/alphagenome/model/variant_scoring/center_mask_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c64062e9898eef5a80dce0d5d103b5008c5f8000 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/center_mask_test.py @@ -0,0 +1,206 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import center_mask +import anndata +import chex +import jax +import jax.numpy as jnp +import numpy as np + + +class CenterMaskVariantScorerTest(parameterized.TestCase): + + @parameterized.parameters([ + dict( + width=None, + output_type=dna_output.OutputType.ATAC, + variant=genome.Variant('chr1', 10, '', ''), + expected_start=0, + expected_end=2048, + ), + dict( + width=None, + output_type=dna_output.OutputType.ATAC, + variant=genome.Variant('chr1', 2049, '', ''), + expected_start=-1, + expected_end=-1, + ), + dict( + width=501, + output_type=dna_output.OutputType.RNA_SEQ, + variant=genome.Variant('chr1', 1, '', ''), + expected_start=0, + expected_end=252, + ), + dict( + width=501, + output_type=dna_output.OutputType.RNA_SEQ, + variant=genome.Variant('chr1', 2048, '', ''), + expected_start=1798, + expected_end=2048, + ), + ]) + def test_masks_and_metadata( + self, + width: int | None, + output_type: dna_output.OutputType, + variant: genome.Variant, + expected_start: int, + expected_end: int, + ): + settings = variant_scorers.CenterMaskScorer( + requested_output=output_type, + aggregation_type=variant_scorers.AggregationType.DIFF_MEAN, + width=width, + ) + interval = genome.Interval('chr1', 0, 2048) + ( + masks, + metadata, + ) = center_mask.CenterMaskVariantScorer().get_masks_and_metadata( + interval, + variant, + settings=settings, + track_metadata=dna_output.OutputMetadata(), + ) + self.assertIsNone(metadata) + + chex.assert_shape(masks, (2048, 1)) + if expected_start >= 0: + self.assertEqual(masks.argmax(axis=0).item(), expected_start) + if expected_end >= 0: + self.assertEqual( + masks.shape[0] - masks[::-1].argmax(axis=0).item(), expected_end + ) + + expected_mask = np.zeros_like(masks) + if expected_start != expected_end: + expected_mask[expected_start:expected_end] = True + np.testing.assert_array_equal(masks, expected_mask) + + @parameterized.product( + [ + dict( + # (0 + 0 + 0) / 3 - (4 + 5 + 6) / 3 = -5 + aggregation_type=variant_scorers.AggregationType.DIFF_MEAN, + expected_score=-5.0, + ), + dict( + # max((0 + 0 + 0) / 3, (4 + 5 + 6) / 3) = 5 + aggregation_type=variant_scorers.AggregationType.ACTIVE_MEAN, + expected_score=5.0, + ), + dict( + # (0 + 0 + 0) - (4 + 5 + 6) = -15 + aggregation_type=variant_scorers.AggregationType.DIFF_SUM, + expected_score=-15.0, + ), + dict( + # max((0 + 0 + 0), (4 + 5 + 6)) = 15 + aggregation_type=variant_scorers.AggregationType.ACTIVE_SUM, + expected_score=15.0, + ), + dict( + # sqrt((0 - 4)**2 + (0 - 5)**2 + (0 - 6)**2) =~ 8.77 + aggregation_type=variant_scorers.AggregationType.L2_DIFF, + expected_score=8.774964332580566, + ), + dict( + # sqrt((log1p(0) - log1p(4))**2 + (log1p(0) - log1p(5))**2 + + # (log1p(0) - log1p(6))**2) =~ 3.096 + aggregation_type=variant_scorers.AggregationType.L2_DIFF_LOG1P, + expected_score=3.096329875472752, + ), + dict( + # log2(0 + 1) * 3 - log2(4 + 1) - log2(5 + 1) - log2(6 + 1) + # =~ -7.71 + aggregation_type=variant_scorers.AggregationType.DIFF_SUM_LOG2, + expected_score=-7.714245517666122, + ), + dict( + # log2( 1 + (0 + 0 + 0)) - log2( 1 + (4 + 5 + 6)) = -4.0 + aggregation_type=variant_scorers.AggregationType.DIFF_LOG2_SUM, + expected_score=-4.0, + ), + ], + transfer_guard=['disallow', 'allow'], + ) + def test_score_variant( + self, + aggregation_type: variant_scorers.AggregationType, + expected_score: float, + transfer_guard: str, + ): + settings = variant_scorers.CenterMaskScorer( + requested_output=dna_output.OutputType.ATAC, + aggregation_type=aggregation_type, + width=None, + ) + + ref = jnp.arange(10, dtype=jnp.float32).repeat(100).reshape((10, 100)) + alt = jnp.zeros((10, 100), dtype=jnp.float32) + mask = np.zeros((10, 1), dtype=bool) + mask[4:7] = True + mask = jnp.array(mask) + + scorer = center_mask.CenterMaskVariantScorer() + + with jax.transfer_guard(transfer_guard): + scores = scorer.score_variant( + {dna_output.OutputType.ATAC: ref}, + {dna_output.OutputType.ATAC: alt}, + masks=jax.device_put(mask), + settings=settings, + )['score'] + + np.testing.assert_almost_equal( + scores, np.full_like(scores, expected_score), decimal=6 + ) + + def test_finalize_variant(self): + scorer = center_mask.CenterMaskVariantScorer() + scores = {'score': np.ones((10,), dtype=np.float32)} + expected_scores = np.ones((8,), dtype=np.float32) + track_metadata = dna_output.OutputMetadata( + atac=track_data.TrackMetadata( + dict( + name=np.arange(8).astype(str), + strand='.', + ) + ) + ) + finalized_score = scorer.finalize_variant( + scores, + track_metadata=track_metadata, + mask_metadata=None, + settings=variant_scorers.CenterMaskScorer( + requested_output=dna_output.OutputType.ATAC, + width=None, + aggregation_type=variant_scorers.AggregationType.DIFF_MEAN, + ), + ) + self.assertIsInstance(finalized_score, anndata.AnnData) + np.testing.assert_array_equal(finalized_score.X[0], expected_scores) + self.assertEqual(finalized_score.n_vars, expected_scores.shape[-1]) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/contact_map.py b/flax_model/alphagenome/model/variant_scoring/contact_map.py new file mode 100644 index 0000000000000000000000000000000000000000..ff189f9338f0c51c62307f4581e5a04566a9b6ee --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/contact_map.py @@ -0,0 +1,130 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implementation of contact map variant scorer.""" + +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import center_mask +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool # pylint: disable=g-multiple-import, g-importing-member +import numpy as np + + +class ContactMapScorer(variant_scoring.VariantScorer): + """Implements the contact map variant scoring strategy from Zhou 2022 (Orca). + + Designed for single nucleotide variant (SNV) scoring, where the expected + effect is local to the variant position. + + Not compatible with indels or structural variants that involve changing more + than the number of nucleotides in a 2Kb window. + + Citation: As described in the Zhou manuscript: + https://doi.org/10.1038/s41588-022-01065-4: + + "The disruption impact on local genome interactions is measured by 1-Mb + structural impact score, which is the average absolute log fold change of + interactions between the disruption position and all other positions in the + 1-Mb window" + + The Orca scoring strategy is open sourced here (line 120): + https://github.com/jzhoulab/orca_manuscript/blob/main/virtual_screen/local_interaction_screen.py + """ + + def get_masks_and_metadata( + self, + interval: genome.Interval, + variant: genome.Variant, + *, + settings: variant_scorers.ContactMapScorer, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[np.ndarray, None]: + """See base class.""" + del track_metadata # Unused. + + resolution = variant_scoring.get_resolution(settings.requested_output) + mask = center_mask.create_center_mask( + interval, variant, width=resolution, resolution=resolution + ) + + if mask.sum() > 1: + raise ValueError( + 'The ContactMapScorer only accepts input variants that affect one bin' + ' position. However, there is more than one position affected by the' + ' variant at this bin resolution. This could indicate a malformed' + ' center mask. Please check `create_center_mask` logic. Debugging' + f' details: {variant=}, {interval=}, bin width={resolution},' + f' {mask.sum()=}.' + ) + elif mask.sum() == 0: + raise ValueError( + 'The variant does not affect any positions at this bin resolution.' + f' Debugging details: {variant=}, {interval=}, bin' + f' width={resolution}, {mask.sum()=}.' + ) + return mask, None + + def score_variant( + self, + ref: variant_scoring.ScoreVariantInput, + alt: variant_scoring.ScoreVariantInput, + *, + masks: Bool[Array, '_ 1'], + settings: variant_scorers.ContactMapScorer, + variant: genome.Variant | None = None, + interval: genome.Interval | None = None, + ) -> variant_scoring.ScoreVariantOutput: + del variant, interval # Unused. + ref = ref[settings.requested_output] + alt = alt[settings.requested_output] + + # Mean absolute difference, reduced over contact map rows. + # Ref, alt shape: [H, W, C] + # Temps shape: [W, C] + abs_diff = jnp.abs(alt - ref).mean(axis=0) + + # JAX dynamic slicing does not work with transfer_guard. + with jax.transfer_guard('allow'): + # Use center mask to select the variant row. + # Right now, assumes there is a single value. + # Output shape: [1, C] + output = abs_diff[jnp.argmax(masks), :] + + return {'score': output} + + def finalize_variant( + self, + scores: variant_scoring.ScoreVariantResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: None, + settings: variant_scorers.ContactMapScorer, + ) -> anndata.AnnData: + """See base class.""" + del mask_metadata # Unused. + output_metadata = track_metadata.get(settings.requested_output) + assert isinstance(output_metadata, track_data.TrackMetadata) + + num_tracks = len(output_metadata) + return variant_scoring.create_anndata( + scores['score'][np.newaxis, :num_tracks], + obs=None, + var=track_metadata.get(settings.requested_output), + ) diff --git a/flax_model/alphagenome/model/variant_scoring/contact_map_test.py b/flax_model/alphagenome/model/variant_scoring/contact_map_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba5f7388a10646f1a21644faf240ff7220d29e5 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/contact_map_test.py @@ -0,0 +1,174 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import mock + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import center_mask +from flax_model.alphagenome.model.variant_scoring import contact_map +import anndata +import jax +import jax.numpy as jnp +import numpy as np + + +def _interval_variant_pairs(interval_width: int, bin_width: int): + return { + 'interval': genome.Interval('chr1', 0, interval_width), + 'variant': genome.Variant( + chromosome='chr1', + position=interval_width // 2, + reference_bases='A', + alternate_bases='C', + ), + 'variant_wrong_chr': genome.Variant( + chromosome='chrX', + position=interval_width, + reference_bases='A', + alternate_bases='C', + ), + 'variant_indel': genome.Variant( + chromosome='chr1', + position=interval_width // 2, + reference_bases='A', + alternate_bases='C' * bin_width * 10, + ), + } + + +class ContactMapVariantScorerTest(parameterized.TestCase): + + @parameterized.named_parameters([ + dict( + testcase_name='snv', + interval=genome.Interval('chr1', 0, 196608), + variant=genome.Variant('chr1', 196608 // 2, 'A', 'C'), + ), + dict( + testcase_name='indel_variant', + interval=genome.Interval('chr1', 0, 196608), + variant=genome.Variant('chr1', 196608 // 2, 'A', 'C' * 2048 * 10), + ), + ]) + def test_masks_and_metadata( + self, interval: genome.Interval, variant: genome.Variant + ): + scorer = contact_map.ContactMapScorer() + + mask, mask_metadata = scorer.get_masks_and_metadata( + interval, + variant, + settings=variant_scorers.ContactMapScorer(), + track_metadata=dna_output.OutputMetadata(), + ) + self.assertIsNone(mask_metadata) + self.assertEqual(mask.sum(), 1) + + def test_no_variant_overlap_errors(self): + scorer = contact_map.ContactMapScorer() + with self.assertRaisesRegex( + ValueError, 'The variant does not affect any positions' + ): + scorer.get_masks_and_metadata( + genome.Interval('chr1', 0, 196608), + genome.Variant('chrX', 196608, 'A', 'C'), + settings=variant_scorers.ContactMapScorer(), + track_metadata=dna_output.OutputMetadata(), + ) + + def test_multiple_bins_raises_error(self): + scorer = contact_map.ContactMapScorer() + mock_mask = np.array([False, True, True]) # More than one True. + + # Mock a call to create_center_mask to return a badly formed center mask. + with mock.patch.object( + center_mask, 'create_center_mask', autospec=True, return_value=mock_mask + ): + with self.assertRaisesRegex( + ValueError, 'only accepts input variants that affect one bin' + ): + scorer.get_masks_and_metadata( + genome.Interval('chr1', 0, 1644), + genome.Variant('chr1', 822, 'A', 'C'), + settings=variant_scorers.ContactMapScorer(), + track_metadata=dna_output.OutputMetadata(), + ) + + @parameterized.product(transfer_guard=['disallow', 'allow']) + def test_score_variant(self, transfer_guard: str): + symmetric_diff = jnp.array( + [[1, 2, 1], [2, -3, 4], [1, 4, 5]], dtype=jnp.float32 + ) + + # Rescaling the second channel to make things slightly different. + second_channel_scale = 0.5 + + # Concatenate on channel dimension to represent two tissues. + alt_contact_map = jnp.concat( + [ + symmetric_diff[:, :, jnp.newaxis], + symmetric_diff[:, :, jnp.newaxis] * second_channel_scale, + ], + axis=-1, + ) + + # Ref alt. + ref = {dna_output.OutputType.CONTACT_MAPS: jnp.zeros_like(alt_contact_map)} + alt = {dna_output.OutputType.CONTACT_MAPS: alt_contact_map} + + # Simple center mask. + mask = np.array([False, True, False])[:, None] + + # Score center column of both channels of the diff. + variant_scores = ( + jnp.array([1, second_channel_scale]) # Channel scales. + * jnp.abs(symmetric_diff[:, 1]).mean() # Mean abs diff. + ) + scorer = contact_map.ContactMapScorer() + with jax.transfer_guard(transfer_guard): + scores = scorer.score_variant( + ref, alt, masks=mask, settings=variant_scorers.ContactMapScorer() + ) + np.testing.assert_array_equal(scores['score'], variant_scores) + + def test_finalize_variant(self): + scorer = contact_map.ContactMapScorer() + scores = {'score': np.ones((10,), dtype=np.float32)} + expected_scores = np.ones((8,), dtype=np.float32) + track_metadata = dna_output.OutputMetadata( + contact_maps=track_data.TrackMetadata( + dict( + name=np.arange(8).astype(str), + strand='.', + ) + ) + ) + finalized_score = scorer.finalize_variant( + scores, + track_metadata=track_metadata, + mask_metadata=None, + settings=variant_scorers.ContactMapScorer(), + ) + self.assertIsInstance(finalized_score, anndata.AnnData) + np.testing.assert_array_equal(finalized_score.X[0], expected_scores) + self.assertEqual(finalized_score.n_vars, expected_scores.shape[-1]) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/gene_mask.py b/flax_model/alphagenome/model/variant_scoring/gene_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..9bbc0b755ffcfc82449e5e1a51a863666188c306 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/gene_mask.py @@ -0,0 +1,175 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implementation of gene mask variant scoring.""" + +import functools + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.data import track_data +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor as gene_mask_extractor_lib +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float32 # pylint: disable=g-multiple-import, g-importing-member +import numpy as np +import pandas as pd + + +_VariantScorerSettings = ( + variant_scorers.GeneMaskLFCScorer + | variant_scorers.GeneMaskActiveScorer + | variant_scorers.GeneMaskSplicingScorer +) + + +@functools.partial(jax.jit, static_argnames=['settings']) +@typing.jaxtyped +def _score_gene_variant( + ref, alt, gene_mask, *, settings: _VariantScorerSettings +) -> Float32[Array, 'G T']: + """Returns a function to score a variant given the settings.""" + + match settings.base_variant_scorer: + case variant_scorers.BaseVariantScorer.GENE_MASK_LFC: + # Scores are the log fold change between the mean prediction of REF and + # ALT within each gene mask. + gene_mask_sum = gene_mask.sum(axis=0)[:, jnp.newaxis] + ref_mean = jnp.einsum('lt,lg->gt', ref, gene_mask) / gene_mask_sum + alt_mean = jnp.einsum('lt,lg->gt', alt, gene_mask) / gene_mask_sum + return jnp.log(alt_mean + 1e-3) - jnp.log(ref_mean + 1e-3) + case variant_scorers.BaseVariantScorer.GENE_MASK_ACTIVE: + # Scores are the maximum of the mean prediction for REF and ALT within + # each gene mask. + gene_mask_sum = gene_mask.sum(axis=0)[:, jnp.newaxis] + ref_score = jnp.einsum('lt,lg->gt', ref, gene_mask) / gene_mask_sum + alt_score = jnp.einsum('lt,lg->gt', alt, gene_mask) / gene_mask_sum + return jnp.maximum(alt_score, ref_score) + case variant_scorers.BaseVariantScorer.GENE_MASK_SPLICING: + # Scores are the maximum of the absolute difference between REF and ALT + # within each gene mask. + # Even for relatively small number of genes the naive implementation + # runs out of memory. We use a map here to reduce the memory footprint. + return jax.lax.map( + lambda mask: jnp.max(jnp.abs(alt - ref) * mask[:, None], axis=0), + jnp.matrix_transpose(gene_mask), + ) # shape: (G, T) + case _: + raise ValueError( + f'Unsupported base variant scorer: {settings.base_variant_scorer}.' + ) + + +class GeneVariantScorer( + variant_scoring.VariantScorer[ + Bool[np.ndarray | Array, 'S G'], + pd.DataFrame, + _VariantScorerSettings, + ] +): + """Variant scorer that computes scores for different genes.""" + + def __init__( + self, + gene_mask_extractor: gene_mask_extractor_lib.GeneMaskExtractor, + ): + """Initializes the GeneVariantScorer. + + Args: + gene_mask_extractor: Gene mask extractor to use. + """ + self._gene_mask_extractor = gene_mask_extractor + + def get_masks_and_metadata( + self, + interval: genome.Interval, + variant: genome.Variant, + *, + settings: _VariantScorerSettings, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[Bool[np.ndarray | Array, 'S G'], pd.DataFrame]: + """Get gene masks and metadata for the given interval and variant. + + Note that the gene mask returned for the REF allele is just the normal + gene mask extracted from the GTF file from the interval. However, the gene + mask can be different for the ALT allele in the case of indels. We handle + this by extracting the indel alignment masks, that will be used to align the + ALT to the REF predictions, so that the same gene mask can be applied to + both. + + Args: + interval: Genomic interval to extract gene masks for. + variant: Variant that may alter the gene mask in the case of the ALT + allele. + settings: The variant scorer settings. + track_metadata: Track metadata for the variant. + + Returns: + Tuple of (gene variant masks, mask metadata). The mask metadata is the + part of the GTF pandas dataframe that was used to construct the gene + masks. + """ + del track_metadata + if variant_scoring.get_resolution(settings.requested_output) != 1: + raise ValueError( + 'Only resolution = 1 is supported for gene variant scoring.' + ) + gene_mask, metadata = self._gene_mask_extractor.extract(interval, variant) + return (gene_mask, metadata) + + @typing.jaxtyped + def score_variant( + self, + ref: variant_scoring.ScoreVariantInput, + alt: variant_scoring.ScoreVariantInput, + *, + masks: Bool[Array, 'S G'], + settings: _VariantScorerSettings, + variant: genome.Variant | None = None, + interval: genome.Interval | None = None, + ) -> variant_scoring.ScoreVariantOutput: + alt = alt[settings.requested_output] + ref = ref[settings.requested_output] + gene_mask = masks + alt = variant_scoring.align_alternate(alt, variant, interval) + + output = _score_gene_variant(ref, alt, gene_mask, settings=settings) + return {'score': output} + + def finalize_variant( + self, + scores: variant_scoring.ScoreVariantResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: pd.DataFrame, + settings: _VariantScorerSettings, + ) -> anndata.AnnData: + """Returns summarized scores for the given scores and metadata.""" + output_metadata = track_metadata.get(settings.requested_output) + assert isinstance(output_metadata, track_data.TrackMetadata) + strand_mask = ( + np.asarray(mask_metadata['strand'].values)[:, None] + == output_metadata['strand'].values[None] + ) | (output_metadata['strand'].values[None] == '.') + + scores = np.where(strand_mask, scores['score'], np.nan) + return variant_scoring.create_anndata( + scores, + obs=mask_metadata, + var=output_metadata, + ) diff --git a/flax_model/alphagenome/model/variant_scoring/gene_mask_extractor.py b/flax_model/alphagenome/model/variant_scoring/gene_mask_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..9d2528c9c0b5174c98c216875b44c480a6b4e595 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/gene_mask_extractor.py @@ -0,0 +1,504 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Gene mask extractor.""" + +import abc +import collections +import dataclasses +import enum +from typing import Sequence + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import gene_annotation +from flax_model.alphagenome._sdk.data import genome +from jaxtyping import Array, Bool # pylint: disable=g-multiple-import, g-importing-member +import numpy as np +import pandas as pd + + +class GeneMaskType(enum.Enum): + """Type of gene mask.""" + + BODY = enum.auto() + EXONS = enum.auto() + + +class GeneQueryType(enum.Enum): + """Type of gene query.""" + + VARIANT_OVERLAPPING = enum.auto() + INTERVAL_CONTAINED = enum.auto() + + +class GeneMaskExtractor: + """Mask extractor yielding tuple (mask, metadata).""" + + def __init__( + self, + gtf: pd.DataFrame, + gene_mask_type: GeneMaskType, + *, + gene_query_type: GeneQueryType = GeneQueryType.INTERVAL_CONTAINED, + filter_protein_coding: bool = False, + cache_size: int = 2, + ): + self._gene_mask_type = gene_mask_type + self._gene_query_type = gene_query_type + self._filter_protein_coding = filter_protein_coding + self._lru_cache = collections.OrderedDict() + self._cache_size = cache_size + if self._filter_protein_coding: + # Use protein-coding annotations at gene level for gene body masks, + # and at transcript level for exon/TSS masks. + gtf = gene_annotation.filter_protein_coding( + gtf, include_gene_entries=(gene_mask_type == GeneMaskType.BODY) + ) + + match self._gene_mask_type: + case GeneMaskType.BODY: + self._mask_extractor = _GeneBodyAnnotationExtractor( + gtf, + gene_query_type=self._gene_query_type, + ) + case GeneMaskType.EXONS: + if self._gene_query_type != GeneQueryType.INTERVAL_CONTAINED: + raise ValueError( + 'Exon masks only support INTERVAL_CONTAINED query type.' + ) + self._mask_extractor = _GeneExonAnnotationExtractor(gtf) + case _: + raise ValueError(f'Unknown gene mask type: {self._gene_mask_type}') + + @typing.jaxtyped + def extract( + self, + interval: genome.Interval, + variant: genome.Variant | None = None, + transcript_ids: Sequence[str] | None = None, + ) -> tuple[Bool[np.ndarray, 'S G'], pd.DataFrame]: + """Extracts gene masks and metadata for a given interval.""" + key = hash((str(interval), str(variant), *(transcript_ids or []))) + if key in self._lru_cache: + mask, metadata = self._lru_cache[key] + self._lru_cache.move_to_end(key) + return mask, metadata.copy() + else: + mask, annotations = self._mask_extractor.extract( + interval=interval, variant=variant, transcript_ids=transcript_ids + ) + mask.setflags(write=False) + self._lru_cache[key] = (mask, annotations.get_metadata()) + while len(self._lru_cache) > self._cache_size: + self._lru_cache.popitem(last=False) + return mask, annotations.get_metadata() + + +@dataclasses.dataclass(frozen=True) +class _GeneAnnotation: + """Gene annotation.""" + + gene_id: Sequence[str] + gene_name: Sequence[str] + gene_type: Sequence[str] + strand: Sequence[str] + interval_start: Sequence[int] + chromosome: Sequence[str] + start: Sequence[int] + end: Sequence[int] + + def get_metadata(self) -> pd.DataFrame: + """Returns the metadata as a DataFrame.""" + return pd.DataFrame({ + 'gene_id': self.gene_id, + 'strand': self.strand, + 'gene_name': self.gene_name, + 'gene_type': self.gene_type, + 'interval_start': self.interval_start, + 'Chromosome': self.chromosome, + 'Start': self.start, + 'End': self.end, + }).reset_index(drop=True) + + +class _GeneAnnotationExtractor(abc.ABC): + """Base class for gene annotation extractors.""" + + @property + def bin_size(self) -> int: + return 1 + + @abc.abstractmethod + def extract( + self, + *, + interval: genome.Interval, + variant: genome.Variant | None = None, + transcript_ids: Sequence[str] | None = None, + ) -> tuple[Bool[np.ndarray, 'S G'], _GeneAnnotation]: + """Returns a list of gene annotations for the given interval or variant.""" + raise NotImplementedError() + + +class _GeneBodyAnnotationExtractor(_GeneAnnotationExtractor): + """Extracts gene annotations for a given interval.""" + + _COLUMNS = [ + 'Chromosome', + 'Start', + 'End', + 'Strand', + 'gene_id', + 'gene_name', + 'gene_type', + ] + + def __init__( + self, + gtf: pd.DataFrame, + gene_query_type: GeneQueryType, + ): + """Init. + + Args: + gtf: GTF DataFrame. + gene_query_type: Type of gene query. + """ + self._gene_mask_extractor = _GeneMaskExtractor(gtf) + self._gene_query_type = gene_query_type + self._df_gene_gtf = gtf[gtf.Feature == 'gene'][self._COLUMNS] + self._df_start_end = { + chromosome: (dfc, dfc['Start'].values, dfc['End'].values) + for chromosome, dfc in self._df_gene_gtf.groupby( + 'Chromosome', observed=False + ) + } + self._df_empty = self._df_gene_gtf.iloc[:0] + + def _extract_interval_contained( + self, interval: genome.Interval + ) -> pd.DataFrame: + """Extracts genes contained by the given interval.""" + if interval.chromosome not in self._df_start_end: + return self._df_empty + else: + dfc, start, end = self._df_start_end[interval.chromosome] + return dfc[(start >= interval.start) & (end <= interval.end)] + + def _extract_variant_overlapping( + self, variant: genome.Variant + ) -> pd.DataFrame: + """Extracts genes overlapping the given variant.""" + if variant.chromosome not in self._df_start_end: + return self._df_empty + else: + dfc, start, end = self._df_start_end[variant.chromosome] + variant_end = max( + variant.end, variant.start + len(variant.alternate_bases) + ) + return dfc[(end > variant.start) & (start < variant_end)] + + def extract( + self, + *, + interval: genome.Interval, + variant: genome.Variant | None = None, + transcript_ids: Sequence[str] | None = None, + ) -> tuple[Bool[np.ndarray, 'S G'], _GeneAnnotation]: + """Returns a list of gene annotations for the given interval. + + Args: + interval: Interval to extract at. + variant: Variant to extract at. + transcript_ids: Not supported and should not be provided. + """ + if transcript_ids is not None: + raise ValueError('transcript_ids not supported for gene body extractor.') + + match self._gene_query_type: + case GeneQueryType.VARIANT_OVERLAPPING: + if variant is None: + raise ValueError('No variant provided for VARIANT_OVERLAPPING query.') + gene_subset = self._extract_variant_overlapping(variant) + case GeneQueryType.INTERVAL_CONTAINED: + gene_subset = self._extract_interval_contained(interval) + case _: + raise ValueError(f'Unknown gene query type: {self._gene_query_type}') + + mask = np.empty((interval.width, len(gene_subset)), dtype=bool) + + for i, row in enumerate(gene_subset.itertuples()): + mask[:, i] = self._gene_mask_extractor.extract(interval, row.gene_id) + + annotations = _GeneAnnotation( + gene_id=gene_subset.gene_id, + gene_name=gene_subset.gene_name, + gene_type=gene_subset.gene_type, + strand=gene_subset.Strand, + interval_start=[interval.start] * len(gene_subset), + chromosome=gene_subset.Chromosome, + start=gene_subset.Start, + end=gene_subset.End, + ) + return mask, annotations + + +class _GeneMaskExtractor: + """Generates binary masks for genes.""" + + def __init__(self, gtf: pd.DataFrame): + """Init. + + Args: + gtf: GTF DataFrame. + """ + self._gtf = gtf + self._genes_by_gene_id = gtf[gtf.Feature == 'gene'][ + ['Chromosome', 'Start', 'End', 'Strand', 'gene_id'] + ].groupby('gene_id', sort=False) + + def extract( + self, + interval: genome.Interval, + gene_id: str, + ) -> Bool[Array | np.ndarray, 'S']: + """Extracts gene masks for a specific gene. + + Args: + interval: Interval to extract at. + gene_id: Gene ID to extract mask for. + + Returns: + Boolean mask of shape (interval.width, 2). + """ + if gene_id not in self._gtf['gene_id'].values: + raise ValueError(f'Gene ID {gene_id} not found in GTF.') + + genes = self._genes_by_gene_id.get_group(gene_id) + intervals = [ + genome.Interval(chr, start, end, strand) + for chr, start, end, strand in zip( + genes.Chromosome, genes.Start, genes.End, genes.Strand + ) + ] + mask = np.zeros((interval.width,), dtype=bool) + for gene_interval in intervals: + if interval.overlaps(gene_interval): + relative_start = max(gene_interval.start - interval.start, 0) + relative_end = min(gene_interval.end - interval.start, interval.width) + mask[relative_start:relative_end] = True + return mask + + +class _GeneExonAnnotationExtractor(_GeneAnnotationExtractor): + """Generates binary masks of overlapping exons.""" + + _GENE_COLUMNS = [ + 'Chromosome', + 'Start', + 'End', + 'Strand', + 'gene_id', + 'gene_name', + 'gene_type', + ] + + def __init__(self, gtf: pd.DataFrame): + """Init. + + Args: + gtf: GTF DataFrame. + """ + self._exon_mask_extractor = _ExonMaskExtractor(gtf) + + # We use transcript's TSS to determine which transcripts to annotate. + self._tss = _PositionExtractor( + gene_annotation.extract_tss(gtf), position_column='Start' + ) + self._gtf = gtf + self._gene_df = gtf[gtf.Feature == 'gene'][self._GENE_COLUMNS].set_index( + 'gene_id' + ) + + def extract( + self, + *, + interval: genome.Interval, + variant: genome.Variant | None = None, + transcript_ids: Sequence[str] | None = None, + ) -> tuple[Bool[np.ndarray, 'S G'], _GeneAnnotation]: + """Extracts exon masks. + + Args: + interval: Interval to extract at. + variant: Variant to extract at. + transcript_ids: Optional list of transcript ids to extract. + + Returns: + A list of gene annotations for the given interval. + """ + if transcript_ids is not None: + # Contains start/end positions for the transcripts. + transcript_subset = self._gtf[ + self._gtf.transcript_id.isin(transcript_ids) + ] + else: + # Contains TSS positions for the transcripts. + transcript_subset = self._tss.extract(interval) + + # Mask for each gene is the OR of the masks for all its exons. + gene_masks = {} + + for row in transcript_subset.itertuples(): + transcript_id = row.transcript_id + gene_id = row.gene_id + + exon_mask = self._exon_mask_extractor.extract(interval, transcript_id) + if (gene_mask := gene_masks.get(gene_id)) is not None: + gene_mask |= exon_mask + else: + gene_masks[gene_id] = exon_mask + + unique_gene_ids = list(transcript_subset['gene_id'].unique()) + gene_metadata = self._gene_df.loc[unique_gene_ids] + mask = np.empty((interval.width, len(unique_gene_ids)), dtype=bool) + for i, gene_id in enumerate(unique_gene_ids): + mask[:, i] = gene_masks[gene_id] + + annotations = _GeneAnnotation( + gene_id=unique_gene_ids, + gene_name=gene_metadata.gene_name, + gene_type=gene_metadata.gene_type, + strand=gene_metadata.Strand, + interval_start=[interval.start] * len(unique_gene_ids), + chromosome=gene_metadata.Chromosome, + start=gene_metadata.Start, + end=gene_metadata.End, + ) + return mask, annotations + + +class _PositionExtractor: + """Extractor focused on single position, rather than an interval. + + This extractor can be up to 20x faster than PyRangesExtractor. + + Interval is considered semi-open [start, end). Rows where + - chromosome == interval.chromosome + - position >= interval.start + - position < interval.end + are returned. + + Note: This code doesn't consider the stand information. + """ + + def __init__( + self, + df: pd.DataFrame, + position_column: str, + chromosome_column: str = 'Chromosome', + ): + """Init. + + Args: + df: dataframe to query with `position_column` and `chromosome_column`. + position_column: Which column in df to use as 0-based position. + chromosome_column: Which column in df to use as chromosome. + """ + self._df_position = { + chromosome: (dfc, dfc[position_column].values) + for chromosome, dfc in df.groupby(chromosome_column, observed=False) + } + + self._df_empty = df.iloc[:0] + + def extract(self, interval: genome.Interval) -> pd.DataFrame: + if interval.chromosome not in self._df_position: + return self._df_empty + else: + dfc, position = self._df_position[interval.chromosome] + return dfc[(position >= interval.start) & (position < interval.end)] + + +class _ExonMaskExtractor: + """Generates binary masks for exons.""" + + def __init__(self, gtf: pd.DataFrame): + """Init. + + Args: + gtf: GTF DataFrame. + """ + self._exon_extractor = _ExonExtractor(gtf) + + def extract( + self, + interval: genome.Interval, + transcript_id: str, + ) -> Bool[Array | np.ndarray, 'S']: + """Extracts exon masks for a single transcript. + + Args: + interval: Interval to extract at. + transcript_id: The transcript to extract exons for. + + Returns: + Boolean mask of shape (interval.width, 2). + """ + exons = self._exon_extractor.extract(transcript_id) + mask = np.zeros((interval.width,), dtype=bool) + for exon in exons: + if interval.overlaps(exon): + relative_start = max(exon.start - interval.start, 0) + relative_end = min(exon.end - interval.start, interval.width) + mask[relative_start:relative_end] = True + return mask + + +class _ExonExtractor: + """Extracts exons for a single transcript.""" + + def __init__(self, gtf: pd.DataFrame): + """Init. + + Args: + gtf: GTF DataFrame. + """ + self._gtf = gtf + self._exons_by_transcript_id = gtf[gtf.Feature == 'exon'][ + ['Chromosome', 'Start', 'End', 'Strand', 'transcript_id'] + ].groupby('transcript_id', sort=False) + + def extract( + self, + transcript_id: str, + ) -> list[genome.Interval]: + """Extracts exons as List[genome.Interval] for a single transcript. + + Args: + transcript_id: The transcript to extract exons for. + + Returns: + List of exon intervals for the transcript. + """ + try: + exons = self._exons_by_transcript_id.get_group(transcript_id) + return [ + genome.Interval(chr, start, end, strand) + for chr, start, end, strand in zip( + exons.Chromosome, exons.Start, exons.End, exons.Strand + ) + ] + except KeyError: + return [] diff --git a/flax_model/alphagenome/model/variant_scoring/gene_mask_extractor_test.py b/flax_model/alphagenome/model/variant_scoring/gene_mask_extractor_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7a0e11eb1244af22899c7a53f356e19b3f4d779c --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/gene_mask_extractor_test.py @@ -0,0 +1,301 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor +import chex +import numpy as np +import pandas as pd + + +def _get_dummy_gtf() -> pd.DataFrame: + """Returns a dummy GTF DataFrame for testing.""" + data = [ + ['gene', 'chr1', 10, 100, '+', 'gene1', 'name1', 'type1', ''], + ['transcript', 'chr1', 10, 100, '+', 'gene1', 'name1', 'type1', 't1'], + ['exon', 'chr1', 10, 50, '+', 'gene1', 'name1', 'type1', 't1'], + ['exon', 'chr1', 70, 100, '+', 'gene1', 'name1', 'type1', 't1'], + ['gene', 'chr1', 120, 150, '-', 'gene2', 'name2', 'type2', ''], + ['transcript', 'chr1', 120, 150, '-', 'gene2', 'name2', 'type2', 't2'], + ['exon', 'chr1', 120, 150, '-', 'gene2', 'name2', 'type2', 't2'], + ] + return pd.DataFrame( + data, + columns=[ + 'Feature', + 'Chromosome', + 'Start', + 'End', + 'Strand', + 'gene_id', + 'gene_name', + 'gene_type', + 'transcript_id', + ], + ) + + +class GeneMaskExtractorTest(parameterized.TestCase): + + def setUp(self): + super().setUp() + self._gtf = _get_dummy_gtf() + + @parameterized.named_parameters([ + # gene_mask_type=BODY, gene_query_type=INTERVAL_CONTAINED + dict( + testcase_name='body_interval_two_genes', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 0, 200), + expected_num_genes=2, + expected_masks_segments=[(0, [(10, 100)]), (1, [(120, 150)])], + expected_gene_ids=['gene1', 'gene2'], + ), + dict( + testcase_name='body_interval_two_genes_shifted_interval', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 5, 200), + expected_num_genes=2, + expected_masks_segments=[(0, [(5, 95)]), (1, [(115, 145)])], + expected_gene_ids=['gene1', 'gene2'], + ), + dict( + testcase_name=( + 'body_interval_two_genes_shifted_interval_outside_of_gene_range' + ), + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 15, 200), + expected_num_genes=1, + expected_masks_segments=[(0, [(105, 135)])], + expected_gene_ids=['gene2'], + ), + dict( + testcase_name='body_interval_one_gene', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 0, 110), + expected_num_genes=1, + expected_masks_segments=[(0, [(10, 100)])], + expected_gene_ids=['gene1'], + ), + dict( + testcase_name='body_interval_no_genes', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 0, 10), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + dict( + testcase_name='body_interval_no_genes_in_region', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 300, 400), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + dict( + testcase_name='body_interval_wrong_chromosome', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr2', 0, 200), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + # gene_mask_type=BODY, gene_query_type=VARIANT_OVERLAPPING + dict( + testcase_name='body_variant_variant_in_gene1', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.VARIANT_OVERLAPPING, + interval=genome.Interval('chr1', 0, 200), + variant=genome.Variant('chr1', 55, 'A', 'G'), + expected_num_genes=1, + expected_masks_segments=[(0, [(10, 100)])], + expected_gene_ids=['gene1'], + ), + dict( + testcase_name='body_variant_variant_in_gene2', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.VARIANT_OVERLAPPING, + interval=genome.Interval('chr1', 0, 200), + variant=genome.Variant('chr1', 130, 'A', 'G'), + expected_num_genes=1, + expected_masks_segments=[(0, [(120, 150)])], + expected_gene_ids=['gene2'], + ), + dict( + testcase_name='body_variant_variant_between_genes', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.VARIANT_OVERLAPPING, + interval=genome.Interval('chr1', 0, 200), + variant=genome.Variant('chr1', 110, 'A', 'G'), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + dict( + testcase_name='body_variant_variant_overlapping_two_genes', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.VARIANT_OVERLAPPING, + interval=genome.Interval('chr1', 0, 200), + variant=genome.Variant('chr1', 99, 'A' * 30, 'G'), + expected_num_genes=2, + expected_masks_segments=[(0, [(10, 100)]), (1, [(120, 150)])], + expected_gene_ids=['gene1', 'gene2'], + ), + dict( + testcase_name='body_variant_variant_in_gene1_shifted_interval', + gene_mask_type=gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.VARIANT_OVERLAPPING, + interval=genome.Interval('chr1', 10, 110), + variant=genome.Variant('chr1', 55, 'A', 'G'), + expected_num_genes=1, + expected_masks_segments=[(0, [(0, 90)])], + expected_gene_ids=['gene1'], + ), + # gene_mask_type=EXONS, gene_query_type=INTERVAL_CONTAINED + dict( + testcase_name='exons_interval_two_genes', + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 0, 200), + expected_num_genes=2, + expected_masks_segments=[ + (0, [(10, 50), (70, 100)]), + (1, [(120, 150)]), + ], + expected_gene_ids=['gene1', 'gene2'], + ), + dict( + testcase_name='exons_interval_two_genes_shifted_interval', + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 5, 200), + expected_num_genes=2, + expected_masks_segments=[(0, [(5, 45), (65, 95)]), (1, [(115, 145)])], + expected_gene_ids=['gene1', 'gene2'], + ), + dict( + testcase_name=( + 'exons_interval_two_genes_shifted_interval_outside_of_gene_range' + ), + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 15, 200), + expected_num_genes=1, + expected_masks_segments=[(0, [(105, 135)])], + expected_gene_ids=['gene2'], + ), + dict( + testcase_name='exons_interval_one_gene', + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 0, 110), + expected_num_genes=1, + expected_masks_segments=[(0, [(10, 50), (70, 100)])], + expected_gene_ids=['gene1'], + ), + dict( + testcase_name='exons_interval_no_genes', + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 0, 10), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + dict( + testcase_name='exons_interval_no_genes_in_region', + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr1', 300, 400), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + dict( + testcase_name='exons_interval_wrong_chromosome', + gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS, + gene_query_type=gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED, + variant=None, + interval=genome.Interval('chr2', 0, 200), + expected_num_genes=0, + expected_masks_segments=[], + expected_gene_ids=[], + ), + ]) + def test_gene_mask_extractor( + self, + gene_mask_type, + gene_query_type, + interval, + variant, + expected_num_genes, + expected_masks_segments, + expected_gene_ids, + ): + extractor = gene_mask_extractor.GeneMaskExtractor( + self._gtf, + gene_mask_type=gene_mask_type, + gene_query_type=gene_query_type, + ) + mask, metadata = extractor.extract(interval, variant) + + chex.assert_shape(mask, (interval.width, expected_num_genes)) + self.assertLen(metadata, expected_num_genes) + if expected_num_genes > 0: + self.assertListEqual(metadata.gene_id.tolist(), expected_gene_ids) + + for i, segments in expected_masks_segments: + expected_mask = np.zeros(interval.width, dtype=bool) + for start, end in segments: + expected_mask[start:end] = True + np.testing.assert_array_equal(mask[:, i], expected_mask) + + def test_gene_mask_extractor_with_wrong_gene_id_raises_error(self): + extractor = gene_mask_extractor._GeneMaskExtractor(self._gtf) # pylint: disable=protected-access + interval = genome.Interval('chr1', 0, 200) + with self.assertRaisesRegex(ValueError, 'Gene ID wrong_gene_id not found'): + extractor.extract(interval, gene_id='wrong_gene_id') + + def test_exon_extractor_transcript_with_no_exons_returns_empty(self): + extractor = gene_mask_extractor._ExonExtractor(self._gtf) # pylint: disable=protected-access + exons = extractor.extract(transcript_id='wrong_transcript_id') + self.assertEmpty(exons) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/gene_mask_test.py b/flax_model/alphagenome/model/variant_scoring/gene_mask_test.py new file mode 100644 index 0000000000000000000000000000000000000000..bc5e721f90bf5715e7ba816cf8c0414c0893097e --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/gene_mask_test.py @@ -0,0 +1,386 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import gene_mask +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor as gene_mask_extractor_lib +import anndata +import jax +import jax.numpy as jnp +import numpy as np +import pandas as pd + + +def _get_mock_gtf(): + # Two genes (G1, G2). + # G1 has 3 transcripts (T1, T2, T3). G2 has 1 transcript (T4). The T4 + # transcript is further annotated as consisting of 2 exons. + gtf = pd.DataFrame({ + 'End': [200, 200, 200, 200, 108, 108, 40, 108], + 'Start': [101, 101, 102, 103, 0, 0, 0, 80], + 'Strand': ['+', '+', '+', '+', '-', '-', '-', '-'], + 'transcript_id': ['', 'T1', 'T2', 'T3', '', 'T4', 'T4', 'T4'], + 'transcript_type': [ + '', + 'protein_coding', + 'protein_coding', + 'protein_coding', + '', + 'protein_coding', + 'protein_coding', + 'protein_coding', + ], + 'gene_id': ['G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2'], + 'gene_name': [ + 'gene_1_name', + 'gene_2_name', + 'gene_1_name', + 'gene_1_name', + 'gene_2_name', + 'gene_2_name', + 'gene_2_name', + 'gene_2_name', + ], + 'Feature': [ + 'gene', + 'transcript', + 'transcript', + 'transcript', + 'gene', + 'transcript', + 'exon', + 'exon', + ], + }) + gtf['Chromosome'] = 'chr1' + gtf['Score'] = '.' + gtf['Frame'] = '.' + gtf['Source'] = 'ENSEMBL' + gtf['gene_type'] = 'protein_coding' + return gtf + + +def _get_mock_rnaseq_track_metadata() -> pd.DataFrame: + return pd.DataFrame({ + 'name': [ + 'CL:0000047 polyA plus RNA-seq', + 'CL:0000062 total RNA-seq', + 'CL:0000084 polyA plus RNA-seq', + 'CL:0000084 total RNA-seq', + 'CL:0000115 total RNA-seq', + 'CL:0000127 total RNA-seq', + ( + 'EFO:0000572 gtex Cells_EBV-transformed_lymphocytes polyA plus' + ' RNA-seq' + ), + 'EFO:0002009 gtex Cells_Cultured_fibroblasts polyA plus RNA-seq', + 'UBERON:0000007 gtex Pituitary polyA plus RNA-seq', + 'UBERON:0000458 gtex Cervix_Endocervix polyA plus RNA-seq', + ], + 'strand': ['+', '+', '+', '+', '+', '+', '.', '.', '.', '.'], + 'gtex_tissue': [ + '', + '', + '', + '', + '', + '', + 'Cells_EBV-transformed_lymphocytes', + 'Cells_Cultured_fibroblasts', + 'Pituitary', + 'Cervix_Endocervix', + ], + 'padding': [False] * 10, + }) + + +class GeneMaskVariantScorerTest(parameterized.TestCase): + + def test_get_masks_and_metadata_body(self): + gene_mask_extractor = gene_mask_extractor_lib.GeneMaskExtractor( + gtf=_get_mock_gtf(), + gene_mask_type=gene_mask_extractor_lib.GeneMaskType.BODY, + ) + gene_variant_scorer = gene_mask.GeneVariantScorer( + gene_mask_extractor=gene_mask_extractor, + ) + interval = genome.Interval('chr1', 0, 256) + variant = genome.Variant('chr1', 10, 'C', 'T') + settings = variant_scorers.GeneMaskLFCScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + ) + track_metadata = dna_output.OutputMetadata( + rna_seq=_get_mock_rnaseq_track_metadata() + ) + gene_masks, metadata = gene_variant_scorer.get_masks_and_metadata( + interval, variant, settings=settings, track_metadata=track_metadata + ) + self.assertIsInstance(metadata, pd.DataFrame) + self.assertLen(metadata, 2) + self.assertSequenceEqual(list(metadata.gene_id), ['G1', 'G2']) + + self.assertEqual(gene_masks.shape, (256, 2)) + expected_g1_mask = np.zeros(256, dtype=bool) + expected_g1_mask[101:200] = True + expected_g2_mask = np.zeros(256, dtype=bool) + expected_g2_mask[0:108] = True + np.testing.assert_array_equal(gene_masks[:, 0], expected_g1_mask) + np.testing.assert_array_equal(gene_masks[:, 1], expected_g2_mask) + + @parameterized.product( + [ + dict( + settings=variant_scorers.GeneMaskLFCScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + ), + # ref values for gene: 4, 5, 6. mean = 5. + # alt values for gene: 1, 1, 1. mean = 1. + # expected_score = log(1 + 1e-3) - log(5 + 1e-3) = -1.6086375 + expected_score=-1.6086375, + ), + dict( + settings=variant_scorers.GeneMaskActiveScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + ), + # ref values for gene: 4, 5, 6. mean = 5. + # alt values for gene: 1, 1, 1. mean = 1. + # expected_score = max(1, 5) = 5. + expected_score=5.0, + ), + ], + transfer_guard=['disallow', 'allow'], + ) + def test_score_variant( + self, settings, expected_score: float, transfer_guard: str + ): + gtf = pd.DataFrame({ + 'End': [7], + 'Start': [4], + 'Strand': ['+'], + 'gene_id': ['G1'], + 'gene_name': ['gene_1_name'], + 'Feature': ['gene'], + 'Chromosome': ['chr1'], + 'Score': ['.'], + 'Frame': ['.'], + 'Source': ['ENSEMBL'], + 'gene_type': ['protein_coding'], + 'transcript_id': [''], + 'transcript_type': [''], + }) + gene_mask_extractor = gene_mask_extractor_lib.GeneMaskExtractor( + gtf=gtf, + gene_mask_type=gene_mask_extractor_lib.GeneMaskType.BODY, + ) + gene_variant_scorer = gene_mask.GeneVariantScorer( + gene_mask_extractor=gene_mask_extractor, + ) + interval = genome.Interval('chr1', 0, 11) + variant = genome.Variant('chr1', 1, 'C', 'T') + track_metadata = dna_output.OutputMetadata( + rna_seq=_get_mock_rnaseq_track_metadata() + ) + num_tracks = len(track_metadata.rna_seq) + gene_masks, _ = gene_variant_scorer.get_masks_and_metadata( + interval, variant, settings=settings, track_metadata=track_metadata + ) + expected_g1_mask = np.zeros((11, 1), dtype=bool) + expected_g1_mask[4:7, 0] = True + np.testing.assert_array_equal(gene_masks, expected_g1_mask) + + ref = ( + jnp.arange(11, dtype=jnp.float32) + .reshape(-1, 1) + .repeat(num_tracks, axis=1) + ) + alt = jnp.ones((11, num_tracks), dtype=jnp.float32) + with jax.transfer_guard(transfer_guard): + scores = gene_variant_scorer.score_variant( + ref={settings.requested_output: ref}, + alt={settings.requested_output: alt}, + masks=jax.device_put(gene_masks), + settings=settings, + variant=variant, + interval=interval, + ) + np.testing.assert_almost_equal( + scores['score'], + np.ones((1, num_tracks), dtype=jnp.float32) * expected_score, + decimal=5, + ) + + @parameterized.product( + variant=[ + genome.Variant('chr1', 5, 'A', 'AT'), + genome.Variant('chr1', 4, 'AA', 'AAT'), + genome.Variant('chr1', 3, 'AAA', 'AAAT'), + ], + transfer_guard=['disallow', 'allow'], + ) + def test_gene_variant_scorer_splicing_insertion( + self, variant: genome.Variant, transfer_guard: str + ): + # Score an insertion that adds a predicted splicing donor at position 5. + # In addition, there is a predicted splicing acceptor at position 7 in the + # REF (position 8 in the ALT due to the insertion), which should be neutral. + gtf = pd.DataFrame({ + 'Chromosome': ['chr1'], + 'Start': [0], + 'End': [20], + 'Strand': ['+'], + 'Feature': ['gene'], + 'gene_id': ['G1'], + 'gene_name': ['Gene1'], + 'gene_type': ['protein_coding'], + 'transcript_id': [''], + 'transcript_type': [''], + }) + variant_scorer = gene_mask.GeneVariantScorer( + gene_mask_extractor=gene_mask_extractor_lib.GeneMaskExtractor( + gtf=gtf, + gene_mask_type=gene_mask_extractor_lib.GeneMaskType.BODY, + gene_query_type=( + gene_mask_extractor_lib.GeneQueryType.VARIANT_OVERLAPPING + ), + ), + ) + track_metadata = dna_output.OutputMetadata() + settings = variant_scorers.GeneMaskSplicingScorer( + requested_output=dna_output.OutputType.SPLICE_SITES, + width=None, + ) + interval = variant.reference_interval.resize(9) + masks, _ = variant_scorer.get_masks_and_metadata( + interval, variant, settings=settings, track_metadata=track_metadata + ) + + alt = jnp.zeros((9, 4), dtype=jnp.float32) + alt = alt.at[4 - interval.start, 0].set(1) + alt = alt.at[7 - interval.start, 2].set(1) + ref = jnp.zeros((9, 4), dtype=jnp.float32) + ref = ref.at[6 - interval.start, 2].set(1) + + with jax.transfer_guard(transfer_guard): + scores = variant_scorer.score_variant( + {dna_output.OutputType.SPLICE_SITES: ref}, + {dna_output.OutputType.SPLICE_SITES: alt}, + masks=jax.device_put(masks), + settings=settings, + variant=variant, + interval=interval, + ) + # A new splicing donor was inserted, so the 0th track should be 1.0. A + # splicing acceptor was kept intact, so the 1st track should remain 0.0. + np.testing.assert_array_equal( + scores['score'][0], np.array([1, 0, 0, 0], dtype=jnp.float32) + ) + + @parameterized.parameters( + genome.Variant('chr1', 5, 'AT', 'A'), + genome.Variant('chr1', 4, 'AAT', 'AA'), + genome.Variant('chr1', 3, 'AAAT', 'AAA'), + ) + def test_gene_variant_scorer_splicing_deletion(self, variant): + # Score a deletion that removes a predicted splicing donor at position 5. + # In addition, there is a predicted splicing acceptor at position 4, + # which should be neutral. + gtf = pd.DataFrame({ + 'Chromosome': ['chr1'], + 'Start': [0], + 'End': [20], + 'Strand': ['+'], + 'Feature': ['gene'], + 'gene_id': ['G1'], + 'gene_name': ['Gene1'], + 'gene_type': ['protein_coding'], + 'transcript_id': [''], + 'transcript_type': [''], + }) + variant_scorer = gene_mask.GeneVariantScorer( + gene_mask_extractor=gene_mask_extractor_lib.GeneMaskExtractor( + gtf=gtf, + gene_mask_type=gene_mask_extractor_lib.GeneMaskType.BODY, + gene_query_type=( + gene_mask_extractor_lib.GeneQueryType.VARIANT_OVERLAPPING + ), + ), + ) + track_metadata = dna_output.OutputMetadata() + settings = variant_scorers.GeneMaskSplicingScorer( + requested_output=dna_output.OutputType.SPLICE_SITES, + width=None, + ) + interval = variant.reference_interval.resize(9) + masks, _ = variant_scorer.get_masks_and_metadata( + interval, variant, settings=settings, track_metadata=track_metadata + ) + + alt = jnp.zeros((9, 4), dtype=jnp.float32) + alt = alt.at[4 - interval.start, 2].set(1) + ref = jnp.zeros((9, 4), dtype=jnp.float32) + ref = ref.at[5 - interval.start, 0].set(1) + ref = ref.at[4 - interval.start, 2].set(1) + + scores = variant_scorer.score_variant( + {dna_output.OutputType.SPLICE_SITES: ref}, + {dna_output.OutputType.SPLICE_SITES: alt}, + masks=jax.device_put(masks), + settings=settings, + variant=variant, + interval=interval, + ) + # A splicing donor was deleted, so the 0th track should be 1.0. A + # splicing acceptor was kept intact, so the other tracks should remain 0.0. + np.testing.assert_array_equal( + scores['score'][0], np.array([1, 0, 0, 0], dtype=jnp.float32) + ) + + def test_finalize_variant(self): + gene_mask_extractor = gene_mask_extractor_lib.GeneMaskExtractor( + gtf=_get_mock_gtf(), + gene_mask_type=gene_mask_extractor_lib.GeneMaskType.BODY, + ) + gene_variant_scorer = gene_mask.GeneVariantScorer( + gene_mask_extractor=gene_mask_extractor, + ) + interval = genome.Interval('chr1', 0, 256) + variant = genome.Variant('chr1', 10, 'C', 'T') + settings = variant_scorers.GeneMaskLFCScorer( + requested_output=dna_output.OutputType.RNA_SEQ, + ) + df_track_metadata = _get_mock_rnaseq_track_metadata() + track_metadata = dna_output.OutputMetadata(rna_seq=df_track_metadata) + _, mask_metadata = gene_variant_scorer.get_masks_and_metadata( + interval, variant, settings=settings, track_metadata=track_metadata + ) + self.assertLen(mask_metadata, 2) # Two genes. + scores = {'score': np.ones((2, len(df_track_metadata)), dtype=np.float32)} + finalized_variant = gene_variant_scorer.finalize_variant( + scores, + track_metadata=track_metadata, + mask_metadata=mask_metadata, + settings=settings, + ) + self.assertIsInstance(finalized_variant, anndata.AnnData) + self.assertLen(finalized_variant.obs, 2) + self.assertLen(finalized_variant.var, len(df_track_metadata)) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/polyadenylation.py b/flax_model/alphagenome/model/variant_scoring/polyadenylation.py new file mode 100644 index 0000000000000000000000000000000000000000..c4f56f81cafd3b8da497c2dae815adc361a71902 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/polyadenylation.py @@ -0,0 +1,227 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Implements a variant scorer for polyadenylation.""" + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor +from flax_model.alphagenome.model.variant_scoring import variant_scoring +import anndata +import chex +import jax +import jax.numpy as jnp +from jaxtyping import Array, Bool, Float32 # pylint: disable=g-multiple-import, g-importing-member +import numpy as np +import pandas as pd + +MAX_GENES = 22 +MAX_PAS = 136 + +_PAS_MASK_WIDTH = 400 + + +@typing.jaxtyped +@chex.dataclass(frozen=True) +class PolyadenylationVariantMasks: + pas_mask: Bool[Array | np.ndarray, 'S G P'] + gene_mask: Bool[Array | np.ndarray, 'G'] + + +@jax.jit +@typing.jaxtyped +def _aggregate_maximum_ratio_coverage_fc( + ref: Float32[Array, 'S T'], + alt: Float32[Array, 'S T'], + gene_pas_mask: Bool[Array, 'S G P'], +) -> Float32[Array, 'G T']: + """Implements the Borzoi statistic for paQTL variant scoring.""" + + ref_aggregation = jnp.einsum('pc,pga->gac', ref, gene_pas_mask) + alt_aggregation = jnp.einsum('pc,pga->gac', alt, gene_pas_mask) + covr_ratio = alt_aggregation / ref_aggregation + covr_ratio = jnp.nan_to_num(covr_ratio, posinf=0, neginf=0, nan=0) + # (gene, pas, tracks) + + # Get proximal vs distal counts for all possible polyadenylation site + # split versions. + k_interval = jnp.arange(MAX_PAS) # All PAS for the interval. + # Create mask for potential proximal pas site splits across the interval. + # Each PAS is added to the mask in sequential order for each gene, which + # ensures that aggregating the proximal counts take the first k PAS sites + # for each gene. + proximal_sites = k_interval[None] <= k_interval[:, None] + + # Get total number of pas sites per gene + k_total = gene_pas_mask.max(axis=0).sum(axis=-1)[:, None] # (gene, 1) + # Get number of pas sites included in the proximal split per gene. + k_gene = gene_pas_mask.max(axis=0).cumsum(axis=-1) # (gene, k) + k_scaling = ((k_total - k_gene) / k_gene).T[:, :, None] # (k, gene, 1) + + proximal_counts = jnp.einsum('gac,ka->kgc', covr_ratio, proximal_sites) + distal_counts = jnp.einsum('gac,ka->kgc', covr_ratio, ~proximal_sites) + + scores = jnp.abs(jnp.log2(k_scaling * proximal_counts / distal_counts)) + # We are converting nan to num to keep all the padding cases at 0. + scores = jnp.nan_to_num(scores, posinf=0, neginf=0, nan=0) + # [k, genes, tracks] + return scores.max(axis=0) + + +class PolyadenylationVariantScorer(variant_scoring.VariantScorer): + """Variant scorer for polyadenylation.""" + + def __init__( + self, + gtf: pd.DataFrame, + pas_gtf: pd.DataFrame, + ): + self._gene_mask_extractor = gene_mask_extractor.GeneMaskExtractor( + gtf, + gene_mask_extractor.GeneMaskType.BODY, + gene_query_type=gene_mask_extractor.GeneQueryType.VARIANT_OVERLAPPING, + ) + if 'gene_id_nopatch' not in pas_gtf: + pas_gtf['gene_id_nopatch'] = pas_gtf['gene_id'].str.split( + '.', expand=True + )[0] + self._pas_per_gene = { + gene_id_gtf: df + for gene_id_gtf, df in pas_gtf.groupby('gene_id_nopatch') + } + + def get_masks_and_metadata( + self, + interval: genome.Interval, + variant: genome.Variant, + *, + settings: variant_scorers.PolyadenylationScorer, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[PolyadenylationVariantMasks, pd.DataFrame]: + """See base class.""" + del settings, track_metadata + _, gene_metadata = self._gene_mask_extractor.extract(interval, variant) + if len(gene_metadata) > MAX_GENES: + raise ValueError( + f'Too many genes found for interval {interval}: {len(gene_metadata)}' + ) + gene_metadata_rows = [] + gene_padding_mask = np.zeros(MAX_GENES, dtype=bool) + pas_mask = np.zeros( + (interval.width, MAX_GENES, MAX_PAS), + dtype=bool, + ) + has_gene_id_nopatch = 'gene_id_nopatch' in gene_metadata.columns + for gene_index, gene_row in gene_metadata.iterrows(): + gene_id = ( + gene_row['gene_id_nopatch'] + if has_gene_id_nopatch + else gene_row['gene_id'].split('.')[0] + ) + if gene_id not in self._pas_per_gene: + continue + gene_pas = self._pas_per_gene[gene_id] + gene_pas = gene_pas[gene_pas['pas_strand'] == gene_row['strand']] + if ( + gene_pas.shape[0] == 0 + # Check at least 80% of a gene's PAS sites fall within the interval. + or np.mean((gene_pas['Start'] >= interval.start).values) < 0.8 + or np.mean((gene_pas['End'] < interval.end).values) < 0.8 + ): + # No PAS sites in interval for the gene. + continue + + # Only look at PAS sites that fall in the interval. + gene_pas = gene_pas[ + (gene_pas['Start'] >= interval.start) + & (gene_pas['End'] < interval.end) + ] + + if gene_pas.shape[0] == 1: + # Only one PAS site in interval for the gene. + continue + else: + pas_interval_start = gene_pas['Start'] - interval.start + gene_pas = gene_pas.sort_values(by='Start') + # Get PAS metadata for gene. + gene_row_metadata = gene_row.to_dict() + dist = np.abs(gene_pas['Start'] - variant.position) + gene_row_metadata['num_pas'] = len(gene_pas) + gene_row_metadata['min_pas_var_distance'] = dist.min() + gene_padding_mask[gene_index] = True + gene_metadata_rows.append(gene_row_metadata) + + for (pas_index, pas_row), p_interval_start in zip( + gene_pas.reset_index(drop=True).iterrows(), + pas_interval_start, + strict=True, + ): + # Defaults`to only doing upstream coverage of PAS site. + if pas_row.pas_strand == '+': + bin_end = p_interval_start + 1 + bin_start = bin_end - _PAS_MASK_WIDTH + else: + bin_start = p_interval_start + bin_end = bin_start + _PAS_MASK_WIDTH + bin_start = max(min(bin_start, interval.width), 0) + bin_end = max(min(bin_end, interval.width), 0) + pas_mask[bin_start:bin_end, gene_index, pas_index] = True + + return ( + PolyadenylationVariantMasks( + pas_mask=pas_mask, gene_mask=gene_padding_mask + ), + pd.DataFrame(gene_metadata_rows), + ) + + def score_variant( + self, + ref: variant_scoring.ScoreVariantInput, + alt: variant_scoring.ScoreVariantInput, + *, + masks: PolyadenylationVariantMasks, + settings: variant_scorers.PolyadenylationScorer, + variant: genome.Variant | None = None, + interval: genome.Interval | None = None, + ) -> variant_scoring.ScoreVariantOutput: + """See base class.""" + ref = ref[settings.requested_output] + alt = alt[settings.requested_output] + + alt = variant_scoring.align_alternate(alt, variant, interval) + return { + 'scores': _aggregate_maximum_ratio_coverage_fc( + ref, alt, jnp.asarray(masks.pas_mask) + ), + 'gene_mask': masks.gene_mask, + } + + def finalize_variant( + self, + scores: variant_scoring.ScoreVariantResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: pd.DataFrame, + settings: variant_scorers.PolyadenylationScorer, + ) -> anndata.AnnData: + """See base class.""" + + track_metadata = track_metadata.get(settings.requested_output) + return variant_scoring.create_anndata( + scores['scores'][scores['gene_mask']], + obs=mask_metadata, + var=track_metadata, + ) diff --git a/flax_model/alphagenome/model/variant_scoring/polyadenylation_test.py b/flax_model/alphagenome/model/variant_scoring/polyadenylation_test.py new file mode 100644 index 0000000000000000000000000000000000000000..24bd0544a9d94d42cfc5d9976ee0ed218d73af22 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/polyadenylation_test.py @@ -0,0 +1,292 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import polyadenylation +import anndata +import chex +import jax +import jax.numpy as jnp +import numpy as np +import pandas as pd + + +def _load_pas_scores(): + common = dict( + Chromosome='chr1', + ) + # PAS sites for 3 genes. G1 PAS sites fall in the middle of the interval, G2 + # PAS sites fall at the beginning of the interval with 80% of them in the + # interval, and G3 PAS sites fall outside of the interval. + apa_gtf = pd.DataFrame({ + 'Start': [ + 1575, + 1585, + 1605, + 980, + 1000, + 1010, + 1020, + 1045, + 3120, + 3150, + 3180, + 1100, + ], + 'pas_strand': [ + '+', + '+', + '+', + '-', + '-', + '-', + '-', + '-', + '+', + '+', + '+', + '+', + ], + 'pas_gene_id': [ + 'G1', + 'G1', + 'G1', + 'G2', + 'G2', + 'G2', + 'G2', + 'G2', + 'G3', + 'G3', + 'G3', + 'G4', + ], + }) + apa_gtf['End'] = apa_gtf['Start'] + 1 + apa_gtf['cutmode'] = apa_gtf['Start'] + apa_gtf['pas_id'] = apa_gtf.index + apa_gtf['gene_id'] = apa_gtf['pas_gene_id'] + + for k, v in common.items(): + apa_gtf[k] = v + return apa_gtf + + +def _load_gtf(): + """Loads a GTF PAS scoring test.""" + common = dict( + Chromosome='chr1', + Score='.', + Frame='.', + Source='ENSEMBL', + gene_type='protein_coding', + Feature='gene', + ) + # Relative to variant at position 1700 in interval (chr1, 1000, 3048) + # Three genes (G1, G2, G3). + # One gene is at the beginning of the query interval, middle, and end. + # Only uses gene elements. + gtf = pd.DataFrame({ + 'Start': [1500, 950, 1600, 1050], + 'End': [1800, 1800, 3100, 1800], + 'Strand': ['+', '-', '+', '+'], + 'gene_id': ['G1', 'G2', 'G3', 'G4'], + 'gene_name': [ + 'gene_1_name', + 'gene_2_name', + 'gene_3_name', + 'gene_4_name', + ], + }) + for k, v in common.items(): + gtf[k] = v + return gtf + + +def _load_pas_scoring_inputs() -> ( + tuple[genome.Variant, genome.Interval, pd.DataFrame, pd.DataFrame] +): + """Loads PAS scoring test specific gtf, PAS gtf, interval, and variant.""" + interval = genome.Interval('chr1', 1000, 3048) + variant = genome.Variant('chr1', 1700, 'C', 'T', name='var_0') + + return variant, interval, _load_gtf(), _load_pas_scores() + + +class PolyadenylationTest(parameterized.TestCase): + + def test_masks_and_metadata(self): + variant, interval, gtf, pas_gtf = _load_pas_scoring_inputs() + + scorer = polyadenylation.PolyadenylationVariantScorer(gtf, pas_gtf) + settings = variant_scorers.PolyadenylationScorer() + masks, metadata = scorer.get_masks_and_metadata( + interval, + variant, + settings=settings, + track_metadata=dna_output.OutputMetadata(), + ) + self.assertSameElements( + [ + 'Chromosome', + 'Start', + 'End', + 'interval_start', + 'strand', + 'gene_name', + 'gene_id', + 'gene_type', + 'num_pas', + 'min_pas_var_distance', + ], + metadata.columns, + ) + # Check there is only metadata for the 2 genes with >1 PAS in the interval. + self.assertLen(metadata, 2) + + chex.assert_shape(masks.gene_mask, (polyadenylation.MAX_GENES,)) + self.assertEqual(masks.gene_mask.sum(), 2) + + chex.assert_shape( + masks.pas_mask, + (interval.width, polyadenylation.MAX_GENES, polyadenylation.MAX_PAS), + ) + + @parameterized.product(transfer_guard=['disallow', 'allow']) + def test_pas_variant_scorer_score_variant(self, transfer_guard: str): + # Use mask for seq len 15, 5 genes, MAX_PAS sites with PAS mask width == 1 + # so aggregated across sequence length == actual value at that point in the + # track. + interval = genome.Interval('chr1', 1000, 1015) + variant = genome.Variant('chr1', 1005, 'C', 'T', name='var_0') + gene_pas_mask = np.zeros( + (interval.width, 6, polyadenylation.MAX_PAS), dtype=bool + ) + # G1 has one PAS sites + gene_pas_mask[0, 0, 0] = True + # G2 has 2 PAS sites + for i in range(1, 3): + gene_pas_mask[i, 1, i] = True + # G3 has 3 PAS sites + for i in range(3, 6): + gene_pas_mask[i, 2, i] = True + # G4 has 4 PAS sites + for i in range(6, 10): + gene_pas_mask[i, 3, i] = True + # G5 has 4 PAS + for i in range(10, 14): + gene_pas_mask[i, 4, i] = True + + # Set up tracks such that MAX COVR RATIO is equal for all tracks + # Score should be zero because only 1 PAS site + g1_values = jnp.array([10], jnp.float32).repeat(100).reshape(1, 100) + # Score should be 0.5, only one coverage ratio fc to take the max over + # because only 2 pas sites to make proximal-distal split + g2_values = jnp.array([2, 4], jnp.float32).repeat(100).reshape(2, 100) + # Score should be 5, argmax k = 2 + g3_values = jnp.array([2, 48, 5], jnp.float32).repeat(100).reshape(3, 100) + # Score should be 2, argmax k = 3 + g4_values = ( + jnp.array([0, 5, 55, 10], jnp.float32).repeat(100).reshape(4, 100) + ) + # Score should be 10, argmax k = 2 + g5_values = ( + jnp.array([10, 90, 5, 5, 0], jnp.float32).repeat(100).reshape(5, 100) + ) + + # Max ratio coverage uses alt_agg/ref_agg, so set alt tracks to the + # covr_ratios needed for test case answers and ref tracks to ones. + alt = jnp.concatenate( + [g1_values, g2_values, g3_values, g4_values, g5_values], + axis=0, + ) + ref = jnp.ones_like(alt) + masks = polyadenylation.PolyadenylationVariantMasks( + pas_mask=gene_pas_mask, + gene_mask=np.array([True] * 5 + [False]), + ) + _, _, gtf, pas_gtf = _load_pas_scoring_inputs() + variant_scorer = polyadenylation.PolyadenylationVariantScorer( + gtf=gtf, pas_gtf=pas_gtf + ) + with jax.transfer_guard(transfer_guard): + scores = variant_scorer.score_variant( + {dna_output.OutputType.RNA_SEQ: ref}, + {dna_output.OutputType.RNA_SEQ: alt}, + masks=jax.device_put(masks), + settings=variant_scorers.PolyadenylationScorer(), + interval=interval, + variant=variant, + ) + np.testing.assert_array_equal( + scores['scores'][0, :], jnp.zeros(100, dtype=jnp.float32) + ) + np.testing.assert_array_equal( + scores['scores'][1, :], + jnp.abs(jnp.log2(np.ones(100, dtype=jnp.float32) * 0.5)), + ) + np.testing.assert_array_equal( + scores['scores'][2, :], + jnp.abs(jnp.log2(np.ones(100, dtype=jnp.float32) * (4 / 53))), + ) + np.testing.assert_array_equal( + scores['scores'][3, :], + jnp.abs(jnp.log2(np.ones(100, dtype=jnp.float32) * (5 / 65))), + ) + np.testing.assert_array_equal( + scores['scores'][4, :], + jnp.abs(jnp.log2(np.ones(100, dtype=jnp.float32) * 10)), + ) + + def test_finalize_variant(self): + variant, interval, gtf, pas_gtf = _load_pas_scoring_inputs() + settings = variant_scorers.PolyadenylationScorer() + variant_scorer = polyadenylation.PolyadenylationVariantScorer( + gtf=gtf, pas_gtf=pas_gtf + ) + track_metadata = pd.DataFrame( + {'name': np.arange(10).astype(str), 'Strand': '.', 'padding': False} + ) + # Scenario of 3 genes in the interval (max possible=4) and 10 output tracks. + expected_scores = np.ones((4, 10), dtype=jnp.float32) + scores = { + 'scores': expected_scores, + 'gene_mask': np.array([True, False, True, False]), + } + + _, mask_metadata = variant_scorer.get_masks_and_metadata( + interval, + variant, + settings=settings, + track_metadata=dna_output.OutputMetadata(), + ) + finalized_variant = variant_scorer.finalize_variant( + scores, + settings=settings, + track_metadata=dna_output.OutputMetadata(rna_seq=track_metadata), + mask_metadata=mask_metadata, + ) + + self.assertIsInstance(finalized_variant, anndata.AnnData) + self.assertTrue(finalized_variant.X.flags['C_CONTIGUOUS']) + + self.assertLen(finalized_variant.var, expected_scores.shape[-1]) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/splice_junction_test.py b/flax_model/alphagenome/model/variant_scoring/splice_junction_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7aaf103d09c95f0234f52817245878557e72d7f1 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/splice_junction_test.py @@ -0,0 +1,248 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from absl.testing import absltest +from absl.testing import parameterized +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import variant_scorers +from flax_model.alphagenome.model.variant_scoring import splice_junction +import anndata +import chex +import jax +import jax.numpy as jnp +import numpy as np +import pandas as pd + + +def _create_fake_gtf(): + # Two genes (G1, G2). + # G1 has 3 transcripts (T1, T2, T3). G2 has 1 transcript (T4). The T4 + # transcript is further annotated as consisting of 2 exons. + gtf = pd.DataFrame({ + 'End': [200, 200, 200, 200, 108, 108, 40, 108], + 'Start': [101, 101, 102, 103, 0, 0, 0, 80], + 'Strand': ['+', '+', '+', '+', '-', '-', '-', '-'], + 'transcript_id': ['', 'T1', 'T2', 'T3', '', 'T4', 'T4', 'T4'], + 'transcript_type': [ + '', + 'protein_coding', + 'protein_coding', + 'protein_coding', + '', + 'protein_coding', + 'protein_coding', + 'protein_coding', + ], + 'gene_id': ['G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2'], + 'gene_name': [ + 'gene_1_name', + 'gene_2_name', + 'gene_1_name', + 'gene_1_name', + 'gene_2_name', + 'gene_2_name', + 'gene_2_name', + 'gene_2_name', + ], + 'Feature': [ + 'gene', + 'transcript', + 'transcript', + 'transcript', + 'gene', + 'transcript', + 'exon', + 'exon', + ], + }) + gtf['Chromosome'] = 'chr1' + gtf['Score'] = '.' + gtf['Frame'] = '.' + gtf['Source'] = 'ENSEMBL' + gtf['gene_type'] = 'protein_coding' + return gtf + + +def _junction_track_metadata() -> pd.DataFrame: + return pd.DataFrame({ + 'name': [ + 'Brain_Cerebellum', + 'Adipose_Subcutaneous', + 'UBERON:0036149', + ], + 'other': ['foo', 'foo', 'foo'], + 'gtex_tissue': [ + 'Brain_Cerebellum', + 'Adipose_Subcutaneous', + '', + ], + }) + + +class SpliceJunctionVariantScorerTest(parameterized.TestCase): + + def test_masks_and_metadata( + self, + ): + settings = variant_scorers.SpliceJunctionScorer() + interval = genome.Interval('chr1', 0, 2048) + variant = genome.Variant('chr1', 105, 'C', 'T', name='var_0') + scorer = splice_junction.SpliceJunctionVariantScorer(_create_fake_gtf()) + ( + masks, + metadata, + ) = scorer.get_masks_and_metadata( + interval, + variant, + settings=settings, + track_metadata=dna_output.OutputMetadata(), + ) + self.assertIsNone(masks) + self.assertIsInstance(metadata, pd.DataFrame) + self.assertContainsSubset( + ['gene_id', 'strand', 'Chromosome', 'Start', 'End', 'interval'], + metadata.columns, + ) + # We expect to retrieve metadata for 2 genes overlapping the variant. + self.assertSequenceEqual(list(metadata.gene_id), ['G1', 'G2']) + + @parameterized.product(transfer_guard=['disallow', 'allow']) + def test_score_variant(self, transfer_guard: str): + scorer = splice_junction.SpliceJunctionVariantScorer(_create_fake_gtf()) + + interval = genome.Interval('chr1', 0, 2048) + variant = genome.Variant('chr1', 105, 'C', 'T') + + max_splice_sites = splice_junction.MAX_SPLICE_SITES + num_splice_sites = max_splice_sites + 1 + num_tracks = 5 + splice_site_positions = ( + jnp.arange(num_splice_sites * 4, dtype=jnp.int32).reshape( + (4, num_splice_sites) + ) + + 1 + ) + reference_predictions = jnp.arange( + num_splice_sites * num_splice_sites * num_tracks, dtype=np.float32 + ).reshape((num_splice_sites, num_splice_sites, num_tracks)) + alternative_predictions = jnp.zeros_like(reference_predictions) + with jax.transfer_guard(transfer_guard): + scores = scorer.score_variant( + ref={ + dna_output.OutputType.SPLICE_JUNCTIONS: { + 'predictions': reference_predictions, + 'splice_site_positions': splice_site_positions, + } + }, + alt={ + dna_output.OutputType.SPLICE_JUNCTIONS: { + 'predictions': alternative_predictions, + 'splice_site_positions': splice_site_positions, + } + }, + masks=None, + settings=variant_scorers.SpliceJunctionScorer(), + interval=interval, + variant=variant, + ) + + np.testing.assert_array_equal( + scores['splice_site_positions'], + splice_site_positions[:, :max_splice_sites], + ) + chex.assert_shape( + scores['delta_counts'], (max_splice_sites, max_splice_sites, num_tracks) + ) + + @parameterized.product(return_empty_anndata=[True, False]) + def test_finalize_variant(self, return_empty_anndata: bool): + settings = variant_scorers.SpliceJunctionScorer() + chromosome = 'chr2' if return_empty_anndata else 'chr1' + interval = genome.Interval(chromosome, 0, 2048) + variant = genome.Variant(chromosome, 10, 'C', 'T', name='var_0') + gtf = _create_fake_gtf() + # Create mock track metadata. + track_metadata = _junction_track_metadata() + scorer = splice_junction.SpliceJunctionVariantScorer(gtf) + _, mask_metadata = scorer.get_masks_and_metadata( + interval, + variant, + track_metadata=dna_output.OutputMetadata( + splice_junctions=track_metadata + ), + settings=settings, + ) + if return_empty_anndata: + self.assertEmpty(mask_metadata) + else: + self.assertLen(mask_metadata, 1) # Only 1 gene overlapping the variant. + + # Create mock predictions. + num_tracks = len(track_metadata) * 2 # 2 strands per track. + max_splice_sites = 5 + predictions = ( + np.arange(max_splice_sites * max_splice_sites * num_tracks) + .reshape((max_splice_sites, max_splice_sites, num_tracks)) + .astype(np.float32) + ) + splice_site_positions = ( + np.arange(4 * max_splice_sites, dtype=np.int32).reshape( + (4, max_splice_sites) + ) + ) + 1 + # Make sure donor are upstream of acceptor. + splice_site_positions[1] = splice_site_positions[1] + 1 + splice_site_positions[2] = splice_site_positions[2] + 20 + splice_site_positions[3] = splice_site_positions[3] + 10 + scores = { + 'delta_counts': predictions, + 'splice_site_positions': splice_site_positions, + } + results = scorer.finalize_variant( + scores, + track_metadata=dna_output.OutputMetadata( + splice_junctions=track_metadata + ), + mask_metadata=mask_metadata, + settings=settings, + ) + + self.assertIsInstance(results, anndata.AnnData) + for column in [ + 'junction_Start', + 'junction_End', + 'gene_id', + 'strand', + 'Chromosome', + ]: + self.assertIn(column, results.obs.columns) + + names = { + 'Brain_Cerebellum', + 'Adipose_Subcutaneous', + 'UBERON:0036149', + } + self.assertEqual(set(results.var['name'].tolist()), names) + + if return_empty_anndata: + self.assertEqual(results.shape, (0, 3)) + else: + # We have 1 gene x 3 tissues, and the two junctions have the same + # junction that has the maximum score. + self.assertEqual(results.shape, (1, 3)) + + +if __name__ == '__main__': + absltest.main() diff --git a/flax_model/alphagenome/model/variant_scoring/variant_scoring.py b/flax_model/alphagenome/model/variant_scoring/variant_scoring.py new file mode 100644 index 0000000000000000000000000000000000000000..444703a1c7ac4f5da030fa70e140048f8c1c2894 --- /dev/null +++ b/flax_model/alphagenome/model/variant_scoring/variant_scoring.py @@ -0,0 +1,259 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Base class for variant scorers.""" + +import abc +from collections.abc import Mapping +import functools +from typing import Generic, TypeVar + +from flax_model.alphagenome._sdk import typing +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_output +import anndata +import jax +import jax.numpy as jnp +from jaxtyping import Array, Float32, Int32, PyTree # pylint: disable=g-multiple-import, g-importing-member +import numpy as np +import pandas as pd + + +VariantMaskT = TypeVar('VariantMaskT') +VariantMetadataT = TypeVar('VariantMetadataT') +VariantSettingsT = TypeVar('VariantSettingsT') + +ScoreVariantOutput = Mapping[str, jax.Array | np.ndarray] +ScoreVariantResult = Mapping[str, np.ndarray] + +ScoreVariantInput = Mapping[ + dna_output.OutputType, PyTree[Float32[Array, '...'] | Int32[Array, '...']] +] + + +@typing.jaxtyped +def create_anndata( + scores: Float32[np.ndarray, 'G T'], + *, + obs: pd.DataFrame | None, + var: pd.DataFrame, +) -> anndata.AnnData: + """Helper function for creating AnnData objects.""" + var = var.copy() + # We explicitly cast the dataframe indices to str to avoid + # ImplicitModificationWarning being logged over and over again. + var.index = var.index.map(str) + + if obs is not None: + obs = obs.copy() + obs.index = obs.index.map(str).astype(str) + return anndata.AnnData(np.ascontiguousarray(scores), obs=obs, var=var) + + +def get_resolution(output_type: dna_output.OutputType): + match output_type: + case dna_output.OutputType.ATAC: + return 1 + case dna_output.OutputType.CAGE: + return 1 + case dna_output.OutputType.DNASE: + return 1 + case dna_output.OutputType.RNA_SEQ: + return 1 + case dna_output.OutputType.CHIP_HISTONE: + return 128 + case dna_output.OutputType.CHIP_TF: + return 128 + case dna_output.OutputType.SPLICE_SITES: + return 1 + case dna_output.OutputType.SPLICE_SITE_USAGE: + return 1 + case dna_output.OutputType.SPLICE_JUNCTIONS: + return 1 + case dna_output.OutputType.CONTACT_MAPS: + return 2048 + case dna_output.OutputType.PROCAP: + return 1 + case _: + raise ValueError(f'Unknown output type: {output_type}.') + + +class VariantScorer( + Generic[VariantMaskT, VariantMetadataT, VariantSettingsT], + metaclass=abc.ABCMeta, +): + """Abstract class for variant scorers.""" + + @abc.abstractmethod + def get_masks_and_metadata( + self, + interval: genome.Interval, + variant: genome.Variant, + *, + settings: VariantSettingsT, + track_metadata: dna_output.OutputMetadata, + ) -> tuple[VariantMaskT, VariantMetadataT]: + """Returns masks and metadata for the given interval, variant and metadata. + + The generated masks and metadata will be passed to `score_variant` and + `finalize_variant` respectively. + + Args: + interval: The interval to score. + variant: The variant to extract the masks/metadata for. + settings: The variant scorer settings. + track_metadata: The track metadata required to finalize the variant. These + will be passed into the `finalize_variants` function. + + Returns: + A tuple of (masks, metadata), where: + masks: The masks required to score the variant, such as gene or TSS or + strand masks. These will be passed into the jitted `score_variants` + function. + metadata: The metadata required to finalize the variant. These will + be passed into the `finalize_variants` function. + + The formats/shapes of masks and metadata will vary across variant scorers + depending on their individual needs. + """ + + @abc.abstractmethod + def score_variant( + self, + ref: ScoreVariantInput, + alt: ScoreVariantInput, + *, + masks: VariantMaskT, + settings: VariantSettingsT, + variant: genome.Variant | None = None, + interval: genome.Interval | None = None, + ) -> ScoreVariantOutput: + """Generates a score per track for the provided ref/alt predictions. + + Args: + ref: Reference predictions. + alt: Alternative predictions. + masks: The masks for scoring the variant. + settings: The variant scorer settings. + variant: The variant to score. + interval: The interval to score. + + Returns: + Dictionary of scores to be passed to `finalize_variant`. + """ + + @abc.abstractmethod + def finalize_variant( + self, + scores: ScoreVariantResult, + *, + track_metadata: dna_output.OutputMetadata, + mask_metadata: VariantMetadataT, + settings: VariantSettingsT, + ) -> anndata.AnnData: + """Returns finalized scores for the given scores and metadata. + + Args: + scores: Dictionary of scores generated from `score_variant` function. + track_metadata: Metadata describing the tracks for each output_type. + mask_metadata: Metadata describing the masks. + settings: The variant scorer settings. + + Returns: + A VariantOutputType object containing the final variant outputs. The + entries will vary across scorers depending on their individual needs. + """ + + +@typing.jaxtyped +def align_alternate( + alt: Float32[Array | np.ndarray, 'S T'], + variant: genome.Variant, + interval: genome.Interval, +) -> Float32[Array, 'S T']: + """Aligns ALT predictions to match the REF allele's sequence length. + + This function adjusts the `alt` prediction array to account for indels + (insertions or deletions) present in the `variant`. + + For insertions, the function summarizes the inserted region by taking the + maximum value across the alternate bases and pads the end with zeros to + maintain the original sequence length. + + For deletions, zero signal is inserted at the locations corresponding to the + deleted bases in the reference. + + Args: + alt: The ALT allele predictions, shape [sequence_length, num_tracks]. + variant: The variant containing the indel information. + interval: The genomic interval. + + Returns: + The aligned ALT predictions, shape [sequence_length, num_tracks]. + """ + + insertion_length = len(variant.alternate_bases) - len(variant.reference_bases) + deletion_length = -insertion_length + variant_start_in_vector = variant.start - interval.start + # We assume that variants are left-aligned, and that insertions/deletions + # for multi-change variants occur at the end of the variant. + # We only need to align that insertion/deletion portion. + variant_start_in_vector += ( + min(len(variant.reference_bases), len(variant.alternate_bases)) - 1 + ) + original_length = alt.shape[0] + + # Summarize potential insertions by computing the maximum score across + # alternate bases. + + @functools.partial(jax.jit, static_argnames=['insertion_length']) + def _apply(alt, insertion_length: int): + if insertion_length > 0: + pool_alt_past_ref = jnp.max( + alt[ + variant_start_in_vector : variant_start_in_vector + + insertion_length + + 1 + ], + axis=0, + keepdims=True, + ) + alt = jnp.concatenate( + [ + alt[:variant_start_in_vector], + pool_alt_past_ref, + alt[(variant_start_in_vector + insertion_length + 1) :], + jnp.zeros((insertion_length, alt.shape[1])), + ], + axis=0, + ) + # Truncate to the original sequence length in case the alt insertion + # spills over the original sequence length. This happens only for + # insertions longer than half the interval. + alt = alt[:original_length] + elif deletion_length > 0: + # Handle potential deletions by inserting zero signal at deletion + # locations. + alt = jnp.concatenate( + [ + alt[: (variant_start_in_vector + 1)], + jnp.zeros((deletion_length, alt.shape[1])), + alt[(variant_start_in_vector + 1) :], + ], + axis=0, + ) + alt = alt[:original_length] + return alt + + return _apply(alt, insertion_length) diff --git a/flax_model/alphagenome/package_config.py b/flax_model/alphagenome/package_config.py new file mode 100644 index 0000000000000000000000000000000000000000..baeaadce647c3f4d2c5ef5dca2ee48b64e15d508 --- /dev/null +++ b/flax_model/alphagenome/package_config.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +""" +AlphaGenome package config. + +Expose runtime metadata files through the normal packaging pipeline so +install scripts do not need to copy files into site-packages manually. +""" + +ALPHAGENOME_PACKAGE_DATA = { + "flax_model.alphagenome.model.metadata": [ + "*.textproto", + ], +} + +ALPHAGENOME_MANIFEST_RULES = [ + "recursive-include flax_model/alphagenome/model/metadata *.textproto", +] + + +def get_package_data(): + return ALPHAGENOME_PACKAGE_DATA + + +def get_manifest_rules(): + return ALPHAGENOME_MANIFEST_RULES diff --git a/scripts/run_finetuning.py b/scripts/run_finetuning.py new file mode 100644 index 0000000000000000000000000000000000000000..ed06cc5532ba6664cb9fcceac7b58e75c2e56c70 --- /dev/null +++ b/scripts/run_finetuning.py @@ -0,0 +1,214 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome finetuning example script. + +This script demonstrates how to finetune the AlphaGenome model on custom genomic data, suitable for the following scenarios: + - ATAC-seq/ChIP-seq signal prediction for new cell types or tissues + - Adaptation to specific experimental data + - Transfer learning to new species + +Data requirements: + - Reference genome FASTA file + - BigWig signal track files pointed to by file_path in metadata + - Training regions CSV file (columns: chromosome, start, end) + +Usage: + python run_finetuning.py \ + --fasta_path /path/to/GRCh38.fa \ + --regions_csv /path/to/regions.csv \ + --output_dir ./finetuned_model \ + --num_steps 1000 \ + --batch_size 2 +""" + +import pathlib +import sys + +_PROJECT_ROOT = pathlib.Path(__file__).resolve().parents[1] +_SRC_DIR = _PROJECT_ROOT / "src" +if str(_SRC_DIR) not in sys.path: + sys.path.insert(0, str(_SRC_DIR)) + +from absl import app +from absl import flags +from absl import logging + +from alphagenome._sdk.data import fold_intervals +from alphagenome._sdk.models import dna_model as dna_model_types +import jax +import optax +import orbax.checkpoint as ocp + +from alphagenome.finetuning.finetune import ( + get_dataset_iterator, + get_forward_fn, + get_train_step, +) +from alphagenome.evals.track_prediction import load_model as load_model_from_kaggle +from alphagenome.model.metadata import metadata as metadata_lib + +FLAGS = flags.FLAGS + +flags.DEFINE_string( + 'fasta_path', + None, + 'Reference genome FASTA path.', + required=True, +) +flags.DEFINE_string( + 'regions_csv', + None, + 'Training regions CSV path with chromosome,start,end columns.', + required=True, +) +flags.DEFINE_list( + 'bigwig_paths', + None, + 'Deprecated compatibility flag. BigWig paths are read from metadata ' + 'file_path columns.', +) +flags.DEFINE_string( + 'model_dir', + None, + 'Pretrained checkpoint directory. If unset, Kaggle Hub is used.', +) +flags.DEFINE_string( + 'output_dir', + './finetuned_model', + 'Directory to save finetuned checkpoints.', +) +flags.DEFINE_integer('num_steps', 1000, 'Number of training steps.') +flags.DEFINE_integer('batch_size', 2, 'Training batch size.') +flags.DEFINE_float('learning_rate', 1e-5, 'Initial learning rate.') +flags.DEFINE_integer('log_every', 50, 'Log interval in steps.') +flags.DEFINE_integer('save_every', 200, 'Checkpoint interval in steps.') +flags.DEFINE_enum( + 'model_version', 'FOLD_0', + ['FOLD_0', 'FOLD_1', 'FOLD_2', 'FOLD_3', 'FOLD_4'], + 'Pretrained model version.', +) +flags.DEFINE_enum( + 'organism', 'HOMO_SAPIENS', + ['HOMO_SAPIENS', 'MUS_MUSCULUS'], + 'Target organism.', +) + + +def _resolve_local_model_dir(path: str) -> pathlib.Path: + model_dir = pathlib.Path(path).expanduser() + if not model_dir.is_dir(): + raise FileNotFoundError( + f'Pretrained checkpoint directory does not exist: {model_dir}' + ) + return model_dir + + +def _load_pretrained_state(model_version: dna_model_types.ModelVersion): + if FLAGS.model_dir: + checkpoint_path = _resolve_local_model_dir(FLAGS.model_dir) + logging.info('Loading pretrained model from local checkpoint: %s', + checkpoint_path) + return ocp.StandardCheckpointer().restore(str(checkpoint_path)) + + logging.info('Loading pretrained model from Kaggle Hub: %s', + model_version.name) + params, state, _ = load_model_from_kaggle(model_version) + return params, state + + +def main(_): + output_dir = pathlib.Path(FLAGS.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + model_version = dna_model_types.ModelVersion[FLAGS.model_version] + organism = dna_model_types.Organism[FLAGS.organism] + + logging.info('JAX devices: %s', jax.devices()) + logging.info('Finetuning config: lr=%.2e, steps=%d, batch_size=%d', + FLAGS.learning_rate, FLAGS.num_steps, FLAGS.batch_size) + + # Load pretrained model parameters, the training forward function reconstructs the loss from the finetuning module. + params, state = _load_pretrained_state(model_version) + + # Load output metadata. + output_metadata = metadata_lib.load(organism) + + # Build the optimizer, using warmup + cosine decay to balance stability and convergence. + schedule = optax.warmup_cosine_decay_schedule( + init_value=0.0, + peak_value=FLAGS.learning_rate, + warmup_steps=100, + decay_steps=FLAGS.num_steps, + ) + optimizer = optax.chain( + optax.clip_by_global_norm(1.0), + optax.adam(learning_rate=schedule), + ) + opt_state = optimizer.init(params) + + # Build finetuning training steps. + forward = get_forward_fn({organism: output_metadata}) + train_step = get_train_step( + predict_fn=forward.apply, + optimizer=optimizer, + ) + + # Build dataset iterator. + logging.info('Building finetuning dataset iterator...') + dataset_iter = get_dataset_iterator( + batch_size=FLAGS.batch_size, + sequence_length=1_048_576, + output_metadata=output_metadata, + model_version=model_version, + subset=fold_intervals.Subset.TRAIN, + organism=organism, + fasta_path=FLAGS.fasta_path, + example_regions_path=FLAGS.regions_csv, + ) + + # Configure checkpoint manager. + checkpointer = ocp.CheckpointManager( + output_dir / 'checkpoints', + options=ocp.CheckpointManagerOptions(max_to_keep=3), + ) + + # Training loop. + logging.info('Starting finetuning training...') + for step, batch in enumerate(dataset_iter): + if step >= FLAGS.num_steps: + break + + params, state, opt_state, metrics = train_step( + params, state, opt_state, batch + ) + + if step % FLAGS.log_every == 0: + loss = float(metrics.get('loss', float('nan'))) + logging.info('Step %d/%d | loss=%.4f', step, FLAGS.num_steps, loss) + + if step % FLAGS.save_every == 0 and step > 0: + checkpointer.save(step, args=ocp.args.StandardSave({'params': params, 'state': state})) + logging.info('Checkpoint saved (step=%d)', step) + + # Save final model. + checkpointer.save( + FLAGS.num_steps, + args=ocp.args.StandardSave({'params': params, 'state': state}), + ) + logging.info('Finetuning complete, final model saved to %s', output_dir / 'checkpoints') + + +if __name__ == '__main__': + app.run(main) \ No newline at end of file diff --git a/scripts/run_inference.py b/scripts/run_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..8470a19129f7a5f6a1765bc6ee2af0b469946ba7 --- /dev/null +++ b/scripts/run_inference.py @@ -0,0 +1,164 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""AlphaGenome inference example script. + +This script demonstrates how to use AlphaGenome for multimodal prediction on genomic intervals, including: + - Gene expression (RNA-seq, CAGE) + - Chromatin accessibility (ATAC-seq, DNase-seq) + - Transcription factor binding (ChIP-seq) + - Hi-C contact maps + - Splice sites + +Usage: + # Automatically download the model using Kaggle Hub (default mode) + python run_inference.py + + # Specify a local reference genome + python run_inference.py \ + --fasta_path /path/to/GRCh38.fa \ + --chromosome chr19 \ + --start 10587331 \ + --end 11635907 \ + --output_dir ./outputs +""" + +import pathlib +import sys + +_PROJECT_ROOT = pathlib.Path(__file__).resolve().parents[1] +_SRC_DIR = _PROJECT_ROOT / "src" +if str(_SRC_DIR) not in sys.path: + sys.path.insert(0, str(_SRC_DIR)) + +from absl import app +from absl import flags +from absl import logging + +from alphagenome._sdk.data import genome +from alphagenome.model import dna_model as dna_model_types +import numpy as np + +from alphagenome.model.dna_model import ( + create, + create_from_kaggle, + OrganismSettings, +) + +FLAGS = flags.FLAGS + +flags.DEFINE_string( + 'fasta_path', + None, + 'Reference genome FASTA path. A .fai index is required.', +) +flags.DEFINE_string( + 'model_dir', + None, + 'Local AlphaGenome checkpoint directory. If unset, Kaggle Hub is used.', +) +flags.DEFINE_string('chromosome', 'chr1', 'Chromosome name, for example chr1.') +flags.DEFINE_integer('start', 1_000_000, 'Interval start, 0-based.') +flags.DEFINE_integer('end', 2_048_576, 'Interval end, exclusive.') +flags.DEFINE_string('output_dir', './outputs', 'Output directory.') +flags.DEFINE_enum( + 'organism', 'HOMO_SAPIENS', + ['HOMO_SAPIENS', 'MUS_MUSCULUS'], + 'Target organism.', +) +flags.DEFINE_enum( + 'model_version', 'FOLD_0', + ['FOLD_0', 'FOLD_1', 'FOLD_2', 'FOLD_3', 'FOLD_4', 'all_folds'], + 'Model version, fold, or all_folds ensemble.', +) + + +def main(_): + output_dir = pathlib.Path(FLAGS.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + organism = dna_model_types.Organism[FLAGS.organism] + model_version = FLAGS.model_version + interval = genome.Interval( + chromosome=FLAGS.chromosome, + start=FLAGS.start, + end=FLAGS.end, + ) + + logging.info('Loading model weights...') + if FLAGS.model_dir: + organism_settings = None + if FLAGS.fasta_path: + organism_settings = { + organism: OrganismSettings( + fasta_path=FLAGS.fasta_path, + ), + } + alphagenome_model = create( + checkpoint_path=FLAGS.model_dir, + organism_settings=organism_settings, + ) + else: + alphagenome_model = create_from_kaggle(model_version) + + logging.info('Running inference: %s', interval) + if FLAGS.fasta_path or not FLAGS.model_dir: + predictions = alphagenome_model.predict_interval( + interval, + organism=organism, + requested_outputs={ + dna_model_types.OutputType.ATAC, + dna_model_types.OutputType.DNASE, + dna_model_types.OutputType.CAGE, + dna_model_types.OutputType.RNA_SEQ, + dna_model_types.OutputType.CHIP_TF, + dna_model_types.OutputType.CHIP_HISTONE, + }, + ontology_terms=None, + ) + else: + logging.warning( + 'No fasta_path was provided; using a random sequence for demo.' + ) + rng = np.random.default_rng(42) + bases = np.array(['A', 'C', 'G', 'T']) + seq_len = interval.end - interval.start + dna_sequence = ''.join(rng.choice(bases, size=seq_len)) + predictions = alphagenome_model.predict_sequence( + dna_sequence, + organism=organism, + requested_outputs={ + dna_model_types.OutputType.ATAC, + dna_model_types.OutputType.DNASE, + dna_model_types.OutputType.RNA_SEQ, + }, + ontology_terms=None, + interval=interval, + ) + + logging.info('Saving predictions to %s', output_dir) + for attr_name in ['atac', 'dnase', 'cage', 'rna_seq', 'chip_tf', + 'chip_histone', 'contact_maps', 'procap']: + output = getattr(predictions, attr_name, None) + if output is not None: + output_path = output_dir / f'{attr_name}.npy' + np.save(output_path, np.array(output.values)) + logging.info(' saved %s: shape=%s', attr_name, + np.array(output.values).shape) + + logging.info('Inference finished.') + + +if __name__ == '__main__': + app.run(main) \ No newline at end of file diff --git a/scripts/run_track.sh b/scripts/run_track.sh new file mode 100644 index 0000000000000000000000000000000000000000..50091a40c7f7ffc688591305a61a18939a2848ad --- /dev/null +++ b/scripts/run_track.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +if [[ -n "${ONESCIENCE_DATASETS_DIR:-}" ]]; then + DATA_ROOT_DIR="${ONESCIENCE_DATASETS_DIR}/AlphaGenome" +else + DATA_ROOT_DIR="${PROJECT_DIR}/data" +fi + +if [[ -n "${ONESCIENCE_MODELS_DIR:-}" ]]; then + MODEL_ROOT_DIR="${ONESCIENCE_MODELS_DIR}/AlphaGenome" +else + MODEL_ROOT_DIR="${PROJECT_DIR}/weight" +fi + +export PYTHONPATH="${PROJECT_DIR}:${PYTHONPATH:-}" + +mkdir -p "${PROJECT_DIR}/outputs_track" +python "${SCRIPT_DIR}/run_track_prediction_eval.py" \ + --model_dir "${MODEL_ROOT_DIR}/alphagenome-all-folds" \ + --model_version ALL_FOLDS \ + --data_dir "${DATA_ROOT_DIR}/v1/train" \ + --output_path "${PROJECT_DIR}/outputs_track/eval_results.csv" + diff --git a/scripts/run_track_prediction_eval.py b/scripts/run_track_prediction_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..a161247a263e3184fa6e0e2cedb580355af57b01 --- /dev/null +++ b/scripts/run_track_prediction_eval.py @@ -0,0 +1,337 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Runs AlphaGenome track prediction evaluation. + +By default this script refuses to download model weights. Pass --model_dir to +load a local Orbax checkpoint, or explicitly pass --allow_download=true to use +the original Kaggle Hub path. +""" + +import functools +import pathlib +import pprint +import sys + +_PROJECT_ROOT = pathlib.Path(__file__).resolve().parents[1] +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +from absl import app +from absl import flags +from absl import logging +from flax_model.alphagenome._sdk.data import fold_intervals +from flax_model.alphagenome._sdk.models import dna_output +from flax_model.alphagenome._sdk.models import dna_model as dna_model_types +from flax_model.alphagenome.evals.track_prediction import ( + load_model as load_model_from_kaggle, +) +from flax_model.alphagenome.evals import regression_metrics +from flax_model.alphagenome.io.bundles import BundleName +from flax_model.alphagenome.io.dataset import get_numpy_dataset_iterator +from flax_model.alphagenome.model import dna_model as research_dna_model +from flax_model.alphagenome.model.metadata import metadata as metadata_lib +import jax +import jax.numpy as jnp +from jax import sharding +from jax.experimental import mesh_utils +import orbax.checkpoint as ocp +import pandas as pd +import tensorflow as tf + + +FLAGS = flags.FLAGS +PS = sharding.PartitionSpec + +flags.DEFINE_string( + "model_version", + "FOLD_0", + "Evaluation fold/model version. Supported values are " + + ",".join(version.name for version in dna_model_types.ModelVersion) + + ".", +) +flags.DEFINE_enum( + "organism", + "HOMO_SAPIENS", + ["HOMO_SAPIENS", "MUS_MUSCULUS"], + "Organism to evaluate.", +) +flags.DEFINE_string( + "output_path", + "./track_prediction_results.csv", + "Output CSV path.", +) +flags.DEFINE_string( + "model_dir", + None, + "Local AlphaGenome Orbax checkpoint directory. When set, model weights are " + "loaded from this directory and no online model download is attempted.", +) +flags.DEFINE_bool( + "allow_download", + False, + "Allow Kaggle Hub model download only when --model_dir is not provided.", +) +flags.DEFINE_string( + "data_dir", + None, + "Optional AlphaGenome TFRecord root. If unset, the dataset loader uses its " + "built-in default path.", +) +flags.DEFINE_list( + "bundles", + None, + "Comma-separated bundle names. Defaults to all supported evaluation " + "bundles: ATAC,CAGE,CHIP_HISTONE,CHIP_TF,DNASE,PROCAP,RNA_SEQ.", +) + +_DEFAULT_EVAL_BUNDLES = [ + BundleName.ATAC, + BundleName.CAGE, + BundleName.CHIP_HISTONE, + BundleName.CHIP_TF, + BundleName.DNASE, + BundleName.PROCAP, + BundleName.RNA_SEQ, +] + + +def _parse_model_version(value: str) -> dna_model_types.ModelVersion: + normalized = value.replace("-", "_").upper() + if normalized.startswith("ALPHAGENOME_"): + normalized = normalized.removeprefix("ALPHAGENOME_") + try: + return dna_model_types.ModelVersion[normalized] + except KeyError as exc: + valid = ", ".join(version.name for version in dna_model_types.ModelVersion) + raise ValueError( + f"Unsupported --model_version={value!r}. Valid values: {valid}." + ) from exc + + +def _resolve_local_model_dir(path: str) -> pathlib.Path: + model_dir = pathlib.Path(path).expanduser() + if not model_dir.is_dir(): + raise FileNotFoundError( + f"Local AlphaGenome model directory does not exist: {model_dir}" + ) + if not (model_dir / "_CHECKPOINT_METADATA").exists(): + raise FileNotFoundError( + "The model directory does not look like an Orbax checkpoint. " + f"Missing: {model_dir / '_CHECKPOINT_METADATA'}" + ) + return model_dir + + +def load_model_from_local_checkpoint( + checkpoint_path: str, + organism: dna_model_types.Organism, +): + """Loads eval params/state/predict_fn like run_inference.py does.""" + checkpoint_path = _resolve_local_model_dir(checkpoint_path) + logging.info("Loading AlphaGenome model from local checkpoint: %s", checkpoint_path) + metadata = {organism: metadata_lib.load(organism)} + init_fn, apply_fn, _ = research_dna_model.create_model(metadata) + dna_sequence_shape = jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32) + organism_index_shape = jax.ShapeDtypeStruct((1,), dtype=jnp.int32) + target_shapes = jax.eval_shape( + init_fn, + jax.random.PRNGKey(0), + dna_sequence_shape, + organism_index_shape, + ) + params, state = ocp.StandardCheckpointer().restore( + str(checkpoint_path), + target=target_shapes, + strict=True, + ) + + @jax.jit + def predict(params, state, dna_sequence, organism_index): + predictions = apply_fn(params, state, dna_sequence, organism_index) + return research_dna_model.extract_predictions(predictions) + + return params, state, predict + + +def _load_model( + model_version: dna_model_types.ModelVersion, + organism: dna_model_types.Organism, +): + if FLAGS.model_dir: + return load_model_from_local_checkpoint(FLAGS.model_dir, organism) + if FLAGS.allow_download: + logging.warning( + "No --model_dir was provided; downloading model weights from " + "Kaggle Hub because --allow_download=true." + ) + return load_model_from_kaggle(model_version) + raise ValueError( + "No --model_dir was provided. Refusing to download model weights. " + "Pass --model_dir /path/to/alphagenome-all-folds, or explicitly pass " + "--allow_download=true to use Kaggle Hub." + ) + + +def _resolve_data_dir(path: str | None) -> str | None: + if not path: + return None + if path.startswith("gs://"): + return path + data_dir = pathlib.Path(path).expanduser() + if not data_dir.is_dir(): + raise FileNotFoundError( + f"Local AlphaGenome dataset directory does not exist: {data_dir}" + ) + return str(data_dir) + + +def _mesh_context(mesh): + if hasattr(jax, "set_mesh"): + return jax.set_mesh(mesh) + return mesh + + +def create_eval_step(predict_fn, bundles): + """Returns a JAX-version-compatible eval step.""" + + @jax.jit + def eval_step(params, state, batch): + predictions = predict_fn( + params, + state, + batch.dna_sequence, + batch.organism_index, + ) + metrics_step = {} + for bundle in bundles: + targets_true, mask = batch.get_genome_tracks(bundle) + targets_pred = predictions[dna_output.OutputType[bundle.name]] + targets_pred = regression_metrics.crop_sequence_length( + targets_pred, + target_length=targets_true.shape[-2], + ) + metrics_step[bundle.name] = regression_metrics.update_regression_metrics( + targets_true, + targets_pred, + mask, + ) + return metrics_step + + return eval_step + + +def evaluate(params, state, predict_fn, bundles, dataset_iterator): + """Evaluates the model without relying on the library's jit decorator style.""" + devices = mesh_utils.create_device_mesh((jax.local_device_count(),)) + mesh = jax.sharding.Mesh(devices, axis_names=("data",)) + sharding_rep = sharding.NamedSharding(mesh, PS()) + sharding_data = sharding.NamedSharding(mesh, PS("data")) + + params = jax.device_put(params, sharding_rep) + state = jax.device_put(state, sharding_rep) + + eval_step = create_eval_step(predict_fn, bundles) + metrics = { + bundle.name: regression_metrics.initialize_regression_metrics() + for bundle in bundles + } + num_elements = 0 + + for i, (batch, _) in enumerate(dataset_iterator): + num_elements += batch.dna_sequence.shape[0] + if i % 5 == 1: + finalized = pprint.pformat( + regression_metrics.finalize_regression_metrics(metrics) + ) + logging.info("step %d: %s", i, finalized) + + with _mesh_context(mesh): + batch = jax.device_put(batch, sharding_data) + step_metrics = eval_step(params, state, batch) + + step_metrics = jax.device_get(step_metrics) + metrics = regression_metrics.reduce_regression_metrics( + metrics, + step_metrics, + ) + + logging.info("num_elements: %d", num_elements) + return regression_metrics.finalize_regression_metrics(metrics) + + +def main(_): + # TensorFlow is only used for data loading; keep GPUs available to JAX. + tf.config.set_visible_devices([], "GPU") + + model_version = _parse_model_version(FLAGS.model_version) + organism = dna_model_types.Organism[FLAGS.organism] + data_dir = _resolve_data_dir(FLAGS.data_dir) + + logging.info("JAX devices: %s", jax.devices()) + logging.info( + "Evaluation config: model_version=%s, organism=%s, model_dir=%s, " + "data_dir=%s", + model_version.name, + FLAGS.organism, + FLAGS.model_dir or "", + data_dir or "", + ) + + if FLAGS.bundles: + eval_bundles = [BundleName[bundle.strip()] for bundle in FLAGS.bundles] + else: + eval_bundles = _DEFAULT_EVAL_BUNDLES + logging.info("Evaluation bundles: %s", [bundle.name for bundle in eval_bundles]) + + params, state, predict_fn = _load_model(model_version, organism) + + dataset_iterator = get_numpy_dataset_iterator( + batch_size=jax.local_device_count(), + organism=organism, + model_version=model_version, + subset=fold_intervals.Subset.VALID, + bundles=eval_bundles, + path=data_dir, + ) + + logging.info("Starting evaluation.") + results = evaluate( + params=params, + state=state, + predict_fn=predict_fn, + bundles=eval_bundles, + dataset_iterator=dataset_iterator, + ) + + rows = [] + for bundle_name, metrics in results.items(): + for metric_name, value in metrics.items(): + logging.info("%s / %s: %.4f", bundle_name, metric_name, value) + rows.append({ + "bundle": bundle_name, + "metric": metric_name, + "value": float(value), + "model_version": model_version.name, + "organism": FLAGS.organism, + }) + + output_path = pathlib.Path(FLAGS.output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + pd.DataFrame(rows).to_csv(output_path, index=False) + logging.info("Saved results to: %s", output_path) + + +if __name__ == "__main__": + app.run(main) diff --git a/scripts/run_variant.sh b/scripts/run_variant.sh new file mode 100644 index 0000000000000000000000000000000000000000..3b4d2a1841efa392287ea2fa3e25bce9dfcbaf4a --- /dev/null +++ b/scripts/run_variant.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PROJECT_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +if [[ -n "${ONESCIENCE_DATASETS_DIR:-}" ]]; then + DATA_ROOT_DIR="${ONESCIENCE_DATASETS_DIR}/AlphaGenome" +else + DATA_ROOT_DIR="${PROJECT_DIR}/data" +fi + +if [[ -n "${ONESCIENCE_MODELS_DIR:-}" ]]; then + MODEL_ROOT_DIR="${ONESCIENCE_MODELS_DIR}/AlphaGenome" +else + MODEL_ROOT_DIR="${PROJECT_DIR}/weight" +fi + +export PYTHONPATH="${PROJECT_DIR}:${PYTHONPATH:-}" + +python "${SCRIPT_DIR}/run_variant_scoring.py" \ + --fasta_path "${DATA_ROOT_DIR}/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa" \ + --model_dir "${MODEL_ROOT_DIR}/alphagenome-all-folds" \ + --output_dir "${PROJECT_DIR}/outputs_variant" diff --git a/scripts/run_variant_scoring.py b/scripts/run_variant_scoring.py new file mode 100644 index 0000000000000000000000000000000000000000..29d013a20f931f64dd7a16f0a99430128c3ec011 --- /dev/null +++ b/scripts/run_variant_scoring.py @@ -0,0 +1,254 @@ +# Copyright 2026 Google LLC. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Example script for AlphaGenome variant scoring. + +This version avoids failing when the model was created without annotation-backed +variant scorers such as GENE_MASK_LFC. It keeps the recommended scorers that +are actually available in the current model instance and skips the rest. +""" + +from collections.abc import Sequence +import pathlib +import sys + +_PROJECT_ROOT = pathlib.Path(__file__).resolve().parents[1] +if str(_PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(_PROJECT_ROOT)) + +from absl import app +from absl import flags +from absl import logging +from flax_model.alphagenome._sdk.data import genome +from flax_model.alphagenome._sdk.models import dna_model as dna_model_types +from flax_model.alphagenome._sdk.models import variant_scorers as variant_scorers_lib +import pandas as pd +from flax_model.alphagenome.model.dna_model import ( + OrganismSettings, + create, + create_from_kaggle, +) + +FLAGS = flags.FLAGS + +flags.DEFINE_string( + "vcf_path", + None, + "Path to a VCF file. If unset, built-in demo variants are used.", +) +flags.DEFINE_string( + "fasta_path", + None, + "Path to the reference genome FASTA file. Required when --model_dir is set.", +) +flags.DEFINE_string( + "model_dir", + None, + "Local AlphaGenome checkpoint directory. If unset, Kaggle Hub is used.", +) +flags.DEFINE_string("output_dir", "./outputs", "Directory for CSV outputs.") +flags.DEFINE_enum( + "organism", + "HOMO_SAPIENS", + ["HOMO_SAPIENS", "MUS_MUSCULUS"], + "Target organism.", +) +flags.DEFINE_enum( + "model_version", + "all_folds", + ["FOLD_0", "FOLD_1", "FOLD_2", "FOLD_3", "FOLD_4", "all_folds"], + "Model version to download from Kaggle.", +) + + +DEMO_VARIANTS = [ + ("chr22:36201698:A>C", "eQTL with SuSiE PIP > 0.9 in GTEx Colon"), + ("chr3:120280774:G>T", "caQTL in GM12878 (DNase)"), + ("chr21:46126238:G>C", "Splice junction variant in COL6A2"), +] + + +def load_demo_variants() -> list[tuple[genome.Variant, str]]: + """Builds the built-in demo variants.""" + return [ + (genome.Variant.from_str(variant_str), description) + for variant_str, description in DEMO_VARIANTS + ] + + +def load_variants_from_vcf(vcf_path: str) -> list[tuple[genome.Variant, str]]: + """Loads variants from a VCF file.""" + variants_df = pd.read_csv( + vcf_path, + sep="\t", + comment="#", + names=["CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO"], + ) + variants_with_desc = [] + for _, row in variants_df.iterrows(): + variant = genome.Variant( + chromosome=row["CHROM"], + position=int(row["POS"]), + reference_bases=row["REF"], + alternate_bases=str(row["ALT"]).split(",")[0], + ) + description = row["ID"] if pd.notna(row["ID"]) else "unknown" + variants_with_desc.append((variant, str(description))) + return variants_with_desc + + +def resolve_variant_scorers( + alphagenome_model, + organism: dna_model_types.Organism, +) -> tuple[ + Sequence[variant_scorers_lib.VariantScorerTypes], + list[str], +]: + """Returns the recommended scorers supported by the current model.""" + recommended_scorers = list( + variant_scorers_lib.get_recommended_scorers(organism.to_proto()) + ) + available_scorer_map = getattr(alphagenome_model, "_variant_scorers", {}).get( + organism, {} + ) + + if not available_scorer_map: + logging.warning( + "Unable to inspect model variant scorers. Falling back to the full " + "recommended scorer list." + ) + return recommended_scorers, [] + + available_base_scorers = set(available_scorer_map) + selected_scorers = [ + scorer + for scorer in recommended_scorers + if scorer.base_variant_scorer in available_base_scorers + ] + skipped_scorers = [ + scorer.base_variant_scorer.name + for scorer in recommended_scorers + if scorer.base_variant_scorer not in available_base_scorers + ] + + if not selected_scorers: + available_names = sorted( + base_scorer.name for base_scorer in available_base_scorers + ) + raise ValueError( + "No compatible recommended variant scorers are available for " + f"{organism.name}. Available scorers: {available_names}." + ) + + return selected_scorers, skipped_scorers + + +def load_alphagenome_model(organism: dna_model_types.Organism): + """Loads AlphaGenome from a local checkpoint when provided.""" + organism_settings = None + if FLAGS.fasta_path: + organism_settings = { + organism: OrganismSettings( + fasta_path=FLAGS.fasta_path, + ), + } + + if FLAGS.model_dir: + if not FLAGS.fasta_path: + raise ValueError("--fasta_path is required when using --model_dir.") + return create( + checkpoint_path=FLAGS.model_dir, + organism_settings=organism_settings, + ) + + return create_from_kaggle( + FLAGS.model_version, + organism_settings=organism_settings, + ) + + +def main(_): + output_dir = pathlib.Path(FLAGS.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + organism = dna_model_types.Organism[FLAGS.organism] + + logging.info("Loading AlphaGenome model...") + alphagenome_model = load_alphagenome_model(organism) + + variant_scorers, skipped_scorers = resolve_variant_scorers( + alphagenome_model, organism + ) + logging.info( + "Using variant scorers: %s", + ", ".join(scorer.base_variant_scorer.name for scorer in variant_scorers), + ) + if skipped_scorers: + logging.warning( + "Skipping unavailable recommended scorers: %s. This usually means the " + "model was loaded without the required annotation resources.", + ", ".join(skipped_scorers), + ) + + if FLAGS.vcf_path: + logging.info("Loading variants from VCF: %s", FLAGS.vcf_path) + variants_with_desc = load_variants_from_vcf(FLAGS.vcf_path) + else: + logging.info("Using built-in demo variants.") + variants_with_desc = load_demo_variants() + + logging.info("Scoring %d variants...", len(variants_with_desc)) + all_results = [] + + for variant, description in variants_with_desc: + logging.info("Processing variant: %s (%s)", variant, description) + + interval = variant.reference_interval.resize(2**20) + scores = alphagenome_model.score_variant( + interval=interval, + variant=variant, + variant_scorers=variant_scorers, + organism=organism, + ) + + all_results.append( + { + "variant": str(variant), + "description": description, + "num_score_tables": len(scores), + "used_variant_scorers": ",".join( + scorer.base_variant_scorer.name for scorer in variant_scorers + ), + "skipped_variant_scorers": ",".join(skipped_scorers), + } + ) + + for i, adata in enumerate(scores): + scorer_name = str(adata.uns.get("variant_scorer", f"scorer_{i}")) + scorer_label = scorer_name.replace(" ", "_").replace("/", "_") + save_path = output_dir / ( + f"variant_{variant.chromosome}_{variant.position}_{scorer_label}.csv" + ) + adata.to_df().to_csv(save_path) + logging.info( + "Saved score table %d: %s (shape=%s)", i, save_path.name, adata.shape + ) + + summary_path = output_dir / "variant_scoring_summary.csv" + pd.DataFrame(all_results).to_csv(summary_path, index=False) + logging.info("Saved summary to %s", summary_path) + + +if __name__ == "__main__": + app.run(main)