wuxing0105 commited on
Commit
871acc0
·
verified ·
1 Parent(s): 2e69359

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +31 -9
  2. LICENSE +203 -0
  3. README.md +248 -0
  4. flax_model/__init__.py +1 -0
  5. flax_model/alphagenome/__init__.py +39 -0
  6. flax_model/alphagenome/_sdk/__init__.py +25 -0
  7. flax_model/alphagenome/_sdk/data/__init__.py +15 -0
  8. flax_model/alphagenome/_sdk/data/genome.py +1181 -0
  9. flax_model/alphagenome/_sdk/models/interval_scorers.py +145 -0
  10. flax_model/alphagenome/_sdk/models/variant_scorers.py +878 -0
  11. flax_model/alphagenome/_sdk/typing.py +39 -0
  12. flax_model/alphagenome/_sdk/visualization/__init__.py +15 -0
  13. flax_model/alphagenome/evals/__init__.py +14 -0
  14. flax_model/alphagenome/evals/regression_metrics.py +204 -0
  15. flax_model/alphagenome/evals/track_prediction.py +202 -0
  16. flax_model/alphagenome/io/__init__.py +15 -0
  17. flax_model/alphagenome/io/bundles.py +91 -0
  18. flax_model/alphagenome/io/dataset.py +255 -0
  19. flax_model/alphagenome/io/dataset_test.py +254 -0
  20. flax_model/alphagenome/io/fasta.py +75 -0
  21. flax_model/alphagenome/io/fasta_test.py +55 -0
  22. flax_model/alphagenome/io/genome.py +139 -0
  23. flax_model/alphagenome/io/genome_test.py +239 -0
  24. flax_model/alphagenome/io/splicing.py +153 -0
  25. flax_model/alphagenome/io/splicing_test.py +115 -0
  26. flax_model/alphagenome/io/testdata/example.fa +4 -0
  27. flax_model/alphagenome/io/testdata/example.fa.fai +2 -0
  28. flax_model/alphagenome/model/__init__.py +15 -0
  29. flax_model/alphagenome/model/attention.py +283 -0
  30. flax_model/alphagenome/model/attention_test.py +78 -0
  31. flax_model/alphagenome/model/augmentation.py +122 -0
  32. flax_model/alphagenome/model/augmentation_test.py +232 -0
  33. flax_model/alphagenome/model/convolutions.py +152 -0
  34. flax_model/alphagenome/model/convolutions_test.py +137 -0
  35. flax_model/alphagenome/model/dna_model.py +1326 -0
  36. flax_model/alphagenome/model/dna_model_test.py +872 -0
  37. flax_model/alphagenome/model/embeddings.py +102 -0
  38. flax_model/alphagenome/model/heads.py +1055 -0
  39. flax_model/alphagenome/model/heads_test.py +677 -0
  40. flax_model/alphagenome/model/interval_scoring/__init__.py +15 -0
  41. flax_model/alphagenome/model/interval_scoring/gene_mask.py +142 -0
  42. flax_model/alphagenome/model/interval_scoring/gene_mask_test.py +266 -0
  43. flax_model/alphagenome/model/interval_scoring/interval_scoring.py +113 -0
  44. flax_model/alphagenome/model/layers.py +123 -0
  45. flax_model/alphagenome/model/layers_test.py +71 -0
  46. flax_model/alphagenome/model/losses.py +184 -0
  47. flax_model/alphagenome/model/losses_test.py +81 -0
  48. flax_model/alphagenome/model/metadata/__init__.py +15 -0
  49. flax_model/alphagenome/model/metadata/metadata.py +159 -0
  50. flax_model/alphagenome/model/model.py +282 -0
.gitattributes CHANGED
@@ -1,35 +1,57 @@
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
 
4
  *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
  *.model filter=lfs diff=lfs merge=lfs -text
13
  *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
  *.onnx filter=lfs diff=lfs merge=lfs -text
17
  *.ot filter=lfs diff=lfs merge=lfs -text
18
  *.parquet filter=lfs diff=lfs merge=lfs -text
19
  *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
  *.pt filter=lfs diff=lfs merge=lfs -text
23
  *.pth filter=lfs diff=lfs merge=lfs -text
24
  *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
  *.xz filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
1
  *.7z filter=lfs diff=lfs merge=lfs -text
2
  *.arrow filter=lfs diff=lfs merge=lfs -text
3
  *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bin.* filter=lfs diff=lfs merge=lfs -text
5
  *.bz2 filter=lfs diff=lfs merge=lfs -text
 
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
9
  *.joblib filter=lfs diff=lfs merge=lfs -text
10
  *.lfs.* filter=lfs diff=lfs merge=lfs -text
 
11
  *.model filter=lfs diff=lfs merge=lfs -text
12
  *.msgpack filter=lfs diff=lfs merge=lfs -text
 
 
13
  *.onnx filter=lfs diff=lfs merge=lfs -text
14
  *.ot filter=lfs diff=lfs merge=lfs -text
15
  *.parquet filter=lfs diff=lfs merge=lfs -text
16
  *.pb filter=lfs diff=lfs merge=lfs -text
 
 
17
  *.pt filter=lfs diff=lfs merge=lfs -text
18
  *.pth filter=lfs diff=lfs merge=lfs -text
19
  *.rar filter=lfs diff=lfs merge=lfs -text
 
20
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
21
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
22
  *.tflite filter=lfs diff=lfs merge=lfs -text
23
  *.tgz filter=lfs diff=lfs merge=lfs -text
 
24
  *.xz filter=lfs diff=lfs merge=lfs -text
25
  *.zip filter=lfs diff=lfs merge=lfs -text
26
+ *.zstandard filter=lfs diff=lfs merge=lfs -text
27
+ *.tfevents* filter=lfs diff=lfs merge=lfs -text
28
+
29
+ *.ark* filter=lfs diff=lfs merge=lfs -text
30
+ **/*ckpt*data* filter=lfs diff=lfs merge=lfs -text
31
+ **/*ckpt*.meta filter=lfs diff=lfs merge=lfs -text
32
+ **/*ckpt*.index filter=lfs diff=lfs merge=lfs -text
33
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
34
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
35
+ *.gguf* filter=lfs diff=lfs merge=lfs -text
36
+ *.ggml filter=lfs diff=lfs merge=lfs -text
37
+ *.llamafile* filter=lfs diff=lfs merge=lfs -text
38
+ *.pt2 filter=lfs diff=lfs merge=lfs -text
39
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
40
+ *.npy filter=lfs diff=lfs merge=lfs -text
41
+ *.npz filter=lfs diff=lfs merge=lfs -text
42
+ *.pickle filter=lfs diff=lfs merge=lfs -text
43
+ *.pkl filter=lfs diff=lfs merge=lfs -text
44
+ *.tar filter=lfs diff=lfs merge=lfs -text
45
+ *.wasm filter=lfs diff=lfs merge=lfs -text
46
  *.zst filter=lfs diff=lfs merge=lfs -text
47
  *tfevents* filter=lfs diff=lfs merge=lfs -text
48
+
49
+ checkpoints/alphagenome-all-folds/ocdbt.process_0/d/48900811ab32b5ad3873d40e96d63846 filter=lfs diff=lfs merge=lfs -text
50
+
51
+ checkpoints/alphagenome-all-folds/ocdbt.process_0/d/bda173d4f00d3afcef0a043614df05a6 filter=lfs diff=lfs merge=lfs -text
52
+ checkpoints/alphagenome-all-folds/ocdbt.process_0/d/6b08a83c9d6a2ade925dbcdd91299ce2 filter=lfs diff=lfs merge=lfs -text
53
+
54
+ flax_model/alphagenome/model/metadata/OutputMetadataResponse_ORGANISM_HOMO_SAPIENS.textproto filter=lfs diff=lfs merge=lfs -text
55
+ weight/alphagenome-all-folds/ocdbt.process_0/d/48900811ab32b5ad3873d40e96d63846 filter=lfs diff=lfs merge=lfs -text
56
+ weight/alphagenome-all-folds/ocdbt.process_0/d/6b08a83c9d6a2ade925dbcdd91299ce2 filter=lfs diff=lfs merge=lfs -text
57
+ weight/alphagenome-all-folds/ocdbt.process_0/d/bda173d4f00d3afcef0a043614df05a6 filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2025 Onescience Authors. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2025 Onescience Authors.
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ tasks:
4
+ - genomic-sequence-modeling
5
+ frameworks:
6
+ - jax
7
+ language:
8
+ - en
9
+ - zh
10
+ tags:
11
+ - OneScience
12
+ - Life Sciences
13
+ - Genomics
14
+ - DNA Sequence Model
15
+ - Variant Effect Prediction
16
+ - AlphaGenome
17
+ datasets:
18
+ - OneScience-Sugon/alphagenome_dataset
19
+ ---
20
+
21
+ <p align="center">
22
+ <strong>
23
+ <span style="font-size: 30px;">AlphaGenome</span>
24
+ </strong>
25
+ </p>
26
+
27
+ # Model Introduction
28
+
29
+ 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.
30
+
31
+ Paper: Advancing regulatory variant effect prediction with AlphaGenome
32
+ https://www.nature.com/articles/s41586-025-10014-0
33
+
34
+ # Model Description
35
+
36
+ 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.
37
+
38
+ # Use Cases
39
+
40
+ | Scenario | Description |
41
+ | :---: | :--- |
42
+ | 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 |
43
+ | 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 |
44
+ | Track prediction evaluation | Uses validation data from the AlphaGenome dataset to compute regression evaluation metrics across different assay bundles |
45
+ | Fine-tuning experiments | Validates a fine-tuning workflow using custom reference genomes, interval CSVs, and BigWig signal files |
46
+ | 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 |
47
+
48
+
49
+
50
+ # Usage Guide
51
+
52
+ ## 1. OneCode Usage
53
+
54
+ Try one-click AI4S development in the OneCode online environment:
55
+
56
+ [Try one-click AI4S development](https://web-2069360198568017922-iaaj.ksai.scnet.cn:58043/home)
57
+
58
+ ## 2. Manual Installation and Usage
59
+
60
+ **Hardware Requirements**
61
+
62
+ - GPU or DCU is recommended.
63
+ - A CPU can be used for import checks and lightweight configuration tests; full training and inference will be slow.
64
+ - DCU users must install DTK in advance. DTK 25.04.2 or later is recommended, or a OneScience-recommended version matching the current cluster.
65
+
66
+
67
+
68
+
69
+
70
+ **Environment Check**
71
+
72
+ - NVIDIA GPU:
73
+
74
+ ```bash
75
+ nvidia-smi
76
+ ```
77
+
78
+ - Hygon DCU:
79
+
80
+ ```bash
81
+ hy-smi
82
+ ```
83
+
84
+ ### Download the Model Package
85
+
86
+ ```bash
87
+ hf download --model OneScience-Sugon/alphagenome --local-dir ./alphagenome
88
+ cd alphagenome
89
+ ```
90
+
91
+ ### Install the Runtime Environment
92
+
93
+ **DCU Environment**
94
+
95
+ ```bash
96
+ # Activate DTK and CONDA first
97
+ conda create -n onescience311 python=3.11 -y
98
+ conda activate onescience311
99
+ # uv installation supported
100
+ pip install onescience[bio-dcu] -i http://mirrors.onescience.ai:3141/pypi/simple/ --trusted-host mirrors.onescience.ai
101
+ ```
102
+
103
+ After installation, return to the model package directory:
104
+
105
+ ```bash
106
+ cd ./alphagenome
107
+ ```
108
+
109
+ ### Data for Inference, Evaluation, and Fine-Tuning
110
+
111
+ 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.
112
+
113
+ ```bash
114
+ hf download --dataset OneScience-Sugon/alphagenome_dataset --local-dir ./data
115
+ ```
116
+
117
+ ### Model Weights
118
+
119
+ The repository already includes `weight/alphagenome-all-folds`, and all scripts allow the model weights directory to be specified via `--model_dir`.
120
+
121
+ ### Preparing Weights
122
+
123
+ If using local weights, place the AlphaGenome Orbax checkpoint in the following directory:
124
+
125
+ ```text
126
+ weight/
127
+ alphagenome-all-folds/
128
+ _CHECKPOINT_METADATA
129
+ _METADATA
130
+ ...
131
+ ```
132
+
133
+ When running in a shared environment, you can also reuse centrally managed model and dataset directories via environment variables:
134
+
135
+ ```bash
136
+ export ONESCIENCE_MODELS_DIR=/path/to/onescience/models
137
+ export ONESCIENCE_DATASETS_DIR=/path/to/onescience/datasets
138
+ ```
139
+
140
+ Scripts look in the following locations first:
141
+
142
+ - `${ONESCIENCE_MODELS_DIR}/AlphaGenome/alphagenome-all-folds`
143
+ - `${ONESCIENCE_DATASETS_DIR}/AlphaGenome`
144
+
145
+ If the above environment variables are not set, the scripts fall back to the following paths under the current model package:
146
+
147
+ - `weight/alphagenome-all-folds`
148
+ - `data/`
149
+
150
+ ### Interval Inference
151
+
152
+ ```bash
153
+ bash scripts/inference.sh
154
+ ```
155
+
156
+ Equivalent Python command example:
157
+
158
+ ```bash
159
+ python scripts/run_inference.py \
160
+ --fasta_path ./data/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa \
161
+ --model_dir ./weight/alphagenome-all-folds \
162
+ --chromosome chr19 \
163
+ --start 10587331 \
164
+ --end 11635907 \
165
+ --output_dir ./outputs
166
+ ```
167
+
168
+ Inference results are saved to `outputs/`.
169
+
170
+ ### Variant Effect Scoring
171
+
172
+ ```bash
173
+ bash scripts/run_variant.sh
174
+ ```
175
+
176
+ To specify a VCF input:
177
+
178
+ ```bash
179
+ python scripts/run_variant_scoring.py \
180
+ --vcf_path ./data/example.vcf \
181
+ --fasta_path ./data/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa \
182
+ --model_dir ./weight/alphagenome-all-folds \
183
+ --output_dir ./outputs_variant
184
+ ```
185
+
186
+ Scoring results are saved as a CSV file.
187
+
188
+ ### Track Prediction Evaluation
189
+
190
+ ```bash
191
+ bash scripts/run_track.sh
192
+ ```
193
+
194
+ You can also explicitly specify data and output paths:
195
+
196
+ ```bash
197
+ python scripts/run_track_prediction_eval.py \
198
+ --model_dir ./weight/alphagenome-all-folds \
199
+ --model_version ALL_FOLDS \
200
+ --data_dir ./data/v1/train \
201
+ --output_path ./outputs_track/eval_results.csv
202
+ ```
203
+
204
+ ### Fine-Tuning Example
205
+
206
+ ```bash
207
+ python scripts/run_finetuning.py \
208
+ --fasta_path ./data/reference/HOMO_SAPIENS/GRCh38.p13.genome.fa \
209
+ --regions_csv ./data/finetune_regions.csv \
210
+ --bigwig_paths ./data/sample_atac.bw \
211
+ --output_dir ./finetuned_model \
212
+ --num_steps 1000 \
213
+ --batch_size 2
214
+ ```
215
+
216
+ # Data Format
217
+
218
+ 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:
219
+
220
+ ```text
221
+ data/
222
+ reference/
223
+ HOMO_SAPIENS/
224
+ GRCh38.p13.genome.fa
225
+ GRCh38.p13.genome.fa.fai
226
+ v1/
227
+ train/
228
+ ...
229
+ ```
230
+
231
+ In this structure:
232
+
233
+ - `reference/HOMO_SAPIENS/GRCh38.p13.genome.fa` is the human reference genome FASTA.
234
+ - `.fai` is the FASTA index file.
235
+ - `v1/train/` is the data directory used for track prediction evaluation.
236
+ - Custom fine-tuning also requires an interval CSV file with column names `chromosome,start,end`, as well as one or more BigWig signal files.
237
+
238
+ # OneScience Official Information
239
+
240
+ | Platform | OneScience Main Repository | Skills Repository |
241
+ | --- | --- | --- |
242
+ | Gitee | https://gitee.com/onescience-ai/onescience | https://gitee.com/onescience-ai/oneskills |
243
+ | GitHub | https://github.com/onescience-ai/OneScience | https://github.com/onescience-ai/oneskills |
244
+
245
+ # Citation & License
246
+
247
+ - This repository is adapted from the open-source AlphaGenome model to support DCUs. The source code is licensed under Apache License 2.0.
248
+ - For scientific use, please cite the original paper: [Advancing regulatory variant effect prediction with AlphaGenome](https://www.nature.com/articles/s41586-025-10014-0).
flax_model/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Local flax_models copied from OneScience for this standalone package."""
flax_model/alphagenome/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome - 统一DNA序列基因组模型,已集成至OneScience。
16
+
17
+ AlphaGenome 是 Google DeepMind 发布的统一DNA序列模型,能够分析最长100万碱基对的
18
+ DNA序列,以单碱基对分辨率预测基因表达、剪接模式、染色质特征和接触图谱。
19
+
20
+ 模块结构:
21
+ model/ - 核心模型组件 (AlphaGenome, SequenceEncoder, 各类Head)
22
+ io/ - 数据输入输出 (BundleName, Dataset, Fasta)
23
+ finetuning/ - 微调工具 (训练步骤、数据管道)
24
+ evals/ - 评估指标 (track预测、回归指标)
25
+ _sdk/ - AlphaGenome SDK (vendored alphagenome v0.6.1)
26
+ 包含数据类型、gRPC客户端、变异/区间评分、可视化和ISM解释工具
27
+
28
+ 使用方式:
29
+ from flax_model.alphagenome.model import model as alphagenome_model
30
+ from flax_model.alphagenome.io import dataset
31
+ from flax_model.alphagenome.finetuning import finetune
32
+
33
+ # SDK 数据类型 (原 from alphagenome.data import genome):
34
+ from flax_model.alphagenome._sdk.data import genome
35
+ from flax_model.alphagenome._sdk.models import dna_model
36
+ from flax_model.alphagenome._sdk.models import dna_output
37
+ """
38
+
39
+ __version__ = '0.1.0'
flax_model/alphagenome/_sdk/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome Python SDK (vendored into OneScience).
16
+
17
+ Original package: alphagenome v0.6.1
18
+ Provides data types, gRPC client, variant/interval scoring,
19
+ visualization, and ISM interpretation utilities for genomic models.
20
+
21
+ This is a vendored copy integrated into OneScience to avoid requiring
22
+ a separate alphagenome package installation.
23
+ """
24
+
25
+ __version__ = '0.6.1'
flax_model/alphagenome/_sdk/data/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Data classes for interacting and visualizing genomic models."""
flax_model/alphagenome/_sdk/data/genome.py ADDED
@@ -0,0 +1,1181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utilities for working with genome-related objects such as intervals."""
16
+
17
+ import collections
18
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
19
+ import copy
20
+ import dataclasses
21
+ import enum
22
+ import re
23
+ import sys
24
+ from typing import Any, Protocol
25
+
26
+ from flax_model.alphagenome._sdk.protos import dna_model_pb2
27
+ import numpy as np
28
+ from typing_extensions import Self
29
+
30
+ STRAND_POSITIVE = '+' # Also called forward strand, 5'->3' direction.
31
+ STRAND_NEGATIVE = '-' # Also called negative strand, 3'->5' direction.
32
+ STRAND_UNSTRANDED = '.'
33
+ STRAND_OPTIONS = (STRAND_POSITIVE, STRAND_NEGATIVE, STRAND_UNSTRANDED)
34
+ _INTERVAL_START_END_REGEX = re.compile(r'(-?\d+)-(-?\d+)')
35
+ VALID_VARIANT_BASES = frozenset('ACGTN')
36
+
37
+
38
+ class Strand(enum.IntEnum):
39
+ """Represents the strand of a DNA sequence.
40
+
41
+ This enum defines the possible strands for a DNA sequence:
42
+
43
+ * `POSITIVE`: The forward strand (5' to 3').
44
+ * `NEGATIVE`: The reverse strand (3' to 5').
45
+ * `UNSTRANDED`: The strand is not specified.
46
+ """
47
+
48
+ POSITIVE = enum.auto()
49
+ NEGATIVE = enum.auto()
50
+ UNSTRANDED = enum.auto()
51
+
52
+ def __str__(self):
53
+ match self:
54
+ case Strand.POSITIVE:
55
+ return STRAND_POSITIVE
56
+ case Strand.NEGATIVE:
57
+ return STRAND_NEGATIVE
58
+ case Strand.UNSTRANDED:
59
+ return STRAND_UNSTRANDED
60
+
61
+ @classmethod
62
+ def from_str(cls, strand: str) -> Self:
63
+ match strand:
64
+ case '+':
65
+ return cls.POSITIVE
66
+ case '-':
67
+ return cls.NEGATIVE
68
+ case '.':
69
+ return cls.UNSTRANDED
70
+ case _:
71
+ raise ValueError(f'Strand needs to be in {STRAND_OPTIONS}')
72
+
73
+ def to_proto(self) -> dna_model_pb2.Strand:
74
+ match self:
75
+ case Strand.POSITIVE:
76
+ return dna_model_pb2.Strand.STRAND_POSITIVE
77
+ case Strand.NEGATIVE:
78
+ return dna_model_pb2.Strand.STRAND_NEGATIVE
79
+ case Strand.UNSTRANDED:
80
+ return dna_model_pb2.Strand.STRAND_UNSTRANDED
81
+
82
+ @classmethod
83
+ def from_proto(cls, strand: dna_model_pb2.Strand) -> Self:
84
+ match strand:
85
+ case dna_model_pb2.Strand.STRAND_POSITIVE:
86
+ return cls.POSITIVE
87
+ case dna_model_pb2.Strand.STRAND_NEGATIVE:
88
+ return cls.NEGATIVE
89
+ case dna_model_pb2.Strand.STRAND_UNSTRANDED:
90
+ return cls.UNSTRANDED
91
+ case _:
92
+ raise ValueError(f'Strand needs to be in {STRAND_OPTIONS}')
93
+
94
+
95
+ PYRANGES_INTERVAL_COLUMNS = ('Chromosome', 'Start', 'End', 'Strand', 'Name')
96
+
97
+
98
+ @dataclasses.dataclass(order=True)
99
+ class Interval:
100
+ """Represents a genomic interval.
101
+
102
+ A genomic interval is a region on a chromosome defined by a start and end
103
+ position. This class provides methods for manipulating and comparing
104
+ intervals, and for calculating coverage and overlap.
105
+
106
+ Attributes:
107
+ chromosome: The chromosome name (e.g., 'chr1', '1').
108
+ start: The 0-based start position.
109
+ end: The 0-based end position (must be greater than or equal to start).
110
+ strand: The strand of the interval ('+', '-', or '.'). Defaults to '.'
111
+ (unstranded).
112
+ name: An optional name for the interval.
113
+ info: An optional dictionary to store additional information.
114
+ negative_strand: True if the interval is on the negative strand, False
115
+ otherwise.
116
+ width: The width of the interval (end - start).
117
+ """
118
+
119
+ chromosome: str
120
+ start: int
121
+ end: int
122
+ strand: str = STRAND_UNSTRANDED
123
+ name: str = dataclasses.field(default='', compare=False, hash=False)
124
+ info: dict[str, Any] = dataclasses.field(
125
+ default_factory=dict, repr=False, compare=False, hash=False
126
+ )
127
+
128
+ def __post_init__(self):
129
+ if self.end < self.start:
130
+ raise ValueError('end < start. Interval: ' + str(self))
131
+ if self.strand not in STRAND_OPTIONS:
132
+ raise ValueError(
133
+ f'Strand needs to be in {STRAND_OPTIONS}, found {self.strand}.'
134
+ )
135
+
136
+ @property
137
+ def negative_strand(self) -> bool:
138
+ """Returns True if interval is on the negative strand, False otherwise."""
139
+ return self.strand == STRAND_NEGATIVE
140
+
141
+ @property
142
+ def width(self) -> int:
143
+ """Returns the width of the interval."""
144
+ return self.end - self.start
145
+
146
+ def copy(self) -> Self:
147
+ """Returns a deep copy of the interval."""
148
+ return copy.deepcopy(self)
149
+
150
+ def __str__(self) -> str:
151
+ """Returns a string representation of the interval."""
152
+ return f'{self.chromosome}:{self.start}-{self.end}:{self.strand}'
153
+
154
+ @classmethod
155
+ def from_str(cls, string: str) -> Self:
156
+ """Creates an Interval from a string (e.g., 'chr1:100-200:+')."""
157
+ chromosome, interval, *strand = string.split(':', maxsplit=2)
158
+ if strand:
159
+ strand = strand[0]
160
+ else:
161
+ strand = STRAND_UNSTRANDED
162
+ # Get start and end from the interval string.
163
+ match = _INTERVAL_START_END_REGEX.fullmatch(interval)
164
+ if match:
165
+ start, end = int(match.group(1)), int(match.group(2))
166
+ else:
167
+ raise ValueError(f'Invalid interval: {string}')
168
+ return cls(
169
+ chromosome=chromosome, start=int(start), end=int(end), strand=strand
170
+ )
171
+
172
+ def to_proto(self) -> dna_model_pb2.Interval:
173
+ """Converts the interval to a protobuf message."""
174
+ return dna_model_pb2.Interval(
175
+ chromosome=self.chromosome,
176
+ start=self.start,
177
+ end=self.end,
178
+ strand=Strand.from_str(self.strand).to_proto(),
179
+ )
180
+
181
+ @classmethod
182
+ def from_proto(cls, proto: dna_model_pb2.Interval) -> Self:
183
+ """Creates an Interval from a protobuf message."""
184
+ return cls(
185
+ chromosome=proto.chromosome,
186
+ start=proto.start,
187
+ end=proto.end,
188
+ strand=str(Strand.from_proto(proto.strand)),
189
+ )
190
+
191
+ def to_interval_dict(self) -> dict[str, str | int]:
192
+ """Converts the interval to a dictionary."""
193
+ return dict(
194
+ chrom=self.chromosome,
195
+ start=self.start,
196
+ end=self.end,
197
+ strand=self.strand,
198
+ )
199
+
200
+ @classmethod
201
+ def from_interval_dict(cls, interval: Mapping[str, str | int]) -> Self:
202
+ """Creates an Interval from a dictionary."""
203
+ return cls(
204
+ chromosome=str(interval['chrom']),
205
+ start=int(interval['start']),
206
+ end=int(interval['end']),
207
+ strand=str(interval.get('strand', STRAND_UNSTRANDED)),
208
+ )
209
+
210
+ @classmethod
211
+ def from_pyranges_dict(
212
+ cls, row: Mapping[str, Any], ignore_info: bool = False
213
+ ) -> 'Interval':
214
+ """Creates an Interval from a pyranges-like dictionary.
215
+
216
+ This method constructs an `Interval` object from a dictionary that follows
217
+ the pyranges format, such as a row from a :class:`pandas.DataFrame`
218
+ converted to a dict.
219
+
220
+ The dictionary should have the following keys:
221
+
222
+ * 'Chromosome': The chromosome name.
223
+ * 'Start': The start position.
224
+ * 'End': The end position.
225
+ * 'Strand': The strand (optional, defaults to unstranded).
226
+ * 'Name': The interval name (optional).
227
+
228
+ Any other keys in the dictionary will be added to the `info` attribute of
229
+ the `Interval` object, unless `ignore_info` is set to True.
230
+
231
+ Args:
232
+ row: A dictionary containing interval data.
233
+ ignore_info: If True, any keys in the dictionary that are not part of the
234
+ standard pyranges columns ('Chromosome', 'Start', 'End', 'Strand',
235
+ 'Name') will not be added to the `info` attribute.
236
+
237
+ Returns:
238
+ An `Interval` object created from the input dictionary.
239
+ """
240
+ if ignore_info:
241
+ info = {}
242
+ else:
243
+ info = {
244
+ k: v for k, v in row.items() if k not in PYRANGES_INTERVAL_COLUMNS
245
+ }
246
+
247
+ return cls(
248
+ chromosome=str(row['Chromosome']),
249
+ start=int(row['Start']),
250
+ end=int(row['End']),
251
+ strand=str(row.get('Strand', STRAND_UNSTRANDED)),
252
+ name=str(row.get('Name', '')),
253
+ info=info,
254
+ )
255
+
256
+ def to_pyranges_dict(self) -> dict[str, int | str]:
257
+ """Converts the interval to a pyranges-like dictionary."""
258
+ return {
259
+ 'Chromosome': self.chromosome,
260
+ 'Start': self.start,
261
+ 'End': self.end,
262
+ 'Name': self.name,
263
+ 'Strand': self.strand,
264
+ **self.info,
265
+ }
266
+
267
+ def swap_strand(self) -> Self:
268
+ """Swaps the strand of the interval."""
269
+ obj = self.copy()
270
+ if obj.strand == STRAND_POSITIVE:
271
+ obj.strand = STRAND_NEGATIVE
272
+ elif obj.strand == STRAND_NEGATIVE:
273
+ obj.strand = STRAND_POSITIVE
274
+ elif obj.strand == STRAND_UNSTRANDED:
275
+ raise ValueError('Cannot swap unstranded intervals.')
276
+ return obj
277
+
278
+ def as_unstranded(self) -> Self:
279
+ """Returns an unstranded copy of the interval."""
280
+ obj = self.copy()
281
+ obj.strand = STRAND_UNSTRANDED
282
+ return obj
283
+
284
+ def within_reference(self, reference_length: int = sys.maxsize) -> bool:
285
+ """Checks if the interval is within the valid reference range."""
286
+ return self.start >= 0 and self.end <= reference_length
287
+
288
+ def truncate(self, reference_length: int = sys.maxsize) -> Self:
289
+ """Truncates the interval to fit within the valid reference range."""
290
+ obj = self.copy()
291
+ if reference_length <= 0:
292
+ raise ValueError('Reference length should be larger than 0.')
293
+ if self.within_reference(reference_length):
294
+ return obj
295
+ else:
296
+ obj.start = max(self.start, 0)
297
+ obj.end = min(self.end, reference_length)
298
+ return obj
299
+
300
+ def center(self, use_strand: bool = True) -> int:
301
+ """Computes the center of the interval.
302
+
303
+ For intervals with an odd width, the center is rounded up for
304
+ positive/unstranded intervals and rounded down for negative strand
305
+ intervals.
306
+
307
+ If `use_strand` is True and the interval is on the negative strand, the
308
+ center is calculated differently to maintain consistency when stacking
309
+ sequences from different intervals oriented in the forward strand direction.
310
+ This ensures that the relative distance between the interval's upstream
311
+ boundary and its center is preserved.
312
+
313
+ Args:
314
+ use_strand: If True, the strand of the interval is considered when
315
+ calculating the center.
316
+
317
+ Returns:
318
+ The integer representing the center position of the interval.
319
+
320
+ Examples:
321
+ >>> Interval('1', 1, 3, '+').center()
322
+ 2
323
+ >>> Interval('1', 1, 3, '-').center() # Strand doesn't matter.
324
+ 2
325
+ >>> Interval('1', 1, 4, '+').center()
326
+ 3
327
+ >>> Interval('1', 1, 4, '-').center()
328
+ 2
329
+ >>> Interval('1', 1, 4, '-').center()
330
+ 2
331
+ >>> Interval('1', 1, 4, '+').center(use_strand=False)
332
+ 3
333
+ >>> Interval('1', 1, 2, '-').center()
334
+ 1
335
+ """
336
+ center = (self.start + self.end) // 2
337
+ if use_strand and self.negative_strand:
338
+ return center
339
+ else:
340
+ return center + self.width % 2
341
+
342
+ def shift(self, offset: int, use_strand: bool = True) -> Self:
343
+ """Shifts the interval by the given offset.
344
+
345
+ Args:
346
+ offset: The amount to shift the interval.
347
+ use_strand: If True, the shift direction is reversed for negative strand
348
+ intervals.
349
+
350
+ Returns:
351
+ A new shifted interval.
352
+ """
353
+ obj = self.copy()
354
+ if use_strand and self.negative_strand:
355
+ offset = -offset
356
+ obj.start = self.start + offset
357
+ obj.end = self.end + offset
358
+ return obj
359
+
360
+ def boundary_shift(
361
+ self, start_offset: int = 0, end_offset: int = 0, use_strand: bool = True
362
+ ) -> Self:
363
+ """Extends or shrinks the interval by adjusting the positions with padding.
364
+
365
+ Args:
366
+ start_offset: The amount to shift the start position.
367
+ end_offset: The amount to shift the end position.
368
+ use_strand: If True, the offsets are applied in reverse for negative
369
+ strand intervals.
370
+
371
+ Returns:
372
+ A new interval with adjusted boundaries.
373
+ """
374
+ return self.pad(-start_offset, end_offset, use_strand=use_strand)
375
+
376
+ def pad(
377
+ self, start_pad: int, end_pad: int, *, use_strand: bool = True
378
+ ) -> Self:
379
+ """Pads the interval by adding the specified padding to the start and end.
380
+
381
+ Args:
382
+ start_pad: The amount of padding to add to the start.
383
+ end_pad: The amount of padding to add to the end.
384
+ use_strand: If True, padding is applied in reverse for negative strand
385
+ intervals.
386
+
387
+ Returns:
388
+ A new padded interval.
389
+ """
390
+ obj = self.copy()
391
+ obj.pad_inplace(start_pad, end_pad, use_strand=use_strand)
392
+ return obj
393
+
394
+ def pad_inplace(
395
+ self, start_pad: int, end_pad: int, *, use_strand: bool = True
396
+ ):
397
+ """Pads the interval in place by adding padding to the start and end.
398
+
399
+ Args:
400
+ start_pad: The amount of padding to add to the start.
401
+ end_pad: The amount of padding to add to the end.
402
+ use_strand: If True, padding is applied in reverse for negative strand
403
+ intervals.
404
+ """
405
+ if use_strand and self.strand == '-':
406
+ start_pad, end_pad = end_pad, start_pad
407
+ self.start -= start_pad
408
+ self.end += end_pad
409
+ if self.width < 0:
410
+ raise ValueError('Resulting interval has negative length')
411
+
412
+ def resize(self, width: int, use_strand: bool = True) -> Self:
413
+ """Resizes the interval to a new width, centered around the original center.
414
+
415
+ Args:
416
+ width: The new width of the interval.
417
+ use_strand: If True, resizing considers the strand orientation.
418
+
419
+ Returns:
420
+ A new resized interval.
421
+ """
422
+ obj = self.copy()
423
+ obj.resize_inplace(width, use_strand)
424
+ return obj
425
+
426
+ def resize_inplace(self, width: int, use_strand: bool = True) -> None:
427
+ """Resizes the interval in place, centered around the original center.
428
+
429
+ Args:
430
+ width: The new width of the interval.
431
+ use_strand: If True, resizing considers the strand orientation.
432
+ """
433
+ if width < 0:
434
+ raise ValueError(f'Width needs to be > 0. Found: {width}.')
435
+
436
+ if width is None or self.width == width:
437
+ return
438
+
439
+ center = self.center()
440
+ if use_strand and self.negative_strand:
441
+ self.start = center - width // 2
442
+ self.end = center + (width + 1) // 2
443
+ else:
444
+ self.start = center - (width + 1) // 2
445
+ self.end = center + width // 2
446
+ assert self.width == width
447
+
448
+ def overlaps(self, interval: Self) -> bool:
449
+ """Checks if this interval overlaps with another interval."""
450
+ return (
451
+ self.chromosome == interval.chromosome
452
+ and self.start < interval.end
453
+ and interval.start < self.end
454
+ )
455
+
456
+ def contains(self, interval: Self) -> bool:
457
+ """Checks if this interval completely contains another interval."""
458
+ return (
459
+ self.chromosome == interval.chromosome
460
+ and self.start <= interval.start
461
+ and self.end >= interval.end
462
+ )
463
+
464
+ def intersect(self, interval: Self) -> Self | None:
465
+ """Returns the intersection of this interval with another interval."""
466
+ output = self.copy()
467
+ if not self.overlaps(interval):
468
+ return None
469
+ output.start = max(self.start, interval.start)
470
+ output.end = min(self.end, interval.end)
471
+ return output
472
+
473
+ def coverage(
474
+ self, intervals: Sequence[Self], *, bin_size: int = 1
475
+ ) -> np.ndarray:
476
+ """Computes coverage track from sequence of intervals overlapping interval.
477
+
478
+ This method calculates the coverage of this interval by a set of other
479
+ intervals. The coverage is defined as the number of intervals that overlap
480
+ each position within this interval.
481
+
482
+ The `bin_size` parameter allows you to bin the coverage into equal-sized
483
+ windows. This can be useful for summarizing coverage over larger regions.
484
+ If `bin_size` is 1, the coverage is calculated at single-base resolution.
485
+
486
+ Args:
487
+ intervals: A sequence of `Interval` objects that may overlap this
488
+ interval.
489
+ bin_size: The size of the bins used to calculate coverage. Must be a
490
+ positive integer that divides the width of the interval.
491
+
492
+ Returns:
493
+ A 1D numpy array representing the coverage track. The length of the array
494
+ is `self.width // bin_size`. Each element in the array represents the
495
+ summed coverage within the corresponding bin.
496
+
497
+ Raises:
498
+ ValueError: If `bin_size` is not a positive integer or if the interval
499
+ width is not divisible by `bin_size`.
500
+ """
501
+ if bin_size <= 0:
502
+ raise ValueError('bin_size needs to be larger or equal to 1.')
503
+ if self.width % bin_size != 0:
504
+ raise ValueError(
505
+ f'interval width {self.width} needs to be divisible '
506
+ f'by bin_size {bin_size}.'
507
+ )
508
+ output = np.zeros((self.width,), dtype=np.int32)
509
+ for interval in intervals:
510
+ if not self.overlaps(interval):
511
+ continue
512
+ relative_start = max(interval.start - self.start, 0)
513
+ relative_end = min(interval.end - self.start, self.width)
514
+ output[relative_start:relative_end] += 1
515
+ if bin_size > 1:
516
+ return output.reshape((self.width // bin_size, bin_size)).sum(axis=-1)
517
+ else:
518
+ return output
519
+
520
+ def overlap_ranges(
521
+ self,
522
+ intervals: Sequence[Self],
523
+ ) -> np.ndarray:
524
+ """Returns overlapping ranges from intervals overlapping this interval.
525
+
526
+ Args:
527
+ intervals: Sequence of candidate intervals to test for overlap.
528
+
529
+ Returns:
530
+ 2D numpy array indicating the start and end of the overlapping ranges.
531
+ """
532
+ output = []
533
+ for interval in intervals:
534
+ if not self.overlaps(interval):
535
+ continue
536
+ relative_start = max(interval.start - self.start, 0)
537
+ relative_end = min(interval.end - self.start, self.width)
538
+ output.append([relative_start, relative_end])
539
+
540
+ return (
541
+ np.asarray(output, dtype=np.int32)
542
+ if output
543
+ else np.empty((0, 2), dtype=np.int32)
544
+ )
545
+
546
+ def binary_mask(
547
+ self, intervals: Sequence[Self], bin_size: int = 1
548
+ ) -> np.ndarray:
549
+ """Boolean mask True if any interval overlaps the bin: coverage > 0."""
550
+ return self.coverage(intervals, bin_size=bin_size) > 0
551
+
552
+ def coverage_stranded(
553
+ self, intervals: Sequence[Self], *, bin_size: int = 1
554
+ ) -> np.ndarray:
555
+ """Computes a coverage track from intervals overlapping this interval.
556
+
557
+ This method considers the strand information of both self and intervals.
558
+
559
+ Args:
560
+ intervals: Sequence of intervals possibly overlapping self.
561
+ bin_size: Resolution at which to bin the output coverage track. Coverage
562
+ within each bin (if larger than 1) will be summarized using sum().
563
+
564
+ Returns:
565
+ Numpy array of shape (self.width // bin_size, 2) where output[:, 0]
566
+ represents coverage for intervals on the same strand as self and
567
+ output[:, 1] represents coverage of intervals on the opposite strand.
568
+ """
569
+ # Split intervals based on strand.
570
+ forward_intervals = []
571
+ reverse_intervals = []
572
+ for interval in intervals:
573
+ if interval.negative_strand:
574
+ reverse_intervals.append(interval)
575
+ else:
576
+ forward_intervals.append(interval)
577
+
578
+ coverage = np.stack(
579
+ [
580
+ self.coverage(forward_intervals, bin_size=bin_size),
581
+ self.coverage(reverse_intervals, bin_size=bin_size),
582
+ ],
583
+ axis=-1,
584
+ )
585
+ if self.negative_strand:
586
+ return coverage[::-1, ::-1]
587
+ else:
588
+ return coverage
589
+
590
+ def binary_mask_stranded(
591
+ self, intervals: Sequence[Self], bin_size: int = 1
592
+ ) -> np.ndarray:
593
+ """Boolean mask True if any interval overlaps the bin: coverage > 0."""
594
+ return self.coverage_stranded(intervals, bin_size=bin_size) > 0
595
+
596
+
597
+ _DEFAULT_REGEX = re.compile(r'(chr(?:X|Y|M|\d+)):(\d+):([ACGTN]*)>([ACGTN]*)')
598
+ _GTEX_REGEX = re.compile(
599
+ r'(chr(?:X|Y|M|\d+))_(\d+)_([ACGTN]*)_([ACGTN]*)_?[a-zA-Z0-9]*'
600
+ )
601
+ _OPEN_TARGETS_REGEX = re.compile(r'((?:X|Y|M|\d+))_(\d+)_([ACGTN]*)_([ACGTN]*)')
602
+ _OPEN_TARGETS_BIGQUERY_REGEX = re.compile(
603
+ r'((?:X|Y|M|\d+)):(\d+):([ACGTN]*):([ACGTN]*)'
604
+ )
605
+ _GNOMAD_REGEX = re.compile(r'((?:X|Y|M|\d+))-(\d+)-([ACGTN]*)-([ACGTN]*)')
606
+
607
+
608
+ class VariantFormat(enum.Enum):
609
+ """A format for parsing a string into a Variant object.
610
+
611
+ This is used to convert from a string to a formal Variant object.
612
+ Note that it does not perform any validation (e.g. it does not verify that the
613
+ reference allele corresponds to the reference genome or that the
614
+ position is valid).
615
+
616
+ Example formats:
617
+ DEFAULT: chr22:1024:A>C
618
+ GTEX: chr22_1024_A_C_b38 (build suffix is optional)
619
+ OPEN_TARGETS: 22_1024_A_C (chr prefix is omitted)
620
+ OPEN_TARGETS_BIGQUERY: 22:1024:A:C (chr prefix is omitted)
621
+ GNOMAD: 22-1024-A-C (chr prefix is omitted)
622
+ """
623
+
624
+ DEFAULT = 'default'
625
+ GTEX = 'gtex'
626
+ OPEN_TARGETS = 'open_targets'
627
+ OPEN_TARGETS_BIGQUERY = 'open_targets_bigquery'
628
+ GNOMAD = 'gnomad'
629
+
630
+ def to_regex(self) -> re.Pattern[str]:
631
+ """Returns a regular expression for the variant format."""
632
+ match self:
633
+ case VariantFormat.DEFAULT:
634
+ return _DEFAULT_REGEX
635
+ case VariantFormat.GTEX:
636
+ return _GTEX_REGEX
637
+ case VariantFormat.OPEN_TARGETS:
638
+ return _OPEN_TARGETS_REGEX
639
+ case VariantFormat.OPEN_TARGETS_BIGQUERY:
640
+ return _OPEN_TARGETS_BIGQUERY_REGEX
641
+ case VariantFormat.GNOMAD:
642
+ return _GNOMAD_REGEX
643
+
644
+
645
+ @dataclasses.dataclass
646
+ class Variant:
647
+ """Represents a genomic variant/mutation.
648
+
649
+ Differs from the Variant definition in a VCF file, which allows
650
+ for multiple alternative bases and contains sample information. This
651
+ `Variant` class does not include sample information or variant call
652
+ quality information.
653
+
654
+ Attributes:
655
+ chromosome: The chromosome name (e.g., 'chr1', '1').
656
+ position: The 1-based position of the variant on the chromosome.
657
+ reference_bases: The reference base(s) at the variant position. Most
658
+ frequently (not always!), these correspond to the sequence in the
659
+ reference genome at positions: [position, ..., position +
660
+ len(reference_bases) - 1]
661
+ alternate_bases: The alternate base(s) that replace the reference. For
662
+ example, if sequence='ACT', position=2, reference_bases='C',
663
+ alternate_bases='TG', then the actual (alternate) sequence would be ATGT.
664
+ name: An optional name for the variant (e.g., a dbSNP ID like rs206437).
665
+ info: An optional dictionary for additional variant information.
666
+ """
667
+
668
+ chromosome: str
669
+ position: int
670
+ reference_bases: str
671
+ alternate_bases: str
672
+ name: str = dataclasses.field(default='', compare=False, hash=False)
673
+ info: dict[str, Any] = dataclasses.field(
674
+ default_factory=dict, repr=False, compare=False, hash=False
675
+ )
676
+
677
+ def __post_init__(self):
678
+ """Validates the variant's position."""
679
+ if self.position < 1:
680
+ raise ValueError(f'Position has to be >=1. Found: {self.position}.')
681
+ if not set(self.reference_bases).issubset(VALID_VARIANT_BASES):
682
+ raise ValueError(
683
+ f'Invalid reference bases: "{self.reference_bases}". Must only'
684
+ ' contain "ACGTN".'
685
+ )
686
+ if not set(self.alternate_bases).issubset(VALID_VARIANT_BASES):
687
+ raise ValueError(
688
+ f'Invalid alternate bases: "{self.alternate_bases}". Must only'
689
+ ' contain "ACGTN".'
690
+ )
691
+
692
+ def __str__(self):
693
+ """Returns a string representation of the variant."""
694
+ ref_alt = f'{self.reference_bases}>{self.alternate_bases}'
695
+ return f'{self.chromosome}:{self.position}:{ref_alt}'
696
+
697
+ def as_truncated_str(self, max_length: int = 50):
698
+ """Truncates the variant str's ref and alt bases to the given max length."""
699
+
700
+ def _truncate(s: str):
701
+ if len(s) <= max_length:
702
+ return s
703
+ else:
704
+ return s[: max_length // 2] + '...' + s[-max_length // 2 :]
705
+
706
+ return (
707
+ f'{self.chromosome}:{self.position}:'
708
+ f'{_truncate(self.reference_bases)}>{_truncate(self.alternate_bases)}'
709
+ )
710
+
711
+ @property
712
+ def start(self) -> int:
713
+ """Returns the 0-based start position of the variant."""
714
+ return self.position - 1
715
+
716
+ @property
717
+ def end(self) -> int:
718
+ """Returns the 0-based end position of the variant."""
719
+ return self.start + len(self.reference_bases)
720
+
721
+ @property
722
+ def reference_interval(self) -> Interval:
723
+ """Returns an `Interval` for the variant's reference sequence."""
724
+ return Interval(self.chromosome, self.start, self.end)
725
+
726
+ def reference_overlaps(self, interval: Interval) -> bool:
727
+ """Checks if the variant's reference overlaps with the interval."""
728
+ return interval.overlaps(Interval(self.chromosome, self.start, self.end))
729
+
730
+ def alternate_overlaps(self, interval: Interval) -> bool:
731
+ """Checks if the variant's alternate overlaps with the interval."""
732
+ return interval.overlaps(
733
+ Interval(
734
+ self.chromosome, self.start, self.start + len(self.alternate_bases)
735
+ )
736
+ )
737
+
738
+ @property
739
+ def is_snv(self) -> bool:
740
+ """Return if the variant is a Single Nucleotide Variant (SNV)."""
741
+ return len(self.reference_bases) == 1 and len(self.alternate_bases) == 1
742
+
743
+ @property
744
+ def is_deletion(self) -> bool:
745
+ """Return if the variant is a deletion."""
746
+ return len(self.reference_bases) > len(self.alternate_bases)
747
+
748
+ @property
749
+ def is_insertion(self) -> bool:
750
+ """Return if the variant is an insertion."""
751
+ return len(self.reference_bases) < len(self.alternate_bases)
752
+
753
+ @property
754
+ def is_frameshift(self) -> bool:
755
+ """Return if the variant is a frameshift."""
756
+ indel_size = abs(len(self.reference_bases) - len(self.alternate_bases))
757
+ return indel_size > 0 and indel_size % 3 != 0
758
+
759
+ @property
760
+ def is_indel(self) -> bool:
761
+ """Return if the variant is an insertion or deletion."""
762
+ return self.is_insertion or self.is_deletion
763
+
764
+ @property
765
+ def is_structural(self) -> bool:
766
+ """Return if the variant is a structural variant."""
767
+ indel_size = abs(len(self.reference_bases) - len(self.alternate_bases))
768
+ return indel_size >= 50
769
+
770
+ def copy(self) -> Self:
771
+ """Returns a deep copy of the variant."""
772
+ return copy.deepcopy(self)
773
+
774
+ @classmethod
775
+ def from_str(
776
+ cls, string: str, variant_format: VariantFormat = VariantFormat.DEFAULT
777
+ ) -> Self:
778
+ """Creates a `Variant` from a string representation.
779
+
780
+ Args:
781
+ string: The string representation.
782
+ variant_format: The format of the variant string. By default, this uses
783
+ "chromosome:position:ref>alt" (for example, "chr1:1024:A>C"). See
784
+ VariantFormat for alternate formatting options.
785
+
786
+ Returns:
787
+ A `Variant` object.
788
+ """
789
+ result = re.fullmatch(variant_format.to_regex(), string)
790
+ if result is None:
791
+ raise ValueError(f'Invalid format for variant string: {string}')
792
+
793
+ chromosome, position, reference, alternate = result.groups()
794
+ # Add chr prefix if not already present.
795
+ if not chromosome.startswith('chr'):
796
+ chromosome = f'chr{chromosome}'
797
+ return cls(
798
+ chromosome=chromosome,
799
+ position=int(position),
800
+ reference_bases=reference,
801
+ alternate_bases=alternate,
802
+ )
803
+
804
+ def to_dict(self) -> dict[str, Any]:
805
+ """Converts the variant to a dictionary."""
806
+ return dataclasses.asdict(self)
807
+
808
+ @classmethod
809
+ def from_dict(cls, dictionary: Mapping[str, Any] | Self) -> Self:
810
+ """Creates a `Variant` from a dictionary."""
811
+ return cls(**dictionary) # pytype: disable=bad-return-type
812
+
813
+ def to_proto(self) -> dna_model_pb2.Variant:
814
+ """Converts the variant to a protobuf message."""
815
+ return dna_model_pb2.Variant(
816
+ chromosome=self.chromosome,
817
+ position=self.position,
818
+ reference_bases=self.reference_bases,
819
+ alternate_bases=self.alternate_bases,
820
+ )
821
+
822
+ @classmethod
823
+ def from_proto(cls, variant: dna_model_pb2.Variant) -> Self:
824
+ """Creates a `Variant` from a protobuf message."""
825
+ return cls(
826
+ chromosome=variant.chromosome,
827
+ position=variant.position,
828
+ reference_bases=variant.reference_bases,
829
+ alternate_bases=variant.alternate_bases,
830
+ )
831
+
832
+ def split(self, anchor: int) -> tuple[Self | None, Self | None]:
833
+ """Splits the variant into two at the anchor point.
834
+
835
+ If the anchor point falls within the variant's reference sequence, the
836
+ variant is split into two new variants: one upstream of the anchor and one
837
+ downstream. If the anchor is outside the variant's reference sequence,
838
+ the original variant is returned on the appropriate side, and None on the
839
+ other.
840
+
841
+ Example:
842
+ position= 3
843
+ ref: ...[ A C ]...
844
+ alt: .....T G T C
845
+ anchor=3 |
846
+ returns: (chr1:3:A>T, chr1:4:C>GTC)
847
+
848
+ Args:
849
+ anchor: The 0-based anchor point to split the variant.
850
+
851
+ Returns:
852
+ A tuple of the upstream and downstream variants. If the variant is only
853
+ on one side of the anchorpoint, then None is returned.
854
+ """
855
+ if anchor <= self.start:
856
+ return None, self.copy()
857
+ elif anchor >= self.end:
858
+ return self.copy(), None
859
+ else:
860
+ mid = anchor - self.start
861
+ upstream, downstream = self.copy(), self.copy()
862
+ upstream.reference_bases = self.reference_bases[:mid]
863
+ upstream.alternate_bases = self.alternate_bases[:mid]
864
+
865
+ downstream.position = anchor + 1
866
+ downstream.reference_bases = self.reference_bases[mid:]
867
+ downstream.alternate_bases = self.alternate_bases[mid:]
868
+ return upstream, downstream
869
+
870
+
871
+ @dataclasses.dataclass
872
+ class Junction(Interval):
873
+ """Represents a splice junction.
874
+
875
+ A splice junction is a point in a pre-mRNA transcript where an intron is
876
+ removed and exons are joined during RNA splicing. This class inherits from
877
+ `Interval` and adds properties and methods specific to splice junctions.
878
+
879
+ Attributes:
880
+ chromosome: The chromosome name.
881
+ start: The 0-based start position of the junction.
882
+ end: The 0-based end position of the junction.
883
+ strand: The strand of the junction ('+' or '-').
884
+ name: An optional name for the junction.
885
+ info: An optional dictionary to store additional information.
886
+ k: An optional integer representing the number of reads supporting the
887
+ splice junction.
888
+
889
+ Raises:
890
+ ValueError: If the strand is unstranded.
891
+ """
892
+
893
+ k: int | None = None
894
+
895
+ def __post_init__(self):
896
+ """Validates that the junction is stranded."""
897
+ super().__post_init__()
898
+ if self.strand == STRAND_UNSTRANDED:
899
+ raise ValueError('Junctions must be stranded.')
900
+
901
+ @property
902
+ def acceptor(self) -> int:
903
+ """Returns the acceptor site position."""
904
+ return self.start if self.strand == STRAND_NEGATIVE else self.end
905
+
906
+ @property
907
+ def donor(self) -> int:
908
+ """Returns the donor site position."""
909
+ return self.end if self.strand == STRAND_NEGATIVE else self.start
910
+
911
+ def dinucleotide_region(self) -> tuple[Interval, Interval]:
912
+ """Returns the dinucleotide regions around acceptor and donor sites."""
913
+ return (
914
+ Interval(
915
+ self.chromosome, self.start, self.start + 2, strand=self.strand
916
+ ),
917
+ Interval(self.chromosome, self.end - 2, self.end, strand=self.strand),
918
+ )
919
+
920
+ def acceptor_region(self, overhang: tuple[int, int] = (250, 250)) -> Interval:
921
+ """Returns the region around the acceptor site with overhang."""
922
+ return Interval(
923
+ self.chromosome, self.acceptor, self.acceptor, strand=self.strand
924
+ ).pad(start_pad=overhang[0], end_pad=overhang[1])
925
+
926
+ def donor_region(self, overhang: tuple[int, int] = (250, 250)) -> Interval:
927
+ """Returns the region around the donor site with overhang."""
928
+ return Interval(
929
+ self.chromosome, self.donor, self.donor, strand=self.strand
930
+ ).pad(start_pad=overhang[0], end_pad=overhang[1])
931
+
932
+
933
+ class _FastaExtractorType(Protocol):
934
+ """Protocol definition for extracting intervals from a Fasta file."""
935
+
936
+ def extract(self, interval: Interval) -> str:
937
+ """Extract and return the DNA sequence for a given interval."""
938
+
939
+
940
+ def _prefix_length(*sequences) -> int:
941
+ """Returns the length of the common prefix for a sequence of strings."""
942
+ i = 0
943
+ for chars in zip(*sequences, strict=False):
944
+ if all(c == chars[0] for c in chars):
945
+ i += 1
946
+ else:
947
+ break
948
+ return i
949
+
950
+
951
+ def normalize_variant(
952
+ variant: Variant, extractor: _FastaExtractorType
953
+ ) -> Variant:
954
+ """Normalize a Variant by left-aligning the reference and alternate bases.
955
+
956
+ Normalization applied following algorithm described in
957
+ https://doi.org/10.1093/bioinformatics/btv112.
958
+
959
+ Args:
960
+ variant: The Variant to normalize.
961
+ extractor: The FastaExtractor to use for extracting the reference sequence.
962
+
963
+ Returns:
964
+ The normalized Variant.
965
+ """
966
+ if variant.is_snv:
967
+ return variant
968
+
969
+ chromosome = variant.chromosome
970
+ genome_sequence = extractor.extract(
971
+ Interval(
972
+ chromosome,
973
+ variant.start,
974
+ variant.start
975
+ + max(len(variant.reference_bases), len(variant.alternate_bases)),
976
+ )
977
+ )
978
+
979
+ position = variant.position
980
+ alleles = [genome_sequence, variant.reference_bases, variant.alternate_bases]
981
+
982
+ # Remove any common suffix from the alleles.
983
+ finished = False
984
+ while not finished:
985
+ suffix_length = _prefix_length(*[reversed(a) for a in alleles])
986
+ if suffix_length > 0:
987
+ alleles = [a[:-suffix_length] for a in alleles]
988
+
989
+ # If any alleles are empty, extend all alleles by 1 nucleotide to the left.
990
+ if not all(alleles):
991
+ position -= 1
992
+ base = extractor.extract(Interval(chromosome, position - 1, position))[0]
993
+ alleles = [base + a for a in alleles]
994
+ else:
995
+ # Finished iff we haven't shifted alleles and don't have a common suffix.
996
+ finished = suffix_length == 0
997
+
998
+ # Left-align the variant to the genome, ensuring at least 1 bp of context.
999
+ max_prefix_length = len(min(alleles)) - 1
1000
+ prefix_length = _prefix_length(*alleles)
1001
+ i = min(max_prefix_length, prefix_length)
1002
+
1003
+ _, reference_bases, alternate_bases = alleles
1004
+ return Variant(
1005
+ chromosome=chromosome,
1006
+ position=position + i,
1007
+ reference_bases=reference_bases[i:],
1008
+ alternate_bases=alternate_bases[i:],
1009
+ )
1010
+
1011
+
1012
+ def _split_intervals(
1013
+ intervals: Iterable[Interval], marker: int, bounds: list[tuple[int, int]]
1014
+ ):
1015
+ """Splits intervals into start and end points with markers."""
1016
+ for i in intervals:
1017
+ bounds.append((i.start, +marker))
1018
+ bounds.append((i.end, -marker))
1019
+
1020
+
1021
+ def _group_by_chromosome(
1022
+ intervals: Iterable[Interval],
1023
+ ) -> dict[str, list[Interval]]:
1024
+ """Groups intervals by chromosome."""
1025
+ interval_map = collections.defaultdict(list)
1026
+ for i in intervals:
1027
+ interval_map[i.chromosome].append(i)
1028
+ return dict(interval_map)
1029
+
1030
+
1031
+ def intersect_intervals(
1032
+ lhs: Iterable[Interval],
1033
+ rhs: Iterable[Interval],
1034
+ *,
1035
+ result_strand: str = '.',
1036
+ ) -> Iterator[Interval]:
1037
+ """Generates the intersection of two interval sets.
1038
+
1039
+ Point ranges (width == 0) are considered to intersect any range which contains
1040
+ them.
1041
+
1042
+ In these examples, the intersection is a point range (2,2)
1043
+ ```
1044
+ 1 2 3 4
1045
+ ..|..|..|..|..
1046
+ <> (start=2, end=2)
1047
+ -------> (..., end=2)
1048
+ ```
1049
+
1050
+ ```
1051
+ 1 2 3 4
1052
+ ..|..|..|..|..
1053
+ <> (start=2, end=2)
1054
+ <------- (start=2, end=...)
1055
+ ```
1056
+
1057
+ For consistency, this means that the following results in a point
1058
+ intersection:
1059
+
1060
+ ```
1061
+ 1 2 3 4
1062
+ ..|..|..|..|..
1063
+ -------> (start=..., end=2)
1064
+ <------- (start=2, end=...)
1065
+ ```
1066
+
1067
+ Args:
1068
+ lhs: A set of intervals.
1069
+ rhs: A set of intervals.
1070
+ result_strand: The strand for the resulting intervals.
1071
+
1072
+ Yields:
1073
+ The intersection of intervals. Overlapping intervals within either `lhs`
1074
+ or `rhs` are implicitly unioned.
1075
+ """
1076
+
1077
+ def _intersect(lhs, rhs, chrom):
1078
+ """Calculates the intersection for a specific chromosome.
1079
+
1080
+ Deconstructs two sets of intervals into (start, +k) and (end, -k) positions,
1081
+ where k is different for each set, then sorts all interval endpoints. By
1082
+ walking the sorted endpoints and accumulating the k's, we can work out when
1083
+ we enter or exit an interval from either set.
1084
+
1085
+ This allows emitting intervals corresponding to the intersection, and with
1086
+ appropriate k's, detecting when we enter an interval in either set before
1087
+ exiting the previous.
1088
+
1089
+ Args:
1090
+ lhs: The first list of `Interval` objects.
1091
+ rhs: The second list of `Interval` objects.
1092
+ chrom: The chromosome name.
1093
+
1094
+ Yields:
1095
+ `Interval` objects representing the intersections.
1096
+ """
1097
+ bounds = []
1098
+ _split_intervals(lhs, 0x00001, bounds)
1099
+ _split_intervals(rhs, 0x10000, bounds)
1100
+ accum = 0
1101
+ start = None
1102
+ for pos, delta in sorted(bounds, key=lambda x: (x[0], -x[1])):
1103
+ old_accum = accum
1104
+ accum += delta
1105
+ if accum & 0xFFFF and accum & 0xFFFF0000:
1106
+ if start is None:
1107
+ start = pos
1108
+ elif old_accum & 0xFFFF and old_accum & 0xFFFF0000:
1109
+ yield Interval(chrom, start, pos, result_strand)
1110
+ start = None
1111
+
1112
+ lhs = _group_by_chromosome(lhs)
1113
+ rhs = _group_by_chromosome(rhs)
1114
+ for chromosome in set(lhs) & set(rhs):
1115
+ yield from _intersect(lhs[chromosome], rhs[chromosome], chromosome)
1116
+
1117
+
1118
+ def union_intervals(
1119
+ lhs: Iterable[Interval],
1120
+ rhs: Iterable[Interval],
1121
+ *,
1122
+ result_strand: str = '.',
1123
+ ) -> Iterator[Interval]:
1124
+ """Generates the union of two interval sets.
1125
+
1126
+ Args:
1127
+ lhs: A non-overlapping set of intervals.
1128
+ rhs: A non-overlapping set of intervals.
1129
+ result_strand: The strand for the resulting intervals.
1130
+
1131
+ Yields:
1132
+ The union of intervals. Any position covered by an interval in `lhs` or
1133
+ `rhs` is covered in the result.
1134
+ """
1135
+
1136
+ def _union(lhs, rhs, chrom):
1137
+ """Calculates the union for a specific chromosome, analog of _intersect."""
1138
+ bounds = []
1139
+ _split_intervals(lhs, 0x00001, bounds)
1140
+ _split_intervals(rhs, 0x10000, bounds)
1141
+ accum = 0
1142
+ start = end = None
1143
+ for pos, delta in sorted(bounds, key=lambda x: (x[0], -x[1])):
1144
+ if accum == 0 and end is not None and end < pos:
1145
+ # Delay generating an interval until after the observed end point.
1146
+ # This merges abutting ranges.
1147
+ yield Interval(chrom, start, end, result_strand)
1148
+ start = end = None
1149
+ accum += delta
1150
+ if accum:
1151
+ if start is None:
1152
+ start = pos
1153
+ else:
1154
+ assert start is not None
1155
+ end = pos
1156
+ if end is not None:
1157
+ yield Interval(chrom, start, end, result_strand)
1158
+
1159
+ lhs = _group_by_chromosome(lhs)
1160
+ rhs = _group_by_chromosome(rhs)
1161
+ for chromosome in set(lhs) | set(rhs):
1162
+ yield from _union(
1163
+ lhs.get(chromosome, []), rhs.get(chromosome, []), chromosome
1164
+ )
1165
+
1166
+
1167
+ def merge_overlapping_intervals(
1168
+ intervals: Sequence[Interval],
1169
+ ) -> list[Interval]:
1170
+ """Merges overlapping intervals and returns a sorted list.
1171
+
1172
+ Args:
1173
+ intervals: A sequence of intervals with the same strand.
1174
+
1175
+ Returns:
1176
+ A new sorted list of merged intervals.
1177
+ """
1178
+ if not intervals:
1179
+ return []
1180
+ assert all(i.strand == intervals[0].strand for i in intervals)
1181
+ return list(union_intervals(intervals, [], result_strand=intervals[0].strand))
flax_model/alphagenome/_sdk/models/interval_scorers.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Module containing interval scorer dataclasses for interval scoring."""
16
+
17
+ import dataclasses
18
+ import enum
19
+ from typing import TypeVar
20
+
21
+ from flax_model.alphagenome._sdk.models import dna_output
22
+ from flax_model.alphagenome._sdk.protos import dna_model_pb2
23
+ import immutabledict
24
+
25
+
26
+ class IntervalAggregationType(enum.Enum):
27
+ """Enum indicating the type of interval scorer aggregation.
28
+
29
+ Attributes:
30
+ MEAN: Mean across positions.
31
+ SUM: Sum across positions.
32
+
33
+ Methods:
34
+ to_proto: Converts the aggregation type to its corresponding proto enum.
35
+ """
36
+
37
+ MEAN = dna_model_pb2.IntervalAggregationType.INTERVAL_AGGREGATION_TYPE_MEAN
38
+ SUM = dna_model_pb2.IntervalAggregationType.INTERVAL_AGGREGATION_TYPE_SUM
39
+
40
+ def to_proto(self) -> dna_model_pb2.IntervalAggregationType:
41
+ return self.value
42
+
43
+ def __repr__(self) -> str:
44
+ return self.name
45
+
46
+
47
+ class BaseIntervalScorer(enum.Enum):
48
+ """Enum indicating the type of interval scoring.
49
+
50
+ Attributes:
51
+ GENE_MASK: Gene-mask scoring (e.g., aggregation of predictions within genes)
52
+ """
53
+
54
+ GENE_MASK = enum.auto()
55
+
56
+
57
+ SUPPORTED_OUTPUT_TYPES = immutabledict.immutabledict({
58
+ BaseIntervalScorer.GENE_MASK: [
59
+ dna_output.OutputType.ATAC,
60
+ dna_output.OutputType.CAGE,
61
+ dna_output.OutputType.CHIP_HISTONE,
62
+ dna_output.OutputType.CHIP_TF,
63
+ dna_output.OutputType.DNASE,
64
+ dna_output.OutputType.RNA_SEQ,
65
+ dna_output.OutputType.SPLICE_SITES,
66
+ dna_output.OutputType.SPLICE_SITE_USAGE,
67
+ ],
68
+ })
69
+
70
+ SUPPORTED_WIDTHS = immutabledict.immutabledict({
71
+ BaseIntervalScorer.GENE_MASK: [None, 501, 2001, 10_001, 100_001, 200_001],
72
+ })
73
+
74
+
75
+ @dataclasses.dataclass(frozen=True)
76
+ class GeneMaskScorer:
77
+ """Interval scorer for gene-mask scoring.
78
+
79
+ Attributes:
80
+ requested_output: The requested output type (e.g. ATAC, DNASE, etc.)
81
+ width: The width of the target interval to include in the aggregation.
82
+ aggregation_type: The type of aggregation to perform.
83
+ base_interval_scorer: The base interval scorer.
84
+ name: The name of the scorer (a composite of the above attributes that
85
+ uniquely identifies a scorer combination).
86
+
87
+ Methods:
88
+ to_proto: Converts the scorer to its corresponding proto message.
89
+
90
+ Raises:
91
+ ValueError: If the requested output is not supported.
92
+ """
93
+
94
+ requested_output: dna_output.OutputType
95
+ width: int | None
96
+ aggregation_type: IntervalAggregationType
97
+
98
+ @property
99
+ def base_interval_scorer(self) -> BaseIntervalScorer:
100
+ return BaseIntervalScorer.GENE_MASK
101
+
102
+ @property
103
+ def name(self) -> str:
104
+ return str(self)
105
+
106
+ def __post_init__(self):
107
+ if (
108
+ self.requested_output
109
+ not in SUPPORTED_OUTPUT_TYPES[self.base_interval_scorer]
110
+ ):
111
+ raise ValueError(
112
+ f'Unsupported requested output: {self.requested_output}. Supported'
113
+ f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_interval_scorer]}'
114
+ )
115
+ if self.width not in SUPPORTED_WIDTHS[self.base_interval_scorer]:
116
+ raise ValueError(
117
+ f'Unsupported width: {self.width}. Supported widths:'
118
+ f' {SUPPORTED_WIDTHS[self.base_interval_scorer]}'
119
+ )
120
+
121
+ def to_proto(self) -> dna_model_pb2.IntervalScorer:
122
+ return dna_model_pb2.IntervalScorer(
123
+ gene_mask=dna_model_pb2.GeneMaskIntervalScorer(
124
+ requested_output=self.requested_output.to_proto(),
125
+ width=self.width,
126
+ aggregation_type=self.aggregation_type.to_proto(),
127
+ )
128
+ )
129
+
130
+
131
+ # TypeVar for all interval scorer types.
132
+ IntervalScorerTypes = TypeVar(
133
+ 'IntervalScorerTypes',
134
+ bound=GeneMaskScorer,
135
+ )
136
+
137
+ # A dict of interval scorers, with our recommended settings for a wide range
138
+ # of different use cases and settings.
139
+ RECOMMENDED_INTERVAL_SCORERS = {
140
+ 'RNA_SEQ': GeneMaskScorer(
141
+ requested_output=dna_output.OutputType.RNA_SEQ,
142
+ width=200_001,
143
+ aggregation_type=IntervalAggregationType.MEAN,
144
+ ),
145
+ }
flax_model/alphagenome/_sdk/models/variant_scorers.py ADDED
@@ -0,0 +1,878 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Module containing variant scorer dataclasses for variant scoring."""
16
+
17
+ from collections.abc import Sequence
18
+ import dataclasses
19
+ import enum
20
+ import itertools
21
+ import math
22
+ from typing import TypeVar
23
+
24
+ from flax_model.alphagenome._sdk.models import dna_output
25
+ from flax_model.alphagenome._sdk.protos import dna_model_pb2
26
+ import anndata
27
+ import immutabledict
28
+ import pandas as pd
29
+
30
+
31
+ class AggregationType(enum.Enum):
32
+ """Enum indicating the type of variant scorer aggregation.
33
+
34
+ Attributes:
35
+ DIFF_MEAN: Difference of means, i.e., mean(`ALT`) - mean(`REF`).
36
+ DIFF_SUM: Difference of sums, i.e., sum(`ALT`) - sum(`REF`).
37
+ DIFF_SUM_LOG2: Log scales predictions, then takes the sum and then the
38
+ difference, i.e., sum(log2(`ALT`)) - sum(log2(`REF`)).
39
+ DIFF_LOG2_SUM: Takes the sum of predictions, applies a log transform, then
40
+ takes the difference between predictions, i.e., log2(sum(`ALT`)) -
41
+ log2(sum(`REF`)).
42
+ L2_DIFF: Takes the difference of `ALT` and `REF` predictions, then computes
43
+ the L2 norm, i.e., l2_norm(`ALT` - `REF`).
44
+ L2_DIFF_LOG1P: Log scales the predictions + 1, takes the difference of `ALT`
45
+ and `REF` predictions, then computes the L2 norm, i.e.,
46
+ l2_norm(log1p(`ALT`) - log1p(`REF`)).
47
+ ACTIVE_MEAN: Maximum of means, i.e., max(mean(`ALT`), mean(`REF`)).
48
+ ACTIVE_SUM: Maximum of sums, i.e., max(sum(`ALT), sum(`REF`)).
49
+
50
+ Methods:
51
+ to_proto: Converts the aggregation type to its corresponding proto enum.
52
+ """
53
+
54
+ DIFF_MEAN = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_MEAN
55
+ DIFF_SUM = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_SUM
56
+ DIFF_SUM_LOG2 = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_SUM_LOG2
57
+ DIFF_LOG2_SUM = dna_model_pb2.AggregationType.AGGREGATION_TYPE_DIFF_LOG2_SUM
58
+ L2_DIFF = dna_model_pb2.AggregationType.AGGREGATION_TYPE_L2_DIFF
59
+ L2_DIFF_LOG1P = dna_model_pb2.AggregationType.AGGREGATION_TYPE_L2_DIFF_LOG1P
60
+ ACTIVE_MEAN = dna_model_pb2.AggregationType.AGGREGATION_TYPE_ACTIVE_MEAN
61
+ ACTIVE_SUM = dna_model_pb2.AggregationType.AGGREGATION_TYPE_ACTIVE_SUM
62
+
63
+ def to_proto(self) -> dna_model_pb2.AggregationType:
64
+ return self.value
65
+
66
+ def __repr__(self) -> str:
67
+ return self.name
68
+
69
+
70
+ class BaseVariantScorer(enum.Enum):
71
+ """Enum indicating the type of variant scoring.
72
+
73
+ Attributes:
74
+ CENTER_MASK: Center mask scorer.
75
+ CONTACT_MAP: Contact map scorer, a center mask scorer that handles 2D
76
+ tensors.
77
+ GENE_MASK_LFC: Gene-mask scoring based on log fold change.
78
+ GENE_MASK_ACTIVE: Gene-mask scoring based on active allele.
79
+ GENE_MASK_SPLICING: Gene-mask scoring for splicing.
80
+ PA_QTL: Polyadenylation QTL scoring.
81
+ SPLICE_JUNCTION: Splice junction scoring.
82
+ """
83
+
84
+ CENTER_MASK = enum.auto()
85
+ CONTACT_MAP = enum.auto()
86
+ GENE_MASK_LFC = enum.auto()
87
+ GENE_MASK_ACTIVE = enum.auto()
88
+ GENE_MASK_SPLICING = enum.auto()
89
+ PA_QTL = enum.auto()
90
+ SPLICE_JUNCTION = enum.auto()
91
+
92
+
93
+ SUPPORTED_ORGANISMS = immutabledict.immutabledict({
94
+ BaseVariantScorer.CENTER_MASK: dna_model_pb2.Organism.values(),
95
+ BaseVariantScorer.CONTACT_MAP: dna_model_pb2.Organism.values(),
96
+ BaseVariantScorer.GENE_MASK_LFC: dna_model_pb2.Organism.values(),
97
+ BaseVariantScorer.GENE_MASK_ACTIVE: dna_model_pb2.Organism.values(),
98
+ BaseVariantScorer.GENE_MASK_SPLICING: dna_model_pb2.Organism.values(),
99
+ BaseVariantScorer.PA_QTL: [dna_model_pb2.Organism.ORGANISM_HOMO_SAPIENS],
100
+ BaseVariantScorer.SPLICE_JUNCTION: dna_model_pb2.Organism.values(),
101
+ })
102
+
103
+ SUPPORTED_OUTPUT_TYPES = immutabledict.immutabledict({
104
+ BaseVariantScorer.CENTER_MASK: [
105
+ dna_output.OutputType.ATAC,
106
+ dna_output.OutputType.CAGE,
107
+ dna_output.OutputType.DNASE,
108
+ dna_output.OutputType.PROCAP,
109
+ dna_output.OutputType.RNA_SEQ,
110
+ dna_output.OutputType.CHIP_HISTONE,
111
+ dna_output.OutputType.CHIP_TF,
112
+ dna_output.OutputType.SPLICE_SITES,
113
+ dna_output.OutputType.SPLICE_SITE_USAGE,
114
+ ],
115
+ BaseVariantScorer.CONTACT_MAP: [dna_output.OutputType.CONTACT_MAPS],
116
+ BaseVariantScorer.GENE_MASK_LFC: [
117
+ dna_output.OutputType.ATAC,
118
+ dna_output.OutputType.CAGE,
119
+ dna_output.OutputType.DNASE,
120
+ dna_output.OutputType.PROCAP,
121
+ dna_output.OutputType.RNA_SEQ,
122
+ dna_output.OutputType.SPLICE_SITES,
123
+ dna_output.OutputType.SPLICE_SITE_USAGE,
124
+ ],
125
+ BaseVariantScorer.GENE_MASK_ACTIVE: [
126
+ dna_output.OutputType.ATAC,
127
+ dna_output.OutputType.CAGE,
128
+ dna_output.OutputType.DNASE,
129
+ dna_output.OutputType.PROCAP,
130
+ dna_output.OutputType.RNA_SEQ,
131
+ dna_output.OutputType.SPLICE_SITES,
132
+ dna_output.OutputType.SPLICE_SITE_USAGE,
133
+ ],
134
+ BaseVariantScorer.GENE_MASK_SPLICING: [
135
+ dna_output.OutputType.SPLICE_SITES,
136
+ dna_output.OutputType.SPLICE_SITE_USAGE,
137
+ ],
138
+ })
139
+
140
+ SUPPORTED_WIDTHS = immutabledict.immutabledict({
141
+ BaseVariantScorer.CENTER_MASK: [None, 501, 2001, 10_001, 100_001, 200_001],
142
+ BaseVariantScorer.GENE_MASK_SPLICING: [None, 101, 1_001, 10_001],
143
+ })
144
+
145
+ SUPPORTED_AGGREGATIONS = immutabledict.immutabledict({
146
+ BaseVariantScorer.CENTER_MASK: [
147
+ AggregationType.DIFF_MEAN,
148
+ AggregationType.DIFF_SUM,
149
+ AggregationType.DIFF_SUM_LOG2,
150
+ AggregationType.DIFF_LOG2_SUM,
151
+ AggregationType.L2_DIFF,
152
+ AggregationType.L2_DIFF_LOG1P,
153
+ AggregationType.ACTIVE_MEAN,
154
+ AggregationType.ACTIVE_SUM,
155
+ ],
156
+ })
157
+
158
+
159
+ @dataclasses.dataclass(frozen=True)
160
+ class CenterMaskScorer:
161
+ """Variant scorer for center mask scorers.
162
+
163
+ Variant scorer that aggregates ALT and REF values using a spatial mask
164
+ centered around the variant before computing the difference. This scorer
165
+ aggregates over the spatial axis and returns one score per output track.
166
+
167
+ Attributes:
168
+ requested_output: The requested output type (e.g., ATAC, DNASE, etc.)
169
+ width: The width of the mask around the variant. If None, the score is
170
+ computed over the entire sequence.
171
+ aggregation_type: The aggregation type.
172
+ base_variant_scorer: The base variant scorer.
173
+ name: The name of the scorer (a composite of the above attributes that
174
+ uniquely identifies a scorer combination).
175
+ is_signed: Whether this variant scorer is directional (such that scores may
176
+ be negative or positive) or non-directional (scores are always positive).
177
+
178
+ Methods:
179
+ to_proto: Converts the scorer to its corresponding proto message.
180
+
181
+ Raises:
182
+ ValueError: If the requested output, width, or aggregation type is not
183
+ supported.
184
+ """
185
+
186
+ requested_output: dna_output.OutputType
187
+ width: int | None
188
+ aggregation_type: AggregationType
189
+
190
+ @property
191
+ def base_variant_scorer(self) -> BaseVariantScorer:
192
+ return BaseVariantScorer.CENTER_MASK
193
+
194
+ @property
195
+ def name(self) -> str:
196
+ return str(self)
197
+
198
+ @property
199
+ def is_signed(self) -> bool:
200
+ # The 'active' scorers track the maximum of the ALT and REF, and are
201
+ # non-directional. All other scorers track ALT - REF, with L2_DIFF
202
+ # nondirectional and the remaining directional.
203
+ return self.aggregation_type in [
204
+ AggregationType.DIFF_MEAN,
205
+ AggregationType.DIFF_SUM,
206
+ AggregationType.DIFF_SUM_LOG2,
207
+ AggregationType.DIFF_LOG2_SUM,
208
+ ]
209
+
210
+ def __post_init__(self):
211
+ if (
212
+ self.requested_output
213
+ not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]
214
+ ):
215
+ raise ValueError(
216
+ f'Unsupported requested output: {self.requested_output}. Supported'
217
+ f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}'
218
+ )
219
+ if self.width not in SUPPORTED_WIDTHS[self.base_variant_scorer]:
220
+ raise ValueError(
221
+ f'Unsupported width: {self.width}. Supported widths:'
222
+ f' {SUPPORTED_WIDTHS[self.base_variant_scorer]}'
223
+ )
224
+ if (
225
+ self.aggregation_type
226
+ not in SUPPORTED_AGGREGATIONS[self.base_variant_scorer]
227
+ ):
228
+ raise ValueError(
229
+ f'Unsupported aggregation type: {self.aggregation_type}. Supported'
230
+ ' aggregation types:'
231
+ f' {SUPPORTED_AGGREGATIONS[self.base_variant_scorer]}'
232
+ )
233
+
234
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
235
+ return dna_model_pb2.VariantScorer(
236
+ center_mask=dna_model_pb2.CenterMaskScorer(
237
+ requested_output=self.requested_output.to_proto(),
238
+ width=self.width,
239
+ aggregation_type=self.aggregation_type.to_proto(),
240
+ )
241
+ )
242
+
243
+
244
+ @dataclasses.dataclass(frozen=True)
245
+ class ContactMapScorer:
246
+ """Variant scorer for contact map scorers.
247
+
248
+ Variant scorer that quantifies local contact disruption between ALT and REF
249
+ alleles. Uses a 1MB window centered around the variant to calculate the
250
+ mean absolute difference of contact frequencies, for all interactions
251
+ involving the variant-containing bin.
252
+
253
+ Attributes:
254
+ requested_output: The requested output type (e.g., CONTACT_MAPS).
255
+ base_variant_scorer: The base variant scorer.
256
+ name: The name of the scorer (a composite of the above attributes that
257
+ uniquely identifies a scorer combination).
258
+ is_signed: Whether this variant scorer is directional (such that scores may
259
+ be negative or positive) or non-directional (scores are always positive).
260
+
261
+ Methods:
262
+ to_proto: Converts the scorer to its corresponding proto message.
263
+ """
264
+
265
+ @property
266
+ def base_variant_scorer(self) -> BaseVariantScorer:
267
+ return BaseVariantScorer.CONTACT_MAP
268
+
269
+ @property
270
+ def name(self) -> str:
271
+ return str(self)
272
+
273
+ @property
274
+ def is_signed(self) -> bool:
275
+ return False
276
+
277
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
278
+ return dna_model_pb2.VariantScorer(
279
+ contact_map=dna_model_pb2.ContactMapScorer()
280
+ )
281
+
282
+ @property
283
+ def requested_output(self) -> dna_output.OutputType:
284
+ return dna_output.OutputType.CONTACT_MAPS
285
+
286
+
287
+ @dataclasses.dataclass(frozen=True)
288
+ class GeneMaskLFCScorer:
289
+ """Variant scorer for gene-mask log fold change scoring.
290
+
291
+ Variant scorer that quantifies impact on overall gene transcript abundance.
292
+ Calculates the log fold change of gene expression level between ALT and REF
293
+ alleles using a gene exon mask.
294
+
295
+ Attributes:
296
+ requested_output: The requested output type (e.g. ATAC, DNASE, etc.)
297
+ base_variant_scorer: The base variant scorer.
298
+ name: The name of the scorer (a composite of the above attributes that
299
+ uniquely identifies a scorer combination).
300
+ is_signed: Whether this variant scorer is directional (such that scores may
301
+ be negative or positive) or non-directional (scores are always positive).
302
+
303
+ Methods:
304
+ to_proto: Converts the scorer to its corresponding proto message.
305
+
306
+ Raises:
307
+ ValueError: If the requested output is not supported.
308
+ """
309
+
310
+ requested_output: dna_output.OutputType
311
+
312
+ @property
313
+ def base_variant_scorer(self) -> BaseVariantScorer:
314
+ return BaseVariantScorer.GENE_MASK_LFC
315
+
316
+ @property
317
+ def name(self) -> str:
318
+ return str(self)
319
+
320
+ @property
321
+ def is_signed(self) -> bool:
322
+ return True
323
+
324
+ def __post_init__(self):
325
+ if (
326
+ self.requested_output
327
+ not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]
328
+ ):
329
+ raise ValueError(
330
+ f'Unsupported requested output: {self.requested_output}. Supported'
331
+ f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}'
332
+ )
333
+
334
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
335
+ return dna_model_pb2.VariantScorer(
336
+ gene_mask=dna_model_pb2.GeneMaskLFCScorer(
337
+ requested_output=self.requested_output.to_proto(),
338
+ )
339
+ )
340
+
341
+
342
+ @dataclasses.dataclass(frozen=True)
343
+ class GeneMaskActiveScorer:
344
+ """Variant scorer for gene-mask active allele scoring.
345
+
346
+ Variant scorer that captures absolute activity level associated with one of
347
+ the alleles, rather than quantifying the difference between the ALT and REF.
348
+ Active allele gene scores are calculated by taking the maximum of the
349
+ aggregated ALT and REF signals across exons for a gene of interest.
350
+
351
+ Attributes:
352
+ requested_output: The requested output type (e.g. ATAC, DNASE, etc.)
353
+ base_variant_scorer: The base variant scorer.
354
+ name: The name of the scorer (a composite of the above attributes that
355
+ uniquely identifies a scorer combination).
356
+ is_signed: Whether this variant scorer is directional (such that scores may
357
+ be negative or positive) or non-directional (scores are always positive).
358
+
359
+ Methods:
360
+ to_proto: Converts the scorer to its corresponding proto message.
361
+
362
+ Raises:
363
+ ValueError: If the requested output is not supported.
364
+ """
365
+
366
+ requested_output: dna_output.OutputType
367
+
368
+ @property
369
+ def base_variant_scorer(self) -> BaseVariantScorer:
370
+ return BaseVariantScorer.GENE_MASK_ACTIVE
371
+
372
+ @property
373
+ def name(self) -> str:
374
+ return str(self)
375
+
376
+ @property
377
+ def is_signed(self) -> bool:
378
+ return False
379
+
380
+ def __post_init__(self):
381
+ if (
382
+ self.requested_output
383
+ not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]
384
+ ):
385
+ raise ValueError(
386
+ f'Unsupported requested output: {self.requested_output}. Supported'
387
+ f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}'
388
+ )
389
+
390
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
391
+ return dna_model_pb2.VariantScorer(
392
+ gene_mask_active=dna_model_pb2.GeneMaskActiveScorer(
393
+ requested_output=self.requested_output.to_proto(),
394
+ )
395
+ )
396
+
397
+
398
+ @dataclasses.dataclass(frozen=True)
399
+ class GeneMaskSplicingScorer:
400
+ """Variant scorer for gene-mask scoring for splicing.
401
+
402
+ Variant scorer that quantifies changes in class assignment probabilties
403
+ (dna_output.OutputType.SPLICE_SITES) or changes in the usage of splice sites
404
+ (dna_output.OutputType.SPLICE_SITE_USAGE) between ALT and REF alleles using
405
+ a gene exon mask.
406
+
407
+ Attributes:
408
+ requested_output: The requested output type (e.g. ATAC, DNASE, etc.)
409
+ width: The width of the mask around the variant.
410
+ base_variant_scorer: The base variant scorer.
411
+ name: The name of the scorer (a composite of the above attributes that
412
+ uniquely identifies a scorer combination).
413
+ is_signed: Whether this variant scorer is directional (such that scores may
414
+ be negative or positive) or non-directional (scores are always positive).
415
+
416
+ Methods:
417
+ to_proto: Converts the scorer to its corresponding proto message.
418
+
419
+ Raises:
420
+ ValueError: If the requested output or width is not supported.
421
+ """
422
+
423
+ requested_output: dna_output.OutputType
424
+ width: int | None
425
+
426
+ @property
427
+ def base_variant_scorer(self) -> BaseVariantScorer:
428
+ return BaseVariantScorer.GENE_MASK_SPLICING
429
+
430
+ @property
431
+ def name(self) -> str:
432
+ return str(self)
433
+
434
+ @property
435
+ def is_signed(self) -> bool:
436
+ return False
437
+
438
+ def __post_init__(self):
439
+ if (
440
+ self.requested_output
441
+ not in SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]
442
+ ):
443
+ raise ValueError(
444
+ f'Unsupported requested output: {self.requested_output}. Supported'
445
+ f' output types: {SUPPORTED_OUTPUT_TYPES[self.base_variant_scorer]}'
446
+ )
447
+ if self.width not in SUPPORTED_WIDTHS[self.base_variant_scorer]:
448
+ raise ValueError(
449
+ f'Unsupported width: {self.width}. Supported widths:'
450
+ f' {SUPPORTED_WIDTHS[self.base_variant_scorer]}'
451
+ )
452
+
453
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
454
+ return dna_model_pb2.VariantScorer(
455
+ gene_mask_splicing=dna_model_pb2.GeneMaskSplicingScorer(
456
+ requested_output=self.requested_output.to_proto(),
457
+ width=self.width,
458
+ )
459
+ )
460
+
461
+
462
+ @dataclasses.dataclass(frozen=True)
463
+ class PolyadenylationScorer:
464
+ """Variant scorer for polyadenylation QTLs (paQTLs).
465
+
466
+ Variant scorer for polyadenylation quantitative trait loci (paQTLs) to capture
467
+ a variant's impact on RNA isoform production.
468
+
469
+ The scoring approach quantifies the maximum log fold change in expression
470
+ between the set of proximal polyadenylation sites (PAS)s vs. the set of
471
+ distal PASs, where the sets of proximal and distal PASs are the PASs upstream
472
+ or downstream of any given 3' cleavage site respectively.
473
+
474
+ Attributes:
475
+ base_variant_scorer: The base variant scorer.
476
+ name: The name of the scorer (a composite of the above attributes that
477
+ uniquely identifies a scorer combination).
478
+ is_signed: Whether this variant scorer is directional (such that scores may
479
+ be negative or positive) or non-directional (scores are always positive).
480
+
481
+ Methods:
482
+ to_proto: Converts the scorer to its corresponding proto message.
483
+ """
484
+
485
+ @property
486
+ def requested_output(self) -> dna_output.OutputType:
487
+ """Returns the scorer's underlying output type."""
488
+ return dna_output.OutputType.RNA_SEQ
489
+
490
+ @property
491
+ def base_variant_scorer(self) -> BaseVariantScorer:
492
+ return BaseVariantScorer.PA_QTL
493
+
494
+ @property
495
+ def name(self) -> str:
496
+ return str(self)
497
+
498
+ @property
499
+ def is_signed(self) -> bool:
500
+ return False
501
+
502
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
503
+ return dna_model_pb2.VariantScorer(
504
+ pa_qtl=dna_model_pb2.PolyadenylationScorer()
505
+ )
506
+
507
+
508
+ @dataclasses.dataclass(frozen=True)
509
+ class SpliceJunctionScorer:
510
+ """Variant scorer for splice junction scoring.
511
+
512
+ Attributes:
513
+ base_variant_scorer: The base variant scorer.
514
+ name: The name of the scorer (a composite of the above attributes that
515
+ uniquely identifies a scorer combination).
516
+ is_signed: Whether this variant scorer is directional (such that scores may
517
+ be negative or positive) or non-directional (scores are always positive).
518
+
519
+ Methods:
520
+ to_proto: Converts the scorer to its corresponding proto message.
521
+ """
522
+
523
+ @property
524
+ def requested_output(self) -> dna_output.OutputType:
525
+ """Returns the scorer's underlying output type."""
526
+ return dna_output.OutputType.SPLICE_JUNCTIONS
527
+
528
+ @property
529
+ def base_variant_scorer(self) -> BaseVariantScorer:
530
+ return BaseVariantScorer.SPLICE_JUNCTION
531
+
532
+ @property
533
+ def name(self) -> str:
534
+ return str(self)
535
+
536
+ @property
537
+ def is_signed(self) -> bool:
538
+ return False
539
+
540
+ def to_proto(self) -> dna_model_pb2.VariantScorer:
541
+ return dna_model_pb2.VariantScorer(
542
+ splice_junction=dna_model_pb2.SpliceJunctionScorer()
543
+ )
544
+
545
+
546
+ # TypeVar for all variant scorer types.
547
+ VariantScorerTypes = TypeVar(
548
+ 'VariantScorerTypes',
549
+ CenterMaskScorer,
550
+ ContactMapScorer,
551
+ GeneMaskLFCScorer,
552
+ GeneMaskActiveScorer,
553
+ GeneMaskSplicingScorer,
554
+ PolyadenylationScorer,
555
+ SpliceJunctionScorer,
556
+ )
557
+
558
+ # A dict of variant scorers, with our recommended settings for a wide range
559
+ # of different use cases and settings.
560
+ RECOMMENDED_VARIANT_SCORERS = immutabledict.immutabledict({
561
+ 'ATAC': CenterMaskScorer(
562
+ requested_output=dna_output.OutputType.ATAC,
563
+ width=501,
564
+ aggregation_type=AggregationType.DIFF_LOG2_SUM,
565
+ ),
566
+ 'CONTACT_MAPS': ContactMapScorer(),
567
+ 'DNASE': CenterMaskScorer(
568
+ requested_output=dna_output.OutputType.DNASE,
569
+ width=501,
570
+ aggregation_type=AggregationType.DIFF_LOG2_SUM,
571
+ ),
572
+ 'CHIP_TF': CenterMaskScorer(
573
+ requested_output=dna_output.OutputType.CHIP_TF,
574
+ width=501,
575
+ aggregation_type=AggregationType.DIFF_LOG2_SUM,
576
+ ),
577
+ 'CHIP_HISTONE': CenterMaskScorer(
578
+ requested_output=dna_output.OutputType.CHIP_HISTONE,
579
+ width=2001,
580
+ aggregation_type=AggregationType.DIFF_LOG2_SUM,
581
+ ),
582
+ 'CAGE': CenterMaskScorer(
583
+ requested_output=dna_output.OutputType.CAGE,
584
+ width=501,
585
+ aggregation_type=AggregationType.DIFF_LOG2_SUM,
586
+ ),
587
+ 'PROCAP': CenterMaskScorer(
588
+ requested_output=dna_output.OutputType.PROCAP,
589
+ width=501,
590
+ aggregation_type=AggregationType.DIFF_LOG2_SUM,
591
+ ),
592
+ # Expression log fold change.
593
+ 'RNA_SEQ': GeneMaskLFCScorer(
594
+ requested_output=dna_output.OutputType.RNA_SEQ
595
+ ),
596
+ 'RNA_SEQ_ACTIVE': GeneMaskActiveScorer(
597
+ requested_output=dna_output.OutputType.RNA_SEQ
598
+ ),
599
+ 'SPLICE_SITES': GeneMaskSplicingScorer(
600
+ requested_output=dna_output.OutputType.SPLICE_SITES,
601
+ width=None,
602
+ ),
603
+ 'SPLICE_SITE_USAGE': GeneMaskSplicingScorer(
604
+ requested_output=dna_output.OutputType.SPLICE_SITE_USAGE,
605
+ width=None,
606
+ ),
607
+ 'SPLICE_JUNCTIONS': SpliceJunctionScorer(),
608
+ 'POLYADENYLATION': PolyadenylationScorer(),
609
+ 'ATAC_ACTIVE': CenterMaskScorer(
610
+ requested_output=dna_output.OutputType.ATAC,
611
+ width=501,
612
+ aggregation_type=AggregationType.ACTIVE_SUM,
613
+ ),
614
+ 'DNASE_ACTIVE': CenterMaskScorer(
615
+ requested_output=dna_output.OutputType.DNASE,
616
+ width=501,
617
+ aggregation_type=AggregationType.ACTIVE_SUM,
618
+ ),
619
+ 'CHIP_TF_ACTIVE': CenterMaskScorer(
620
+ requested_output=dna_output.OutputType.CHIP_TF,
621
+ width=501,
622
+ aggregation_type=AggregationType.ACTIVE_SUM,
623
+ ),
624
+ 'CHIP_HISTONE_ACTIVE': CenterMaskScorer(
625
+ requested_output=dna_output.OutputType.CHIP_HISTONE,
626
+ width=2001,
627
+ aggregation_type=AggregationType.ACTIVE_SUM,
628
+ ),
629
+ 'CAGE_ACTIVE': CenterMaskScorer(
630
+ requested_output=dna_output.OutputType.CAGE,
631
+ width=501,
632
+ aggregation_type=AggregationType.ACTIVE_SUM,
633
+ ),
634
+ 'PROCAP_ACTIVE': CenterMaskScorer(
635
+ requested_output=dna_output.OutputType.PROCAP,
636
+ width=501,
637
+ aggregation_type=AggregationType.ACTIVE_SUM,
638
+ ),
639
+ })
640
+
641
+
642
+ def get_recommended_scorers(
643
+ organism: dna_model_pb2.Organism,
644
+ ) -> list[VariantScorerTypes]:
645
+ """Returns the recommended variant scorers for a given organism."""
646
+ return [
647
+ scorer
648
+ for scorer in RECOMMENDED_VARIANT_SCORERS.values()
649
+ if organism in SUPPORTED_ORGANISMS[scorer.base_variant_scorer]
650
+ ]
651
+
652
+
653
+ def tidy_anndata(
654
+ adata: anndata.AnnData,
655
+ match_gene_strand: bool = True,
656
+ include_extended_metadata: bool = True,
657
+ ) -> pd.DataFrame:
658
+ """Formats an :class:`~anndata.AnnData` score as a tidy DataFrame.
659
+
660
+ This function converts the score output from an AnnData object into a
661
+ long-format pandas DataFrame, where each row represents:
662
+
663
+ - For non-gene-centric variant scorers: Score for a variant-track pair.
664
+ - For non-gene-centric interval scorers: Score for an interval-track pair.
665
+ - For gene-centric variant/interval scoring: Score for a
666
+ variant/interval-gene-track combination.
667
+
668
+ Args:
669
+ adata: An AnnData object containing scores.
670
+ match_gene_strand: If True (and using gene-centric scoring), rows with
671
+ mismatched gene and track strands are removed.
672
+ include_extended_metadata: If True, includes additional columns derived from
673
+ metadata specific to the output type, such as biosample name and type,
674
+ gtex tissue, transcription factor, and histone mark, if available. If
675
+ False, only includes minimal metadata columns required to unique identify
676
+ a track withing a given output type: track_name and track_strand.
677
+
678
+ Returns:
679
+ A pandas DataFrame with one score per row. The DataFrame includes
680
+ columns for variant ID (if applicable), scored interval, gene information
681
+ (if applicable), output type, variant/interval scorer, track name,
682
+ ontology term, assay type, track strand, and raw score. Additional metadata
683
+ such as biosample name and type, gtex tissue are also returned (where
684
+ available). See :func:`full_path_to.tidy_scores` for more details on the
685
+ returned columns.
686
+
687
+ Raises:
688
+ ValueError: If the input is not an AnnData object.
689
+ """
690
+ if not isinstance(adata, anndata.AnnData):
691
+ raise ValueError('Invalid input type. Must be an AnnData object.')
692
+
693
+ # Columns to include from the gene metadata. If the column did not
694
+ # exist in the original metadata (or if the scores do not have a concept
695
+ # of a gene), a column of all Nones is added.
696
+ gene_columns = [
697
+ 'gene_id',
698
+ 'gene_name',
699
+ 'gene_type',
700
+ 'gene_strand',
701
+ 'junction_Start',
702
+ 'junction_End',
703
+ ]
704
+ if math.prod(adata.X.shape) == 0:
705
+ # Scores are empty, so we return an empty dataframe.
706
+ return pd.DataFrame()
707
+ elif 'gene_id' in adata.obs and 'strand' in adata.obs:
708
+ # Scores are for a gene-based scorer.
709
+ obs = adata.obs.rename({'strand': 'gene_strand'}, axis=1)
710
+
711
+ # Remove patch number from gene_id.
712
+ obs['gene_id'] = obs['gene_id'].str.split('.', expand=True).get(0)
713
+ for col in gene_columns:
714
+ if col not in obs:
715
+ obs[col] = None
716
+ elif adata.X.shape[0] == 1 and adata.obs.empty:
717
+ # Scores are for a non-gene-based scorer.
718
+ obs = pd.DataFrame([[None] * len(gene_columns)], columns=gene_columns)
719
+ else:
720
+ raise ValueError('Scores contain gene metadata but no gene_id/strand.')
721
+
722
+ # Columns to include from the track metadata. Only added if the column
723
+ # appears in the original metadata.
724
+ var = adata.var.rename(
725
+ {'strand': 'track_strand', 'name': 'track_name'}, axis=1
726
+ )
727
+ track_columns = ['track_name', 'track_strand']
728
+ if include_extended_metadata:
729
+ extended_metadata_columns = [
730
+ 'Assay title',
731
+ 'ontology_curie',
732
+ 'biosample_name',
733
+ 'biosample_type',
734
+ 'biosample_life_stage',
735
+ 'gtex_tissue',
736
+ 'data_source',
737
+ 'endedness',
738
+ 'genetically_modified',
739
+ 'transcription_factor',
740
+ 'histone_mark',
741
+ ]
742
+ track_columns.extend([c for c in extended_metadata_columns if c in var])
743
+
744
+ # Construct score dataframe.
745
+ df = pd.merge(var, obs, how='cross')
746
+ df['scored_interval'] = adata.uns['interval']
747
+
748
+ # Add id and scorer information depending on the type of score.
749
+ if 'variant_scorer' in adata.uns:
750
+ df['variant_id'] = adata.uns['variant']
751
+ df['output_type'] = adata.uns['variant_scorer'].requested_output.name
752
+ df['variant_scorer'] = str(adata.uns['variant_scorer'])
753
+ id_columns = ['variant_id', 'scored_interval']
754
+ scorer_columns = ['output_type', 'variant_scorer']
755
+ elif 'interval_scorer' in adata.uns:
756
+ df['output_type'] = adata.uns['interval_scorer'].requested_output.name
757
+ df['interval_scorer'] = str(adata.uns['interval_scorer'])
758
+ id_columns = ['scored_interval']
759
+ scorer_columns = ['output_type', 'interval_scorer']
760
+ else:
761
+ raise ValueError(
762
+ 'Invalid scores, expected either variant_scorer or interval_scorer.'
763
+ )
764
+
765
+ # Formatting final touches.
766
+ df = df.loc[:, id_columns + gene_columns + scorer_columns + track_columns]
767
+ df['raw_score'] = adata.X.T.reshape((-1,))
768
+ if 'quantiles' in adata.layers:
769
+ df['quantile_score'] = adata.layers['quantiles'].T.reshape((-1,))
770
+
771
+ # Remove entries where DNA strands are mismatched. Note that we still retain
772
+ # all tracks that have strand '.' which indicates the data is unstranded.
773
+ if match_gene_strand:
774
+ mismatched_strands = (df['gene_strand'] == '+') & (
775
+ df['track_strand'] == '-'
776
+ ) | (df['gene_strand'] == '-') & (df['track_strand'] == '+')
777
+ df = df[~mismatched_strands].reset_index(drop=True)
778
+ return df.reset_index(drop=True)
779
+
780
+
781
+ def tidy_scores(
782
+ scores: Sequence[anndata.AnnData] | Sequence[Sequence[anndata.AnnData]],
783
+ match_gene_strand: bool = True,
784
+ include_extended_metadata: bool = True,
785
+ ) -> pd.DataFrame | None:
786
+ """Formats scores into a tidy (long) pandas DataFrame.
787
+
788
+ This function reformats variant scores into a more readable DataFrame with one
789
+ score per row. This function supports both scores generated from variant
790
+ scorers (e.g., the output of `score_variant` or `score_variants`) or interval
791
+ scorers (e.g., the output of `score_interval` or `score_intervals`).
792
+
793
+ It handles both variant/interval-centric scoring (producing one score row per
794
+ variant/interval-track pair) and gene-centric scoring (one score row per
795
+ variant/interval-gene-track combination).
796
+
797
+ The function accepts these score input types:
798
+
799
+ - A sequence of AnnData objects (e.g., output of `score_variant` with one or
800
+ more scorers).
801
+ - A nested sequence of AnnData objects (e.g., output of `score_variants`
802
+ with multiple variants).
803
+
804
+ Scores from multiple scorers or multiple variants/intervals are concatenated
805
+ together into a single pandas DataFrame, containing the union of all
806
+ applicable columns across scorers.
807
+
808
+ Args:
809
+ scores: Scoring output as either a sequence of AnnData objects, or a nested
810
+ sequence of AnnData objects (for example, the outputs of `score_variant`
811
+ and `score_variants`, respectively).
812
+ match_gene_strand: If True (and using gene-centric scoring), rows with
813
+ mismatched gene and track strands are removed.
814
+ include_extended_metadata: Argument passed to `tidy_anndata` to include
815
+ additional metadata columns where available.
816
+
817
+ Returns:
818
+ pd.DataFrame with columns:
819
+
820
+ - variant_id (when applicable): Variant of interest (e.g.
821
+ chr22:36201698:A>C).
822
+ - scored_interval: Genomic interval scored (e.g. chr22:36100000-36300000).
823
+ - gene_id: ENSEMBL gene identifier without version number.
824
+ (e.g. ENSG00000100342), or None if not applicable.
825
+ - gene_name: HGNC gene symbol (e.g. APOL1), or None if not applicable.
826
+ - gene_type: Gene biotype (e.g. protein_coding, lncRNA), or None if not
827
+ applicable.
828
+ - gene_strand: Strand of the gene ('+', '-', '.'), or None if not
829
+ applicable.
830
+ - output_type: Type of the output from the model (e.g. RNA_SEQ, DNASE).
831
+ - interval_scorer (when applicable): Name of the interval scorer used.
832
+ - variant_scorer (when applicable): Name of the variant scorer used.
833
+ - track_name: Name of the output track (e.g. UBERON:0036149 total
834
+ RNA-seq).
835
+ - track_strand: Strand of the track ('+', '-', or '.').
836
+ - ontology_curie: Ontology term for the cell type or tissue of the track
837
+ (e.g. UBERON:0036149), or NaN if not applicable.
838
+ - gtex_tissue: Name of the gtex tissue (e.g. Liver), or NaN if not
839
+ applicable.
840
+ - Assay title: Subtype of the assay (e.g., total RNA-seq), or NaN if not
841
+ applicable.
842
+ - biosample_name: Name of the biosample (e.g. liver), or NaN if not
843
+ applicable.
844
+ - biosample_type: Type of biosample (e.g. 'tissue' or 'primary cell'), or
845
+ NaN if not applicable.
846
+ - transcription_factor: Name of the transcription factor (e.g. 'CTCF'), or
847
+ NaN if not applicable.
848
+ - histone_mark: Name of the histological mark (e.g. 'H3K4ME3'), or NaN if
849
+ not applicable.
850
+ - raw_score: Raw variant score.
851
+ - quantile_score (when applicable): Quantile score.
852
+
853
+ Raises:
854
+ ValueError: If the input is not a valid type (sequence of AnnData or nested
855
+ sequence of AnnDatas).
856
+ """
857
+ if isinstance(scores, Sequence):
858
+ tidied_anndata = [
859
+ tidy_anndata(adata, match_gene_strand, include_extended_metadata)
860
+ for adata in itertools.chain.from_iterable(scores)
861
+ ]
862
+ if not tidied_anndata:
863
+ return None
864
+
865
+ concatenated_df = pd.concat(tidied_anndata, axis=0, ignore_index=True)
866
+ # Put the raw_score (and quantile_score when applicable) columns last.
867
+ last_columns = ['raw_score']
868
+ if 'quantile_score' in concatenated_df.columns:
869
+ last_columns.append('quantile_score')
870
+ return concatenated_df[
871
+ [col for col in concatenated_df.columns if col not in last_columns]
872
+ + last_columns
873
+ ]
874
+ else:
875
+ raise ValueError(
876
+ 'Invalid input type. Must be sequence of AnnDatas or nested sequence of'
877
+ ' AnnDatas.'
878
+ )
flax_model/alphagenome/_sdk/typing.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utility functions for type annotations."""
16
+
17
+ import importlib.metadata
18
+ from typing import TypeVar
19
+
20
+ import jaxtyping
21
+ import typeguard
22
+
23
+ _T = TypeVar('_T')
24
+
25
+
26
+ def jaxtyped(fn: _T) -> _T:
27
+ """Wrapper around jaxtyping.jaxtyped that uses typeguard iff typeguard < 3."""
28
+ try:
29
+ major, *_ = importlib.metadata.version('typeguard').split('.')
30
+ except importlib.metadata.PackageNotFoundError:
31
+ major = -1
32
+
33
+ # Only use jaxtyping if typeguard is < 3. See
34
+ # https://docs.kidger.site/jaxtyping/api/runtime-type-checking/#runtime-type-checking
35
+ # for more details.
36
+ if int(major) < 3:
37
+ return jaxtyping.jaxtyped(fn, typechecker=typeguard.typechecked)
38
+ else:
39
+ return fn
flax_model/alphagenome/_sdk/visualization/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Library of tools for visualizing with genomic model predictions."""
flax_model/alphagenome/evals/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 DeepMind Technologies Limited
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """AlphaGenome Evaluation Utilities."""
flax_model/alphagenome/evals/regression_metrics.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utility functions for experiments."""
16
+
17
+ from typing import Sequence
18
+ from flax_model.alphagenome._sdk import typing
19
+ import chex
20
+ import jax
21
+ import jax.numpy as jnp
22
+ from jaxtyping import ArrayLike, Float, PyTree # pylint: disable=g-importing-member, g-multiple-import
23
+ import numpy as np
24
+
25
+
26
+ @chex.dataclass
27
+ class _PearsonRState:
28
+ """State to compute PearsonR correlation coefficient."""
29
+
30
+ xy_sum: jax.Array
31
+ x_sum: jax.Array
32
+ xx_sum: jax.Array
33
+ y_sum: jax.Array
34
+ yy_sum: jax.Array
35
+ count: jax.Array
36
+
37
+ def __add__(self, other: '_PearsonRState') -> '_PearsonRState':
38
+ return jax.tree.map(lambda x, y: x + y, self, other)
39
+
40
+
41
+ def _pearsonr_initialize() -> '_PearsonRState':
42
+ """Initialize PearsonrState with zeros."""
43
+ return _PearsonRState(
44
+ xy_sum=np.zeros(()),
45
+ x_sum=np.zeros(()),
46
+ xx_sum=np.zeros(()),
47
+ y_sum=np.zeros(()),
48
+ yy_sum=np.zeros(()),
49
+ count=np.zeros(()),
50
+ )
51
+
52
+
53
+ def _pearsonr_update(
54
+ x: jax.Array,
55
+ y: jax.Array,
56
+ axis: Sequence[int] | int | None = None,
57
+ mask: jax.Array | None = None,
58
+ ) -> _PearsonRState:
59
+ """Construct PearsonrState by correlating two arrays."""
60
+ if mask is not None:
61
+ mask = jnp.astype(mask, bool)
62
+ return _PearsonRState(
63
+ xy_sum=jnp.sum(x * y, axis=axis, where=mask, dtype=jnp.float32),
64
+ x_sum=jnp.sum(x, axis=axis, where=mask, dtype=jnp.float32),
65
+ xx_sum=jnp.sum(jnp.square(x), axis=axis, where=mask, dtype=jnp.float32),
66
+ y_sum=jnp.sum(y, axis=axis, where=mask, dtype=jnp.float32),
67
+ yy_sum=jnp.sum(jnp.square(y), axis=axis, where=mask, dtype=jnp.float32),
68
+ count=jnp.sum(jnp.ones_like(x), axis=axis, where=mask, dtype=jnp.float32),
69
+ )
70
+
71
+
72
+ def _pearsonr_result(state: _PearsonRState) -> jax.Array:
73
+ """Get PearsonR correlation coeficient."""
74
+ x_mean = state.x_sum / state.count
75
+ y_mean = state.y_sum / state.count
76
+
77
+ covariance = state.xy_sum - state.count * x_mean * y_mean
78
+
79
+ x_var = state.xx_sum - state.count * x_mean * x_mean
80
+ y_var = state.yy_sum - state.count * y_mean * y_mean
81
+ variance = x_var**0.5 * y_var**0.5
82
+ eps = jnp.finfo(variance.dtype).eps # Avoid division by zero.
83
+ return covariance / (variance + eps)
84
+
85
+
86
+ @chex.dataclass
87
+ class RegressionState:
88
+ """State for accumulating regression statistics."""
89
+
90
+ pearsonr: _PearsonRState
91
+ pearsonr_log1p: _PearsonRState
92
+ sq_error: jax.Array
93
+ abs_error: jax.Array
94
+ count: jax.Array
95
+
96
+ def __add__(self, other: 'RegressionState') -> 'RegressionState':
97
+ return jax.tree.map(
98
+ lambda a, b: a + b,
99
+ self,
100
+ other,
101
+ )
102
+
103
+
104
+ def initialize_regression_metrics() -> RegressionState:
105
+ """Initialize metric state."""
106
+ return RegressionState(
107
+ pearsonr=_pearsonr_initialize(),
108
+ pearsonr_log1p=_pearsonr_initialize(),
109
+ sq_error=np.zeros(()),
110
+ abs_error=np.zeros(()),
111
+ count=np.zeros(()),
112
+ )
113
+
114
+
115
+ def update_regression_metrics(
116
+ y_true: jax.Array,
117
+ y_pred: jax.Array,
118
+ mask: jax.Array | None = None,
119
+ ) -> RegressionState:
120
+ y_true = jnp.astype(y_true, jnp.float32)
121
+ y_pred = jnp.astype(y_pred, jnp.float32)
122
+ return RegressionState(
123
+ pearsonr=_pearsonr_update(y_true, y_pred, mask=mask, axis=(-2, -3)),
124
+ pearsonr_log1p=_pearsonr_update(
125
+ jnp.log1p(y_true), jnp.log1p(y_pred), mask=mask, axis=(-2, -3)
126
+ ),
127
+ sq_error=jnp.sum(
128
+ jnp.square(y_true - y_pred),
129
+ axis=(-2, -3),
130
+ where=mask,
131
+ dtype=jnp.float32,
132
+ ),
133
+ abs_error=jnp.sum(
134
+ jnp.abs(y_true - y_pred),
135
+ axis=(-2, -3),
136
+ where=mask,
137
+ dtype=jnp.float32,
138
+ ),
139
+ count=jnp.sum(
140
+ jnp.ones_like(y_true), axis=(-2, -3), where=mask, dtype=jnp.float32
141
+ ),
142
+ )
143
+
144
+
145
+ def finalize_regression_metrics(
146
+ state: PyTree[RegressionState],
147
+ ) -> PyTree[jax.Array]:
148
+ """Compute final metrics from accumulated state."""
149
+
150
+ def _finalize(state: RegressionState) -> PyTree[jax.Array]:
151
+ return {
152
+ 'pearsonr': (
153
+ _pearsonr_result(state.pearsonr).mean(
154
+ where=state.pearsonr.count > 0
155
+ )
156
+ ),
157
+ 'pearsonr_log1p': (
158
+ _pearsonr_result(state.pearsonr_log1p).mean(
159
+ where=state.pearsonr_log1p.count > 0
160
+ )
161
+ ),
162
+ 'mse': jnp.mean(state.sq_error / state.count, where=state.count > 0),
163
+ 'mae': jnp.mean(state.abs_error / state.count, where=state.count > 0),
164
+ }
165
+
166
+ return jax.tree.map(
167
+ _finalize, state, is_leaf=lambda x: isinstance(x, RegressionState)
168
+ )
169
+
170
+
171
+ def reduce_regression_metrics(
172
+ previous_metrics: PyTree[RegressionState],
173
+ current_metrics: PyTree[RegressionState],
174
+ ) -> RegressionState:
175
+ """Reduce metrics from a single device to a single scalar."""
176
+ return jax.tree.map(
177
+ lambda x, y: x + y,
178
+ previous_metrics,
179
+ current_metrics,
180
+ is_leaf=lambda x: isinstance(x, RegressionState),
181
+ )
182
+
183
+
184
+ @typing.jaxtyped
185
+ def crop_sequence_length(
186
+ x: Float[ArrayLike, '... S D'], *, target_length: int
187
+ ) -> Float[ArrayLike, '... {target_length} D']:
188
+ """Crops an array to match the target length along the sequence dimension."""
189
+ sequence_axis = -2
190
+ if x.shape[sequence_axis] < target_length:
191
+ raise ValueError(
192
+ f'Input length {x.shape[sequence_axis]} is shorter than the requested'
193
+ f' cropped length of {target_length}.'
194
+ )
195
+ elif x.shape[sequence_axis] == target_length:
196
+ return x
197
+ else:
198
+ ltrim = (x.shape[sequence_axis] - target_length) // 2
199
+ rtrim = x.shape[sequence_axis] - target_length - ltrim
200
+ slices = [
201
+ slice(None),
202
+ ] * len(x.shape)
203
+ slices[sequence_axis] = slice(ltrim, -rtrim)
204
+ return x[tuple(slices)]
flax_model/alphagenome/evals/track_prediction.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Evaluates AlphaGenome track prediction performance."""
16
+
17
+ from collections.abc import Iterator
18
+ import pprint
19
+ from typing import Callable, Sequence
20
+ from absl import app
21
+ from absl import logging
22
+ from flax_model.alphagenome._sdk.data import fold_intervals
23
+ from flax_model.alphagenome._sdk.models import dna_output
24
+ from flax_model.alphagenome.evals import regression_metrics
25
+ from flax_model.alphagenome.io import bundles as bundles_lib
26
+ from flax_model.alphagenome.io import dataset
27
+ from flax_model.alphagenome.model import dna_model
28
+ from flax_model.alphagenome.model import model as model_lib
29
+ from flax_model.alphagenome.model import schemas
30
+ from flax_model.alphagenome.model.metadata import metadata as metadata_lib
31
+ import haiku as hk
32
+ import jax
33
+ from jax import sharding
34
+ from jax.experimental import mesh_utils
35
+ from jaxtyping import PyTree # pylint: disable=g-importing-member
36
+ import jmp
37
+ import kagglehub
38
+ import orbax.checkpoint as ocp
39
+ import pandas as pd
40
+ import tensorflow as tf
41
+
42
+
43
+ PS = sharding.PartitionSpec
44
+ PredictFn = Callable[
45
+ [
46
+ hk.Params,
47
+ hk.State,
48
+ jax.Array,
49
+ jax.Array,
50
+ ],
51
+ PyTree[jax.Array],
52
+ ]
53
+
54
+ _SUBSET = fold_intervals.Subset.VALID
55
+ _LOG_FREQUENCY = 5
56
+ _EVAL_BUNDLES = [
57
+ bundles_lib.BundleName.ATAC,
58
+ bundles_lib.BundleName.CAGE,
59
+ bundles_lib.BundleName.CHIP_HISTONE,
60
+ bundles_lib.BundleName.CHIP_TF,
61
+ bundles_lib.BundleName.DNASE,
62
+ bundles_lib.BundleName.PROCAP,
63
+ bundles_lib.BundleName.RNA_SEQ,
64
+ ]
65
+
66
+
67
+ def load_model(
68
+ model_version: dna_model.ModelVersion = dna_model.ModelVersion.FOLD_0,
69
+ ) -> tuple[hk.Params, hk.State, PredictFn]:
70
+ """Loads the model consiting of params, state and predict function."""
71
+ checkpoint_path = kagglehub.model_download(
72
+ f'google/alphagenome/jax/{model_version.name.lower()}'
73
+ )
74
+ params, state = ocp.StandardCheckpointer().restore(checkpoint_path)
75
+ metadata = {
76
+ organism: metadata_lib.load(organism) for organism in dna_model.Organism
77
+ }
78
+
79
+ @hk.transform_with_state
80
+ def forward(dna_sequence, organism_index):
81
+ policy = jmp.get_policy('params=float32,compute=bfloat16,output=bfloat16')
82
+ with hk.mixed_precision.push_policy(model_lib.AlphaGenome, policy):
83
+ return model_lib.AlphaGenome(metadata)(dna_sequence, organism_index)
84
+
85
+ @jax.jit(
86
+ in_shardings=(PS(), PS(), PS('data'), PS('data')),
87
+ out_shardings=PS('data'),
88
+ )
89
+ def predict(params, state, dna_sequence, organism_index) -> PyTree[jax.Array]:
90
+ (predictions, _), _ = forward.apply(
91
+ params, state, None, dna_sequence, organism_index
92
+ )
93
+ predictions = dna_model.extract_predictions(predictions)
94
+ return predictions
95
+
96
+ return params, state, predict
97
+
98
+
99
+ def create_eval_step(
100
+ predict_fn: PredictFn, bundles: Sequence[bundles_lib.BundleName]
101
+ ):
102
+ """Returns the eval step function."""
103
+
104
+ @jax.jit(
105
+ in_shardings=(PS(), PS(), PS('data')),
106
+ out_shardings=PS(),
107
+ )
108
+ def eval_step(params, state, batch: schemas.DataBatch):
109
+ predictions = predict_fn(
110
+ params, state, batch.dna_sequence, batch.organism_index
111
+ )
112
+ metrics_step = {}
113
+ for bundle in bundles:
114
+ targets_true, mask = batch.get_genome_tracks(bundle)
115
+ targets_pred = predictions[dna_output.OutputType[bundle.name]]
116
+ targets_pred = regression_metrics.crop_sequence_length(
117
+ targets_pred, target_length=targets_true.shape[-2]
118
+ )
119
+ metrics_step[bundle.name] = regression_metrics.update_regression_metrics(
120
+ targets_true, targets_pred, mask
121
+ )
122
+ return metrics_step
123
+
124
+ return eval_step
125
+
126
+
127
+ def evaluate(
128
+ params: hk.Params,
129
+ state: hk.State,
130
+ predict_fn: PredictFn,
131
+ bundles: Sequence[bundles_lib.BundleName],
132
+ dataset_iterator: Iterator[tuple[schemas.DataBatch, dataset.BatchMetadata]],
133
+ ):
134
+ """Evaluates the model."""
135
+ # Setup Mesh.
136
+ devices = mesh_utils.create_device_mesh((jax.local_device_count(),))
137
+ mesh = jax.sharding.Mesh(devices, axis_names=('data',))
138
+ sharding_rep = sharding.NamedSharding(mesh, PS())
139
+ sharding_data = sharding.NamedSharding(mesh, PS('data'))
140
+
141
+ # Replicate params and state.
142
+ params = jax.device_put(params, sharding_rep)
143
+ state = jax.device_put(state, sharding_rep)
144
+
145
+ eval_step = create_eval_step(predict_fn, bundles)
146
+ metrics = {
147
+ b.name: regression_metrics.initialize_regression_metrics()
148
+ for b in bundles
149
+ }
150
+ num_elements = 0
151
+
152
+ for i, (batch, _) in enumerate(dataset_iterator):
153
+ num_elements += batch.dna_sequence.shape[0]
154
+ if i % _LOG_FREQUENCY == 1:
155
+ m = pprint.pformat(
156
+ regression_metrics.finalize_regression_metrics(metrics)
157
+ )
158
+ logging.info('step %d: %s', i, m)
159
+
160
+ with jax.set_mesh(mesh):
161
+ batch = jax.device_put(batch, sharding_data)
162
+ step_metrics = eval_step(params, state, batch)
163
+
164
+ # Accumulate metrics.
165
+ step_metrics = jax.device_get(step_metrics)
166
+ metrics = regression_metrics.reduce_regression_metrics(
167
+ metrics, step_metrics
168
+ )
169
+ logging.info('num_elements: %d', num_elements)
170
+ return regression_metrics.finalize_regression_metrics(metrics)
171
+
172
+
173
+ def run(
174
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
175
+ model_version: dna_model.ModelVersion = dna_model.ModelVersion.FOLD_0,
176
+ ) -> pd.DataFrame:
177
+ """Runs the track prediction experiment."""
178
+ logging.info('Starting track prediction experiment.')
179
+ params, state, predict_fn = load_model(model_version)
180
+ dataset_iterator = dataset.get_numpy_dataset_iterator(
181
+ batch_size=jax.local_device_count(),
182
+ organism=organism,
183
+ model_version=model_version,
184
+ bundles=_EVAL_BUNDLES,
185
+ subset=_SUBSET,
186
+ )
187
+ results = evaluate(params, state, predict_fn, _EVAL_BUNDLES, dataset_iterator)
188
+ flattened_results = {}
189
+ for bundle, result in results.items():
190
+ for metric, value in result.items():
191
+ logging.info('bundle: %s, metric: %s, value: %s', bundle, metric, value)
192
+ flattened_results[f'{bundle}_{metric}'] = value
193
+ df = pd.DataFrame(
194
+ {'metric': flattened_results.keys(), 'value': flattened_results.values()}
195
+ )
196
+ return df
197
+
198
+
199
+ if __name__ == '__main__':
200
+ # Hide local GPUs from TF. TF is only used for data loading.
201
+ tf.config.set_visible_devices([], 'GPU')
202
+ app.run(lambda _: run())
flax_model/alphagenome/io/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utilities for reading and writing data."""
flax_model/alphagenome/io/bundles.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Bundle names and their associated keys and resolutions."""
16
+
17
+ import enum
18
+ import tensorflow as tf
19
+
20
+
21
+ class BundleName(enum.Enum):
22
+ """Bundle names."""
23
+
24
+ ATAC = 'atac'
25
+ DNASE = 'dnase'
26
+ PROCAP = 'procap'
27
+ CAGE = 'cage'
28
+ RNA_SEQ = 'rna_seq'
29
+ CHIP_TF = 'chip_tf'
30
+ CHIP_HISTONE = 'chip_histone'
31
+ CONTACT_MAPS = 'contact_maps'
32
+ SPLICE_SITES_CLASSIFICATION = 'splice_sites'
33
+ SPLICE_SITES_USAGE = 'splice_site_usage'
34
+ SPLICE_SITES_JUNCTION = 'splice_junctions'
35
+ SPLICE_SITES_POSITIONS = 'splice_site_positions'
36
+
37
+ def get_dtypes(self) -> dict[str, tf.DType]:
38
+ """Returns the keys and dtypes for the given bundle."""
39
+ match self:
40
+ case BundleName.ATAC:
41
+ return {'atac': tf.bfloat16, 'atac_mask': tf.bool}
42
+ case BundleName.DNASE:
43
+ return {'dnase': tf.bfloat16, 'dnase_mask': tf.bool}
44
+ case BundleName.PROCAP:
45
+ return {'procap': tf.bfloat16, 'procap_mask': tf.bool}
46
+ case BundleName.CAGE:
47
+ return {'cage': tf.bfloat16, 'cage_mask': tf.bool}
48
+ case BundleName.RNA_SEQ:
49
+ return {
50
+ 'rna_seq': tf.bfloat16,
51
+ 'rna_seq_mask': tf.bool,
52
+ 'rna_seq_strand': tf.int32,
53
+ }
54
+ case BundleName.CHIP_TF:
55
+ return {'chip_tf': tf.float32, 'chip_tf_mask': tf.bool}
56
+ case BundleName.CHIP_HISTONE:
57
+ return {'chip_histone': tf.float32, 'chip_histone_mask': tf.bool}
58
+ case BundleName.CONTACT_MAPS:
59
+ return {'contact_maps': tf.float32}
60
+ case BundleName.SPLICE_SITES_CLASSIFICATION:
61
+ return {'splice_sites': tf.bool}
62
+ case BundleName.SPLICE_SITES_USAGE:
63
+ return {'splice_site_usage': tf.float16}
64
+ case BundleName.SPLICE_SITES_JUNCTION:
65
+ return {'splice_junctions': tf.float32}
66
+ case BundleName.SPLICE_SITES_POSITIONS:
67
+ return {'splice_site_positions': tf.int32}
68
+ case _:
69
+ raise ValueError(f'Unknown bundle name: {self}')
70
+
71
+ def get_resolution(self) -> int:
72
+ """Returns the resolutions for the given bundle."""
73
+ match self:
74
+ case (
75
+ BundleName.ATAC
76
+ | BundleName.DNASE
77
+ | BundleName.PROCAP
78
+ | BundleName.CAGE
79
+ | BundleName.RNA_SEQ
80
+ | BundleName.SPLICE_SITES_CLASSIFICATION
81
+ | BundleName.SPLICE_SITES_USAGE
82
+ | BundleName.SPLICE_SITES_JUNCTION
83
+ | BundleName.SPLICE_SITES_POSITIONS
84
+ ):
85
+ return 1
86
+ case BundleName.CHIP_TF | BundleName.CHIP_HISTONE:
87
+ return 128
88
+ case BundleName.CONTACT_MAPS:
89
+ return 2_048
90
+ case _:
91
+ raise ValueError(f'Unknown bundle name: {self}')
flax_model/alphagenome/io/dataset.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Reading AlphaGenome data from TFRecords.
16
+
17
+ This module provides functions to load AlphaGenome datasets from TFRecord files.
18
+ Each TFRecord file contains data from a particular bundle (see `bundles.py`)
19
+ for a set of intervals.
20
+
21
+ We recommend using `get_numpy_dataset_iterator` to load the data for a
22
+ particular organism, fold split, and subset. The iterator yields batches of
23
+ data, where each batch is a tuple of `schemas.DataBatch` and a metadata
24
+ dictionary containing the chromosome, start, and end of each interval.
25
+ """
26
+
27
+ from collections.abc import Iterator, Mapping
28
+ import functools
29
+ import os
30
+ import re
31
+ from typing import Any, Sequence
32
+
33
+ from flax_model.alphagenome._sdk.data import fold_intervals
34
+ from flax_model.alphagenome._sdk.models import dna_model
35
+ from flax_model.alphagenome.io import bundles as bundles_lib
36
+ from flax_model.alphagenome.model import dna_model as research_dna_model
37
+ from flax_model.alphagenome.model import schemas
38
+ from etils import epath
39
+ import numpy as np
40
+ import pandas as pd
41
+ import tensorflow as tf
42
+
43
+ _DEFAULT_PATH = 'gs:///alphagenome-datasets/v1/train/'
44
+
45
+ BatchMetadata = Mapping[str, Any]
46
+
47
+ _DNA_SEQUENCE_DTYPE = tf.float32
48
+ _DNA_SEQUENCE_FEATURE_SPEC = {
49
+ 'dna_sequence': tf.io.FixedLenFeature([], tf.string)
50
+ }
51
+ _INTERVAL_FEATURE_SPEC = {
52
+ 'interval/chromosome': tf.io.FixedLenFeature([], tf.string),
53
+ 'interval/start': tf.io.FixedLenFeature([], tf.int64),
54
+ 'interval/end': tf.io.FixedLenFeature([], tf.int64),
55
+ }
56
+ _FILENAME_REGEX = re.compile(
57
+ r'data_(?P<chr>.+)_(?P<shard>\d+)-(?P<num_shards>\d+)\.gz\.tfrecord'
58
+ )
59
+
60
+
61
+ def get_tfrecords_df(
62
+ *,
63
+ organism: dna_model.Organism | None = None,
64
+ bundle: bundles_lib.BundleName | None = None,
65
+ fold_split: dna_model.ModelVersion | None = None,
66
+ subset: fold_intervals.Subset | None = None,
67
+ chromosome: str | None = None,
68
+ path: str | os.PathLike[str] | None = None,
69
+ ) -> pd.DataFrame:
70
+ """Return a dataframe with metadata about the TFRecord files.
71
+
72
+ Args:
73
+ organism: The organism to load. If None, all organisms are loaded.
74
+ bundle: The bundle to load. If None, all bundles are loaded.
75
+ fold_split: The fold split to load. If None, all fold splits are loaded.
76
+ subset: The subset to load. If None, all subsets are loaded.
77
+ chromosome: The chromosome to load. If None, all chromosomes are loaded.
78
+ path: The path to the TFRecord files. If None, the default path is used.
79
+ """
80
+ organism_pattern = organism.name if organism is not None else '*'
81
+ fold_split_pattern = fold_split.name if fold_split is not None else '*'
82
+ subset_pattern = subset.name if subset is not None else '*'
83
+ chromosome_pattern = chromosome if chromosome is not None else '*'
84
+ bundle_pattern = bundle.value.upper() if bundle is not None else '*'
85
+ glob_pattern = '/'.join([
86
+ fold_split_pattern,
87
+ organism_pattern,
88
+ subset_pattern,
89
+ bundle_pattern,
90
+ f'data_{chromosome_pattern}_*-*.gz.tfrecord',
91
+ ])
92
+ tfrecord_paths = epath.Path(path or _DEFAULT_PATH).glob(glob_pattern)
93
+
94
+ def _parse_path(tfrecord_path: epath.Path):
95
+ base_name = tfrecord_path.name
96
+ match_ = _FILENAME_REGEX.match(base_name)
97
+ if not match_:
98
+ raise ValueError(f'Could not parse metadata for file: {base_name}')
99
+
100
+ parsed = match_.groupdict()
101
+ metadata = {
102
+ 'organism': tfrecord_path.parts[-4],
103
+ 'bundle': tfrecord_path.parts[-2],
104
+ 'fold_split': tfrecord_path.parts[-5],
105
+ 'subset': tfrecord_path.parts[-3],
106
+ 'chromosome': parsed['chr'],
107
+ 'shard': int(parsed['shard']),
108
+ 'num_shards': int(parsed['num_shards']),
109
+ 'path': str(tfrecord_path),
110
+ }
111
+ return pd.DataFrame(metadata, index=[0])
112
+
113
+ if not tfrecord_paths:
114
+ return pd.DataFrame()
115
+
116
+ return pd.concat(
117
+ [_parse_path(epath.Path(p)) for p in tfrecord_paths]
118
+ ).reset_index(drop=True)
119
+
120
+
121
+ def _get_parse_function(bundle: bundles_lib.BundleName):
122
+ """Get parse function for a given output type."""
123
+ feature_spec = (
124
+ _DNA_SEQUENCE_FEATURE_SPEC
125
+ | _INTERVAL_FEATURE_SPEC
126
+ | {
127
+ key: tf.io.FixedLenFeature([], tf.string)
128
+ for key in bundle.get_dtypes().keys()
129
+ }
130
+ )
131
+ output_dtypes = bundle.get_dtypes() | {'dna_sequence': _DNA_SEQUENCE_DTYPE}
132
+
133
+ def _parse(proto):
134
+ example = tf.io.parse_single_example(proto, feature_spec)
135
+ for key, dtype in output_dtypes.items():
136
+ example[key] = tf.io.parse_tensor(example[key], dtype)
137
+ return example
138
+
139
+ return _parse
140
+
141
+
142
+ def _get_tfrecords_dataset(
143
+ paths: Sequence[str | os.PathLike[str]], bundle: bundles_lib.BundleName
144
+ ) -> tf.data.Dataset:
145
+ """Returns a dataset for a given output type from a sequence of paths."""
146
+ parser = _get_parse_function(bundle)
147
+
148
+ def _get(p):
149
+ ds = tf.data.TFRecordDataset(p, compression_type='GZIP')
150
+ ds = ds.map(parser, num_parallel_calls=tf.data.AUTOTUNE)
151
+ return ds
152
+
153
+ ds = _get(paths[0])
154
+ for p in paths[1:]:
155
+ ds_next = _get(p)
156
+ ds = ds.concatenate(ds_next)
157
+ return ds
158
+
159
+
160
+ def create_dataset(
161
+ *,
162
+ organism: dna_model.Organism,
163
+ fold_split: dna_model.ModelVersion,
164
+ subset: fold_intervals.Subset,
165
+ bundles: Sequence[bundles_lib.BundleName] | None = None,
166
+ path: str | os.PathLike[str] | None = None,
167
+ ) -> tf.data.Dataset:
168
+ """Returns AlphaGenome dataset for a given organism, fold and subset.
169
+
170
+ Args:
171
+ organism: The organism to load.
172
+ fold_split: The fold split to load.
173
+ subset: The subset to load.
174
+ bundles: The bundles to load. If None, all bundles are loaded.
175
+ path: The path to the TFRecord files. If None, the default path is used.
176
+ """
177
+ bundles = bundles or [None]
178
+ records = []
179
+ for bundle in bundles:
180
+ records.append(
181
+ get_tfrecords_df(
182
+ organism=organism,
183
+ bundle=bundle,
184
+ fold_split=fold_split,
185
+ subset=subset,
186
+ path=path,
187
+ )
188
+ )
189
+ df = pd.concat(records)
190
+ num_paths = df.groupby('bundle').agg('path').count()
191
+ if num_paths.nunique() != 1:
192
+ raise ValueError(
193
+ f'Number of TFRecord files per bundle is not the same: {num_paths}'
194
+ )
195
+ dataset_per_bundle = []
196
+ bundles = df['bundle'].unique()
197
+ for bundle in bundles:
198
+ dft = df[df['bundle'] == bundle].sort_values('shard')
199
+ if dft.empty:
200
+ raise ValueError(f'No data found for {bundle=}.')
201
+ dataset_per_bundle.append(
202
+ _get_tfrecords_dataset(
203
+ dft['path'].tolist(), bundles_lib.BundleName(bundle.lower())
204
+ )
205
+ )
206
+
207
+ # Zip datasets across bundles.
208
+ return tf.data.Dataset.zip(*dataset_per_bundle)
209
+
210
+
211
+ def _parse_batch(
212
+ element,
213
+ bundles: Sequence[bundles_lib.BundleName] | None,
214
+ organism_index: int,
215
+ batch_size: int,
216
+ ) -> tuple[schemas.DataBatch, BatchMetadata]:
217
+ """Parses a raw dataset element into Input and Target schemas."""
218
+
219
+ if bundles is None:
220
+ bundles = list(bundles_lib.BundleName)
221
+ if len(bundles) == 1:
222
+ element = (element,)
223
+
224
+ merged_data = functools.reduce(lambda x, y: x | y, element)
225
+ organism_index = np.full((batch_size,), organism_index, dtype=np.int32)
226
+ metadata = {
227
+ 'interval/chromosome': merged_data.pop('interval/chromosome'),
228
+ 'interval/start': merged_data.pop('interval/start'),
229
+ 'interval/end': merged_data.pop('interval/end'),
230
+ }
231
+ batch = schemas.DataBatch(organism_index=organism_index, **merged_data)
232
+ return batch, metadata
233
+
234
+
235
+ def get_numpy_dataset_iterator(
236
+ *,
237
+ batch_size: int,
238
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
239
+ model_version: dna_model.ModelVersion = dna_model.ModelVersion.FOLD_0,
240
+ subset: fold_intervals.Subset = fold_intervals.Subset.VALID,
241
+ bundles: Sequence[bundles_lib.BundleName] | None = None,
242
+ path: str | os.PathLike[str] | None = None,
243
+ ) -> Iterator[tuple[schemas.DataBatch, BatchMetadata]]:
244
+ """Yields numpy batches of data from the dataset."""
245
+ ds = create_dataset(
246
+ organism=organism,
247
+ fold_split=model_version,
248
+ subset=subset,
249
+ bundles=bundles,
250
+ path=path,
251
+ )
252
+ organism_index = research_dna_model.convert_to_organism_index(organism)
253
+ ds = ds.batch(batch_size, drop_remainder=True).prefetch(tf.data.AUTOTUNE)
254
+ for element in ds.as_numpy_iterator():
255
+ yield _parse_batch(element, bundles, organism_index, batch_size)
flax_model/alphagenome/io/dataset_test.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import pathlib
15
+
16
+ from absl.testing import absltest
17
+ from absl.testing import parameterized
18
+ from flax_model.alphagenome._sdk.data import fold_intervals
19
+ from flax_model.alphagenome._sdk.data import genome
20
+ from flax_model.alphagenome._sdk.models import dna_model
21
+ from flax_model.alphagenome.io import bundles
22
+ from flax_model.alphagenome.io import dataset
23
+ from flax_model.alphagenome.model import schemas
24
+ import jax
25
+ import jax.numpy as jnp
26
+ import numpy as np
27
+ import tensorflow as tf
28
+
29
+
30
+ def _bytes_feature(value):
31
+ """Returns a bytes_list from a string / byte."""
32
+ if isinstance(value, type(tf.constant(0))):
33
+ value = value.numpy()
34
+ return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
35
+
36
+
37
+ def _int64_feature(value):
38
+ """Returns an int64_list from a bool / enum / int / uint."""
39
+ return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
40
+
41
+
42
+ def to_tf_example(data):
43
+ """Creates a tf.train.Example message from a data dictionary."""
44
+ features = {}
45
+ for key, value in data.items():
46
+ if isinstance(value, int):
47
+ features[key] = _int64_feature(value)
48
+ elif isinstance(value, str):
49
+ features[key] = _bytes_feature(value.encode('utf-8'))
50
+ elif isinstance(value, np.ndarray):
51
+ features[key] = _bytes_feature(tf.io.serialize_tensor(value).numpy())
52
+ else:
53
+ raise ValueError(f'Unsupported data type for key {key}: {type(value)}')
54
+ return tf.train.Example(
55
+ features=tf.train.Features(feature=features)
56
+ ).SerializeToString()
57
+
58
+
59
+ def _write_tfrecord(path: pathlib.Path, data_list):
60
+ """Writes a list of data to a TFRecord file."""
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ options = tf.io.TFRecordOptions(compression_type='GZIP')
63
+ with tf.io.TFRecordWriter(str(path), options=options) as writer:
64
+ for data in data_list:
65
+ writer.write(to_tf_example(data))
66
+
67
+
68
+ class LoadDataTest(parameterized.TestCase):
69
+
70
+ def setUp(self):
71
+ super().setUp()
72
+ self.tmpdir = self.create_tempdir().full_path
73
+ self._num_channels = 7
74
+ self._seq_len = int(2**5)
75
+ self._num_shards = 2
76
+ self._intervals = {
77
+ 'chr1': {
78
+ '1': [
79
+ genome.Interval(
80
+ start=10, end=10 + self._seq_len, chromosome='chr1'
81
+ ),
82
+ genome.Interval(
83
+ start=100, end=100 + self._seq_len, chromosome='chr1'
84
+ ),
85
+ ],
86
+ '2': [
87
+ genome.Interval(
88
+ start=200, end=200 + self._seq_len, chromosome='chr1'
89
+ ),
90
+ ],
91
+ },
92
+ 'chr3': {
93
+ '1': [
94
+ genome.Interval(
95
+ start=30, end=30 + self._seq_len, chromosome='chr3'
96
+ ),
97
+ ],
98
+ '2': [
99
+ genome.Interval(
100
+ start=130, end=130 + self._seq_len, chromosome='chr3'
101
+ ),
102
+ genome.Interval(
103
+ start=230, end=230 + self._seq_len, chromosome='chr3'
104
+ ),
105
+ ],
106
+ },
107
+ }
108
+ self._organism = dna_model.Organism.HOMO_SAPIENS
109
+ self._fold_split = dna_model.ModelVersion.FOLD_0
110
+ self._subset = fold_intervals.Subset.TRAIN
111
+ self._bundles = [
112
+ bundles.BundleName.ATAC,
113
+ bundles.BundleName.RNA_SEQ,
114
+ ]
115
+ self._create_dummy_files()
116
+
117
+ def _create_dummy_files(self):
118
+ """Creates data for two bundles in two chromosomes."""
119
+ for bundle in self._bundles:
120
+ for chromosome, shard_intervals_map in self._intervals.items():
121
+ for shard_idx, intervals in shard_intervals_map.items():
122
+ data_list = []
123
+ for interval in intervals:
124
+ data = {
125
+ 'dna_sequence': np.zeros((self._seq_len, 4), dtype=np.float32),
126
+ 'interval/chromosome': interval.chromosome,
127
+ 'interval/start': interval.start,
128
+ 'interval/end': interval.end,
129
+ f'{bundle.value}': np.zeros(
130
+ (self._seq_len, self._num_channels), dtype=jnp.bfloat16
131
+ ),
132
+ f'{bundle.value}_mask': np.ones(
133
+ (1, self._num_channels), dtype=bool
134
+ ),
135
+ }
136
+ if bundle == bundles.BundleName.RNA_SEQ:
137
+ data['rna_seq_strand'] = np.zeros(
138
+ (1, self._num_channels), dtype=np.int32
139
+ )
140
+ data_list.append(data)
141
+
142
+ path = (
143
+ pathlib.Path(self.tmpdir)
144
+ / self._fold_split.name
145
+ / self._organism.name
146
+ / self._subset.name
147
+ / bundle.name
148
+ / f'data_{chromosome}_{shard_idx}-{self._num_shards}.gz.tfrecord'
149
+ )
150
+ _write_tfrecord(path, data_list)
151
+
152
+ def test_get_tfrecords_df(self):
153
+ df = dataset.get_tfrecords_df(path=self.tmpdir)
154
+ self.assertLen(df, 8)
155
+ self.assertSameElements(df.organism, ['HOMO_SAPIENS'])
156
+ self.assertSameElements(df.bundle, ['ATAC', 'RNA_SEQ'])
157
+ self.assertSameElements(df.fold_split, ['FOLD_0'])
158
+ self.assertSameElements(df.subset, ['TRAIN'])
159
+ self.assertSameElements(df.chromosome, ['chr1', 'chr3'])
160
+ self.assertSameElements(df.shard, [1, 2])
161
+
162
+ @parameterized.parameters(True, False)
163
+ def test_create_dataset(self, shuffle_dataset: bool):
164
+ ds = dataset.create_dataset(
165
+ organism=self._organism,
166
+ fold_split=self._fold_split,
167
+ subset=self._subset,
168
+ bundles=self._bundles,
169
+ path=self.tmpdir,
170
+ )
171
+ if shuffle_dataset:
172
+ ds = ds.shuffle(buffer_size=100)
173
+ ds_iterator = ds.as_numpy_iterator()
174
+ intervals = []
175
+
176
+ # 6 intervals in total: 3 in chr1, 3 in chr3
177
+ for _ in range(6):
178
+ data = next(ds_iterator)
179
+ self.assertLen(data, 2) # 2 bundles
180
+ data_atac, data_rna_seq = (
181
+ (data[0], data[1])
182
+ if bundles.BundleName.ATAC.value in data[0]
183
+ else (data[1], data[0])
184
+ )
185
+
186
+ self.assertIn('atac', data_atac)
187
+ self.assertIn('rna_seq', data_rna_seq)
188
+ self.assertEqual(
189
+ data_atac['interval/chromosome'], data_rna_seq['interval/chromosome']
190
+ )
191
+ self.assertEqual(
192
+ data_atac['interval/start'], data_rna_seq['interval/start']
193
+ )
194
+ self.assertEqual(data_atac['interval/end'], data_rna_seq['interval/end'])
195
+ intervals.append(
196
+ genome.Interval(
197
+ start=data_atac['interval/start'],
198
+ end=data_atac['interval/end'],
199
+ chromosome=data_atac['interval/chromosome'].decode('utf-8'),
200
+ )
201
+ )
202
+ self.assertEqual(data_atac['atac'].dtype, tf.bfloat16)
203
+ self.assertEqual(data_rna_seq['rna_seq'].dtype, tf.bfloat16)
204
+
205
+ def _interval_to_tuple(interval):
206
+ # Convert interval to tuple to check equality.
207
+ return (interval.chromosome, interval.start, interval.end)
208
+
209
+ all_intervals = jax.tree.reduce(
210
+ lambda x, y: x + y,
211
+ self._intervals,
212
+ is_leaf=lambda x: isinstance(x, list),
213
+ )
214
+ self.assertEqual(
215
+ set(_interval_to_tuple(i) for i in intervals),
216
+ set(_interval_to_tuple(i) for i in all_intervals),
217
+ )
218
+
219
+ with self.subTest('Dataset length is correct'):
220
+ with self.assertRaises(StopIteration):
221
+ next(ds_iterator)
222
+
223
+ @parameterized.parameters(
224
+ ([bundles.BundleName.ATAC],),
225
+ ([bundles.BundleName.ATAC, bundles.BundleName.RNA_SEQ],),
226
+ )
227
+ def test_get_numpy_dataset_iterator(self, requested_bundles):
228
+ batch_size = 2
229
+ ds_iterator = dataset.get_numpy_dataset_iterator(
230
+ batch_size=batch_size,
231
+ organism=self._organism,
232
+ model_version=self._fold_split,
233
+ subset=self._subset,
234
+ bundles=requested_bundles,
235
+ path=self.tmpdir,
236
+ )
237
+
238
+ num_batches = 0
239
+ for batch, metadata in ds_iterator:
240
+ self.assertIsInstance(batch, schemas.DataBatch)
241
+ self.assertEqual(batch.dna_sequence.shape[0], batch_size)
242
+ self.assertEqual(batch.organism_index.shape[0], batch_size)
243
+ for bundle in requested_bundles:
244
+ self.assertIsNotNone(getattr(batch, bundle.value))
245
+ self.assertIsNotNone(getattr(batch, f'{bundle.value}_mask'))
246
+ self.assertLen(metadata, 3)
247
+ self.assertEqual(metadata['interval/start'].shape[0], batch_size)
248
+ num_batches += 1
249
+
250
+ self.assertEqual(num_batches, 6 // batch_size)
251
+
252
+
253
+ if __name__ == '__main__':
254
+ absltest.main()
flax_model/alphagenome/io/fasta.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Extractors for working with FASTA files."""
16
+
17
+ import os
18
+
19
+ from flax_model.alphagenome._sdk.data import genome
20
+ import fsspec
21
+ import pyfaidx
22
+
23
+ _REVERSE_COMPLEMENT_TRANSLATION = str.maketrans('ATCGN', 'TAGCN')
24
+
25
+
26
+ def reverse_complement(sequence: str) -> str:
27
+ """Returns the reverse complement of a DNA sequence string."""
28
+ return sequence.translate(_REVERSE_COMPLEMENT_TRANSLATION)[::-1]
29
+
30
+
31
+ class FastaExtractor:
32
+ """FASTA file extractor."""
33
+
34
+ def __init__(self, fasta_path: str | os.PathLike[str]):
35
+ self._faidx = pyfaidx.Faidx(
36
+ fsspec.open(fasta_path),
37
+ as_raw=True,
38
+ mutable=False,
39
+ build_index=False,
40
+ sequence_always_upper=True,
41
+ )
42
+
43
+ def extract(self, interval: genome.Interval) -> str:
44
+ """Returns the FASTA sequence in some given interval as a string.
45
+
46
+ Args:
47
+ interval: the interval to query.
48
+
49
+ Returns:
50
+ sequence of requested interval.
51
+ """
52
+ if (chromosome := self._faidx.index.get(interval.chromosome)) is None:
53
+ raise ValueError(f'Chromosome "{interval.chromosome}" not found.')
54
+
55
+ chromosome_length = chromosome.rlen
56
+
57
+ if interval.start >= chromosome_length or interval.end < 0:
58
+ raise ValueError(f'Interval fully out of bounds. {interval=}')
59
+ elif interval.within_reference(chromosome_length):
60
+ sequence = self._faidx.fetch(
61
+ interval.chromosome, interval.start + 1, interval.end
62
+ )
63
+ else:
64
+ start_padding = 'N' * max(-interval.start, 0)
65
+ end_padding = 'N' * max(interval.end - chromosome_length, 0)
66
+ trimmed_interval = interval.truncate(chromosome_length)
67
+ sequence = self._faidx.fetch(
68
+ interval.chromosome, trimmed_interval.start + 1, trimmed_interval.end
69
+ )
70
+ sequence = start_padding + sequence + end_padding
71
+
72
+ if interval.negative_strand:
73
+ return reverse_complement(sequence)
74
+ else:
75
+ return sequence
flax_model/alphagenome/io/fasta_test.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import pathlib
17
+
18
+ from absl.testing import absltest
19
+ from absl.testing import parameterized
20
+ from flax_model.alphagenome._sdk.data import genome
21
+ from flax_model.alphagenome.io import fasta
22
+
23
+
24
+ def _get_test_fasta_path() -> str | os.PathLike[str]:
25
+ return pathlib.Path(__file__).parent / 'testdata' / 'example.fa'
26
+
27
+
28
+ class FastaExtractorTest(parameterized.TestCase):
29
+
30
+ @parameterized.parameters([
31
+ dict(interval='chr1:0-9:+', expected='TAATATGCT'),
32
+ dict(interval='chr1:0-9:-', expected='AGCATATTA'),
33
+ dict(interval='chr2:70-78', expected='CAGATACA'),
34
+ dict(interval='chr1:-10-1', expected='NNNNNNNNNNT'),
35
+ dict(interval='chr1:50-55:.', expected='ANNNN'),
36
+ dict(interval='chr1:50-55:-', expected='NNNNT'),
37
+ ])
38
+ def test_extract(self, interval: str, expected: str):
39
+ extractor = fasta.FastaExtractor(_get_test_fasta_path())
40
+ interval = genome.Interval.from_str(interval)
41
+ self.assertEqual(extractor.extract(interval), expected)
42
+
43
+ def test_extract_fully_out_of_bounds_raises(self):
44
+ extractor = fasta.FastaExtractor(_get_test_fasta_path())
45
+ with self.assertRaisesRegex(ValueError, 'Interval fully out of bounds.'):
46
+ extractor.extract(genome.Interval('chr1', 100, 1000))
47
+
48
+ def test_invalid_chromosome_raises(self):
49
+ extractor = fasta.FastaExtractor(_get_test_fasta_path())
50
+ with self.assertRaisesRegex(ValueError, 'Chromosome "foo" not found.'):
51
+ extractor.extract(genome.Interval('foo', 0, 10))
52
+
53
+
54
+ if __name__ == '__main__':
55
+ absltest.main()
flax_model/alphagenome/io/genome.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utilities for working with genome-related objects such as intervals."""
16
+
17
+ from flax_model.alphagenome._sdk.data import genome
18
+ from flax_model.alphagenome.io import fasta
19
+
20
+
21
+ def insert_reference_variant(
22
+ sequence: str,
23
+ interval: genome.Interval,
24
+ variant: genome.Variant,
25
+ ) -> str:
26
+ """Replace reference genome sequence with variant REF sequences.
27
+
28
+ Args:
29
+ sequence: Reference genome DNA sequence.
30
+ interval: Interval from which the reference genome sequence was extracted.
31
+ variant: A variant.
32
+
33
+ Returns:
34
+ Sequence of the same length as input `sequence`, but with variant.REF
35
+ integrated in case it mismatches it.
36
+ """
37
+ if interval.negative_strand:
38
+ raise ValueError('Interval must not be on the negative strand.')
39
+
40
+ if not variant.reference_overlaps(interval):
41
+ return sequence
42
+
43
+ # Relative start/end must be within the interval boundaries.
44
+ relative_start = max(variant.start - interval.start, 0)
45
+ relative_end = min(variant.end - interval.start, interval.width)
46
+
47
+ # Remove reference bases outside the interval.
48
+ clip_start = max(interval.start - variant.start, 0)
49
+ clip_end = min(interval.end - variant.start, variant.end - variant.start)
50
+ variant_reference_bases = variant.reference_bases[clip_start:clip_end]
51
+
52
+ return (
53
+ sequence[:relative_start]
54
+ + variant_reference_bases
55
+ + sequence[relative_end:]
56
+ )
57
+
58
+
59
+ def insert_alternate_variant(
60
+ sequence: str, interval: genome.Interval, variant: genome.Variant
61
+ ) -> str:
62
+ """Replace reference genome sequence with a single variant ALT sequence.
63
+
64
+ Args:
65
+ sequence: Reference genome DNA sequence.
66
+ interval: Interval corresponding to reference sequence.
67
+ variant: Variant to integrate.
68
+
69
+ Returns:
70
+ DNA sequence with integrated variant. Length of the sequence might be
71
+ be different from the input sequence.
72
+ """
73
+ if interval.negative_strand:
74
+ raise ValueError('Interval must not be on the negative strand.')
75
+
76
+ if not (
77
+ variant.reference_overlaps(interval)
78
+ or (not variant.reference_bases and variant.alternate_overlaps(interval))
79
+ ):
80
+ return sequence
81
+
82
+ if variant.end > interval.end:
83
+ # Variant reference is partially outside of the interval at the end.
84
+ variant, _ = variant.split(interval.end)
85
+ assert isinstance(variant, genome.Variant)
86
+
87
+ if variant.start < interval.start:
88
+ # Variant reference is partially outside of the interval at the start.
89
+ _, variant = variant.split(interval.start)
90
+ assert isinstance(variant, genome.Variant)
91
+
92
+ relative_start = variant.start - interval.start
93
+ relative_end = relative_start + len(variant.reference_bases)
94
+ return (
95
+ sequence[:relative_start]
96
+ + variant.alternate_bases
97
+ + sequence[relative_end:]
98
+ )
99
+
100
+
101
+ def extract_variant_sequences(
102
+ interval: genome.Interval,
103
+ variant: genome.Variant,
104
+ extractor: fasta.FastaExtractor,
105
+ ) -> tuple[str, str]:
106
+ """Extracts the interval and inserts variant to generate ref/alt sequences.
107
+
108
+ Args:
109
+ interval: Interval of interest from which to query the sequence.
110
+ variant: Variant to insert.
111
+ extractor: FASTA extractor for extracting the sequence.
112
+
113
+ Returns:
114
+ Tuple of reference and alternate sequences.
115
+ """
116
+
117
+ # If the variant is a deletion, extend the interval to account for the
118
+ # shrinking sequence.
119
+ interval_length = interval.width
120
+ extended_length = max(
121
+ 0, len(variant.reference_bases) - len(variant.alternate_bases)
122
+ )
123
+ extended_unstranded_interval = interval.as_unstranded().boundary_shift(
124
+ end_offset=extended_length
125
+ )
126
+
127
+ sequence = extractor.extract(extended_unstranded_interval)
128
+ reference_sequence = insert_reference_variant(
129
+ sequence, extended_unstranded_interval, variant
130
+ )[:interval_length]
131
+ alternate_sequence = insert_alternate_variant(
132
+ sequence, extended_unstranded_interval, variant
133
+ )[:interval_length]
134
+
135
+ if interval.negative_strand:
136
+ reference_sequence = fasta.reverse_complement(reference_sequence)
137
+ alternate_sequence = fasta.reverse_complement(alternate_sequence)
138
+
139
+ return reference_sequence, alternate_sequence
flax_model/alphagenome/io/genome_test.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from unittest import mock
16
+
17
+ from absl.testing import absltest
18
+ from absl.testing import parameterized
19
+ from flax_model.alphagenome._sdk.data import genome
20
+ from flax_model.alphagenome.io import fasta
21
+ from flax_model.alphagenome.io import genome as genome_io
22
+
23
+
24
+ class VariantTest(parameterized.TestCase):
25
+
26
+ @parameterized.named_parameters([
27
+ dict(
28
+ testcase_name='Modification',
29
+ sequence='AAAA',
30
+ interval=genome.Interval('chr1', 0, 4),
31
+ variant=genome.Variant('chr1', 3, 'A', 'G'),
32
+ expected='AAGA',
33
+ ),
34
+ dict(
35
+ testcase_name='Insertion',
36
+ sequence='AAAA',
37
+ interval=genome.Interval('chr2', 0, 4),
38
+ variant=genome.Variant('chr2', 2, 'A', 'GGGG'),
39
+ expected='AGGGGAA',
40
+ ),
41
+ dict(
42
+ testcase_name='Deletion',
43
+ sequence='AAAA',
44
+ interval=genome.Interval('chr3', 0, 4),
45
+ variant=genome.Variant('chr3', 2, 'AA', ''),
46
+ expected='AA',
47
+ ),
48
+ dict(
49
+ testcase_name='NoOverlap',
50
+ sequence='AAAA',
51
+ interval=genome.Interval('chr4', 0, 4),
52
+ variant=genome.Variant('chr4', 6, 'A', 'G'),
53
+ expected='AAAA',
54
+ ),
55
+ dict(
56
+ testcase_name='OverlapStart',
57
+ sequence='AAAA',
58
+ interval=genome.Interval('chr4', 4, 8),
59
+ variant=genome.Variant('chr4', 1, 'TTTTT', 'GGGGG'),
60
+ expected='GAAA',
61
+ ),
62
+ dict(
63
+ testcase_name='OverlapEnd',
64
+ sequence='AAAA',
65
+ interval=genome.Interval('chr4', 0, 4),
66
+ variant=genome.Variant('chr4', 4, 'TTTTTT', 'GG'),
67
+ expected='AAAG',
68
+ ),
69
+ dict(
70
+ testcase_name='DifferentChromosomes',
71
+ sequence='AAAA',
72
+ interval=genome.Interval('chr1', 0, 4),
73
+ variant=genome.Variant('chr2', 1, 'A', 'G'),
74
+ expected='AAAA',
75
+ ),
76
+ ])
77
+ def test_insert_alternate_variant(
78
+ self,
79
+ sequence: str,
80
+ interval: genome.Interval,
81
+ variant: genome.Variant,
82
+ expected: str,
83
+ ):
84
+ alternate_sequence = genome_io.insert_alternate_variant(
85
+ sequence, interval, variant
86
+ )
87
+ self.assertEqual(alternate_sequence, expected)
88
+
89
+ def test_insert_alternate_variant_negative_strand_raises(self):
90
+ with self.assertRaisesRegex(
91
+ ValueError, 'Interval must not be on the negative strand.'
92
+ ):
93
+ _ = genome_io.insert_alternate_variant(
94
+ sequence='AAAA',
95
+ interval=genome.Interval('chr1', 0, 4, '-'),
96
+ variant=genome.Variant('chr1', 2, 'A', 'G'),
97
+ )
98
+
99
+ @parameterized.named_parameters([
100
+ dict(
101
+ testcase_name='Normal',
102
+ sequence='AAAA',
103
+ interval=genome.Interval('chr1', 0, 4),
104
+ variant=genome.Variant('chr1', 2, 'A', 'G'),
105
+ expected='AAAA',
106
+ ),
107
+ dict(
108
+ testcase_name='ModifiedReference',
109
+ sequence='AAAA',
110
+ interval=genome.Interval('chr2', 0, 4),
111
+ variant=genome.Variant('chr2', 2, 'GGG', ''),
112
+ expected='AGGG',
113
+ ),
114
+ dict(
115
+ testcase_name='NoOverlap',
116
+ sequence='AAAA',
117
+ interval=genome.Interval('chr4', 0, 4),
118
+ variant=genome.Variant('chr4', 6, 'G', ''),
119
+ expected='AAAA',
120
+ ),
121
+ dict(
122
+ testcase_name='OverlapStart',
123
+ sequence='AAAA',
124
+ interval=genome.Interval('chr4', 4, 8),
125
+ variant=genome.Variant('chr4', 1, 'GGGGG', ''),
126
+ expected='GAAA',
127
+ ),
128
+ dict(
129
+ testcase_name='OverlapEnd',
130
+ sequence='AAAA',
131
+ interval=genome.Interval('chr4', 0, 4),
132
+ variant=genome.Variant('chr4', 4, 'GGG', ''),
133
+ expected='AAAG',
134
+ ),
135
+ dict(
136
+ testcase_name='DifferentChromosomes',
137
+ sequence='AAAA',
138
+ interval=genome.Interval('chr1', 0, 4),
139
+ variant=genome.Variant('chr2', 1, 'G', ''),
140
+ expected='AAAA',
141
+ ),
142
+ ])
143
+ def test_insert_reference_variant(
144
+ self,
145
+ sequence: str,
146
+ interval: genome.Interval,
147
+ variant: genome.Variant,
148
+ expected: str,
149
+ ):
150
+ reference_sequence = genome_io.insert_reference_variant(
151
+ sequence, interval, variant
152
+ )
153
+ self.assertEqual(reference_sequence, expected)
154
+
155
+ def test_insert_reference_variant_negative_strand_raises(self):
156
+ with self.assertRaisesRegex(
157
+ ValueError, 'Interval must not be on the negative strand.'
158
+ ):
159
+ _ = genome_io.insert_reference_variant(
160
+ sequence='AAAA',
161
+ interval=genome.Interval('chr1', 0, 4, '-'),
162
+ variant=genome.Variant('chr1', 2, 'A', 'G'),
163
+ )
164
+
165
+ @parameterized.named_parameters([
166
+ dict(
167
+ testcase_name='Normal',
168
+ sequence='AAAA',
169
+ interval=genome.Interval('chr1', 0, 4),
170
+ variant=genome.Variant('chr1', 2, 'A', 'G'),
171
+ expected_reference='AAAA',
172
+ expected_alternate='AGAA',
173
+ ),
174
+ dict(
175
+ testcase_name='ModifiedReference',
176
+ sequence='AAAA',
177
+ interval=genome.Interval('chr2', 0, 4),
178
+ variant=genome.Variant('chr2', 2, 'G', 'G'),
179
+ expected_reference='AGAA',
180
+ expected_alternate='AGAA',
181
+ ),
182
+ dict(
183
+ testcase_name='Insertion',
184
+ sequence='AAAA',
185
+ interval=genome.Interval('chr3', 0, 4),
186
+ variant=genome.Variant('chr3', 2, 'A', 'GGGG'),
187
+ expected_reference='AAAA',
188
+ expected_alternate='AGGG',
189
+ ),
190
+ dict(
191
+ testcase_name='Deletion',
192
+ sequence='GATACA',
193
+ interval=genome.Interval('chr3', 0, 4),
194
+ variant=genome.Variant('chr3', 2, 'AT', ''),
195
+ expected_reference='GATA',
196
+ expected_alternate='GACA',
197
+ ),
198
+ dict(
199
+ testcase_name='NoOverlap',
200
+ sequence='GGGG',
201
+ interval=genome.Interval('chr4', 0, 4),
202
+ variant=genome.Variant('chr4', 6, 'T', 'T'),
203
+ expected_reference='GGGG',
204
+ expected_alternate='GGGG',
205
+ ),
206
+ dict(
207
+ testcase_name='NegativeStrand',
208
+ sequence='AAAAA',
209
+ interval=genome.Interval('chr1', 0, 5, '-'),
210
+ variant=genome.Variant('chr1', 2, 'A', 'G'),
211
+ expected_reference='TTTTT',
212
+ expected_alternate='TTTCT',
213
+ ),
214
+ ])
215
+ def test_extract_variant_sequences(
216
+ self,
217
+ sequence: str,
218
+ interval: genome.Interval,
219
+ variant: genome.Variant,
220
+ expected_reference: str,
221
+ expected_alternate: str,
222
+ ):
223
+ def _extract(interval: genome.Interval) -> str:
224
+ self.assertLen(sequence, interval.width, f'{interval=}')
225
+ return sequence
226
+
227
+ extractor = mock.create_autospec(fasta.FastaExtractor)
228
+ extractor.extract.side_effect = _extract
229
+ reference_sequence, alternate_sequence = (
230
+ genome_io.extract_variant_sequences(interval, variant, extractor)
231
+ )
232
+ self.assertLen(reference_sequence, interval.width)
233
+ self.assertLen(alternate_sequence, interval.width)
234
+ self.assertEqual(reference_sequence, expected_reference)
235
+ self.assertEqual(alternate_sequence, expected_alternate)
236
+
237
+
238
+ if __name__ == '__main__':
239
+ absltest.main()
flax_model/alphagenome/io/splicing.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Extractors for working with splicing data."""
16
+
17
+ from flax_model.alphagenome._sdk.data import genome
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+
22
+ class PositionExtractor:
23
+ """Extractor focused on single position, rather than an interval.
24
+
25
+ Interval is considered semi-open [start, end) rows where:
26
+ - chromosome == interval.chromosome,
27
+ - position >= interval.start,
28
+ - position < interval.end,
29
+ are returned.
30
+
31
+ Note: This code doesn't consider stand information.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ df: pd.DataFrame,
37
+ position_column: str,
38
+ chromosome_column: str = 'Chromosome',
39
+ ):
40
+ """Init.
41
+
42
+ Args:
43
+ df: dataframe to query with `position_column` and `chromosome_column`.
44
+ position_column: Which column in the dataframe to use as 0-based position.
45
+ chromosome_column: Which column in the dataframe to use as chromosome.
46
+ """
47
+ self._positions = {
48
+ chromosome: (values, values[position_column].values)
49
+ for chromosome, values in df.groupby(chromosome_column, observed=False)
50
+ }
51
+
52
+ self._empty = df.iloc[:0]
53
+
54
+ def extract(self, interval: genome.Interval) -> pd.DataFrame:
55
+ if interval.chromosome not in self._positions:
56
+ return self._empty
57
+ else:
58
+ dfc, position = self._positions[interval.chromosome]
59
+ return dfc[(position >= interval.start) & (position < interval.end)]
60
+
61
+
62
+ class SpliceSiteAnnotationExtractor:
63
+ """Generate binary masks of overlapping splice sites."""
64
+
65
+ def __init__(
66
+ self,
67
+ junction_starts: pd.DataFrame,
68
+ junction_ends: pd.DataFrame,
69
+ ):
70
+ """Init.
71
+
72
+ Args:
73
+ junction_starts: DataFrame of splice junctions starts with columns:
74
+ Chromosome, Start, Strand and an optional set of tissue columns. The
75
+ `Start` column must be 0-based position of the first nucleotide of the
76
+ intron.
77
+ junction_ends: DataFrame of splice junctions ends with columns:
78
+ Chromosome, End, Strand and an optional set of tissue columns. The `End`
79
+ column must be the 1-based position of the last nucleotide of the
80
+ intron.
81
+ """
82
+ self._tissues = [
83
+ c for c in junction_starts if c not in ['Chromosome', 'Strand', 'Start']
84
+ ]
85
+ ends_tissues = [
86
+ c for c in junction_ends if c not in ['Chromosome', 'Strand', 'End']
87
+ ]
88
+ if self._tissues != ends_tissues:
89
+ raise ValueError('Tissues mismatch:', self._tissues, ends_tissues)
90
+
91
+ # Junctions describe intron intervals as [Start, End). Start point to the
92
+ # first nucleotide of the intron and End point to the fist nucleotide of the
93
+ # the next exon. We label DONOR the last nucleotide of the exon before the
94
+ # intron (so we move Start back by 1) and ACCEPTOR the first nucleotide of
95
+ # the exon after the intron (so End are not moved).
96
+ junction_starts.update(junction_starts['Start'] - 1)
97
+
98
+ self._start_position_extractor = PositionExtractor(junction_starts, 'Start')
99
+ self._end_position_extractor = PositionExtractor(junction_ends, 'End')
100
+
101
+ def extract(self, interval: genome.Interval) -> np.ndarray:
102
+ """Extract splice site masks."""
103
+ splice_junctions_starts = self._start_position_extractor.extract(interval)
104
+ splice_junctions_ends = self._end_position_extractor.extract(interval)
105
+ tissues = self._tissues
106
+ splice_junctions_starts = splice_junctions_starts[
107
+ ['Chromosome', 'Strand', 'Start'] + tissues
108
+ ]
109
+ splice_junctions_ends = splice_junctions_ends[
110
+ ['Chromosome', 'Strand', 'End'] + tissues
111
+ ]
112
+
113
+ donors_fw = splice_junctions_starts[splice_junctions_starts.Strand == '+']
114
+ accept_fw = splice_junctions_ends[splice_junctions_ends.Strand == '+']
115
+ donors_rw = splice_junctions_ends[splice_junctions_ends.Strand == '-']
116
+ accept_rw = splice_junctions_starts[splice_junctions_starts.Strand == '-']
117
+
118
+ donor_idx_fw = (donors_fw.Start.values - interval.start).astype(np.int32)
119
+ accept_idx_fw = (accept_fw.End.values - interval.start).astype(np.int32)
120
+ donor_idx_rw = (donors_rw.End.values - interval.start).astype(np.int32)
121
+ accept_idx_rw = (accept_rw.Start.values - interval.start).astype(np.int32)
122
+
123
+ if tissues:
124
+ donor_theta_fw = donors_fw[tissues].to_numpy()
125
+ accept_theta_fw = accept_fw[tissues].to_numpy()
126
+ donor_theta_rw = donors_rw[tissues].to_numpy()
127
+ accept_theta_rw = accept_rw[tissues].to_numpy()
128
+ else:
129
+ donor_theta_fw = True
130
+ accept_theta_fw = True
131
+ donor_theta_rw = True
132
+ accept_theta_rw = True
133
+
134
+ if interval.negative_strand:
135
+ # Then model sees negative strand data as positive strand, swap arrays.
136
+ donor_idx_fw, donor_idx_rw = donor_idx_rw, donor_idx_fw
137
+ accept_idx_fw, accept_idx_rw = accept_idx_rw, accept_idx_fw
138
+ donor_theta_fw, donor_theta_rw = donor_theta_rw, donor_theta_fw
139
+ accept_theta_fw, accept_theta_rw = accept_theta_rw, accept_theta_fw
140
+ # Sequence is flipped, so indices must start at end of sequence.
141
+ donor_idx_fw = interval.width - 1 - donor_idx_fw
142
+ accept_idx_fw = interval.width - 1 - accept_idx_fw
143
+ donor_idx_rw = interval.width - 1 - donor_idx_rw
144
+ accept_idx_rw = interval.width - 1 - accept_idx_rw
145
+
146
+ splice_sites = np.zeros((interval.width, 5), dtype=bool)
147
+ splice_sites[donor_idx_fw, 0] = np.any(donor_theta_fw > 0)
148
+ splice_sites[accept_idx_fw, 1] = np.any(accept_theta_fw > 0)
149
+ splice_sites[donor_idx_rw, 2] = np.any(donor_theta_rw > 0)
150
+ splice_sites[accept_idx_rw, 3] = np.any(accept_theta_rw > 0)
151
+ splice_sites[:, 4] = np.logical_not(np.any(splice_sites[:, :4], axis=1))
152
+
153
+ return splice_sites
flax_model/alphagenome/io/splicing_test.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from absl.testing import absltest
16
+ from absl.testing import parameterized
17
+ from flax_model.alphagenome._sdk.data import genome
18
+ from flax_model.alphagenome.io import splicing
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+
23
+ class SpliceSiteAnnotationExtractorTest(parameterized.TestCase):
24
+
25
+ @parameterized.product(interval_strand=['+', '-'], with_tissues=[True, False])
26
+ def test_extract(self, interval_strand, with_tissues):
27
+ interval_start = 100
28
+ interval_end = 116
29
+
30
+ pos_first_bp_intron_0based = np.asarray([101, 106, 107])
31
+ neg_first_bp_intron_0based = np.asarray([101, 106, 107])
32
+ pos_last_bp_intron_1based = np.asarray([104, 109, 115])
33
+ neg_last_bp_intron_1based = np.asarray([104, 109, 115])
34
+ junction_starts = pd.DataFrame({
35
+ 'Chromosome': 'chr1',
36
+ 'Start': [*pos_first_bp_intron_0based, *neg_first_bp_intron_0based],
37
+ 'Strand': ['+', '+', '+', '-', '-', '-'],
38
+ })
39
+ junction_ends = pd.DataFrame({
40
+ 'Chromosome': 'chr1',
41
+ 'End': [*pos_last_bp_intron_1based, *neg_last_bp_intron_1based],
42
+ 'Strand': ['+', '+', '+', '-', '-', '-'],
43
+ })
44
+ if with_tissues:
45
+ junction_starts['Tissue_0'] = [1, 3, 5, 2, 4, 6]
46
+ junction_starts['Tissue_1'] = [2, 4, 6, 3, 5, 7]
47
+ junction_ends['Tissue_0'] = [1, 3, 5, 2, 4, 6]
48
+ junction_ends['Tissue_1'] = [2, 4, 6, 3, 5, 7]
49
+
50
+ interval = genome.Interval(
51
+ 'chr1', interval_start, interval_end, interval_strand
52
+ )
53
+ extractor = splicing.SpliceSiteAnnotationExtractor(
54
+ junction_starts, junction_ends
55
+ )
56
+ result = extractor.extract(interval)
57
+
58
+ expected_sites = np.zeros((interval.width, 5), dtype=bool)
59
+
60
+ # Move all to the exon bp, and to 0-based coordinates within the interval.
61
+ pos_last_exon_before = pos_first_bp_intron_0based - interval_start - 1
62
+ pos_first_exon_after = pos_last_bp_intron_1based - interval_start
63
+ neg_first_exon_after = neg_last_bp_intron_1based - interval_start
64
+ neg_last_exon_before = neg_first_bp_intron_0based - interval_start - 1
65
+ if interval_strand == '+':
66
+ expected_sites[pos_last_exon_before, 0] = True
67
+ expected_sites[pos_first_exon_after, 1] = True
68
+ expected_sites[neg_first_exon_after, 2] = True
69
+ expected_sites[neg_last_exon_before, 3] = True
70
+ elif interval_strand == '-':
71
+ pos_last_exon_before = interval.width - 1 - pos_last_exon_before
72
+ pos_first_exon_after = interval.width - 1 - pos_first_exon_after
73
+ neg_last_exon_before = interval.width - 1 - neg_last_exon_before
74
+ neg_first_exon_after = interval.width - 1 - neg_first_exon_after
75
+ expected_sites[neg_first_exon_after, 0] = True
76
+ expected_sites[neg_last_exon_before, 1] = True
77
+ expected_sites[pos_last_exon_before, 2] = True
78
+ expected_sites[pos_first_exon_after, 3] = True
79
+ expected_sites[:, 4] = np.logical_not(np.any(expected_sites, axis=1))
80
+
81
+ np.testing.assert_array_equal(result, expected_sites)
82
+
83
+ def test_tissue_mismatch_raises(self):
84
+ junction_starts = pd.DataFrame({
85
+ 'Chromosome': 'chr1',
86
+ 'Start': [101, 106, 107],
87
+ 'Strand': ['+', '+', '+'],
88
+ 'Tissue_0': [1, 3, 5],
89
+ })
90
+ junction_ends = pd.DataFrame({
91
+ 'Chromosome': 'chr1',
92
+ 'End': [104, 109, 115],
93
+ 'Strand': ['+', '+', '+'],
94
+ 'Tissue_1': [1, 3, 5],
95
+ })
96
+ with self.assertRaisesRegex(ValueError, 'Tissues mismatch'):
97
+ _ = splicing.SpliceSiteAnnotationExtractor(junction_starts, junction_ends)
98
+
99
+
100
+ class PositionExtractorTest(parameterized.TestCase):
101
+
102
+ def test_extract(self):
103
+ df = pd.DataFrame({'Chromosome': ['chr1'], 'position': [1]})
104
+ ex = splicing.PositionExtractor(df, position_column='position')
105
+ # Inside.
106
+ self.assertLen(ex.extract(genome.Interval('chr1', 0, 2)), 1)
107
+ self.assertLen(ex.extract(genome.Interval('chr1', 1, 2)), 1)
108
+ # Outside.
109
+ self.assertEmpty(ex.extract(genome.Interval('chr2', 0, 2)))
110
+ self.assertEmpty(ex.extract(genome.Interval('chr1', 0, 1)))
111
+ self.assertEmpty(ex.extract(genome.Interval('chr1', 2, 3)))
112
+
113
+
114
+ if __name__ == '__main__':
115
+ absltest.main()
flax_model/alphagenome/io/testdata/example.fa ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ >chr1
2
+ TAATATGCTATATATGATACAGATACAGATACAGATACAGATACAAAAAAA
3
+ >chr2
4
+ GATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACAGATACA
flax_model/alphagenome/io/testdata/example.fa.fai ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ chr1 51 6 51 52
2
+ chr2 78 64 78 79
flax_model/alphagenome/model/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome Model."""
flax_model/alphagenome/model/attention.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Attention layers."""
16
+
17
+ import math
18
+ from flax_model.alphagenome._sdk import typing
19
+ from flax_model.alphagenome.model import layers
20
+ import chex
21
+ from einshape import jax_einshape as einshape # pylint: disable=g-importing-member
22
+ import haiku as hk
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from jaxtyping import Array, Float, Int # pylint: disable=g-importing-member, g-multiple-import
26
+
27
+
28
+ _MAX_RELATIVE_DISTANCE = 8192 # 1Mb / 128bp.
29
+
30
+
31
+ def _shift(
32
+ x: jnp.ndarray,
33
+ query_length: int,
34
+ key_length: int,
35
+ ) -> jnp.ndarray:
36
+ """Shifts the diagonal of a 2D array."""
37
+ chex.assert_axis_dimension(x, -2, query_length)
38
+ chex.assert_axis_dimension(x, -1, query_length + key_length)
39
+ *batch_shapes, n_rows, n_diags = x.shape
40
+ x = x.reshape(batch_shapes + [n_diags, n_rows])
41
+ x = x[..., 1:, :]
42
+ x = x.reshape(batch_shapes + [n_rows, n_diags - 1])
43
+ return x[..., :key_length]
44
+
45
+
46
+ def _central_mask_features(
47
+ *, distances: jnp.ndarray, feature_size: int, seq_length: int
48
+ ) -> jnp.ndarray:
49
+ """Positional features using exponentially-spaced central mask."""
50
+ if feature_size > seq_length:
51
+ raise ValueError(f'{feature_size=} must be <= than {seq_length=}. ')
52
+ center_widths = jnp.arange(feature_size) + jnp.geomspace(
53
+ 1, seq_length - feature_size + 1, feature_size, endpoint=False
54
+ )
55
+ center_widths = jax.lax.broadcast_to_rank(center_widths, distances.ndim)
56
+ outputs = (center_widths > distances[..., None]).astype(distances.dtype)
57
+ chex.assert_shape(outputs, expected_shapes=distances.shape + (feature_size,))
58
+ return outputs
59
+
60
+
61
+ def apply_rope(
62
+ x: Float[Array, 'B S H C'],
63
+ positions: Int[Array, 'B S'] | None,
64
+ max_position: int,
65
+ ) -> Float[Array, 'B S H C']:
66
+ """Applies Rotary Position Embeddings to the input tensor."""
67
+ if positions is None:
68
+ positions = jnp.arange(x.shape[1]).astype(x.dtype).reshape(1, x.shape[1])
69
+ num_freq = x.shape[-1] // 2
70
+ inv_freq = 1.0 / (
71
+ jnp.arange(num_freq)
72
+ + jnp.geomspace(1, max_position - num_freq + 1, num_freq)
73
+ ).astype(x.dtype)
74
+ theta = jnp.einsum('bs,f->bsf', positions, inv_freq)
75
+ theta = jnp.repeat(theta, 2, axis=-1)[..., None, :] # [b, s, 1, c]
76
+ x_rotated = jnp.stack([-x[..., 1::2], x[..., ::2]], axis=-1).reshape(
77
+ x.shape
78
+ ) # [b, s, h, c]
79
+ return x * jnp.cos(theta) + x_rotated * jnp.sin(theta)
80
+
81
+
82
+ class MLPBlock(hk.Module):
83
+ """MLP block for sequence representations."""
84
+
85
+ @typing.jaxtyped
86
+ def __call__(self, x: Float[Array, 'B S D']) -> Float[Array, 'B S D']:
87
+ h = layers.RMSBatchNorm()(x)
88
+ h = hk.Linear(x.shape[-1] * 2)(h)
89
+ h = jax.nn.relu(h)
90
+ h = hk.Linear(x.shape[-1])(h)
91
+ return layers.RMSBatchNorm()(h)
92
+
93
+
94
+ class PairMLPBlock(hk.Module):
95
+ """MLP block for pairwise representations."""
96
+
97
+ @typing.jaxtyped
98
+ def __call__(
99
+ self, pair_input: Float[Array, 'B S S F']
100
+ ) -> Float[Array, 'B S S F']:
101
+ x = layers.LayerNorm(rms_norm=True)(pair_input)
102
+ hidden_channels = 2 * pair_input.shape[-1]
103
+ x = hk.Linear(hidden_channels)(x)
104
+ x = jax.nn.relu(x)
105
+ x = hk.Linear(pair_input.shape[-1])(x)
106
+ return x
107
+
108
+
109
+ class MHABlock(hk.Module):
110
+ """Multi-Head Attention block with residual connection."""
111
+
112
+ @typing.jaxtyped
113
+ def __call__(
114
+ self, x: Float[Array, 'B S D'], attention_bias: Float[Array, 'B H S S']
115
+ ) -> Float[Array, 'B S D']:
116
+ batch_size, seq_len, _ = x.shape
117
+ h = layers.RMSBatchNorm()(x)
118
+ q = layers.LayerNorm(name='norm_q')(
119
+ hk.Linear(8 * 128, with_bias=False, name='q_layer')(h).reshape(
120
+ batch_size, seq_len, 8, 128
121
+ )
122
+ )
123
+ k = layers.LayerNorm(name='norm_k')(
124
+ hk.Linear(128, with_bias=False, name='k_layer')(h).reshape(
125
+ batch_size, seq_len, 1, 128
126
+ )
127
+ )
128
+ v = layers.LayerNorm(name='norm_v')(
129
+ hk.Linear(192, with_bias=False, name='v_layer')(h).reshape(
130
+ batch_size, seq_len, 1, 192
131
+ )
132
+ )
133
+ q = apply_rope(q, None, max_position=_MAX_RELATIVE_DISTANCE)
134
+ k = apply_rope(k, None, max_position=_MAX_RELATIVE_DISTANCE)
135
+
136
+ logits_dtype = jnp.float32
137
+ attention_logits = jnp.einsum(
138
+ 'bshc,bS1c->bhsS',
139
+ q,
140
+ k,
141
+ precision=jax.lax.Precision.DEFAULT,
142
+ # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
143
+ preferred_element_type=logits_dtype,
144
+ )
145
+ attention_logits = attention_logits / math.sqrt(128.0)
146
+ attention_logits = (attention_logits + attention_bias).astype(logits_dtype)
147
+ logits_soft_cap = 5.0
148
+ attention_logits = (
149
+ jnp.tanh(attention_logits / logits_soft_cap) * logits_soft_cap
150
+ )
151
+ attention_weights = jax.nn.softmax(attention_logits, axis=-1)
152
+
153
+ y = jnp.einsum(
154
+ 'bhsS,bS1c->bshc',
155
+ attention_weights,
156
+ v,
157
+ # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
158
+ precision=jax.lax.Precision.DEFAULT,
159
+ ).astype(q.dtype)
160
+ y = hk.Linear(x.shape[-1], name='linear_embedding')(
161
+ y.reshape(batch_size, seq_len, -1)
162
+ )
163
+ return layers.RMSBatchNorm()(y)
164
+
165
+
166
+ class AttentionBiasBlock(hk.Module):
167
+ """Generates attention bias for Multi-Head Attention."""
168
+
169
+ @typing.jaxtyped
170
+ def __call__(self, x: Float[Array, 'B s s D']) -> Float[Array, 'B H S S']:
171
+ x = jax.nn.gelu(layers.RMSBatchNorm()(x))
172
+ # 8 = number of heads in sequence MHA.
173
+ x = hk.Linear(8, with_bias=False)(x)
174
+ for axis in [1, 2]:
175
+ x = jnp.repeat(x, repeats=16, axis=axis) # [B S S H]
176
+ return jnp.moveaxis(x, 3, 1)
177
+
178
+
179
+ class RowAttentionBlock(hk.Module):
180
+ """Self-attention block applied along rows of pairwise representations."""
181
+
182
+ @typing.jaxtyped
183
+ def __call__(
184
+ self, pair_input: Float[Array, 'B s s F']
185
+ ) -> Float[Array, 'B s s F']:
186
+ x = layers.LayerNorm(rms_norm=True)(pair_input)
187
+ k = hk.Linear(128, with_bias=False, name='linear_k')(x)
188
+ q = hk.Linear(128, with_bias=False, name='linear_q')(x)
189
+ v = hk.Linear(128, name='linear_v')(x)
190
+ x = jnp.einsum(
191
+ 'bpqf,bpkf->bpqk',
192
+ q,
193
+ k,
194
+ # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
195
+ precision=jax.lax.Precision.DEFAULT,
196
+ preferred_element_type=jnp.float32,
197
+ ) / math.sqrt(128)
198
+ x = jax.nn.softmax(x, axis=-1)
199
+ x = jnp.einsum(
200
+ 'bpqk,bpkf->bpqf',
201
+ x,
202
+ v,
203
+ # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
204
+ precision=jax.lax.Precision.DEFAULT,
205
+ ).astype(q.dtype)
206
+ return x
207
+
208
+
209
+ class SequenceToPairBlock(hk.Module):
210
+ """Converts sequence representations to pairwise representations."""
211
+
212
+ @typing.jaxtyped
213
+ def __call__(
214
+ self, x: Float[Array, 'B S D']
215
+ ) -> Float[Array, 'B S//16 S//16 F']:
216
+ x = layers.LayerNorm(rms_norm=True, name='norm_seq2pair')(
217
+ layers.pool(x, by=16, reduce='mean')
218
+ )
219
+ batch_size, seq_len = x.shape[0], x.shape[1]
220
+ q = hk.Linear(32 * 128, with_bias=False, name='linear_q')(x).reshape(
221
+ batch_size, seq_len, 32, 128
222
+ )
223
+ k = hk.Linear(32 * 128, with_bias=False, name='linear_k')(x).reshape(
224
+ batch_size, seq_len, 32, 128
225
+ )
226
+
227
+ relative_positions = jnp.arange(-seq_len, seq_len).astype(jnp.float32)
228
+ pos_features = _central_mask_features(
229
+ distances=jnp.abs(relative_positions),
230
+ feature_size=32,
231
+ seq_length=_MAX_RELATIVE_DISTANCE // 16,
232
+ ).astype(x.dtype)
233
+ pos_features = jnp.concatenate(
234
+ [pos_features, jnp.sign(relative_positions)[..., None] * pos_features],
235
+ axis=-1,
236
+ ).astype(x.dtype)
237
+ pos_encoding = hk.Linear(32 * 128, name='linear_pos_features')(
238
+ pos_features
239
+ ).reshape(2 * seq_len, 32, 128)
240
+
241
+ q_bias = hk.get_parameter(
242
+ 'q_r_bias', (1, 1, 32, 128), init=jnp.zeros
243
+ ).astype(x.dtype)
244
+ k_bias = hk.get_parameter(
245
+ 'k_r_bias', (1, 1, 32, 128), init=jnp.zeros
246
+ ).astype(x.dtype)
247
+
248
+ rel_q_a = _shift(
249
+ jnp.einsum('bqhc,phc->bhqp', q + q_bias, pos_encoding), seq_len, seq_len
250
+ )
251
+ rel_k_a = _shift(
252
+ jnp.einsum('bkhc,phc->bhkp', k + k_bias, pos_encoding), seq_len, seq_len
253
+ )
254
+
255
+ a = jnp.einsum('bqhc,bkhc->bqkh', q, k)
256
+ a += 0.5 * (
257
+ einshape('bhqp->bqph', rel_q_a) + einshape('bhkp->bpkh', rel_k_a)
258
+ )
259
+
260
+ y_q = hk.Linear(128, with_bias=False, name='linear_y_q')(jax.nn.gelu(x))
261
+ y_k = hk.Linear(128, with_bias=False, name='linear_y_k')(jax.nn.gelu(x))
262
+ pair_act = (
263
+ hk.Linear(128, name='linear_pair')(a)
264
+ + y_q[:, :, None, :]
265
+ + y_k[:, None, :, :]
266
+ )
267
+ return pair_act
268
+
269
+
270
+ class PairUpdateBlock(hk.Module):
271
+ """Updates pairwise representations."""
272
+
273
+ @typing.jaxtyped
274
+ def __call__(
275
+ self,
276
+ sequence_input: Float[Array, 'B S C'],
277
+ pair_input: Float[Array, 'B S//16 S//16 F'] | None,
278
+ ):
279
+ y = SequenceToPairBlock()(sequence_input)
280
+ x = y if pair_input is None else (pair_input + y)
281
+ x += RowAttentionBlock()(x)
282
+ x += PairMLPBlock()(x)
283
+ return x
flax_model/alphagenome/model/attention_test.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from absl.testing import absltest
16
+ from absl.testing import parameterized
17
+ from flax_model.alphagenome.model import attention
18
+ import chex
19
+ import haiku as hk
20
+ import jax
21
+ import jax.numpy as jnp
22
+
23
+
24
+ class ConvolutionsTest(parameterized.TestCase):
25
+
26
+ def setUp(self):
27
+ super().setUp()
28
+ self._batch_size = 4
29
+ self._sequence_length = 4096
30
+ self._pair_sequence_length = self._sequence_length // 16
31
+ self._hidden_size = 64
32
+
33
+ def test_mlp_block_output_shape(self):
34
+ """Tests that MLPBlock produces the expected output shape."""
35
+ rng = jax.random.PRNGKey(42)
36
+
37
+ def _forward(x):
38
+ module = attention.MLPBlock()
39
+ return module(x)
40
+
41
+ init, apply = hk.transform_with_state(_forward)
42
+ x = jnp.zeros((self._batch_size, self._sequence_length, self._hidden_size))
43
+ params, state = init(rng, x)
44
+ output, _ = apply(params, state, rng, x)
45
+ chex.assert_shape(
46
+ output, (self._batch_size, self._sequence_length, self._hidden_size)
47
+ )
48
+
49
+ def test_pair_mlp_block_output_shape(self):
50
+ """Tests that PairMLPBlock produces the expected output shape."""
51
+ rng = jax.random.PRNGKey(42)
52
+
53
+ def _forward(x):
54
+ module = attention.PairMLPBlock()
55
+ return module(x)
56
+
57
+ init, apply = hk.transform_with_state(_forward)
58
+ x = jnp.zeros((
59
+ self._batch_size,
60
+ self._pair_sequence_length,
61
+ self._pair_sequence_length,
62
+ self._hidden_size,
63
+ ))
64
+ params, state = init(rng, x)
65
+ output, _ = apply(params, state, rng, x)
66
+ chex.assert_shape(
67
+ output,
68
+ (
69
+ self._batch_size,
70
+ self._pair_sequence_length,
71
+ self._pair_sequence_length,
72
+ self._hidden_size,
73
+ ),
74
+ )
75
+
76
+
77
+ if __name__ == "__main__":
78
+ absltest.main()
flax_model/alphagenome/model/augmentation.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Utilities for augmenting predictions, e.g. reverse complementation."""
16
+
17
+ from collections.abc import Mapping
18
+ from typing import TypeAlias
19
+
20
+ from flax_model.alphagenome._sdk import typing
21
+ from flax_model.alphagenome._sdk.models import dna_output
22
+ import chex
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from jaxtyping import Array, Bool, Float, Int32, PyTree # pylint: disable=g-importing-member, g-multiple-import
26
+
27
+ _Predictions: TypeAlias = PyTree[Float[Array, 'B ...'] | Int32[Array, 'B ...']]
28
+
29
+
30
+ @typing.jaxtyped
31
+ def reverse_complement_output_type(
32
+ predictions: _Predictions,
33
+ *,
34
+ output_type: dna_output.OutputType,
35
+ strand_reindexing: Int32[Array, '_'] | None,
36
+ sequence_length: Int32[Array, ''] | int,
37
+ ) -> _Predictions:
38
+ """Reverse complement predictions for a given output type."""
39
+ match output_type: # pytype: disable=incomplete-match
40
+ case dna_output.OutputType.SPLICE_JUNCTIONS:
41
+ splice_junction_predictions = predictions['predictions']
42
+ chex.assert_rank(splice_junction_predictions, 4)
43
+ # Only need to strand flip for junction outputs. Index flipping is done
44
+ # with splice_site_positions.
45
+ chex.assert_equal_shape(
46
+ (splice_junction_predictions, strand_reindexing), dims=-1
47
+ )
48
+ predictions['predictions'] = splice_junction_predictions[
49
+ ..., strand_reindexing
50
+ ]
51
+
52
+ splice_site_positions = predictions['splice_site_positions']
53
+ chex.assert_rank(splice_site_positions, 3)
54
+ padding_predictions = splice_site_positions < 0
55
+ splice_site_positions = sequence_length - 1 - splice_site_positions
56
+ splice_site_positions = jnp.where(
57
+ padding_predictions, -1, splice_site_positions
58
+ )
59
+ splice_site_positions = splice_site_positions[:, jnp.array([2, 3, 0, 1])]
60
+
61
+ predictions['splice_site_positions'] = splice_site_positions
62
+ case dna_output.OutputType.CONTACT_MAPS:
63
+ chex.assert_rank(predictions, 4)
64
+ # Contact maps are unstranded, so no need to strand flip.
65
+ return predictions[:, ::-1, ::-1]
66
+ case _:
67
+ chex.assert_rank(predictions, 3)
68
+ predictions = predictions[:, ::-1]
69
+ if strand_reindexing is not None:
70
+ predictions = predictions[..., strand_reindexing]
71
+ # For DNASE, +ve strand predictions are not aligned with -ve strand
72
+ # predictions after reverse-complementation:
73
+ # Input positions:
74
+ # [ 0 ][ 1 ][ 2 ]
75
+ # Track values:
76
+ # [ A ][ B ][ C ][ D ]
77
+ # In this example, output predictions are determined by the track value
78
+ # at the start of the position. Thus, when read forwards, the + strand
79
+ # will give ABC and the - strand will give DCB. If we want predictions to
80
+ # align after reverse-complementation (for example, to perform TTA or to
81
+ # return aligned, unstranded predictions for both + and -), we need to
82
+ # shift predictions by 1 after rc.
83
+ if output_type == dna_output.OutputType.DNASE:
84
+ predictions = jnp.roll(predictions, 1, axis=1)
85
+ predictions = predictions.at[:, 0].set(0)
86
+
87
+ return predictions
88
+
89
+
90
+ @typing.jaxtyped
91
+ def reverse_complement(
92
+ predictions: Mapping[dna_output.OutputType, _Predictions],
93
+ reverse_complement_mask: Bool[Array, 'B'],
94
+ *,
95
+ strand_reindexing: Mapping[dna_output.OutputType, Int32[Array, '_']],
96
+ sequence_length: int,
97
+ ) -> Mapping[dna_output.OutputType, _Predictions]:
98
+ """Reverse complement predictions."""
99
+
100
+ def _reverse_complement(predictions: _Predictions):
101
+ result = {}
102
+ for output_type in dna_output.OutputType:
103
+ if (prediction := predictions.get(output_type)) is not None:
104
+ result[output_type] = reverse_complement_output_type(
105
+ prediction,
106
+ output_type=output_type,
107
+ strand_reindexing=strand_reindexing.get(output_type),
108
+ sequence_length=sequence_length,
109
+ )
110
+ return result
111
+
112
+ # Add single batch dimension to vmap over.
113
+ predictions = jax.tree.map(lambda x: jnp.expand_dims(x, axis=1), predictions)
114
+ predictions = jax.vmap(
115
+ lambda prediction, should_reverse: jax.lax.cond(
116
+ should_reverse,
117
+ _reverse_complement,
118
+ lambda prediction: prediction,
119
+ prediction,
120
+ )
121
+ )(predictions, reverse_complement_mask)
122
+ return jax.tree.map(lambda x: jnp.squeeze(x, axis=1), predictions)
flax_model/alphagenome/model/augmentation_test.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from collections.abc import Sequence
16
+ import functools
17
+
18
+ from absl.testing import absltest
19
+ from absl.testing import parameterized
20
+ from flax_model.alphagenome._sdk.models import dna_output
21
+ from flax_model.alphagenome.model import augmentation
22
+ import chex
23
+ import jax
24
+ from jax import numpy as jnp
25
+ from jaxtyping import PyTree # pylint: disable=g-importing-member
26
+ import ml_dtypes
27
+ import numpy as np
28
+
29
+
30
+ class AugmentationTest(chex.TestCase, parameterized.TestCase):
31
+
32
+ @chex.variants(with_jit=True, without_jit=True)
33
+ @parameterized.parameters(
34
+ dict(
35
+ output_type=dna_output.OutputType.SPLICE_JUNCTIONS,
36
+ predictions={
37
+ 'predictions': np.array(
38
+ [[
39
+ [[0, 1, 2, 3], [4, 5, 6, 7]],
40
+ [[8, 9, 10, 11], [12, 13, 14, 15]],
41
+ ]],
42
+ dtype=np.float32,
43
+ ),
44
+ 'splice_site_positions': np.array(
45
+ [[[0, 1], [-1, 3], [4, -1], [6, 7]]],
46
+ dtype=np.int32,
47
+ ),
48
+ },
49
+ strand_reindexing=np.array([3, 2, 1, 0], dtype=np.int32),
50
+ expected={
51
+ 'predictions': np.array(
52
+ [[
53
+ [[3, 2, 1, 0], [7, 6, 5, 4]],
54
+ [[11, 10, 9, 8], [15, 14, 13, 12]],
55
+ ]],
56
+ dtype=np.float32,
57
+ ),
58
+ 'splice_site_positions': np.array(
59
+ [[[-1, -1], [-3, -4], [3, 2], [-1, 0]]],
60
+ dtype=np.int32,
61
+ ),
62
+ },
63
+ sequence_length=4,
64
+ ),
65
+ dict(
66
+ output_type=dna_output.OutputType.CONTACT_MAPS,
67
+ predictions=np.array(
68
+ [[
69
+ [[0, 1], [2, 3], [4, 5], [6, 7]],
70
+ [[8, 9], [10, 11], [12, 13], [14, 15]],
71
+ [[16, 17], [18, 19], [20, 21], [22, 23]],
72
+ [[24, 25], [26, 27], [28, 29], [30, 31]],
73
+ ]],
74
+ dtype=ml_dtypes.bfloat16,
75
+ ),
76
+ strand_reindexing=None,
77
+ expected=np.array(
78
+ [[
79
+ [[30, 31], [28, 29], [26, 27], [24, 25]],
80
+ [[22, 23], [20, 21], [18, 19], [16, 17]],
81
+ [[14, 15], [12, 13], [10, 11], [8, 9]],
82
+ [[6, 7], [4, 5], [2, 3], [0, 1]],
83
+ ]],
84
+ dtype=ml_dtypes.bfloat16,
85
+ ),
86
+ sequence_length=-1, # Unused.
87
+ ),
88
+ dict(
89
+ output_type=dna_output.OutputType.RNA_SEQ,
90
+ predictions=np.array(
91
+ [[[0, 1], [2, 3], [4, 5], [6, 7]]],
92
+ dtype=ml_dtypes.bfloat16,
93
+ ),
94
+ strand_reindexing=np.array([1, 0], dtype=np.int32),
95
+ expected=np.array(
96
+ [[[7, 6], [5, 4], [3, 2], [1, 0]]],
97
+ dtype=ml_dtypes.bfloat16,
98
+ ),
99
+ sequence_length=-1, # Unused.
100
+ ),
101
+ dict(
102
+ output_type=dna_output.OutputType.DNASE,
103
+ predictions=np.array(
104
+ [[[0, 1], [2, 3], [4, 5], [6, 7]]],
105
+ dtype=ml_dtypes.bfloat16,
106
+ ),
107
+ strand_reindexing=np.array([1, 0], dtype=np.int32),
108
+ expected=np.array(
109
+ [[[0, 0], [7, 6], [5, 4], [3, 2]]],
110
+ dtype=ml_dtypes.bfloat16,
111
+ ),
112
+ sequence_length=-1, # Unused.
113
+ ),
114
+ )
115
+ def test_reverse_complement_output_type(
116
+ self,
117
+ output_type: dna_output.OutputType,
118
+ predictions: PyTree[np.ndarray],
119
+ strand_reindexing: np.ndarray,
120
+ expected: PyTree[np.ndarray],
121
+ sequence_length: int,
122
+ ):
123
+ output = self.variant(
124
+ augmentation.reverse_complement_output_type,
125
+ static_argnames=['output_type'],
126
+ )(
127
+ jax.tree.map(jnp.asarray, predictions),
128
+ output_type=output_type,
129
+ strand_reindexing=jnp.asarray(strand_reindexing)
130
+ if strand_reindexing is not None
131
+ else None,
132
+ sequence_length=sequence_length,
133
+ )
134
+ jax.tree.map(np.testing.assert_array_equal, output, expected)
135
+
136
+ @chex.variants(with_jit=True, without_jit=True)
137
+ @parameterized.product(
138
+ mask=[[True, False], [False, False], [True, True]],
139
+ )
140
+ def test_reverse_complement(self, mask: Sequence[bool]):
141
+ sequence_length = 64
142
+ example = {
143
+ dna_output.OutputType.ATAC: (
144
+ jnp.arange(sequence_length * 2, dtype=jnp.bfloat16).reshape(
145
+ 1, sequence_length, 2
146
+ )
147
+ ),
148
+ dna_output.OutputType.DNASE: (
149
+ jnp.arange(sequence_length * 2, dtype=jnp.bfloat16).reshape(
150
+ 1, sequence_length, 2
151
+ )
152
+ ),
153
+ dna_output.OutputType.SPLICE_JUNCTIONS: {
154
+ 'predictions': (
155
+ jnp.arange(32, dtype=jnp.bfloat16).reshape(1, 4, 4, 2)
156
+ ),
157
+ 'splice_site_positions': (
158
+ jnp.arange(16, dtype=jnp.int32).reshape(1, 4, 4)
159
+ ),
160
+ },
161
+ dna_output.OutputType.CONTACT_MAPS: (
162
+ jnp.arange(400, dtype=jnp.bfloat16).reshape(1, 10, 10, 4)
163
+ ),
164
+ }
165
+ strand_reindexing = {
166
+ dna_output.OutputType.ATAC: jnp.array([1, 0], dtype=jnp.int32),
167
+ dna_output.OutputType.DNASE: jnp.array([1, 0], dtype=jnp.int32),
168
+ dna_output.OutputType.SPLICE_JUNCTIONS: jnp.array(
169
+ [0, 1], dtype=jnp.int32
170
+ ),
171
+ }
172
+ splice_site_positions_reversed = (
173
+ sequence_length
174
+ - 1
175
+ - example[dna_output.OutputType.SPLICE_JUNCTIONS][
176
+ 'splice_site_positions'
177
+ ]
178
+ )
179
+ expected_reversed = {
180
+ dna_output.OutputType.ATAC: example[dna_output.OutputType.ATAC][
181
+ :, ::-1, strand_reindexing[dna_output.OutputType.ATAC]
182
+ ],
183
+ dna_output.OutputType.DNASE: jnp.pad(
184
+ example[dna_output.OutputType.DNASE][
185
+ :, :0:-1, strand_reindexing[dna_output.OutputType.DNASE]
186
+ ],
187
+ ((0, 0), (1, 0), (0, 0)),
188
+ ),
189
+ dna_output.OutputType.SPLICE_JUNCTIONS: {
190
+ 'predictions': example[dna_output.OutputType.SPLICE_JUNCTIONS][
191
+ 'predictions'
192
+ ],
193
+ 'splice_site_positions': splice_site_positions_reversed[
194
+ :,
195
+ (2, 3, 0, 1),
196
+ ],
197
+ },
198
+ dna_output.OutputType.CONTACT_MAPS: example[
199
+ dna_output.OutputType.CONTACT_MAPS
200
+ ][:, ::-1, ::-1],
201
+ }
202
+ batched_example = jax.tree.map(
203
+ lambda x: jnp.repeat(x, len(mask), axis=0), example
204
+ )
205
+ expected = jax.tree.map(
206
+ lambda *x: jnp.concatenate(x, axis=0),
207
+ *[expected_reversed if m else example for m in mask],
208
+ )
209
+
210
+ result = self.variant(
211
+ augmentation.reverse_complement,
212
+ static_argnames=['sequence_length'],
213
+ )(
214
+ batched_example,
215
+ jnp.asarray(mask, dtype=bool),
216
+ strand_reindexing=strand_reindexing,
217
+ sequence_length=sequence_length,
218
+ )
219
+
220
+ for output_type in dna_output.OutputType:
221
+ if (prediction := result.get(output_type)) is not None:
222
+ jax.tree.map(
223
+ functools.partial(
224
+ np.testing.assert_array_equal, err_msg=f'{output_type=}'
225
+ ),
226
+ prediction,
227
+ expected.get(output_type),
228
+ )
229
+
230
+
231
+ if __name__ == '__main__':
232
+ absltest.main()
flax_model/alphagenome/model/convolutions.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Convolutional layers."""
16
+
17
+ from flax_model.alphagenome._sdk import typing
18
+ from flax_model.alphagenome.model import layers
19
+ import chex
20
+ import haiku as hk
21
+ import jax
22
+ import jax.numpy as jnp
23
+ from jaxtyping import Array, Float # pylint: disable=g-importing-member, g-multiple-import
24
+
25
+
26
+ class ConvBlock(hk.Module):
27
+ """A convolutional block with GELU activation and RMS Batch Normalization."""
28
+
29
+ def __init__(self, num_channels: int, width: int, name: str | None = None):
30
+ """Initializes the convolutional block.
31
+
32
+ Args:
33
+ num_channels: The number of output channels.
34
+ width: The width of the convolution. If 1, a linear layer is used instead.
35
+ name: The name of the module.
36
+ """
37
+ super().__init__(name=name)
38
+ self._num_channels = num_channels
39
+ self._width = width
40
+
41
+ @typing.jaxtyped
42
+ def __call__(
43
+ self, x: Float[Array, 'B S D']
44
+ ) -> Float[Array, 'B S {self._num_channels}']:
45
+ x = layers.gelu(layers.RMSBatchNorm()(x))
46
+ if self._width == 1:
47
+ return hk.Linear(self._num_channels)(x)
48
+ else:
49
+ return StandardizedConv1D(
50
+ num_channels=self._num_channels, width=self._width
51
+ )(x)
52
+
53
+
54
+ class StandardizedConv1D(hk.Module):
55
+ """Standardized 1D Convolution with scaled weight standardization."""
56
+
57
+ def __init__(
58
+ self,
59
+ num_channels: int,
60
+ width: int,
61
+ name: str | None = None,
62
+ ):
63
+ super().__init__(name=name)
64
+ self._num_channels = num_channels
65
+ self._width = width
66
+
67
+ @typing.jaxtyped
68
+ def __call__(
69
+ self, x: Float[Array, 'B S D']
70
+ ) -> Float[Array, 'B S {self._num_channels}']:
71
+ input_channels = x.shape[-1]
72
+ fan_in = self._width * input_channels
73
+ kernel_shape = (self._width, input_channels, self._num_channels)
74
+ w = hk.get_parameter('w', shape=kernel_shape, dtype=x.dtype, init=jnp.zeros)
75
+
76
+ # Weight standardization
77
+ w -= jnp.mean(w, axis=(0, 1), keepdims=True)
78
+ var_w = jnp.var(w, axis=(0, 1), keepdims=True)
79
+ scale = hk.get_parameter(
80
+ 'scale',
81
+ shape=[1, 1, self._num_channels],
82
+ init=jnp.ones,
83
+ dtype=w.dtype,
84
+ )
85
+ scale = scale * jax.lax.rsqrt(jnp.maximum(fan_in * var_w, 1e-4))
86
+ w_standardized = w * scale
87
+
88
+ out = jax.lax.conv_general_dilated(
89
+ lhs=x,
90
+ rhs=w_standardized,
91
+ window_strides=[1],
92
+ padding='SAME',
93
+ dimension_numbers=jax.lax.ConvDimensionNumbers(
94
+ lhs_spec=(0, 2, 1), rhs_spec=(2, 1, 0), out_spec=(0, 2, 1)
95
+ ),
96
+ )
97
+ bias = hk.get_parameter(
98
+ 'bias', shape=(self._num_channels,), dtype=x.dtype, init=jnp.zeros
99
+ )
100
+ bias = jnp.broadcast_to(bias, out.shape)
101
+ return out + bias
102
+
103
+
104
+ class DnaEmbedder(hk.Module):
105
+ """Encodes one-hot encoded DNA sequences into a fixed-length embedding."""
106
+
107
+ @typing.jaxtyped
108
+ def __call__(
109
+ self, dna_sequence: Float[Array, 'B S 4']
110
+ ) -> Float[Array, 'B S 768']:
111
+ x = hk.Conv1D(output_channels=768, kernel_shape=15)(dna_sequence)
112
+ return x + ConvBlock(num_channels=768, width=5)(x)
113
+
114
+
115
+ class DownResBlock(hk.Module):
116
+ """Down resolution convolution."""
117
+
118
+ @typing.jaxtyped
119
+ def __call__(self, x: Float[Array, 'B S D']) -> Float[Array, 'B S D+128']:
120
+ num_out_channels = x.shape[-1] + 128
121
+ out = ConvBlock(num_channels=num_out_channels, width=5)(x)
122
+ out = out + jnp.pad(
123
+ x, [(0, 0), (0, 0), (0, 128)]
124
+ ) # Padding for residual connection
125
+ return out + ConvBlock(num_channels=out.shape[-1], width=5)(out)
126
+
127
+
128
+ class UpResBlock(hk.Module):
129
+ """Upsampling residual block."""
130
+
131
+ @typing.jaxtyped
132
+ def __call__(
133
+ self, x: Float[Array, 'B S D'], unet_skip: Float[Array, 'B S_skip D_skip']
134
+ ) -> Float[Array, 'B S_up D_skip']:
135
+ chex.assert_rank(x, 3)
136
+ chex.assert_rank(unet_skip, 3)
137
+ num_channels = unet_skip.shape[-1]
138
+ out = (
139
+ ConvBlock(num_channels=num_channels, width=5, name='conv_in')(x)
140
+ + x[:, :, :num_channels]
141
+ )
142
+ out = jnp.repeat(out, 2, axis=1) # Upsampling
143
+ residual_scale = hk.get_parameter(
144
+ 'residual_scale', (), init=jnp.ones
145
+ ).astype(out.dtype)
146
+ out *= residual_scale
147
+ out += ConvBlock(
148
+ num_channels=num_channels, width=1, name='pointwise_conv_unet_skip'
149
+ )(unet_skip)
150
+ return out + ConvBlock(num_channels=num_channels, width=5, name='conv_out')(
151
+ out
152
+ )
flax_model/alphagenome/model/convolutions_test.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from absl.testing import absltest
16
+ from absl.testing import parameterized
17
+ from flax_model.alphagenome.model import convolutions
18
+ import chex
19
+ import haiku as hk
20
+ import jax
21
+ import jax.numpy as jnp
22
+
23
+
24
+ class ConvolutionsTest(parameterized.TestCase):
25
+
26
+ def setUp(self):
27
+ super().setUp()
28
+ self._batch_size = 4
29
+ self._sequence_length = 200
30
+ self._input_channels = 768
31
+ self._output_channels = 256
32
+ self._dna_embedder_output_channels = 768
33
+ self._unet_skip_channels = 512
34
+ self._down_block_added_channels = 128
35
+ self._rng = jax.random.PRNGKey(42)
36
+
37
+ @parameterized.named_parameters(
38
+ dict(testcase_name='width_1', width=1),
39
+ dict(testcase_name='width_5', width=5),
40
+ )
41
+ def test_conv_block_output_shape(self, width: int):
42
+ def _conv_block(x):
43
+ return convolutions.ConvBlock(
44
+ num_channels=self._output_channels, width=width
45
+ )(x)
46
+
47
+ conv_block = hk.transform_with_state(_conv_block)
48
+ x = jnp.zeros(
49
+ (self._batch_size, self._sequence_length, self._input_channels)
50
+ )
51
+ params, state = conv_block.init(self._rng, x)
52
+ out, state = conv_block.apply(params, state, self._rng, x)
53
+ chex.assert_shape(
54
+ out, (self._batch_size, self._sequence_length, self._output_channels)
55
+ )
56
+ self.assertNotEmpty(state)
57
+
58
+ def test_standardized_conv1d_output_shape(self):
59
+ def _standardized_conv1d(x):
60
+ return convolutions.StandardizedConv1D(
61
+ num_channels=self._output_channels, width=5
62
+ )(x)
63
+
64
+ standardized_conv1d = hk.transform_with_state(_standardized_conv1d)
65
+ x = jnp.zeros(
66
+ (self._batch_size, self._sequence_length, self._input_channels)
67
+ )
68
+ params, state = standardized_conv1d.init(self._rng, x)
69
+ out, state = standardized_conv1d.apply(params, state, self._rng, x)
70
+ chex.assert_shape(
71
+ out, (self._batch_size, self._sequence_length, self._output_channels)
72
+ )
73
+
74
+ def test_dna_embedder_output_shape(self):
75
+ def _dna_embedder(x):
76
+ return convolutions.DnaEmbedder()(x)
77
+
78
+ dna_embedder = hk.transform_with_state(_dna_embedder)
79
+ x = jnp.zeros((self._batch_size, self._sequence_length, 4))
80
+ params, state = dna_embedder.init(self._rng, x)
81
+ out, state = dna_embedder.apply(params, state, self._rng, x)
82
+ chex.assert_shape(
83
+ out,
84
+ (
85
+ self._batch_size,
86
+ self._sequence_length,
87
+ self._dna_embedder_output_channels,
88
+ ),
89
+ )
90
+ self.assertNotEmpty(state)
91
+
92
+ def test_down_res_block_output_shape(self):
93
+ def _down_res_block(x):
94
+ return convolutions.DownResBlock()(x)
95
+
96
+ down_res_block = hk.transform_with_state(_down_res_block)
97
+ x = jnp.zeros(
98
+ (self._batch_size, self._sequence_length, self._input_channels)
99
+ )
100
+ params, state = down_res_block.init(self._rng, x)
101
+ out, state = down_res_block.apply(params, state, self._rng, x)
102
+ chex.assert_shape(
103
+ out,
104
+ (
105
+ self._batch_size,
106
+ self._sequence_length,
107
+ self._input_channels + self._down_block_added_channels,
108
+ ),
109
+ )
110
+ self.assertNotEmpty(state)
111
+
112
+ def test_up_res_block_output_shape(self):
113
+ def _up_res_block(x, unet_skip):
114
+ return convolutions.UpResBlock()(x, unet_skip)
115
+
116
+ up_res_block = hk.transform_with_state(_up_res_block)
117
+ x = jnp.zeros(
118
+ (self._batch_size, self._sequence_length, self._input_channels)
119
+ )
120
+ unet_skip = jnp.zeros(
121
+ (self._batch_size, self._sequence_length * 2, self._unet_skip_channels)
122
+ )
123
+ params, state = up_res_block.init(self._rng, x, unet_skip)
124
+ out, state = up_res_block.apply(params, state, self._rng, x, unet_skip)
125
+ chex.assert_shape(
126
+ out,
127
+ (
128
+ self._batch_size,
129
+ self._sequence_length * 2,
130
+ self._unet_skip_channels,
131
+ ),
132
+ )
133
+ self.assertNotEmpty(state)
134
+
135
+
136
+ if __name__ == '__main__':
137
+ absltest.main()
flax_model/alphagenome/model/dna_model.py ADDED
@@ -0,0 +1,1326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Implementation of alphagenome DNAModel interface."""
16
+
17
+ from collections.abc import Callable, Iterable, Mapping, Sequence
18
+ import dataclasses
19
+ import functools
20
+ import os
21
+ import threading
22
+ from typing import TypeAlias
23
+
24
+ from flax_model.alphagenome._sdk import tensor_utils
25
+ from flax_model.alphagenome._sdk import typing
26
+ from flax_model.alphagenome._sdk.data import genome
27
+ from flax_model.alphagenome._sdk.data import junction_data
28
+ from flax_model.alphagenome._sdk.data import ontology
29
+ from flax_model.alphagenome._sdk.data import track_data
30
+ from flax_model.alphagenome._sdk.interpretation import ism
31
+ from flax_model.alphagenome._sdk.models import dna_model
32
+ from flax_model.alphagenome._sdk.models import dna_output
33
+ from flax_model.alphagenome._sdk.models import interval_scorers as interval_scorers_lib
34
+ from flax_model.alphagenome._sdk.models import variant_scorers as variant_scorers_lib
35
+ from flax_model.alphagenome.io import fasta
36
+ from flax_model.alphagenome.io import genome as genome_io
37
+ from flax_model.alphagenome.io import splicing as splicing_io
38
+ from flax_model.alphagenome.model import augmentation
39
+ from flax_model.alphagenome.model import model
40
+ from flax_model.alphagenome.model import one_hot_encoder
41
+ from flax_model.alphagenome.model import splicing
42
+ from flax_model.alphagenome.model.interval_scoring import gene_mask as interval_gene_mask
43
+ from flax_model.alphagenome.model.metadata import metadata as metadata_lib
44
+ from flax_model.alphagenome.model.variant_scoring import center_mask
45
+ from flax_model.alphagenome.model.variant_scoring import contact_map
46
+ from flax_model.alphagenome.model.variant_scoring import gene_mask
47
+ from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor
48
+ from flax_model.alphagenome.model.variant_scoring import polyadenylation
49
+ from flax_model.alphagenome.model.variant_scoring import splice_junction
50
+ from flax_model.alphagenome.model.variant_scoring import variant_scoring
51
+ import anndata
52
+ import chex
53
+ import haiku as hk
54
+ import huggingface_hub
55
+ import jax
56
+ import jax.numpy as jnp
57
+ from jaxtyping import Array, Bool, Float, Float32, Int32, PyTree, Shaped # pylint: disable=g-importing-member, g-multiple-import
58
+ import jmp
59
+ import kagglehub
60
+ from kagglehub import auth as kaggle_auth
61
+ import numpy as np
62
+ import orbax.checkpoint as ocp
63
+ import pandas as pd
64
+
65
+
66
+ AlphaGenomeOutputMetadata: TypeAlias = metadata_lib.AlphaGenomeOutputMetadata
67
+ ModelVersion: TypeAlias = dna_model.ModelVersion
68
+ Organism: TypeAlias = dna_model.Organism
69
+ Output: TypeAlias = dna_output.Output
70
+ OutputMetadata: TypeAlias = dna_output.OutputMetadata
71
+ OutputType: TypeAlias = dna_output.OutputType
72
+ VariantOutput: TypeAlias = dna_output.VariantOutput
73
+ Organism: TypeAlias = dna_model.Organism
74
+
75
+ BatchPrediction: TypeAlias = PyTree[
76
+ Float[Array, 'B ...'] | Int32[Array, 'B ...']
77
+ ]
78
+
79
+ ApplyFn = Callable[
80
+ [
81
+ hk.Params,
82
+ hk.State,
83
+ Float32[Array, 'B S 4'],
84
+ Int32[Array, 'B'],
85
+ ],
86
+ BatchPrediction,
87
+ ]
88
+ JunctionsApplyFn = Callable[
89
+ [
90
+ hk.Params,
91
+ hk.State,
92
+ Float32[Array, 'B S D'],
93
+ Int32[Array, 'B 4 K'],
94
+ Int32[Array, 'B'],
95
+ ],
96
+ BatchPrediction,
97
+ ]
98
+
99
+
100
+ def extract_predictions(
101
+ predictions: BatchPrediction,
102
+ ) -> Mapping[dna_output.OutputType, BatchPrediction]:
103
+ """Extracts predictions from the model predictions."""
104
+ results = {}
105
+ for output_type in dna_output.OutputType:
106
+ match output_type:
107
+ case dna_output.OutputType.ATAC:
108
+ prediction = predictions.get('atac', {}).get('predictions_1bp')
109
+ case dna_output.OutputType.CAGE:
110
+ prediction = predictions.get('cage', {}).get('predictions_1bp')
111
+ case dna_output.OutputType.DNASE:
112
+ prediction = predictions.get('dnase', {}).get('predictions_1bp')
113
+ case dna_output.OutputType.RNA_SEQ:
114
+ prediction = predictions.get('rna_seq', {}).get('predictions_1bp')
115
+ case dna_output.OutputType.CHIP_HISTONE:
116
+ prediction = predictions.get('chip_histone', {}).get(
117
+ 'predictions_128bp'
118
+ )
119
+ case dna_output.OutputType.CHIP_TF:
120
+ prediction = predictions.get('chip_tf', {}).get('predictions_128bp')
121
+ case dna_output.OutputType.SPLICE_SITES:
122
+ prediction = predictions.get('splice_sites_classification', {}).get(
123
+ 'predictions'
124
+ )
125
+ case dna_output.OutputType.SPLICE_SITE_USAGE:
126
+ prediction = predictions.get('splice_sites_usage', {}).get(
127
+ 'predictions'
128
+ )
129
+ case dna_output.OutputType.SPLICE_JUNCTIONS:
130
+ if (
131
+ splice_site_preds := predictions.get('splice_sites_junction')
132
+ ) is not None:
133
+ prediction = {
134
+ 'predictions': splice_site_preds.get('predictions'),
135
+ 'splice_site_positions': splice_site_preds.get(
136
+ 'splice_site_positions'
137
+ ),
138
+ }
139
+ else:
140
+ prediction = None
141
+ case dna_output.OutputType.CONTACT_MAPS:
142
+ prediction = predictions.get('contact_maps', {}).get('predictions')
143
+ case dna_output.OutputType.PROCAP:
144
+ prediction = predictions.get('procap', {}).get('predictions_1bp')
145
+ case _:
146
+ raise ValueError(f'Unsupported output type: {output_type}')
147
+ if prediction is not None:
148
+ results[output_type] = prediction
149
+ return results
150
+
151
+
152
+ @typing.jaxtyped
153
+ def _predict(
154
+ params: hk.Params,
155
+ state: hk.State,
156
+ sequences: Float32[Array, 'B S 4'],
157
+ organism_indices: Int32[Array, 'B'],
158
+ *,
159
+ strand_reindexing: Mapping[dna_output.OutputType, Int32[Array, '_']],
160
+ negative_strand_mask: Bool[Array, 'B'],
161
+ apply_fn: ApplyFn,
162
+ ) -> Mapping[dna_output.OutputType, BatchPrediction]:
163
+ """Maps predictions to output types and optionally reverse complements."""
164
+ predictions = apply_fn(params, state, sequences, organism_indices)
165
+ predictions = extract_predictions(predictions)
166
+ predictions = augmentation.reverse_complement(
167
+ predictions,
168
+ negative_strand_mask,
169
+ strand_reindexing=strand_reindexing,
170
+ sequence_length=sequences.shape[1],
171
+ )
172
+ return predictions
173
+
174
+
175
+ @typing.jaxtyped
176
+ def _predict_variant(
177
+ params: hk.Params,
178
+ state: hk.State,
179
+ reference_sequences: Float32[Array, 'B S 4'],
180
+ alternate_sequences: Float32[Array, 'B S 4'],
181
+ splice_sites: Bool[Array, 'B S 5'] | None,
182
+ organism_indices: Int32[Array, 'B'],
183
+ strand_reindexing: Mapping[dna_output.OutputType, Int32[Array, '_']],
184
+ negative_strand_mask: Bool[Array, 'B'],
185
+ *,
186
+ apply_fn: ApplyFn,
187
+ junctions_apply_fn: JunctionsApplyFn,
188
+ num_splice_sites: int,
189
+ splice_site_threshold: float,
190
+ ) -> tuple[
191
+ Mapping[dna_output.OutputType, BatchPrediction],
192
+ Mapping[dna_output.OutputType, BatchPrediction],
193
+ ]:
194
+ """Computes and reverse-complements variant predictions."""
195
+ chex.assert_equal_shape([reference_sequences, alternate_sequences])
196
+ sequence_length = reference_sequences.shape[1]
197
+
198
+ reference_predictions = apply_fn(
199
+ params,
200
+ state,
201
+ reference_sequences,
202
+ organism_indices,
203
+ )
204
+ alternate_predictions = apply_fn(
205
+ params,
206
+ state,
207
+ alternate_sequences,
208
+ organism_indices,
209
+ )
210
+ # Get union of splice site positions across ref and alt.
211
+ ref_and_alt_splice_site_positions = splicing.generate_splice_site_positions(
212
+ ref=reference_predictions['splice_sites_classification']['predictions'],
213
+ alt=alternate_predictions['splice_sites_classification']['predictions'],
214
+ splice_sites=splice_sites,
215
+ k=num_splice_sites,
216
+ pad_to_length=num_splice_sites,
217
+ threshold=splice_site_threshold,
218
+ )
219
+ reference_predictions['splice_sites_junction'] = junctions_apply_fn(
220
+ params,
221
+ state,
222
+ reference_predictions['embeddings_1bp'],
223
+ ref_and_alt_splice_site_positions,
224
+ organism_indices,
225
+ )
226
+ alternate_predictions['splice_sites_junction'] = junctions_apply_fn(
227
+ params,
228
+ state,
229
+ alternate_predictions['embeddings_1bp'],
230
+ ref_and_alt_splice_site_positions,
231
+ organism_indices,
232
+ )
233
+
234
+ def _extract_and_rc(predictions):
235
+ return augmentation.reverse_complement(
236
+ extract_predictions(predictions),
237
+ negative_strand_mask,
238
+ strand_reindexing=strand_reindexing,
239
+ sequence_length=sequence_length,
240
+ )
241
+
242
+ return (
243
+ _extract_and_rc(reference_predictions),
244
+ _extract_and_rc(alternate_predictions),
245
+ )
246
+
247
+
248
+ @typing.jaxtyped
249
+ def _filter_predictions(
250
+ predictions: Mapping[dna_output.OutputType, BatchPrediction],
251
+ *,
252
+ track_masks: Mapping[dna_output.OutputType, Bool[Array, '_']],
253
+ ) -> Mapping[dna_output.OutputType, BatchPrediction]:
254
+ """Filters predictions by mapping of track masks."""
255
+ result = {}
256
+ for output_type, mask in track_masks.items():
257
+ if (prediction := predictions.get(output_type)) is not None:
258
+ # JAX dynamic slicing does not work with transfer_guard.
259
+ with jax.transfer_guard('allow'):
260
+ if output_type == dna_output.OutputType.SPLICE_JUNCTIONS:
261
+ result[output_type] = {
262
+ 'predictions': prediction['predictions'][
263
+ ..., jnp.tile(mask, reps=2)
264
+ ],
265
+ 'splice_site_positions': prediction['splice_site_positions'],
266
+ }
267
+ else:
268
+ result[output_type] = prediction[..., mask]
269
+ return result
270
+
271
+
272
+ @functools.partial(jax.jit, static_argnames=['transfer_to_host'])
273
+ @typing.jaxtyped
274
+ def _upcast_single_batch_predictions(
275
+ x: PyTree[Float[Array, '1 ...'] | Int32[Array, '1 ...']],
276
+ *,
277
+ transfer_to_host: bool = True,
278
+ ) -> PyTree[
279
+ Float32[Array | np.ndarray, '...'] | Int32[Array | np.ndarray, '...']
280
+ ]:
281
+ """Helper to upcast and optionally transfer predictions to host."""
282
+ x = jax.tree.map(lambda x: tensor_utils.upcast_floating(x[0]), x)
283
+ # return jax.device_put(x, jax.memory.Space.Host) if transfer_to_host else x
284
+ return jax.device_put(x, jax.devices("cpu")[0]) if transfer_to_host else x
285
+
286
+
287
+
288
+ @typing.jaxtyped
289
+ def _filter_variant_predictions(
290
+ reference_predictions: Mapping[dna_output.OutputType, BatchPrediction],
291
+ alternate_predictions: Mapping[dna_output.OutputType, BatchPrediction],
292
+ *,
293
+ track_masks: Mapping[dna_output.OutputType, Bool[Array, '_']],
294
+ ) -> tuple[
295
+ Mapping[dna_output.OutputType, BatchPrediction],
296
+ Mapping[dna_output.OutputType, BatchPrediction],
297
+ ]:
298
+ """Filters variant predictions to a set of output types."""
299
+ return (
300
+ _filter_predictions(reference_predictions, track_masks=track_masks),
301
+ _filter_predictions(alternate_predictions, track_masks=track_masks),
302
+ )
303
+
304
+
305
+ class _DeviceContextManager:
306
+ """Context manager for managing a jax.Device."""
307
+
308
+ def __init__(self, device: jax.Device):
309
+ self._device = device
310
+ self._lock = threading.Lock()
311
+
312
+ def __enter__(self) -> jax.Device:
313
+ self._lock.acquire()
314
+ return self._device
315
+
316
+ def __exit__(self, exc_type, exc_value, traceback):
317
+ del exc_type, exc_value, traceback
318
+ self._lock.release()
319
+
320
+
321
+ class AlphaGenomeModel(dna_model.DnaModel):
322
+ """Abstract class for DNA sequence models."""
323
+
324
+ def __init__(
325
+ self,
326
+ *,
327
+ params: hk.Params,
328
+ state: hk.State,
329
+ apply_fn: ApplyFn,
330
+ junctions_apply_fn: JunctionsApplyFn,
331
+ metadata: Mapping[dna_model.Organism, AlphaGenomeOutputMetadata],
332
+ fasta_extractors: (
333
+ Mapping[dna_model.Organism, fasta.FastaExtractor] | None
334
+ ) = None,
335
+ splice_site_extractors: (
336
+ Mapping[dna_model.Organism, splicing_io.SpliceSiteAnnotationExtractor]
337
+ | None
338
+ ) = None,
339
+ gtfs: Mapping[dna_model.Organism, pd.DataFrame] | None = None,
340
+ pas_gtfs: Mapping[dna_model.Organism, pd.DataFrame] | None = None,
341
+ num_splice_sites: int = 512,
342
+ splice_site_threshold: float = 0.1,
343
+ device: jax.Device | None = None,
344
+ ):
345
+ """Initializes the AlphaGenomeModel.
346
+
347
+ Args:
348
+ params: Model parameters.
349
+ state: Model state.
350
+ apply_fn: A function that takes model parameters, state, DNA sequence and
351
+ organism index; and returns the model's predictions.
352
+ junctions_apply_fn: A function that takes model parameters, state,
353
+ embeddings and splice site positions; and returns the model's junctions
354
+ predictions.
355
+ metadata: A mapping of organism to OutputMetadata.
356
+ fasta_extractors: Optional mapping of organism to FastaExtractor. If not
357
+ provided, functions that require sequence extraction will fail.
358
+ splice_site_extractors: Optional mapping of organism to
359
+ SpliceSiteAnnotationExtractor. If not provided, reference splice sits
360
+ will not be used in variant predictions.
361
+ gtfs: Optional mapping of organism to GENCODE GTF Pandas dataframe. If not
362
+ provided, variant scorers that require GTFs will not be available.
363
+ pas_gtfs: Optional mapping of organism to polyadenylation annotation
364
+ dataframe. If not provided, variant scorers that require polyadenylation
365
+ annotations will not be available.
366
+ num_splice_sites: The maximum number of splice sites that are extracted
367
+ from the splice site classification predictions.
368
+ splice_site_threshold: The threshold to use for splice site prediction.
369
+ device: Optional device to use for model prediction. If None, the first
370
+ local device will be used.
371
+ """
372
+ if device is None:
373
+ device = jax.default_device.value or jax.local_devices()[0]
374
+ if device.platform not in {'gpu', 'tpu'}:
375
+ raise ValueError(
376
+ 'Cannot find any GPU or TPU devices. We strondly recommend running'
377
+ ' on GPU or TPU, but if you wish to run on CPU, please explicitly'
378
+ ' pass the JAX device to run the model.'
379
+ )
380
+ self._device_context = _DeviceContextManager(device)
381
+ self._params = jax.device_put(params, device)
382
+ self._state = jax.device_put(state, device)
383
+ self._metadata = metadata
384
+ self._one_hot_encoder = one_hot_encoder.DNAOneHotEncoder()
385
+ self._fasta_extractors = fasta_extractors or {}
386
+ self._splice_site_extractors = splice_site_extractors or {}
387
+
388
+ self._predict = jax.jit(functools.partial(_predict, apply_fn=apply_fn))
389
+ self._predict_variant = jax.jit(
390
+ functools.partial(
391
+ _predict_variant,
392
+ apply_fn=jax.jit(apply_fn),
393
+ junctions_apply_fn=jax.jit(junctions_apply_fn),
394
+ num_splice_sites=num_splice_sites,
395
+ splice_site_threshold=splice_site_threshold,
396
+ )
397
+ )
398
+
399
+ # Metadata for each organism without padding.
400
+ self._output_metadata_by_organism = {}
401
+
402
+ gtfs = gtfs or {}
403
+ pas_gtfs = pas_gtfs or {}
404
+
405
+ for organism, organism_metadata in self._metadata.items():
406
+ masks = jax.tree.map(np.logical_not, organism_metadata.padding)
407
+ output_metadata = {
408
+ output_type.name.lower(): m[masks[output_type]]
409
+ for output_type in dna_output.OutputType
410
+ if (m := organism_metadata.get(output_type)) is not None
411
+ }
412
+ self._output_metadata_by_organism[organism] = dna_output.OutputMetadata(
413
+ **output_metadata
414
+ )
415
+
416
+ self._variant_scorers = {}
417
+
418
+ for organism in metadata.keys():
419
+ self._variant_scorers[organism]: dict[
420
+ variant_scorers_lib.BaseVariantScorer, variant_scoring.VariantScorer
421
+ ] = {
422
+ variant_scorers_lib.BaseVariantScorer.CENTER_MASK: (
423
+ center_mask.CenterMaskVariantScorer()
424
+ ),
425
+ variant_scorers_lib.BaseVariantScorer.CONTACT_MAP: (
426
+ contact_map.ContactMapScorer()
427
+ ),
428
+ }
429
+ if (gtf := gtfs.get(organism)) is not None:
430
+ gene_scorer = gene_mask.GeneVariantScorer(
431
+ gene_mask_extractor=gene_mask_extractor.GeneMaskExtractor(
432
+ gtf=gtf,
433
+ gene_query_type=(
434
+ gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED
435
+ ),
436
+ gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS,
437
+ ),
438
+ )
439
+ self._variant_scorers[organism][
440
+ variant_scorers_lib.BaseVariantScorer.GENE_MASK_LFC
441
+ ] = gene_scorer
442
+ self._variant_scorers[organism][
443
+ variant_scorers_lib.BaseVariantScorer.GENE_MASK_ACTIVE
444
+ ] = gene_scorer
445
+ self._variant_scorers[organism][
446
+ variant_scorers_lib.BaseVariantScorer.GENE_MASK_SPLICING
447
+ ] = gene_scorer
448
+ self._variant_scorers[organism][
449
+ variant_scorers_lib.BaseVariantScorer.SPLICE_JUNCTION
450
+ ] = splice_junction.SpliceJunctionVariantScorer(gtf)
451
+ if (pas_gtf := pas_gtfs.get(organism)) is not None:
452
+ self._variant_scorers[organism][
453
+ variant_scorers_lib.BaseVariantScorer.PA_QTL
454
+ ] = polyadenylation.PolyadenylationVariantScorer(gtf, pas_gtf)
455
+
456
+ self._interval_scorers = {}
457
+
458
+ for organism in metadata.keys():
459
+ self._interval_scorers[organism] = {}
460
+ if (gtf := gtfs.get(organism)) is not None:
461
+ self._interval_scorers[organism][
462
+ interval_scorers_lib.BaseIntervalScorer.GENE_MASK
463
+ ] = interval_gene_mask.GeneIntervalScorer(
464
+ gene_mask_extractor=gene_mask_extractor.GeneMaskExtractor(
465
+ gtf=gtf,
466
+ gene_query_type=(
467
+ gene_mask_extractor.GeneQueryType.INTERVAL_CONTAINED
468
+ ),
469
+ gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS,
470
+ ),
471
+ )
472
+
473
+ def _get_fasta_extractor(
474
+ self, organism: dna_model.Organism
475
+ ) -> fasta.FastaExtractor:
476
+ """Returns the FastaExtractor for a given organism."""
477
+ if extractor := self._fasta_extractors.get(organism):
478
+ return extractor
479
+ else:
480
+ raise ValueError(f'FastaExtractor not found for {organism.name=}')
481
+
482
+ def predict_sequence(
483
+ self,
484
+ sequence: str,
485
+ *,
486
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
487
+ requested_outputs: Iterable[dna_output.OutputType],
488
+ ontology_terms: Iterable[ontology.OntologyTerm | str] | None,
489
+ interval: genome.Interval | None = None,
490
+ ) -> dna_output.Output:
491
+ """Predicts the sequence."""
492
+ if ontology_terms is not None:
493
+ ontology_terms = set(
494
+ ontology.from_curie(o) if isinstance(o, str) else o
495
+ for o in ontology_terms
496
+ )
497
+ metadata = self._metadata[organism]
498
+ track_masks = metadata_lib.create_track_masks(
499
+ metadata,
500
+ requested_outputs=set(requested_outputs),
501
+ requested_ontologies=ontology_terms,
502
+ )
503
+
504
+ with self._device_context as device, jax.transfer_guard('disallow'):
505
+ organism_index = jax.device_put(
506
+ np.full((1,), convert_to_organism_index(organism), dtype=np.int32),
507
+ device,
508
+ )
509
+ sequence = jax.device_put(
510
+ np.asarray(self._one_hot_encoder.encode(sequence))[np.newaxis], device
511
+ )
512
+ predictions = self._predict(
513
+ self._params,
514
+ self._state,
515
+ sequence,
516
+ organism_index,
517
+ negative_strand_mask=jax.device_put(np.asarray([False]), device),
518
+ strand_reindexing=jax.device_put(metadata.strand_reindexing, device),
519
+ )
520
+ predictions = _filter_predictions(
521
+ predictions, track_masks=jax.device_put(track_masks, device)
522
+ )
523
+ predictions = _upcast_single_batch_predictions(predictions)
524
+ return _construct_output_from_predictions(
525
+ predictions,
526
+ track_masks=track_masks,
527
+ metadata=metadata,
528
+ interval=interval,
529
+ )
530
+
531
+ def predict_interval(
532
+ self,
533
+ interval: genome.Interval,
534
+ *,
535
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
536
+ requested_outputs: Iterable[dna_output.OutputType],
537
+ ontology_terms: Iterable[ontology.OntologyTerm | str] | None,
538
+ ) -> dna_output.Output:
539
+ if ontology_terms is not None:
540
+ ontology_terms = set(
541
+ ontology.from_curie(o) if isinstance(o, str) else o
542
+ for o in ontology_terms
543
+ )
544
+ sequence = self._get_fasta_extractor(organism).extract(interval)
545
+ metadata = self._metadata[organism]
546
+ track_masks = metadata_lib.create_track_masks(
547
+ metadata,
548
+ requested_outputs=set(requested_outputs),
549
+ requested_ontologies=ontology_terms,
550
+ )
551
+
552
+ with self._device_context as device, jax.transfer_guard('disallow'):
553
+ organism_index = jax.device_put(
554
+ np.full((1,), convert_to_organism_index(organism), dtype=np.int32),
555
+ device,
556
+ )
557
+ sequence = jax.device_put(
558
+ np.asarray(self._one_hot_encoder.encode(sequence))[np.newaxis], device
559
+ )
560
+ predictions = self._predict(
561
+ self._params,
562
+ self._state,
563
+ sequence,
564
+ organism_index,
565
+ negative_strand_mask=jax.device_put(
566
+ np.asarray([interval.negative_strand]), device
567
+ ),
568
+ strand_reindexing=jax.device_put(metadata.strand_reindexing, device),
569
+ )
570
+ predictions = _filter_predictions(
571
+ predictions, track_masks=jax.device_put(track_masks, device)
572
+ )
573
+ predictions = _upcast_single_batch_predictions(predictions)
574
+ return _construct_output_from_predictions(
575
+ predictions,
576
+ track_masks=track_masks,
577
+ metadata=metadata,
578
+ interval=interval,
579
+ )
580
+
581
+ def predict_variant(
582
+ self,
583
+ interval: genome.Interval,
584
+ variant: genome.Variant,
585
+ *,
586
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
587
+ requested_outputs: Iterable[dna_output.OutputType],
588
+ ontology_terms: Iterable[ontology.OntologyTerm | str] | None,
589
+ ) -> dna_output.VariantOutput:
590
+ if ontology_terms is not None:
591
+ ontology_terms = set(
592
+ ontology.from_curie(o) if isinstance(o, str) else o
593
+ for o in ontology_terms
594
+ )
595
+ reference_sequence, alternate_sequence = (
596
+ genome_io.extract_variant_sequences(
597
+ interval, variant, self._get_fasta_extractor(organism)
598
+ )
599
+ )
600
+ metadata = self._metadata[organism]
601
+ track_masks = metadata_lib.create_track_masks(
602
+ metadata,
603
+ requested_outputs=set(requested_outputs),
604
+ requested_ontologies=ontology_terms,
605
+ )
606
+ splice_sites = None
607
+ if splice_site_extractor := self._splice_site_extractors.get(organism):
608
+ splice_sites = splice_site_extractor.extract(interval)[np.newaxis]
609
+
610
+ with self._device_context as device, jax.transfer_guard('disallow'):
611
+ reference_sequence = jax.device_put(
612
+ np.asarray(self._one_hot_encoder.encode(reference_sequence))[
613
+ np.newaxis
614
+ ],
615
+ device,
616
+ )
617
+ alternate_sequence = jax.device_put(
618
+ np.asarray(self._one_hot_encoder.encode(alternate_sequence))[
619
+ np.newaxis
620
+ ],
621
+ device,
622
+ )
623
+ organism_indices = jax.device_put(
624
+ np.full((1,), convert_to_organism_index(organism), dtype=np.int32),
625
+ device,
626
+ )
627
+ reference_predictions, alt_predictions = self._predict_variant(
628
+ self._params,
629
+ self._state,
630
+ reference_sequence,
631
+ alternate_sequence,
632
+ jax.device_put(splice_sites, device),
633
+ organism_indices,
634
+ negative_strand_mask=jax.device_put(
635
+ np.asarray([interval.negative_strand]), device
636
+ ),
637
+ strand_reindexing=jax.device_put(metadata.strand_reindexing, device),
638
+ )
639
+ reference_predictions, alt_predictions = _filter_variant_predictions(
640
+ reference_predictions,
641
+ alt_predictions,
642
+ track_masks=jax.device_put(track_masks, device),
643
+ )
644
+ reference_predictions, alt_predictions = _upcast_single_batch_predictions(
645
+ (reference_predictions, alt_predictions)
646
+ )
647
+
648
+ return dna_output.VariantOutput(
649
+ reference=_construct_output_from_predictions(
650
+ reference_predictions,
651
+ track_masks=track_masks,
652
+ metadata=metadata,
653
+ interval=interval,
654
+ ),
655
+ alternate=_construct_output_from_predictions(
656
+ alt_predictions,
657
+ track_masks=track_masks,
658
+ metadata=metadata,
659
+ interval=interval,
660
+ ),
661
+ )
662
+
663
+ def score_interval(
664
+ self,
665
+ interval: genome.Interval,
666
+ interval_scorers: Sequence[interval_scorers_lib.IntervalScorerTypes] = (),
667
+ *,
668
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
669
+ ) -> list[anndata.AnnData]:
670
+ if not interval_scorers:
671
+ interval_scorers = list(
672
+ interval_scorers_lib.RECOMMENDED_INTERVAL_SCORERS.values()
673
+ )
674
+
675
+ sequence = self._get_fasta_extractor(organism).extract(interval)
676
+ sequence = np.array(self._one_hot_encoder.encode(sequence))[np.newaxis]
677
+ organism_indices = np.full(
678
+ (1,), convert_to_organism_index(organism), dtype=np.int32
679
+ )
680
+
681
+ requested_outputs = set(
682
+ scorer.requested_output for scorer in interval_scorers
683
+ )
684
+
685
+ track_metadata = self._metadata[organism]
686
+ track_masks = metadata_lib.create_track_masks(
687
+ track_metadata,
688
+ requested_outputs=requested_outputs,
689
+ requested_ontologies=None,
690
+ )
691
+
692
+ with self._device_context as device, jax.transfer_guard('disallow'):
693
+ predictions = self._predict(
694
+ self._params,
695
+ self._state,
696
+ jax.device_put(sequence, device),
697
+ jax.device_put(organism_indices, device),
698
+ negative_strand_mask=jax.device_put(
699
+ np.asarray([interval.negative_strand]), device
700
+ ),
701
+ strand_reindexing=jax.device_put(
702
+ track_metadata.strand_reindexing, device
703
+ ),
704
+ )
705
+ predictions = _filter_predictions(
706
+ predictions,
707
+ track_masks=jax.device_put(track_masks, device),
708
+ )
709
+ predictions = _upcast_single_batch_predictions(
710
+ predictions,
711
+ transfer_to_host=False,
712
+ )
713
+ output_metadata = self.output_metadata(organism)
714
+
715
+ results = []
716
+
717
+ for scorer_settings in interval_scorers:
718
+ scorer = self._interval_scorers[organism][
719
+ scorer_settings.base_interval_scorer
720
+ ]
721
+ masks, metadata = scorer.get_masks_and_metadata(
722
+ interval,
723
+ settings=scorer_settings,
724
+ track_metadata=output_metadata,
725
+ )
726
+ masks = jax.device_put(masks, device)
727
+ scores = scorer.score_interval(
728
+ predictions,
729
+ masks=masks,
730
+ settings=scorer_settings,
731
+ interval=interval,
732
+ )
733
+ result = scorer.finalize_interval(
734
+ jax.device_get(scores),
735
+ track_metadata=output_metadata,
736
+ mask_metadata=metadata,
737
+ settings=scorer_settings,
738
+ )
739
+ result.uns['interval'] = interval
740
+ result.uns['interval_scorer'] = scorer_settings
741
+ results.append(result)
742
+
743
+ return results
744
+
745
+ def score_variant(
746
+ self,
747
+ interval: genome.Interval,
748
+ variant: genome.Variant,
749
+ variant_scorers: Sequence[variant_scorers_lib.VariantScorerTypes] = (),
750
+ *,
751
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
752
+ ) -> list[anndata.AnnData]:
753
+ if not variant_scorers:
754
+ variant_scorers = variant_scorers_lib.get_recommended_scorers(
755
+ organism.to_proto()
756
+ )
757
+ for scorer in variant_scorers:
758
+ if scorer.base_variant_scorer not in self._variant_scorers[organism]:
759
+ raise ValueError(
760
+ f"Scorer '{scorer.base_variant_scorer}' is missing for"
761
+ f' {organism.name=}. This may be due to a missing variant scorer'
762
+ ' metadata.'
763
+ )
764
+ reference_sequence, alternate_sequence = (
765
+ genome_io.extract_variant_sequences(
766
+ interval, variant, self._get_fasta_extractor(organism)
767
+ )
768
+ )
769
+ reference_sequence = np.asarray(
770
+ self._one_hot_encoder.encode(reference_sequence)
771
+ )[np.newaxis]
772
+ alternate_sequence = np.asarray(
773
+ self._one_hot_encoder.encode(alternate_sequence)
774
+ )[np.newaxis]
775
+ organism_indices = np.full(
776
+ (1,), convert_to_organism_index(organism), dtype=np.int32
777
+ )
778
+ splice_sites = None
779
+ if splice_site_extractor := self._splice_site_extractors.get(organism):
780
+ splice_sites = splice_site_extractor.extract(interval)[np.newaxis]
781
+
782
+ requested_outputs = set(
783
+ scorer.requested_output for scorer in variant_scorers
784
+ )
785
+
786
+ track_metadata = self._metadata[organism]
787
+ track_masks = metadata_lib.create_track_masks(
788
+ track_metadata,
789
+ requested_outputs=requested_outputs,
790
+ requested_ontologies=None,
791
+ )
792
+
793
+ with self._device_context as device, jax.transfer_guard('disallow'):
794
+
795
+ reference_predictions, alternate_predictions = self._predict_variant(
796
+ self._params,
797
+ self._state,
798
+ jax.device_put(reference_sequence, device),
799
+ jax.device_put(alternate_sequence, device),
800
+ jax.device_put(splice_sites, device),
801
+ jax.device_put(organism_indices, device),
802
+ negative_strand_mask=jax.device_put(
803
+ np.asarray([interval.negative_strand]), device
804
+ ),
805
+ strand_reindexing=jax.device_put(
806
+ track_metadata.strand_reindexing, device
807
+ ),
808
+ )
809
+ reference_predictions, alternate_predictions = (
810
+ _filter_variant_predictions(
811
+ reference_predictions,
812
+ alternate_predictions,
813
+ track_masks=jax.device_put(track_masks, device),
814
+ )
815
+ )
816
+ reference_predictions, alternate_predictions = (
817
+ _upcast_single_batch_predictions(
818
+ (reference_predictions, alternate_predictions),
819
+ transfer_to_host=False,
820
+ )
821
+ )
822
+ output_metadata = self.output_metadata(organism)
823
+
824
+ results = []
825
+
826
+ for scorer_settings in variant_scorers:
827
+ scorer = self._variant_scorers[organism][
828
+ scorer_settings.base_variant_scorer
829
+ ]
830
+ masks, metadata = scorer.get_masks_and_metadata(
831
+ interval,
832
+ variant,
833
+ settings=scorer_settings,
834
+ track_metadata=output_metadata,
835
+ )
836
+ masks = jax.device_put(masks, device)
837
+ scores = scorer.score_variant(
838
+ reference_predictions,
839
+ alternate_predictions,
840
+ masks=masks,
841
+ settings=scorer_settings,
842
+ variant=variant,
843
+ interval=interval,
844
+ )
845
+ result = scorer.finalize_variant(
846
+ jax.device_get(scores),
847
+ track_metadata=output_metadata,
848
+ mask_metadata=metadata,
849
+ settings=scorer_settings,
850
+ )
851
+ result.uns['interval'] = interval
852
+ result.uns['variant'] = variant
853
+ result.uns['variant_scorer'] = scorer_settings
854
+ results.append(result)
855
+
856
+ return results
857
+
858
+ def score_ism_variants(
859
+ self,
860
+ interval: genome.Interval,
861
+ ism_interval: genome.Interval,
862
+ variant_scorers: Sequence[variant_scorers_lib.VariantScorerTypes] = (),
863
+ *,
864
+ organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS,
865
+ interval_variant: genome.Variant | None = None,
866
+ ) -> list[list[anndata.AnnData]]:
867
+ """Generate in-silico mutagenesis (ISM) variant scores for a given interval.
868
+
869
+ Args:
870
+ interval: DNA interval to make the prediction for.
871
+ ism_interval: Interval to perform ISM.
872
+ variant_scorers: Sequence of variant scorers to use for scoring each
873
+ variant. If no variant scorers are provided, the recommended variant
874
+ scorers for the organism will be used.
875
+ organism: Organism to use for the prediction.
876
+ interval_variant: Optional variant to apply to the sequence. If provided,
877
+ the alternate allele is used for in-silico mutagenesis, otherwise the
878
+ unaltered reference sequence is used.
879
+
880
+ Returns:
881
+ List of variant scores for each variant in the ISM interval.
882
+ """
883
+ extractor = self._get_fasta_extractor(organism)
884
+ if interval_variant is not None:
885
+ _, sequence = genome_io.extract_variant_sequences(
886
+ interval, interval_variant, extractor
887
+ )
888
+ else:
889
+ sequence = extractor.extract(interval)
890
+
891
+ interval_slice = interval.intersect(ism_interval)
892
+ if interval_slice is None:
893
+ raise ValueError(f'{ism_interval=} not fully contained in {interval=}.')
894
+ start = interval_slice.start - interval.start
895
+ end = interval_slice.end - interval.start
896
+ ism_sequence = sequence[start:end]
897
+
898
+ variants = ism.ism_variants(ism_interval, ism_sequence)
899
+ return self.score_variants(
900
+ interval, variants, variant_scorers, organism=organism
901
+ )
902
+
903
+ def output_metadata(
904
+ self, organism: dna_model.Organism = dna_model.Organism.HOMO_SAPIENS
905
+ ) -> dna_output.OutputMetadata:
906
+ """Get the metadata for a given organism.
907
+
908
+ Args:
909
+ organism: Organism to get metadata for.
910
+
911
+ Returns:
912
+ OutputMetadata for the provided organism.
913
+ """
914
+ return self._output_metadata_by_organism[organism]
915
+
916
+
917
+ @typing.jaxtyped
918
+ def _construct_output_from_predictions(
919
+ predictions: Mapping[
920
+ dna_output.OutputType,
921
+ PyTree[Float[Array, '...'] | Int32[Array, '...']],
922
+ ],
923
+ *,
924
+ track_masks: Mapping[dna_output.OutputType, Bool[np.ndarray, '_']],
925
+ metadata: AlphaGenomeOutputMetadata,
926
+ interval: genome.Interval | None = None,
927
+ ) -> dna_output.Output:
928
+ """Returns a dna_output.Output from model predictions with data on CPU."""
929
+
930
+ def _convert_to_track_data(
931
+ output_type: dna_output.OutputType,
932
+ ) -> track_data.TrackData | None:
933
+ track_metadata = metadata.get(output_type)
934
+ prediction = predictions.get(output_type)
935
+ if prediction is None or track_metadata is None:
936
+ # No tracks are predicted for this head.
937
+ return None
938
+ return track_data.TrackData(
939
+ values=jax.device_get(prediction),
940
+ resolution=metadata.resolution(output_type),
941
+ metadata=track_metadata[track_masks[output_type]],
942
+ interval=interval,
943
+ )
944
+
945
+ def _convert_to_junction_data() -> junction_data.JunctionData | None:
946
+ """Returns a splice junction prediction."""
947
+ output_type = dna_output.OutputType.SPLICE_JUNCTIONS
948
+ junction_metadata = metadata.get(output_type)
949
+ splice_junction_predictions = predictions.get(output_type)
950
+ if junction_metadata is None or splice_junction_predictions is None:
951
+ return None
952
+ splice_junctions = splice_junction_predictions['predictions']
953
+ splice_site_positions = splice_junction_predictions['splice_site_positions']
954
+
955
+ junction_predictions, strands, starts, ends = (
956
+ splice_junction.unstack_junction_predictions(
957
+ jax.device_get(splice_junctions),
958
+ jax.device_get(splice_site_positions),
959
+ interval,
960
+ )
961
+ )
962
+ chromosome = interval.chromosome if interval is not None else None
963
+ junctions = [
964
+ genome.Junction(chromosome, start, end, strand)
965
+ for start, end, strand in zip(starts, ends, strands)
966
+ if start < end
967
+ ]
968
+ return junction_data.JunctionData(
969
+ junctions=np.asarray(junctions),
970
+ values=junction_predictions,
971
+ metadata=junction_metadata[track_masks[output_type]],
972
+ interval=interval,
973
+ )
974
+
975
+ return dna_output.Output(
976
+ atac=_convert_to_track_data(dna_output.OutputType.ATAC),
977
+ dnase=_convert_to_track_data(dna_output.OutputType.DNASE),
978
+ procap=_convert_to_track_data(dna_output.OutputType.PROCAP),
979
+ cage=_convert_to_track_data(dna_output.OutputType.CAGE),
980
+ rna_seq=_convert_to_track_data(dna_output.OutputType.RNA_SEQ),
981
+ chip_histone=_convert_to_track_data(dna_output.OutputType.CHIP_HISTONE),
982
+ chip_tf=_convert_to_track_data(dna_output.OutputType.CHIP_TF),
983
+ contact_maps=_convert_to_track_data(dna_output.OutputType.CONTACT_MAPS),
984
+ splice_sites=_convert_to_track_data(dna_output.OutputType.SPLICE_SITES),
985
+ splice_site_usage=_convert_to_track_data(
986
+ dna_output.OutputType.SPLICE_SITE_USAGE
987
+ ),
988
+ splice_junctions=_convert_to_junction_data(),
989
+ )
990
+
991
+
992
+ def convert_to_organism_index(
993
+ organism: dna_model.Organism,
994
+ ) -> int:
995
+ """Converts a dna_model.Organism to a organism index."""
996
+ match organism:
997
+ case dna_model.Organism.HOMO_SAPIENS:
998
+ return 0
999
+ case dna_model.Organism.MUS_MUSCULUS:
1000
+ return 1
1001
+ case _:
1002
+ raise ValueError(f'Unsupported organism: {organism}')
1003
+
1004
+
1005
+ @dataclasses.dataclass(frozen=True, kw_only=True)
1006
+ class ModelSettings:
1007
+ """Settings for the AlphaGenomeModel."""
1008
+
1009
+ # The maximum number of splice sites that are extracted from the splice site
1010
+ # classification predictions.
1011
+ num_splice_sites: int = 512
1012
+ # The threshold to use for splice site prediction.
1013
+ splice_site_threshold: float = 0.1
1014
+
1015
+
1016
+ @dataclasses.dataclass(frozen=True, kw_only=True)
1017
+ class OrganismSettings:
1018
+ """Settings for a specific organism."""
1019
+
1020
+ # Optional output metadata. If None, we load the default AlphaGenome metadata
1021
+ # for the organism.
1022
+ metadata: AlphaGenomeOutputMetadata | None = None
1023
+
1024
+ # Optional paths to the reference genome and annotation data. If None,
1025
+ # functions that accept intervals or variants will fail.
1026
+ fasta_path: str | os.PathLike[str] | None = None
1027
+
1028
+ # Optional paths to the reference annotation data. If None, variant scorers
1029
+ # that require a GTF will not be available.
1030
+ gtf_feather_path: str | os.PathLike[str] | None = None
1031
+
1032
+ # Optional path to reference polyadenylation annotation data. If None,
1033
+ # variant scorers that require a PAS GTF will not be available.
1034
+ pas_feather_path: str | os.PathLike[str] | None = None
1035
+
1036
+ # Optional paths to the reference splice site data. If None, no reference
1037
+ # splice sites will be used during variant predictions.
1038
+ splice_site_starts_feather_path: str | os.PathLike[str] | None = None
1039
+ splice_site_ends_feather_path: str | os.PathLike[str] | None = None
1040
+
1041
+
1042
+ def default_organism_settings() -> (
1043
+ Mapping[dna_model.Organism, OrganismSettings]
1044
+ ):
1045
+ """Returns the default organism settings for the AlphaGenomeModel."""
1046
+ return {
1047
+ dna_model.Organism.HOMO_SAPIENS: OrganismSettings(
1048
+ fasta_path=(
1049
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1050
+ 'hg38/GRCh38.p13.genome.fa'
1051
+ ),
1052
+ gtf_feather_path=(
1053
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1054
+ 'hg38/gencode.v46.annotation.gtf.gz.feather'
1055
+ ),
1056
+ pas_feather_path=(
1057
+ 'https://storage.googleapis.com/alphagenome/reference/exon/hg38/'
1058
+ 'polyadb_human_v3_exon3_contiguous_gtfv46.feather'
1059
+ ),
1060
+ splice_site_starts_feather_path=(
1061
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1062
+ 'hg38/gencode.v46.splice_sites_starts.feather'
1063
+ ),
1064
+ splice_site_ends_feather_path=(
1065
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1066
+ 'hg38/gencode.v46.splice_sites_ends.feather'
1067
+ ),
1068
+ ),
1069
+ dna_model.Organism.MUS_MUSCULUS: OrganismSettings(
1070
+ fasta_path=(
1071
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1072
+ 'mm10/GRCm38.p6.genome.fa'
1073
+ ),
1074
+ gtf_feather_path=(
1075
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1076
+ 'mm10/gencode.vM23.annotation.gtf.gz.feather'
1077
+ ),
1078
+ pas_feather_path=None,
1079
+ splice_site_starts_feather_path=(
1080
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1081
+ 'mm10/gencode.vM23.splice_sites_starts.feather'
1082
+ ),
1083
+ splice_site_ends_feather_path=(
1084
+ 'https://storage.googleapis.com/alphagenome/reference/gencode/'
1085
+ 'mm10/gencode.vM23.splice_sites_ends.feather'
1086
+ ),
1087
+ ),
1088
+ }
1089
+
1090
+
1091
+ @typing.jaxtyped
1092
+ def create_model(
1093
+ metadata: Mapping[dna_model.Organism, AlphaGenomeOutputMetadata],
1094
+ *,
1095
+ num_splice_sites: int = model.DEFAULT_NUM_SPLICE_SITES,
1096
+ splice_site_threshold: float = model.DEFAULT_SPLICE_SITE_THRESHOLD,
1097
+ ) -> tuple[
1098
+ Callable[
1099
+ [chex.PRNGKey, Float[Array, 'B S 4'], Int32[Array, 'B']],
1100
+ tuple[hk.Params, hk.State],
1101
+ ],
1102
+ ApplyFn,
1103
+ JunctionsApplyFn,
1104
+ ]:
1105
+ """Helper to create AlphaGenome init and two apply functions."""
1106
+
1107
+ jmp_policy = jmp.get_policy('params=float32,compute=bfloat16,output=bfloat16')
1108
+
1109
+ @hk.transform_with_state
1110
+ def _forward(
1111
+ dna_sequence: Float[Array, 'B S 4'],
1112
+ organism_index: Int32[Array, 'B'],
1113
+ ):
1114
+ """AlphaGenome default forward pass."""
1115
+ with hk.mixed_precision.push_policy(model.AlphaGenome, jmp_policy):
1116
+ return model.AlphaGenome(
1117
+ metadata,
1118
+ num_splice_sites=num_splice_sites,
1119
+ splice_site_threshold=splice_site_threshold,
1120
+ )(dna_sequence, organism_index)
1121
+
1122
+ def _apply_fn(
1123
+ params: hk.Params,
1124
+ state: hk.State,
1125
+ dna_sequence: Float[Array, 'B S 4'],
1126
+ organism_index: Int32[Array, 'B'],
1127
+ ) -> PyTree[Shaped[Array, 'B ...']]:
1128
+ """AlphaGenome default apply function."""
1129
+ (predictions, _), _ = _forward.apply(
1130
+ params, state, None, dna_sequence, organism_index
1131
+ )
1132
+ return predictions
1133
+
1134
+ def _junctions_apply_fn(
1135
+ params: hk.Params,
1136
+ state: hk.State,
1137
+ trunk_embeddings: Float[Array, 'B S D'],
1138
+ splice_site_positions: Int32[Array, 'B 4 K'],
1139
+ organism_index: Int32[Array, 'B'],
1140
+ ):
1141
+ """AlphaGenome junctions apply function."""
1142
+
1143
+ @hk.transform_with_state
1144
+ def _forward_junctions(
1145
+ trunk_embeddings, splice_site_positions, organism_index
1146
+ ):
1147
+ with hk.mixed_precision.push_policy(model.AlphaGenome, jmp_policy):
1148
+ return model.AlphaGenome(
1149
+ metadata,
1150
+ num_splice_sites=num_splice_sites,
1151
+ splice_site_threshold=splice_site_threshold,
1152
+ ).predict_junctions(
1153
+ trunk_embeddings, splice_site_positions, organism_index
1154
+ )
1155
+
1156
+ predictions, _ = _forward_junctions.apply(
1157
+ params,
1158
+ state,
1159
+ None,
1160
+ trunk_embeddings,
1161
+ splice_site_positions,
1162
+ organism_index,
1163
+ )
1164
+ return predictions
1165
+
1166
+ return _forward.init, _apply_fn, _junctions_apply_fn
1167
+
1168
+
1169
+ def create(
1170
+ checkpoint_path: str | os.PathLike[str],
1171
+ *,
1172
+ organism_settings: (
1173
+ Mapping[dna_model.Organism, OrganismSettings] | None
1174
+ ) = None,
1175
+ model_settings: ModelSettings = ModelSettings(),
1176
+ device: jax.Device | None = None,
1177
+ ) -> AlphaGenomeModel:
1178
+ """Returns a AlphaGenomeModel from a checkpoint stored at the given path.
1179
+
1180
+ Args:
1181
+ checkpoint_path: Path to the checkpoint to load.
1182
+ organism_settings: Optional organism settings to use. If not set, will use
1183
+ default organism settings.
1184
+ model_settings: Settings for the model. If not set, will use default model
1185
+ settings.
1186
+ device: Optional device to use for model prediction. If None, the first
1187
+ local device will be used.
1188
+ """
1189
+ if organism_settings is None:
1190
+ organism_settings = default_organism_settings()
1191
+
1192
+ metadata = {}
1193
+ fasta_extractors = {}
1194
+ splice_site_extractors = {}
1195
+ gtfs = {}
1196
+ pas_gtfs = {}
1197
+ validate_checkpoint = True
1198
+
1199
+ for organism, settings in organism_settings.items():
1200
+ if settings.metadata is not None:
1201
+ metadata[organism] = settings.metadata
1202
+ validate_checkpoint = False
1203
+ else:
1204
+ metadata[organism] = metadata_lib.load(organism)
1205
+
1206
+ if settings.fasta_path is not None:
1207
+ fasta_extractors[organism] = fasta.FastaExtractor(settings.fasta_path)
1208
+ if settings.gtf_feather_path is not None:
1209
+ gtfs[organism] = pd.read_feather(settings.gtf_feather_path)
1210
+ if settings.pas_feather_path is not None:
1211
+ pas_gtfs[organism] = pd.read_feather(settings.pas_feather_path)
1212
+ if settings.splice_site_starts_feather_path is not None:
1213
+ splice_site_extractors[organism] = (
1214
+ splicing_io.SpliceSiteAnnotationExtractor(
1215
+ junction_starts=pd.read_feather(
1216
+ settings.splice_site_starts_feather_path
1217
+ ),
1218
+ junction_ends=pd.read_feather(
1219
+ settings.splice_site_ends_feather_path
1220
+ ),
1221
+ )
1222
+ )
1223
+
1224
+ init_fn, apply_fn, junctions_apply_fn = create_model(
1225
+ metadata,
1226
+ num_splice_sites=model_settings.num_splice_sites,
1227
+ splice_site_threshold=model_settings.splice_site_threshold,
1228
+ )
1229
+
1230
+ dna_sequence_shape = jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32)
1231
+ organism_index_shape = jax.ShapeDtypeStruct((1,), dtype=jnp.int32)
1232
+ target_shapes = jax.eval_shape(
1233
+ init_fn, jax.random.PRNGKey(0), dna_sequence_shape, organism_index_shape
1234
+ )
1235
+ checkpointer = ocp.StandardCheckpointer()
1236
+ params, state = checkpointer.restore(
1237
+ checkpoint_path,
1238
+ target=target_shapes if validate_checkpoint else None,
1239
+ strict=validate_checkpoint,
1240
+ )
1241
+
1242
+ return AlphaGenomeModel(
1243
+ params=params,
1244
+ state=state,
1245
+ apply_fn=apply_fn,
1246
+ junctions_apply_fn=junctions_apply_fn,
1247
+ metadata=metadata,
1248
+ fasta_extractors=fasta_extractors,
1249
+ splice_site_extractors=splice_site_extractors,
1250
+ gtfs=gtfs,
1251
+ pas_gtfs=pas_gtfs,
1252
+ num_splice_sites=model_settings.num_splice_sites,
1253
+ splice_site_threshold=model_settings.splice_site_threshold,
1254
+ device=device,
1255
+ )
1256
+
1257
+
1258
+ def create_from_kaggle(
1259
+ model_version: str | ModelVersion,
1260
+ *,
1261
+ organism_settings: (
1262
+ Mapping[dna_model.Organism, OrganismSettings] | None
1263
+ ) = None,
1264
+ device: jax.Device | None = None,
1265
+ ) -> AlphaGenomeModel:
1266
+ """Helper function to create a model from Kaggle.
1267
+
1268
+ Args:
1269
+ model_version: The model version to use, e.g. all_folds.
1270
+ organism_settings: Optional organism settings to use. If unset, will use
1271
+ default organism settings.
1272
+ device: Optional device to use for model prediction. If None, the first
1273
+ local device will be used.
1274
+
1275
+ Returns:
1276
+ AlphaGenomeModel created from the Kaggle checkpoint.
1277
+ """
1278
+ if kaggle_auth.get_username() is None:
1279
+ kagglehub.login()
1280
+
1281
+ if isinstance(model_version, ModelVersion):
1282
+ model_version = model_version.name
1283
+
1284
+ checkpoint_path = kagglehub.model_download(
1285
+ f'google/alphagenome/jax/{model_version.lower()}'
1286
+ )
1287
+ return create(
1288
+ checkpoint_path, organism_settings=organism_settings, device=device
1289
+ )
1290
+
1291
+
1292
+ def create_from_huggingface(
1293
+ model_version: str | ModelVersion,
1294
+ *,
1295
+ organism_settings: (
1296
+ Mapping[dna_model.Organism, OrganismSettings] | None
1297
+ ) = None,
1298
+ device: jax.Device | None = None,
1299
+ ) -> AlphaGenomeModel:
1300
+ """Helper function to create a DNA model from HuggingFace.
1301
+
1302
+ Args:
1303
+ model_version: The model version to use, e.g. all_folds.
1304
+ organism_settings: Optional organism settings to use. If unset, will use
1305
+ default organism settings.
1306
+ device: Optional device to use for model prediction. If None, the first
1307
+ local device will be used.
1308
+
1309
+ Returns:
1310
+ AlphaGenomeModel created from the Hugging Face checkpoint.
1311
+ """
1312
+
1313
+ try:
1314
+ huggingface_hub.whoami()
1315
+ except huggingface_hub.errors.LocalTokenNotFoundError:
1316
+ huggingface_hub.login()
1317
+
1318
+ if isinstance(model_version, ModelVersion):
1319
+ model_version = model_version.name
1320
+
1321
+ checkpoint_path = huggingface_hub.snapshot_download(
1322
+ repo_id=f'google/alphagenome-{model_version.replace("_", "-").lower()}'
1323
+ )
1324
+ return create(
1325
+ checkpoint_path, organism_settings=organism_settings, device=device
1326
+ )
flax_model/alphagenome/model/dna_model_test.py ADDED
@@ -0,0 +1,872 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import pathlib
17
+ from unittest import mock
18
+
19
+ from absl.testing import absltest
20
+ from absl.testing import parameterized
21
+ from flax_model.alphagenome._sdk.data import genome
22
+ from flax_model.alphagenome._sdk.data import ontology
23
+ from flax_model.alphagenome._sdk.models import dna_output
24
+ from flax_model.alphagenome._sdk.models import interval_scorers
25
+ from flax_model.alphagenome._sdk.models import variant_scorers
26
+ from flax_model.alphagenome.io import fasta
27
+ from flax_model.alphagenome.io import splicing
28
+ from flax_model.alphagenome.model import dna_model
29
+ from flax_model.alphagenome.model.metadata import metadata
30
+ import chex
31
+ import huggingface_hub
32
+ import jax
33
+ import jax.numpy as jnp
34
+ import kagglehub
35
+ from kagglehub import auth as kaggle_auth
36
+ import numpy as np
37
+ import orbax.checkpoint as ocp
38
+ import pandas as pd
39
+
40
+
41
+ MOCK_SHAPES = ({}, {})
42
+
43
+
44
+ def _create_mock_gtf() -> pd.DataFrame:
45
+ return pd.DataFrame({
46
+ 'Chromosome': 'chr1',
47
+ 'Start': [101, 101, 102, 103, 0, 0, 0, 80],
48
+ 'End': [200, 200, 200, 200, 108, 108, 40, 108],
49
+ 'Strand': ['+', '+', '+', '+', '-', '-', '-', '-'],
50
+ 'transcript_id': [None, 'T1', 'T2', 'T2', None, 'T4', 'T4', 'T4'],
51
+ 'gene_id': ['G1', 'G1', 'G1', 'G1', 'G2', 'G2', 'G2', 'G2'],
52
+ 'Feature': [
53
+ 'gene',
54
+ 'transcript',
55
+ 'transcript',
56
+ 'exon',
57
+ 'gene',
58
+ 'transcript',
59
+ 'exon',
60
+ 'exon',
61
+ ],
62
+ 'gene_type': 'protein_coding',
63
+ 'gene_name': 'GX_name',
64
+ 'transcript_type': 'protein_coding',
65
+ })
66
+
67
+
68
+ def _create_mock_splice_sites() -> tuple[pd.DataFrame, pd.DataFrame]:
69
+ return pd.DataFrame(
70
+ {'Chromosome': 'chr1', 'Start': [40], 'Strand': ['-'], 'Tissue_0': [1]}
71
+ ), pd.DataFrame(
72
+ {'Chromosome': 'chr1', 'End': [80], 'Strand': ['-'], 'Tissue_0': [1]}
73
+ )
74
+
75
+
76
+ def _create_polya_df_gtf() -> pd.DataFrame:
77
+ return pd.DataFrame({
78
+ 'End': [103, 104, 1, 81],
79
+ 'Start': [102, 103, 0, 80],
80
+ 'cutmode': [102, 103, 0, 80],
81
+ 'pas_strand': ['+', '+', '-', '-'],
82
+ 'pas_id': ['P1', 'P2', 'P3', 'P4'],
83
+ 'gene_id': ['G1', 'G1', 'G2', 'G2'],
84
+ 'pas_gene_id': ['G1', 'G1', 'G2', 'G2'],
85
+ 'Chromosome': 'chr1',
86
+ })
87
+
88
+
89
+ def _get_test_fasta_path() -> str | os.PathLike[str]:
90
+ root_dir = pathlib.Path(__file__).parent.parent
91
+ return root_dir / 'io' / 'testdata' / 'example.fa'
92
+
93
+
94
+ class DnaModelTest(parameterized.TestCase):
95
+
96
+ def setUp(self):
97
+ super().setUp()
98
+
99
+ self._num_tissues = 10
100
+ self._num_splice_sites = 100
101
+ self._metadata = metadata.AlphaGenomeOutputMetadata(
102
+ atac=pd.DataFrame({
103
+ 'name': ['atac1', 'atac1'],
104
+ 'strand': ['+', '-'],
105
+ 'ontology_curie': ['CL:0000001', 'CL:0000001'],
106
+ 'nonzero_mean': [1.0, 1.0],
107
+ }),
108
+ dnase=pd.DataFrame({
109
+ 'name': ['acc_1'],
110
+ 'strand': ['.'],
111
+ 'ontology_curie': ['UBERON:0000001'],
112
+ 'nonzero_mean': [1.0],
113
+ }),
114
+ contact_maps=pd.DataFrame({
115
+ 'name': ['hic_1', 'hic_2'],
116
+ 'ontology_curie': ['UBERON:0000001', 'UBERON:0000002'],
117
+ 'strand': '.',
118
+ }),
119
+ splice_sites=pd.DataFrame({
120
+ 'name': ['donor', 'acceptor', 'donor', 'acceptor', 'padding'],
121
+ 'strand': ['+', '+', '-', '-', '.'],
122
+ }),
123
+ splice_junctions=pd.DataFrame({
124
+ 'name': (
125
+ [f'tissue_{i}' for i in range(self._num_tissues)]
126
+ + ['Padding'] * 2
127
+ ),
128
+ 'ontology_curie': ['UBERON:0000001'] * (self._num_tissues + 2),
129
+ }),
130
+ chip_tf=pd.DataFrame({
131
+ 'name': ['chip_1', 'chip_2'],
132
+ 'strand': ['+', '-'],
133
+ 'ontology_curie': 'UBERON:0000001',
134
+ 'nonzero_mean': 1.0,
135
+ }),
136
+ )
137
+
138
+ def _apply_fn(params, state, dna_sequence, organism_index):
139
+ del params, state, organism_index
140
+ batch_size, sequence_length = dna_sequence.shape[0], dna_sequence.shape[1]
141
+ splice_site_positions = (
142
+ np.ones((batch_size, 4, self._num_splice_sites), dtype=np.int32) * -1
143
+ )
144
+ splice_site_positions[:, 0, 0] = 100 # pos donor
145
+ splice_site_positions[:, 1, 0] = 200 # pos acceptor
146
+ splice_site_positions[:, 2, 0] = 300 # neg donor
147
+ splice_site_positions[:, 3, 0] = 50 # neg acceptor
148
+ return {
149
+ 'atac': {
150
+ 'predictions_1bp': jnp.zeros(
151
+ (batch_size, sequence_length, len(self._metadata.atac)),
152
+ dtype=jnp.bfloat16,
153
+ )
154
+ },
155
+ 'dnase': {
156
+ 'predictions_1bp': jnp.zeros(
157
+ (batch_size, sequence_length, len(self._metadata.dnase))
158
+ )
159
+ },
160
+ 'contact_maps': {
161
+ 'predictions': jnp.zeros((
162
+ batch_size,
163
+ sequence_length // 2048,
164
+ sequence_length // 2048,
165
+ len(self._metadata.contact_maps),
166
+ ))
167
+ },
168
+ 'splice_sites_classification': {
169
+ 'predictions': jnp.ones(
170
+ (
171
+ batch_size,
172
+ sequence_length,
173
+ 5,
174
+ ),
175
+ dtype=jnp.bfloat16,
176
+ ),
177
+ },
178
+ 'splice_sites_junction': {
179
+ 'predictions': jnp.ones(
180
+ (
181
+ batch_size,
182
+ self._num_splice_sites,
183
+ self._num_splice_sites,
184
+ 2 * self._num_tissues + 4, # Add 4 to mimic padding.
185
+ ),
186
+ dtype=jnp.bfloat16,
187
+ ),
188
+ 'splice_site_positions': jnp.array(splice_site_positions),
189
+ },
190
+ 'embeddings_1bp': jnp.zeros(
191
+ (batch_size, sequence_length, 1536), dtype=jnp.bfloat16
192
+ ),
193
+ 'chip_tf': {
194
+ 'predictions_128bp': jnp.zeros(
195
+ (batch_size, sequence_length // 128, 2), dtype=jnp.bfloat16
196
+ )
197
+ },
198
+ }
199
+
200
+ self._mock_model = _apply_fn
201
+
202
+ def _apply_fn_junctions(
203
+ params, state, trunk_embeddings, splice_site_positions, organism_index
204
+ ):
205
+ del params, state, trunk_embeddings, organism_index
206
+ batch_size, _, num_splice_sites = splice_site_positions.shape
207
+ return {
208
+ 'predictions': jnp.ones(
209
+ (
210
+ batch_size,
211
+ num_splice_sites,
212
+ num_splice_sites,
213
+ 2 * self._num_tissues + 4, # Add 4 to mimic padding.
214
+ ),
215
+ dtype=jnp.bfloat16,
216
+ ),
217
+ 'splice_site_positions': jnp.array(splice_site_positions),
218
+ }
219
+
220
+ self._mock_model_junctions = _apply_fn_junctions
221
+
222
+ @parameterized.parameters([
223
+ dict(organism=dna_model.Organism.HOMO_SAPIENS, expected_index=0),
224
+ dict(organism=dna_model.Organism.MUS_MUSCULUS, expected_index=1),
225
+ ])
226
+ def test_convert_to_organism_index(self, organism, expected_index):
227
+ self.assertEqual(
228
+ dna_model.convert_to_organism_index(organism),
229
+ expected_index,
230
+ )
231
+
232
+ @parameterized.parameters([
233
+ dict(
234
+ requested_outputs=[
235
+ dna_output.OutputType.ATAC,
236
+ dna_output.OutputType.DNASE,
237
+ ],
238
+ requested_ontologies=None,
239
+ expected_shapes={
240
+ dna_output.OutputType.ATAC: (65_536, 2),
241
+ dna_output.OutputType.DNASE: (65_536, 1),
242
+ },
243
+ ),
244
+ dict(
245
+ requested_outputs=[
246
+ dna_output.OutputType.ATAC,
247
+ dna_output.OutputType.DNASE,
248
+ ],
249
+ requested_ontologies=[ontology.from_curie('CL:0000001')],
250
+ expected_shapes={
251
+ dna_output.OutputType.ATAC: (65_536, 2),
252
+ dna_output.OutputType.DNASE: (65_536, 0),
253
+ },
254
+ ),
255
+ ])
256
+ def test_predict_sequence(
257
+ self, requested_outputs, requested_ontologies, expected_shapes
258
+ ):
259
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
260
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
261
+ model = dna_model.AlphaGenomeModel(
262
+ params={},
263
+ state={},
264
+ apply_fn=self._mock_model,
265
+ junctions_apply_fn=self._mock_model_junctions,
266
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
267
+ fasta_extractors={
268
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
269
+ },
270
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
271
+ device=jax.local_devices()[0],
272
+ )
273
+ seq = 'ATGC' * int(2**14)
274
+ predictions = model.predict_sequence(
275
+ seq,
276
+ requested_outputs=requested_outputs,
277
+ ontology_terms=requested_ontologies,
278
+ )
279
+ for output_type, expected_shape in expected_shapes.items():
280
+ output = predictions.get(output_type)
281
+ self.assertIsNotNone(output)
282
+ chex.assert_shape(output.values, expected_shape)
283
+
284
+ @parameterized.parameters([
285
+ dict(
286
+ requested_outputs=[dna_output.OutputType.ATAC],
287
+ requested_ontologies=None,
288
+ expected_shapes={dna_output.OutputType.ATAC: (2048, 2)},
289
+ ),
290
+ dict(
291
+ requested_outputs=[dna_output.OutputType.DNASE],
292
+ requested_ontologies=[ontology.from_curie('UBERON:0000001')],
293
+ expected_shapes={dna_output.OutputType.DNASE: (2048, 1)},
294
+ ),
295
+ ])
296
+ def test_predict_interval(
297
+ self, requested_outputs, requested_ontologies, expected_shapes
298
+ ):
299
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
300
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
301
+ model = dna_model.AlphaGenomeModel(
302
+ params={},
303
+ state={},
304
+ apply_fn=self._mock_model,
305
+ junctions_apply_fn=self._mock_model_junctions,
306
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
307
+ fasta_extractors={
308
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
309
+ },
310
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
311
+ device=jax.local_devices()[0],
312
+ )
313
+ interval = genome.Interval.from_str('chr1:0-2048:.')
314
+ output = model.predict_interval(
315
+ interval,
316
+ requested_outputs=requested_outputs,
317
+ ontology_terms=requested_ontologies,
318
+ )
319
+ for output_type, expected_shape in expected_shapes.items():
320
+ output = output.get(output_type)
321
+ self.assertIsNotNone(output)
322
+ chex.assert_shape(output.values, expected_shape)
323
+
324
+ def test_predict_interval_with_splicing(self):
325
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
326
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
327
+ model = dna_model.AlphaGenomeModel(
328
+ params={},
329
+ state={},
330
+ apply_fn=self._mock_model,
331
+ junctions_apply_fn=self._mock_model_junctions,
332
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
333
+ fasta_extractors={
334
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
335
+ },
336
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
337
+ device=jax.local_devices()[0],
338
+ )
339
+ interval = genome.Interval.from_str('chr1:0-2048:.')
340
+ output = model.predict_interval(
341
+ interval,
342
+ requested_outputs=[
343
+ dna_output.OutputType.ATAC,
344
+ dna_output.OutputType.SPLICE_JUNCTIONS,
345
+ ],
346
+ ontology_terms=None,
347
+ )
348
+ atac_output = output.atac
349
+ self.assertIsNotNone(atac_output)
350
+ chex.assert_shape(atac_output.values, (interval.width, 2))
351
+
352
+ splice_junctions_output = output.splice_junctions
353
+ self.assertIsNotNone(splice_junctions_output)
354
+ self.assertLen(splice_junctions_output.junctions, 2)
355
+ chex.assert_shape(splice_junctions_output.values, (2, self._num_tissues))
356
+ self.assertEqual(
357
+ splice_junctions_output.junctions[0],
358
+ genome.Junction('chr1', 101, 200, '+'),
359
+ )
360
+ self.assertEqual(
361
+ splice_junctions_output.junctions[1],
362
+ genome.Junction('chr1', 51, 300, '-'),
363
+ )
364
+
365
+ def test_predict_interval_missing_fasta_raises_error(self):
366
+ model = dna_model.AlphaGenomeModel(
367
+ params={},
368
+ state={},
369
+ apply_fn=self._mock_model,
370
+ junctions_apply_fn=self._mock_model_junctions,
371
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
372
+ device=jax.local_devices()[0],
373
+ )
374
+ with self.assertRaisesRegex(
375
+ ValueError, "FastaExtractor not found for organism.name='HOMO_SAPIENS'"
376
+ ):
377
+ model.predict_interval(
378
+ genome.Interval.from_str('chr1:0-2048:.'),
379
+ requested_outputs=[dna_output.OutputType.ATAC],
380
+ ontology_terms=None,
381
+ )
382
+
383
+ @parameterized.parameters([
384
+ dict(
385
+ requested_outputs=[
386
+ dna_output.OutputType.ATAC,
387
+ dna_output.OutputType.DNASE,
388
+ ],
389
+ requested_ontologies=None,
390
+ expected_shapes={
391
+ dna_output.OutputType.ATAC: (2048, 2),
392
+ dna_output.OutputType.DNASE: (2048, 1),
393
+ },
394
+ ),
395
+ dict(
396
+ requested_outputs=[
397
+ dna_output.OutputType.ATAC,
398
+ dna_output.OutputType.DNASE,
399
+ ],
400
+ requested_ontologies=[ontology.from_curie('CL:0000001')],
401
+ expected_shapes={
402
+ dna_output.OutputType.ATAC: (2048, 2),
403
+ dna_output.OutputType.DNASE: (2048, 0),
404
+ },
405
+ ),
406
+ ])
407
+ def test_predict_variant(
408
+ self, requested_outputs, requested_ontologies, expected_shapes
409
+ ):
410
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
411
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
412
+
413
+ mock_splice_sites_extractor = mock.create_autospec(
414
+ splicing.SpliceSiteAnnotationExtractor, instance=True
415
+ )
416
+ mock_splice_sites_extractor.extract.side_effect = lambda x: np.zeros(
417
+ (x.width, 5), dtype=bool
418
+ )
419
+
420
+ model = dna_model.AlphaGenomeModel(
421
+ params={},
422
+ state={},
423
+ apply_fn=self._mock_model,
424
+ junctions_apply_fn=self._mock_model_junctions,
425
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
426
+ fasta_extractors={
427
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
428
+ },
429
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
430
+ device=jax.local_devices()[0],
431
+ splice_site_extractors={
432
+ dna_model.Organism.HOMO_SAPIENS: mock_splice_sites_extractor
433
+ },
434
+ )
435
+ interval = genome.Interval.from_str('chr1:0-2048:.')
436
+ predictions = model.predict_variant(
437
+ interval,
438
+ variant=genome.Variant.from_str('chr1:1024:A>C'),
439
+ requested_outputs=requested_outputs,
440
+ ontology_terms=requested_ontologies,
441
+ )
442
+ for output_type, expected_shape in expected_shapes.items():
443
+ output = predictions.reference.get(output_type)
444
+ self.assertIsNotNone(output)
445
+ chex.assert_shape(output.values, expected_shape)
446
+ for output_type, expected_shape in expected_shapes.items():
447
+ output = predictions.alternate.get(output_type)
448
+ self.assertIsNotNone(output)
449
+ chex.assert_shape(output.values, expected_shape)
450
+
451
+ def test_score_variant(self):
452
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
453
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
454
+
455
+ mock_splice_sites_extractor = mock.create_autospec(
456
+ splicing.SpliceSiteAnnotationExtractor, instance=True
457
+ )
458
+ mock_splice_sites_extractor.extract.side_effect = lambda x: np.zeros(
459
+ (x.width, 5), dtype=bool
460
+ )
461
+
462
+ model = dna_model.AlphaGenomeModel(
463
+ params={},
464
+ state={},
465
+ apply_fn=self._mock_model,
466
+ junctions_apply_fn=self._mock_model_junctions,
467
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
468
+ fasta_extractors={
469
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
470
+ },
471
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
472
+ pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()},
473
+ device=jax.local_devices()[0],
474
+ splice_site_extractors={
475
+ dna_model.Organism.HOMO_SAPIENS: mock_splice_sites_extractor
476
+ },
477
+ )
478
+ interval = genome.Interval.from_str('chr1:0-2048:.')
479
+ variant = genome.Variant.from_str('chr1:1024:A>C')
480
+ scorers = [
481
+ variant_scorers.CenterMaskScorer(
482
+ aggregation_type=variant_scorers.AggregationType.DIFF_MEAN,
483
+ requested_output=dna_output.OutputType.ATAC,
484
+ width=501,
485
+ ),
486
+ variant_scorers.CenterMaskScorer(
487
+ requested_output=dna_output.OutputType.CHIP_TF,
488
+ width=501,
489
+ aggregation_type=variant_scorers.AggregationType.DIFF_LOG2_SUM,
490
+ ),
491
+ variant_scorers.ContactMapScorer(),
492
+ variant_scorers.GeneMaskLFCScorer(
493
+ requested_output=dna_output.OutputType.ATAC
494
+ ),
495
+ variant_scorers.SpliceJunctionScorer(),
496
+ ]
497
+ output = model.score_variant(interval, variant, variant_scorers=scorers)
498
+ self.assertLen(output, len(scorers))
499
+ for result, scorer in zip(output, scorers):
500
+ self.assertEqual(result.uns['interval'], interval)
501
+ self.assertEqual(result.uns['variant'], variant)
502
+ self.assertEqual(result.uns['variant_scorer'], scorer)
503
+
504
+ df = variant_scorers.tidy_scores(output)
505
+ self.assertCountEqual(
506
+ [
507
+ 'variant_id',
508
+ 'scored_interval',
509
+ 'gene_id',
510
+ 'gene_name',
511
+ 'gene_type',
512
+ 'gene_strand',
513
+ 'junction_Start',
514
+ 'junction_End',
515
+ 'output_type',
516
+ 'variant_scorer',
517
+ 'track_name',
518
+ 'track_strand',
519
+ 'ontology_curie',
520
+ 'raw_score',
521
+ ],
522
+ df.columns,
523
+ )
524
+
525
+ def test_missing_gtf_raises_scorer_missing_error(self):
526
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
527
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
528
+ model = dna_model.AlphaGenomeModel(
529
+ params={},
530
+ state={},
531
+ apply_fn=self._mock_model,
532
+ junctions_apply_fn=self._mock_model_junctions,
533
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
534
+ fasta_extractors={
535
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
536
+ },
537
+ device=jax.local_devices()[0],
538
+ )
539
+ interval = genome.Interval.from_str('chr1:0-2048:.')
540
+ variant = genome.Variant.from_str('chr1:1024:A>C')
541
+ scorers = [
542
+ variant_scorers.GeneMaskLFCScorer(
543
+ requested_output=dna_output.OutputType.ATAC
544
+ )
545
+ ]
546
+ with self.assertRaisesRegex(
547
+ ValueError, "Scorer 'BaseVariantScorer.GENE_MASK_LFC' is missing"
548
+ ):
549
+ model.score_variant(interval, variant, variant_scorers=scorers)
550
+
551
+ def test_missing_pas_raises_scorer_missing_error(self):
552
+ model = dna_model.AlphaGenomeModel(
553
+ params={},
554
+ state={},
555
+ apply_fn=self._mock_model,
556
+ junctions_apply_fn=self._mock_model_junctions,
557
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
558
+ pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()},
559
+ device=jax.local_devices()[0],
560
+ )
561
+ interval = genome.Interval.from_str('chr1:0-2048:.')
562
+ variant = genome.Variant.from_str('chr1:1024:A>C')
563
+ scorers = [variant_scorers.PolyadenylationScorer()]
564
+ with self.assertRaisesRegex(
565
+ ValueError, "Scorer 'BaseVariantScorer.PA_QTL' is missing"
566
+ ):
567
+ model.score_variant(interval, variant, variant_scorers=scorers)
568
+
569
+ def test_score_interval(self):
570
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
571
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
572
+ model = dna_model.AlphaGenomeModel(
573
+ params={},
574
+ state={},
575
+ apply_fn=self._mock_model,
576
+ junctions_apply_fn=self._mock_model_junctions,
577
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
578
+ fasta_extractors={
579
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
580
+ },
581
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
582
+ pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()},
583
+ device=jax.local_devices()[0],
584
+ )
585
+ interval = genome.Interval.from_str('chr1:0-2048:.')
586
+ scorers = [
587
+ interval_scorers.GeneMaskScorer(
588
+ aggregation_type=interval_scorers.IntervalAggregationType.MEAN,
589
+ requested_output=dna_output.OutputType.ATAC,
590
+ width=501,
591
+ )
592
+ ]
593
+ output = model.score_interval(interval, interval_scorers=scorers)
594
+ self.assertLen(output, len(scorers))
595
+ for result, scorer in zip(output, scorers):
596
+ self.assertEqual(result.uns['interval'], interval)
597
+ self.assertEqual(result.uns['interval_scorer'], scorer)
598
+
599
+ @parameterized.parameters([
600
+ dict(
601
+ ism_interval=genome.Interval.from_str('chr1:10-11:.'),
602
+ interval_variant=None,
603
+ expected_variants=[
604
+ genome.Variant('chr1', 11, 'A', 'C'),
605
+ genome.Variant('chr1', 11, 'A', 'G'),
606
+ genome.Variant('chr1', 11, 'A', 'T'),
607
+ ],
608
+ ),
609
+ dict(
610
+ ism_interval=genome.Interval.from_str('chr1:10-11:.'),
611
+ interval_variant=genome.Variant.from_str('chr1:11:A>C'),
612
+ expected_variants=[
613
+ genome.Variant('chr1', 11, 'C', 'A'),
614
+ genome.Variant('chr1', 11, 'C', 'G'),
615
+ genome.Variant('chr1', 11, 'C', 'T'),
616
+ ],
617
+ ),
618
+ ])
619
+ def test_score_ism_variants(
620
+ self,
621
+ ism_interval: genome.Interval,
622
+ interval_variant: genome.Variant | None,
623
+ expected_variants: list[genome.Variant],
624
+ ):
625
+ mock_fasta_extractor = mock.create_autospec(fasta.FastaExtractor)
626
+ mock_fasta_extractor.extract.side_effect = lambda x: 'A' * x.width
627
+
628
+ mock_splice_sites_extractor = mock.create_autospec(
629
+ splicing.SpliceSiteAnnotationExtractor, instance=True
630
+ )
631
+ mock_splice_sites_extractor.extract.side_effect = lambda x: np.zeros(
632
+ (x.width, 5), dtype=bool
633
+ )
634
+
635
+ model = dna_model.AlphaGenomeModel(
636
+ params={},
637
+ state={},
638
+ apply_fn=self._mock_model,
639
+ junctions_apply_fn=self._mock_model_junctions,
640
+ metadata={dna_model.Organism.HOMO_SAPIENS: self._metadata},
641
+ fasta_extractors={
642
+ dna_model.Organism.HOMO_SAPIENS: mock_fasta_extractor
643
+ },
644
+ gtfs={dna_model.Organism.HOMO_SAPIENS: _create_mock_gtf()},
645
+ pas_gtfs={dna_model.Organism.HOMO_SAPIENS: _create_polya_df_gtf()},
646
+ device=jax.local_devices()[0],
647
+ splice_site_extractors={
648
+ dna_model.Organism.HOMO_SAPIENS: mock_splice_sites_extractor
649
+ },
650
+ )
651
+ interval = genome.Interval.from_str('chr1:0-2048:.')
652
+
653
+ scores = model.score_ism_variants(
654
+ interval,
655
+ ism_interval,
656
+ interval_variant=interval_variant,
657
+ variant_scorers=[
658
+ variant_scorers.CenterMaskScorer(
659
+ aggregation_type=variant_scorers.AggregationType.DIFF_MEAN,
660
+ requested_output=dna_output.OutputType.ATAC,
661
+ width=501,
662
+ )
663
+ ],
664
+ )
665
+ scores = sorted(scores, key=lambda x: str(x[0].uns['variant']))
666
+ self.assertLen(scores, len(expected_variants))
667
+ for expected, scores in zip(expected_variants, scores, strict=True):
668
+ self.assertEqual(expected, scores[0].uns['variant'])
669
+
670
+ @parameterized.parameters(
671
+ dict(model_metadata=None),
672
+ dict(
673
+ model_metadata=metadata.AlphaGenomeOutputMetadata(
674
+ atac=metadata.load(dna_model.Organism.HOMO_SAPIENS).atac,
675
+ dnase=metadata.load(dna_model.Organism.HOMO_SAPIENS).dnase,
676
+ )
677
+ ),
678
+ )
679
+ def test_create(
680
+ self, model_metadata: metadata.AlphaGenomeOutputMetadata | None
681
+ ):
682
+ init_fn, _, _ = dna_model.create_model(
683
+ {o: metadata.load(o) for o in dna_model.Organism}
684
+ )
685
+ params, state = jax.jit(init_fn)(
686
+ jax.random.PRNGKey(0),
687
+ jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32),
688
+ jax.ShapeDtypeStruct((1,), dtype=jnp.int32),
689
+ )
690
+ checkpointer = ocp.StandardCheckpointer()
691
+ checkpoint_dir = os.path.join(self.create_tempdir().full_path, 'ckpt')
692
+ checkpointer.save(checkpoint_dir, (params, state))
693
+ gtf_path = os.path.join(self.create_tempdir().full_path, 'hg38.feather')
694
+ _create_mock_gtf().to_feather(gtf_path)
695
+ polya_gtf_path = os.path.join(
696
+ self.create_tempdir().full_path, 'polya_gtf.feather'
697
+ )
698
+ _create_polya_df_gtf().to_feather(polya_gtf_path)
699
+ splice_starts, splice_ends = _create_mock_splice_sites()
700
+ splice_starts_path = os.path.join(
701
+ self.create_tempdir().full_path, 'splice_starts.feather'
702
+ )
703
+ splice_ends_path = os.path.join(
704
+ self.create_tempdir().full_path, 'splice_ends.feather'
705
+ )
706
+ splice_starts.to_feather(splice_starts_path)
707
+ splice_ends.to_feather(splice_ends_path)
708
+ checkpointer.wait_until_finished()
709
+
710
+ model = dna_model.create(
711
+ checkpoint_dir,
712
+ organism_settings={
713
+ dna_model.Organism.HOMO_SAPIENS: dna_model.OrganismSettings(
714
+ fasta_path=_get_test_fasta_path(),
715
+ gtf_feather_path=gtf_path,
716
+ pas_feather_path=polya_gtf_path,
717
+ splice_site_starts_feather_path=splice_starts_path,
718
+ splice_site_ends_feather_path=splice_ends_path,
719
+ metadata=model_metadata,
720
+ )
721
+ },
722
+ device=jax.local_devices()[0],
723
+ )
724
+ self.assertIsInstance(model, dna_model.AlphaGenomeModel)
725
+
726
+ def test_default_organism_settings(self):
727
+ organism_settings = dna_model.default_organism_settings()
728
+ self.assertContainsSubset(
729
+ [
730
+ dna_model.Organism.HOMO_SAPIENS,
731
+ dna_model.Organism.MUS_MUSCULUS,
732
+ ],
733
+ organism_settings.keys(),
734
+ )
735
+
736
+ def test_create_model(self):
737
+ init, apply, apply_junctions = dna_model.create_model(
738
+ {dna_model.Organism.HOMO_SAPIENS: self._metadata}
739
+ )
740
+
741
+ dna_sequence_shape = jax.ShapeDtypeStruct((1, 2048, 4), dtype=jnp.float32)
742
+ organism_index_shape = jax.ShapeDtypeStruct((1,), dtype=jnp.int32)
743
+
744
+ params, state = jax.eval_shape(
745
+ init, jax.random.PRNGKey(0), dna_sequence_shape, organism_index_shape
746
+ )
747
+
748
+ predictions = jax.eval_shape(
749
+ apply, params, state, dna_sequence_shape, organism_index_shape
750
+ )
751
+ expected_predictions = {
752
+ dna_output.OutputType.ATAC: jax.ShapeDtypeStruct(
753
+ (1, 2048, 2), dtype=jnp.bfloat16
754
+ ),
755
+ dna_output.OutputType.DNASE: jax.ShapeDtypeStruct(
756
+ (1, 2048, 1), dtype=jnp.bfloat16
757
+ ),
758
+ dna_output.OutputType.CHIP_TF: jax.ShapeDtypeStruct(
759
+ (1, 16, 2), dtype=jnp.bfloat16
760
+ ),
761
+ dna_output.OutputType.SPLICE_SITES: jax.ShapeDtypeStruct(
762
+ (1, 2048, 5), dtype=jnp.bfloat16
763
+ ),
764
+ dna_output.OutputType.SPLICE_JUNCTIONS: {
765
+ 'predictions': jax.ShapeDtypeStruct(
766
+ (1, 512, 512, 24), dtype=jnp.bfloat16
767
+ ),
768
+ 'splice_site_positions': jax.ShapeDtypeStruct(
769
+ (1, 4, 512), dtype=jnp.int32
770
+ ),
771
+ },
772
+ dna_output.OutputType.CONTACT_MAPS: jax.ShapeDtypeStruct(
773
+ (1, 1, 1, 2), dtype=jnp.bfloat16
774
+ ),
775
+ }
776
+ chex.assert_trees_all_equal_shapes_and_dtypes(
777
+ dna_model.extract_predictions(predictions), expected_predictions
778
+ )
779
+
780
+ junction_predictions = jax.eval_shape(
781
+ apply_junctions,
782
+ params,
783
+ state,
784
+ predictions['embeddings_1bp'],
785
+ predictions['splice_sites_junction']['splice_site_positions'],
786
+ organism_index_shape,
787
+ )
788
+ expected_junction_predictions = {
789
+ 'predictions': jax.ShapeDtypeStruct(
790
+ (1, 512, 512, 24), dtype=jnp.bfloat16
791
+ ),
792
+ 'splice_junction_mask': jax.ShapeDtypeStruct(
793
+ (1, 512, 512, 24), dtype=jnp.bool
794
+ ),
795
+ 'splice_site_positions': jax.ShapeDtypeStruct(
796
+ (1, 4, 512), dtype=jnp.int32
797
+ ),
798
+ }
799
+ chex.assert_trees_all_equal_shapes_and_dtypes(
800
+ junction_predictions, expected_junction_predictions
801
+ )
802
+
803
+ @parameterized.parameters(('all_folds',), (dna_model.ModelVersion.ALL_FOLDS,))
804
+ @mock.patch.object(jax, 'eval_shape', return_value=MOCK_SHAPES, autospec=True)
805
+ def test_create_from_kaggle(self, version, mock_eval_shape):
806
+ del mock_eval_shape
807
+ checkpointer = ocp.StandardCheckpointer()
808
+ checkpoint_dir = os.path.join(self.create_tempdir().full_path, 'ckpt')
809
+ checkpointer.save(checkpoint_dir, ({}, {}))
810
+ checkpointer.wait_until_finished()
811
+ with (
812
+ mock.patch.object(kagglehub, 'model_download') as mock_model_download,
813
+ mock.patch.object(kaggle_auth, 'get_username') as mock_get_username,
814
+ mock.patch.object(kagglehub, 'login') as mock_login,
815
+ ):
816
+ mock_get_username.return_value = None
817
+ mock_model_download.return_value = checkpoint_dir
818
+ model = dna_model.create_from_kaggle(
819
+ version, organism_settings={}, device=jax.local_devices()[0]
820
+ )
821
+
822
+ self.assertIsInstance(model, dna_model.AlphaGenomeModel)
823
+ mock_get_username.assert_called_once()
824
+ mock_login.assert_called_once()
825
+ mock_model_download.assert_called_once_with(
826
+ 'google/alphagenome/jax/all_folds'
827
+ )
828
+
829
+ @parameterized.parameters(('fold_0',), (dna_model.ModelVersion.FOLD_0,))
830
+ @mock.patch.object(jax, 'eval_shape', return_value=MOCK_SHAPES, autospec=True)
831
+ def test_create_from_huggingface(self, version, mock_eval_shape):
832
+ del mock_eval_shape
833
+ checkpointer = ocp.StandardCheckpointer()
834
+ checkpoint_dir = os.path.join(self.create_tempdir().full_path, 'ckpt')
835
+ checkpointer.save(checkpoint_dir, ({}, {}))
836
+ checkpointer.wait_until_finished()
837
+ with (
838
+ mock.patch.object(
839
+ huggingface_hub, 'snapshot_download'
840
+ ) as mock_snapshot_download,
841
+ mock.patch.object(huggingface_hub, 'login') as mock_login,
842
+ mock.patch.object(huggingface_hub, 'whoami') as mock_whoami,
843
+ ):
844
+ mock_snapshot_download.return_value = checkpoint_dir
845
+ mock_whoami.side_effect = huggingface_hub.errors.LocalTokenNotFoundError()
846
+ model = dna_model.create_from_huggingface(
847
+ version, organism_settings={}, device=jax.local_devices()[0]
848
+ )
849
+
850
+ self.assertIsInstance(model, dna_model.AlphaGenomeModel)
851
+ mock_login.assert_called_once()
852
+ mock_whoami.assert_called_once()
853
+ mock_snapshot_download.assert_called_once_with(
854
+ repo_id='google/alphagenome-fold-0'
855
+ )
856
+
857
+ def test_default_create_with_cpu_raises_error(self):
858
+ with jax.default_device(jax.devices(backend='cpu')[0]):
859
+ with self.assertRaisesRegex(
860
+ ValueError, 'Cannot find any GPU or TPU devices'
861
+ ):
862
+ _ = dna_model.AlphaGenomeModel(
863
+ params={},
864
+ state={},
865
+ apply_fn=self._mock_model,
866
+ junctions_apply_fn=self._mock_model_junctions,
867
+ metadata={},
868
+ )
869
+
870
+
871
+ if __name__ == '__main__':
872
+ absltest.main()
flax_model/alphagenome/model/embeddings.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Embeddings for AlphaGenome."""
16
+
17
+ from flax_model.alphagenome._sdk import typing
18
+ from flax_model.alphagenome.model import layers
19
+ import chex
20
+ import haiku as hk
21
+ import jax.numpy as jnp
22
+ from jaxtyping import Array, Float, Int # pylint: disable=g-importing-member, g-multiple-import
23
+
24
+
25
+ @typing.jaxtyped
26
+ @chex.dataclass(frozen=True, kw_only=True)
27
+ class Embeddings:
28
+ """AlphaGenome embeddings."""
29
+
30
+ embeddings_1bp: Float[Array, 'B S 1536'] | None = None
31
+ embeddings_128bp: Float[Array, 'B S//128 3072'] | None = None
32
+ embeddings_pair: Float[Array, 'B S//2048 S//2048 128'] | None = None
33
+
34
+ def get_sequence_embeddings(self, resolution: int) -> Float[Array, 'B S D']:
35
+ if resolution == 128:
36
+ return self.embeddings_128bp
37
+ elif resolution == 1:
38
+ return self.embeddings_1bp
39
+ else:
40
+ raise ValueError(f'Unsupported resolution: {resolution}')
41
+
42
+
43
+ class OutputEmbedder(hk.Module):
44
+ """Generates output embeddings with organism-specific adjustments."""
45
+
46
+ def __init__(self, num_organisms: int, name: str | None = None):
47
+ """Initializes the OutputEmbedder module.
48
+
49
+ Args:
50
+ num_organisms: The number of organisms to embed. Typically 2 (human and
51
+ mouse).
52
+ name: The name of the module.
53
+ """
54
+ super().__init__(name=name)
55
+ self._num_organisms = num_organisms
56
+
57
+ @typing.jaxtyped
58
+ def __call__(
59
+ self,
60
+ x: Float[Array, 'B S D'],
61
+ organism_index: Int[Array, 'B'],
62
+ skip_x: Float[Array, 'B S_skip D_skip'] | None = None,
63
+ ) -> Float[Array, 'B S D_out']:
64
+ x = hk.Linear(2 * x.shape[-1])(x)
65
+ if skip_x is not None:
66
+ # Assumes skip_x needs to be upsampled to match x's sequence length
67
+ skip_x = hk.Linear(x.shape[-1], with_bias=False)(skip_x)
68
+ x += jnp.repeat(skip_x, x.shape[1] // skip_x.shape[1], axis=1)
69
+
70
+ x = layers.RMSBatchNorm()(x)
71
+ if self._num_organisms >= 1:
72
+ organism_embedding = hk.Embed(self._num_organisms, x.shape[-1])(
73
+ organism_index
74
+ )[:, None, :]
75
+ x += organism_embedding
76
+ return layers.gelu(x)
77
+
78
+
79
+ class OutputPair(hk.Module):
80
+ """Generates output pairwise embeddings with organism-specific adjustments."""
81
+
82
+ def __init__(self, num_organisms: int, name: str | None = None):
83
+ """Initializes the OutputPair module.
84
+
85
+ Args:
86
+ num_organisms: The number of organisms to embed. Typically 2 (human and
87
+ mouse).
88
+ name: The name of the module.
89
+ """
90
+ super().__init__(name=name)
91
+ self._num_organisms = num_organisms
92
+
93
+ @typing.jaxtyped
94
+ def __call__(
95
+ self, x: Float[Array, 'B S S F'], organism_index: Int[Array, 'B']
96
+ ) -> Float[Array, 'B S S 128']:
97
+ x = (x + jnp.swapaxes(x, 1, 2)) / 2.0 # Symmetrize.
98
+ x = layers.LayerNorm(rms_norm=True)(x)
99
+ if self._num_organisms >= 1:
100
+ organism_embedding = hk.Embed(self._num_organisms, 128)(organism_index)
101
+ x += organism_embedding[:, None, None, :]
102
+ return layers.gelu(x)
flax_model/alphagenome/model/heads.py ADDED
@@ -0,0 +1,1055 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Heads for AlphaGenome."""
16
+
17
+ import abc
18
+ from collections.abc import Mapping, Sequence
19
+ import dataclasses
20
+ import enum
21
+ import functools
22
+ import math
23
+ from flax_model.alphagenome._sdk import typing
24
+ from flax_model.alphagenome._sdk.data import junction_data
25
+ from flax_model.alphagenome._sdk.data import track_data
26
+ from flax_model.alphagenome._sdk.models import dna_model
27
+ from flax_model.alphagenome._sdk.models import dna_output
28
+ from flax_model.alphagenome.io import bundles
29
+ from flax_model.alphagenome.model import attention
30
+ from flax_model.alphagenome.model import embeddings as embeddings_module
31
+ from flax_model.alphagenome.model import losses
32
+ from flax_model.alphagenome.model import schemas
33
+ from flax_model.alphagenome.model.metadata import metadata as metadata_lib
34
+ import chex
35
+ import haiku as hk
36
+ import jax
37
+ import jax.numpy as jnp
38
+ from jaxtyping import Array, ArrayLike, Bool, Float, Int, PyTree, Shaped # pylint: disable=g-importing-member, g-multiple-import
39
+ import numpy as np
40
+
41
+ _SOFT_CLIP_VALUE = 10.0
42
+
43
+
44
+ class HeadType(enum.Enum):
45
+ """Head types."""
46
+
47
+ GENOME_TRACKS = 'genome_tracks'
48
+ CONTACT_MAPS = 'contact_maps'
49
+ SPLICE_SITES_CLASSIFICATION = 'splice_sites_classification'
50
+ SPLICE_SITES_USAGE = 'splice_sites_usage'
51
+ SPLICE_SITES_JUNCTION = 'splice_sites_junction'
52
+
53
+
54
+ class HeadName(enum.Enum):
55
+ """Output heads."""
56
+
57
+ ATAC = 'atac'
58
+ DNASE = 'dnase'
59
+ PROCAP = 'procap'
60
+ CAGE = 'cage'
61
+ RNA_SEQ = 'rna_seq'
62
+ CHIP_TF = 'chip_tf'
63
+ CHIP_HISTONE = 'chip_histone'
64
+ CONTACT_MAPS = 'contact_maps'
65
+ SPLICE_SITES_CLASSIFICATION = 'splice_sites_classification'
66
+ SPLICE_SITES_USAGE = 'splice_sites_usage'
67
+ SPLICE_SITES_JUNCTION = 'splice_sites_junction'
68
+
69
+
70
+ @dataclasses.dataclass
71
+ class HeadConfig:
72
+ type: HeadType
73
+ name: str
74
+ output_type: dna_output.OutputType
75
+
76
+
77
+ @dataclasses.dataclass
78
+ class GenomeTracksHeadConfig(HeadConfig):
79
+ resolutions: Sequence[int]
80
+ apply_squashing: bool
81
+ bundle: bundles.BundleName
82
+
83
+
84
+ def create_head(
85
+ config: HeadConfig,
86
+ metadata: Mapping[
87
+ dna_model.Organism, metadata_lib.AlphaGenomeOutputMetadata
88
+ ],
89
+ *,
90
+ num_organisms: int | None = None,
91
+ ) -> 'Head':
92
+ match config.type:
93
+ case HeadType.GENOME_TRACKS:
94
+ assert isinstance(config, GenomeTracksHeadConfig)
95
+ return GenomeTracksHead(
96
+ name=config.name,
97
+ output_type=config.output_type,
98
+ metadata=metadata,
99
+ resolutions=config.resolutions,
100
+ apply_squashing=config.apply_squashing,
101
+ bundle=config.bundle,
102
+ num_organisms=num_organisms,
103
+ )
104
+ case HeadType.CONTACT_MAPS:
105
+ return ContactMapsHead(
106
+ name=config.name,
107
+ output_type=config.output_type,
108
+ metadata=metadata,
109
+ num_organisms=num_organisms,
110
+ )
111
+ case HeadType.SPLICE_SITES_CLASSIFICATION:
112
+ return SpliceSitesClassificationHead(
113
+ name=config.name,
114
+ output_type=config.output_type,
115
+ metadata=metadata,
116
+ num_organisms=num_organisms,
117
+ )
118
+ case HeadType.SPLICE_SITES_USAGE:
119
+ return SpliceSitesUsageHead(
120
+ name=config.name,
121
+ output_type=config.output_type,
122
+ metadata=metadata,
123
+ num_organisms=num_organisms,
124
+ )
125
+ case HeadType.SPLICE_SITES_JUNCTION:
126
+ return SpliceSitesJunctionHead(
127
+ name=config.name,
128
+ output_type=config.output_type,
129
+ metadata=metadata,
130
+ num_organisms=num_organisms,
131
+ )
132
+ case _:
133
+ raise ValueError(f'Unknown head type: {config.type}')
134
+
135
+
136
+ def get_head_config(head_name: HeadName) -> HeadConfig:
137
+ """Returns a head for the given head name."""
138
+ match head_name:
139
+ case HeadName.ATAC:
140
+ return GenomeTracksHeadConfig(
141
+ type=HeadType.GENOME_TRACKS,
142
+ name=HeadName.ATAC.value,
143
+ output_type=dna_output.OutputType.ATAC,
144
+ resolutions=[1, 128],
145
+ apply_squashing=False,
146
+ bundle=bundles.BundleName.ATAC,
147
+ )
148
+ case HeadName.DNASE:
149
+ return GenomeTracksHeadConfig(
150
+ type=HeadType.GENOME_TRACKS,
151
+ name=HeadName.DNASE.value,
152
+ output_type=dna_output.OutputType.DNASE,
153
+ resolutions=[1, 128],
154
+ apply_squashing=False,
155
+ bundle=bundles.BundleName.DNASE,
156
+ )
157
+ case HeadName.PROCAP:
158
+ return GenomeTracksHeadConfig(
159
+ type=HeadType.GENOME_TRACKS,
160
+ name=HeadName.PROCAP.value,
161
+ output_type=dna_output.OutputType.PROCAP,
162
+ resolutions=[1, 128],
163
+ apply_squashing=False,
164
+ bundle=bundles.BundleName.PROCAP,
165
+ )
166
+ case HeadName.CAGE:
167
+ return GenomeTracksHeadConfig(
168
+ type=HeadType.GENOME_TRACKS,
169
+ name=HeadName.CAGE.value,
170
+ output_type=dna_output.OutputType.CAGE,
171
+ resolutions=[1, 128],
172
+ apply_squashing=False,
173
+ bundle=bundles.BundleName.CAGE,
174
+ )
175
+ case HeadName.RNA_SEQ:
176
+ return GenomeTracksHeadConfig(
177
+ type=HeadType.GENOME_TRACKS,
178
+ name=HeadName.RNA_SEQ.value,
179
+ output_type=dna_output.OutputType.RNA_SEQ,
180
+ resolutions=[1, 128],
181
+ apply_squashing=True,
182
+ bundle=bundles.BundleName.RNA_SEQ,
183
+ )
184
+ case HeadName.CHIP_TF:
185
+ return GenomeTracksHeadConfig(
186
+ type=HeadType.GENOME_TRACKS,
187
+ name=HeadName.CHIP_TF.value,
188
+ output_type=dna_output.OutputType.CHIP_TF,
189
+ resolutions=[128],
190
+ apply_squashing=False,
191
+ bundle=bundles.BundleName.CHIP_TF,
192
+ )
193
+ case HeadName.CHIP_HISTONE:
194
+ return GenomeTracksHeadConfig(
195
+ type=HeadType.GENOME_TRACKS,
196
+ name=HeadName.CHIP_HISTONE.value,
197
+ output_type=dna_output.OutputType.CHIP_HISTONE,
198
+ resolutions=[128],
199
+ apply_squashing=False,
200
+ bundle=bundles.BundleName.CHIP_HISTONE,
201
+ )
202
+ case HeadName.CONTACT_MAPS:
203
+ return HeadConfig(
204
+ type=HeadType.CONTACT_MAPS,
205
+ name=HeadName.CONTACT_MAPS.value,
206
+ output_type=dna_output.OutputType.CONTACT_MAPS,
207
+ )
208
+ case HeadName.SPLICE_SITES_CLASSIFICATION:
209
+ return HeadConfig(
210
+ type=HeadType.SPLICE_SITES_CLASSIFICATION,
211
+ name=HeadName.SPLICE_SITES_CLASSIFICATION.value,
212
+ output_type=dna_output.OutputType.SPLICE_SITES,
213
+ )
214
+ case HeadName.SPLICE_SITES_USAGE:
215
+ return HeadConfig(
216
+ type=HeadType.SPLICE_SITES_USAGE,
217
+ name=HeadName.SPLICE_SITES_USAGE.value,
218
+ output_type=dna_output.OutputType.SPLICE_SITE_USAGE,
219
+ )
220
+ case HeadName.SPLICE_SITES_JUNCTION:
221
+ return HeadConfig(
222
+ type=HeadType.SPLICE_SITES_JUNCTION,
223
+ name=HeadName.SPLICE_SITES_JUNCTION.value,
224
+ output_type=dna_output.OutputType.SPLICE_JUNCTIONS,
225
+ )
226
+ case _:
227
+ raise ValueError(f'Unknown head name: {head_name}')
228
+
229
+
230
+ @typing.jaxtyped
231
+ def _sum_pool(
232
+ x: Float[Array, 'B S C'], width: int
233
+ ) -> Float[Array, 'B S//{width} C']:
234
+ return x.reshape((x.shape[0], x.shape[1] // width, width, x.shape[2])).sum(
235
+ axis=-2, dtype=jnp.float32
236
+ )
237
+
238
+
239
+ @typing.jaxtyped
240
+ def _get_param_for_index(
241
+ params: Float[ArrayLike, 'P ...'], index: Int[Array, 'B']
242
+ ) -> Float[ArrayLike, 'B ...']:
243
+ """Returns a parameter for a specific index.
244
+
245
+ Embeds the params into the graph.
246
+
247
+ Args:
248
+ params: The parameters to embed.
249
+ index: The index to get the parameter for.
250
+ """
251
+ return jnp.asarray(params)[(index,)]
252
+
253
+
254
+ class _MultiOrganismLinear(hk.Module):
255
+ """A linear layer with organism-specific weights and biases."""
256
+
257
+ def __init__(
258
+ self,
259
+ output_size: int,
260
+ num_organisms: int,
261
+ name: str | None = 'multi_organism_linear',
262
+ ):
263
+ super().__init__(name=name)
264
+ self._output_size = output_size
265
+ self._num_organisms = num_organisms
266
+
267
+ @typing.jaxtyped
268
+ def __call__(
269
+ self, x: Float[Array, 'B *S D'], organism_index: Int[Array, 'B']
270
+ ) -> Float[Array, 'B *S {self._output_size}']:
271
+ w_shape = (self._num_organisms, x.shape[-1], self._output_size)
272
+ stddev = 1.0 / np.sqrt(x.shape[-1])
273
+ w_init = hk.initializers.TruncatedNormal(stddev=stddev)
274
+ w = hk.get_parameter('w', w_shape, init=w_init).astype(x.dtype)
275
+ w = _get_param_for_index(w, organism_index)
276
+ b_shape = (self._num_organisms, self._output_size)
277
+ b = hk.get_parameter('b', b_shape, init=jnp.zeros).astype(x.dtype)
278
+ b = _get_param_for_index(b, organism_index)
279
+ num_inner_dims = len(x.shape) - 2
280
+ target_b_shape = (b.shape[0],) + (1,) * num_inner_dims + (b.shape[1],)
281
+ return jnp.einsum(
282
+ 'b...i,bij->b...j', x, w, preferred_element_type=jnp.float32
283
+ ) + b.reshape(target_b_shape)
284
+
285
+
286
+ def predictions_scaling(
287
+ x: Float[ArrayLike, 'B S C'],
288
+ track_means: Float[ArrayLike, 'B C'],
289
+ resolution: int,
290
+ apply_squashing: bool,
291
+ soft_clip_value: float = _SOFT_CLIP_VALUE,
292
+ ) -> Float[ArrayLike, 'S C']:
293
+ """Scales predictions to experimental data scale.
294
+
295
+ Args:
296
+ x: Experimental target counts.
297
+ track_means: Mean values per track (broadcastable).
298
+ resolution: The bin resolution of the targets (e.g., 1 or 128).
299
+ apply_squashing: Whether to apply power law compression (for RNA-seq).
300
+ soft_clip_value: The value to soft clip the predictions to.
301
+
302
+ Returns:
303
+ Scaled predictions.
304
+ """
305
+ xnp = jnp if isinstance(x, jnp.ndarray) else np
306
+ x = xnp.where(
307
+ x > soft_clip_value,
308
+ (x + soft_clip_value) ** 2 / (4 * soft_clip_value),
309
+ x,
310
+ )
311
+ if apply_squashing:
312
+ x = xnp.power(x, 1.0 / 0.75)
313
+ x = x * (track_means[:, None] * resolution).astype(x.dtype)
314
+ return x
315
+
316
+
317
+ @typing.jaxtyped
318
+ def targets_scaling(
319
+ targets: Float[ArrayLike, 'B S C'],
320
+ track_means: Float[ArrayLike, 'B C'],
321
+ resolution: int,
322
+ apply_squashing: bool,
323
+ soft_clip_value: float = _SOFT_CLIP_VALUE,
324
+ ) -> Float[Array, 'B S C']:
325
+ """Scales experimental targets to the model prediction space.
326
+
327
+ Args:
328
+ targets: Experimental target counts.
329
+ track_means: Mean values per track.
330
+ resolution: The bin resolution of the targets (e.g., 1 or 128).
331
+ apply_squashing: Whether to apply power law compression (for RNA-seq).
332
+ soft_clip_value: The value to soft clip the targets to.
333
+
334
+ Returns:
335
+ Scaled targets ready for loss calculation.
336
+ """
337
+ xnp = jnp if isinstance(targets, jnp.ndarray) else np
338
+ targets = targets / (track_means[:, None] * resolution).astype(targets.dtype)
339
+
340
+ if apply_squashing:
341
+ targets = xnp.power(targets, 0.75)
342
+
343
+ # Where(targets > 10.0, 2 * Sqrt(x * 10.0) - 10.0, targets)
344
+ return xnp.where(
345
+ targets > soft_clip_value,
346
+ 2.0 * jnp.sqrt(targets * soft_clip_value) - soft_clip_value,
347
+ targets,
348
+ )
349
+
350
+
351
+ class Head(metaclass=abc.ABCMeta):
352
+ """Abstract class for a model head."""
353
+
354
+ def __init__(
355
+ self,
356
+ *,
357
+ name: str,
358
+ output_type: dna_output.OutputType,
359
+ metadata: Mapping[
360
+ dna_model.Organism,
361
+ metadata_lib.AlphaGenomeOutputMetadata,
362
+ ],
363
+ num_organisms: int | None = None,
364
+ ):
365
+ """Initializes the Head class.
366
+
367
+ Args:
368
+ name: The name of the head.
369
+ output_type: The type of output to predict.
370
+ metadata: A dictionary of track metadata for each organism. The metadata
371
+ should be a ordered aligned with the organism index. E.g.,
372
+ organism_index=0 should correspond to the first organism in the metadata
373
+ dictionary.
374
+ num_organisms: Optional number of organisms. If not provided, the number
375
+ of organisms will be inferred from the metadata.
376
+ """
377
+
378
+ self._name = name
379
+ self._output_type = output_type
380
+ self._metadata = metadata
381
+ self._num_organisms = (
382
+ num_organisms if num_organisms is not None else len(metadata)
383
+ )
384
+ if not self._metadata:
385
+ raise ValueError('No metadata provided for any organism.')
386
+ self._num_tracks = self._get_num_tracks()
387
+
388
+ @property
389
+ def name(self) -> str:
390
+ return self._name
391
+
392
+ @property
393
+ def num_tracks(self) -> int:
394
+ """Returns the maximum number of tracks for the head across all organisms."""
395
+ return self._num_tracks
396
+
397
+ def _get_num_tracks(self) -> int:
398
+ """Returns the number of tracks for the head."""
399
+ num_tracks = []
400
+ for organism in self._metadata.keys():
401
+ if (track_metadata := self.get_metadata(organism)) is not None:
402
+ num_tracks.append(len(track_metadata))
403
+
404
+ if not num_tracks:
405
+ raise ValueError(
406
+ f'No metadata found for any organism for {self._output_type=}.'
407
+ )
408
+
409
+ if len(set(num_tracks)) > 1:
410
+ raise ValueError(
411
+ 'Number of tracks is not the same for all organisms. Please pad the'
412
+ ' metadata to have the same number of tracks for all organisms.'
413
+ )
414
+ return num_tracks[0]
415
+
416
+ @typing.jaxtyped
417
+ def get_multi_organism_track_mask(
418
+ self,
419
+ ) -> Bool[Array, '{len(self._metadata)} {self.num_tracks}']:
420
+ """Returns the track mask for all organisms."""
421
+ track_masks = []
422
+ for organism in self._metadata.keys():
423
+ padding = self._metadata[organism].padding[self._output_type]
424
+ chex.assert_shape(padding, (self.num_tracks,))
425
+ track_masks.append(np.logical_not(padding))
426
+ return jnp.stack(track_masks).astype(bool)
427
+
428
+ def get_metadata(
429
+ self, organism: dna_model.Organism
430
+ ) -> track_data.TrackMetadata | junction_data.JunctionMetadata | None:
431
+ return self._metadata.get(organism, {}).get(self._output_type)
432
+
433
+ def __call__(
434
+ self,
435
+ embeddings: embeddings_module.Embeddings,
436
+ organism_index: Int[Array, 'B'],
437
+ **kwargs,
438
+ ) -> PyTree[Shaped[Array, 'B ...'] | None]:
439
+ """Calls the head's predict function as a module."""
440
+ return hk.to_module(self.predict)(self._name)(
441
+ embeddings, organism_index, **kwargs
442
+ )
443
+
444
+ @abc.abstractmethod
445
+ def predict(
446
+ self,
447
+ embeddings: embeddings_module.Embeddings,
448
+ organism_index: Int[Array, 'B'],
449
+ **kwargs,
450
+ ) -> PyTree[Shaped[Array, 'B ...'] | None]:
451
+ """Returns the predictions for the head."""
452
+
453
+ @abc.abstractmethod
454
+ def loss(
455
+ self,
456
+ predictions: PyTree[Shaped[Array, 'B ...']],
457
+ batch: schemas.DataBatch,
458
+ ) -> PyTree[Float[Array, '']]:
459
+ """Returns the loss for the head."""
460
+
461
+
462
+ class GenomeTracksHead(Head):
463
+ """A model head that predicts at multiple resolutions.
464
+
465
+ This module takes embeddings at different resolutions and produces predictions
466
+ for a specified number of tracks. It uses organism-specific linear layers and
467
+ learnt scales to generate the predictions.
468
+ """
469
+
470
+ def __init__(
471
+ self,
472
+ *,
473
+ name: str,
474
+ output_type: dna_output.OutputType,
475
+ apply_squashing: bool,
476
+ resolutions: Sequence[int],
477
+ bundle: bundles.BundleName | None = None,
478
+ metadata: Mapping[
479
+ dna_model.Organism,
480
+ metadata_lib.AlphaGenomeOutputMetadata,
481
+ ],
482
+ num_organisms: int | None = None,
483
+ ):
484
+ """Initializes the BaseResolutionHead module.
485
+
486
+ Args:
487
+ name: The name of the head.
488
+ output_type: The type of output to predict.
489
+ apply_squashing: Whether to apply squashing to the predictions.
490
+ resolutions: The resolutions to predict.
491
+ bundle: The name of the dataset bundle associated with this head. This is
492
+ required to fetch the target tracks for loss computation. If None, the
493
+ `loss` method will not be functional.
494
+ metadata: A dictionary mapping each organism to its track metadata. The
495
+ order of organisms in the dictionary is important, as it must align with
496
+ the organism index provided in the data batches (e.g., organism_index=0
497
+ corresponds to the first organism in `metadata`). For each organism, the
498
+ metadata for `output_type` should contain the same number of rows
499
+ (tracks), padded if necessary. If the metadata includes a 'nonzero_mean'
500
+ column, these values are used to scale predictions and targets.
501
+ Otherwise, scaling is omitted. Note that squashing is only applied if
502
+ `apply_squashing` is True.
503
+ num_organisms: Optional number of organisms. If not provided, the number
504
+ of organisms will be inferred from the metadata.
505
+ """
506
+
507
+ super().__init__(
508
+ name=name,
509
+ output_type=output_type,
510
+ metadata=metadata,
511
+ num_organisms=num_organisms,
512
+ )
513
+ self._apply_squashing = apply_squashing
514
+ self._resolutions = sorted(resolutions)
515
+ self._bundle = bundle
516
+
517
+ def _get_track_means(organism: dna_model.Organism) -> Float[Array, 'C']:
518
+ metadata = self.get_metadata(organism)
519
+ if metadata is None or metadata.get('nonzero_mean') is None:
520
+ return jnp.ones((self.num_tracks,))
521
+ else:
522
+ return metadata['nonzero_mean'].values
523
+
524
+ self._track_means = jnp.stack(
525
+ [_get_track_means(organism) for organism in self._metadata.keys()]
526
+ )
527
+
528
+ @typing.jaxtyped
529
+ def unscale(
530
+ self,
531
+ x: Float[Array, 'B S C'],
532
+ organism_index: Int[Array, 'B'],
533
+ resolution: int,
534
+ ) -> Float[Array, 'B S C'] | None:
535
+ """Unscales predictions to experimental data scale.
536
+
537
+ Requires the column `nonzero_mean` to be present in the metadata to result
538
+ in valid scaling.
539
+
540
+ Args:
541
+ x: The predictions to unscale.
542
+ organism_index: The organism index.
543
+ resolution: The resolution of the predictions.
544
+ """
545
+ track_means = _get_param_for_index(self._track_means, organism_index)
546
+ return predictions_scaling(
547
+ x,
548
+ track_means=track_means,
549
+ resolution=resolution,
550
+ apply_squashing=self._apply_squashing,
551
+ )
552
+
553
+ @typing.jaxtyped
554
+ def scale(
555
+ self,
556
+ x: Float[Array, 'B S C'],
557
+ organism_index: Int[Array, 'B'],
558
+ resolution: int,
559
+ ) -> Float[Array, 'B S C']:
560
+ """Scales targets to model predictions scale."""
561
+ track_means = _get_param_for_index(self._track_means, organism_index)
562
+ return targets_scaling(
563
+ x,
564
+ track_means=track_means,
565
+ resolution=resolution,
566
+ apply_squashing=self._apply_squashing,
567
+ )
568
+
569
+ @hk.transparent
570
+ @typing.jaxtyped
571
+ def _predict(
572
+ self, x: Float[Array, 'B S D'], organism_index: Int[Array, 'B']
573
+ ) -> Float[Array, 'B S {self.num_tracks}']:
574
+ """Predicts genome tracks."""
575
+ x = _MultiOrganismLinear(self.num_tracks, self._num_organisms)(
576
+ x, organism_index
577
+ )
578
+ residual_scales = hk.get_parameter(
579
+ 'learnt_scale', (self._num_organisms, self.num_tracks), init=jnp.ones
580
+ ).astype(x.dtype)
581
+ residual_scale = _get_param_for_index(residual_scales, organism_index)
582
+ return jax.nn.softplus(x) * jax.nn.softplus(residual_scale[:, None, :])
583
+
584
+ def predict(
585
+ self,
586
+ embeddings: embeddings_module.Embeddings,
587
+ organism_index: Int[Array, 'B'],
588
+ **kwargs,
589
+ ) -> PyTree[Float[Array, 'B ...'] | None]:
590
+ predictions = {}
591
+ for resolution in self._resolutions:
592
+ with hk.name_scope(f'resolution_{resolution}'):
593
+ scaled_predictions = self._predict(
594
+ embeddings.get_sequence_embeddings(resolution), organism_index
595
+ )
596
+ predictions[f'scaled_predictions_{resolution}bp'] = scaled_predictions
597
+ predictions[f'predictions_{resolution}bp'] = self.unscale(
598
+ scaled_predictions, organism_index, resolution
599
+ )
600
+ return predictions
601
+
602
+ @typing.jaxtyped
603
+ def _compute_loss(
604
+ self,
605
+ *,
606
+ organism_index: Int[Array, 'B'],
607
+ predictions: Float[Array, 'B S C'],
608
+ targets: Float[Array, 'B S C'],
609
+ targets_mask: Bool[Array, 'B 1 C'] | None,
610
+ resolution: int,
611
+ ) -> PyTree[Float[Array, '']]:
612
+ """Computes the loss for the head at a given resolution."""
613
+ chex.assert_equal_shape([predictions, targets])
614
+ scaled_targets = self.scale(targets, organism_index, resolution)
615
+ all_losses = losses.multinomial_loss(
616
+ y_pred=predictions,
617
+ y_true=scaled_targets,
618
+ mask=targets_mask,
619
+ positional_weight=5.0,
620
+ multinomial_resolution=int(2**17) // resolution,
621
+ )
622
+ return all_losses
623
+
624
+ @typing.jaxtyped
625
+ def loss(
626
+ self,
627
+ predictions: PyTree[Float[Array, 'B ...']],
628
+ batch: schemas.DataBatch,
629
+ ) -> PyTree[Float[Array, '']]:
630
+ """Returns the loss for the head."""
631
+ if self._bundle is None:
632
+ raise ValueError('Bundle is required for loss computation.')
633
+
634
+ tracks, mask = batch.get_genome_tracks(self._bundle)
635
+
636
+ if mask.shape[-2] != 1:
637
+ raise ValueError(
638
+ 'We assume the mask to broadcast over the sequence length.'
639
+ )
640
+
641
+ bundle_resolution = self._bundle.get_resolution()
642
+ loss_sum, scalars = 0.0, {}
643
+
644
+ for resolution in self._resolutions:
645
+ predictions_for_resolution = predictions[
646
+ f'scaled_predictions_{resolution}bp'
647
+ ]
648
+ if resolution == bundle_resolution:
649
+ targets = tracks
650
+ else:
651
+ targets = _sum_pool(tracks, resolution)
652
+
653
+ all_losses = self._compute_loss(
654
+ organism_index=batch.get_organism_index(),
655
+ predictions=predictions_for_resolution,
656
+ targets=targets,
657
+ targets_mask=mask,
658
+ resolution=resolution,
659
+ )
660
+ for k, v in all_losses.items():
661
+ scalars[f'{k}_{resolution}bp'] = v
662
+ loss_sum += all_losses['loss']
663
+
664
+ scalars['loss'] = loss_sum
665
+ return scalars
666
+
667
+
668
+ class ContactMapsHead(Head):
669
+ """A model head that predicts contact maps from pairwise embeddings."""
670
+
671
+ @typing.jaxtyped
672
+ @hk.transparent
673
+ def _predict(
674
+ self,
675
+ pair_embeddings: Float[Array, 'B S S D'],
676
+ organism_index: Int[Array, 'B'],
677
+ ) -> Float[Array, 'B S S {self.num_tracks}']:
678
+ """Predicts contact maps from pairwise embeddings."""
679
+ return _MultiOrganismLinear(self.num_tracks, self._num_organisms)(
680
+ pair_embeddings, organism_index
681
+ )
682
+
683
+ def predict(
684
+ self,
685
+ embeddings: embeddings_module.Embeddings,
686
+ organism_index: Int[Array, 'B'],
687
+ **kwargs,
688
+ ) -> PyTree[Float[Array, 'B ...'] | None]:
689
+ """Predicts contact maps from embeddings."""
690
+ return {
691
+ 'predictions': self._predict(embeddings.embeddings_pair, organism_index)
692
+ }
693
+
694
+ def _get_targets_mask(
695
+ self,
696
+ organism_index: Int[Array, 'B'],
697
+ ) -> Bool[Array, 'B 1 1 {self.num_tracks}']:
698
+ """Returns a mask for padding channels."""
699
+ track_mask = self.get_multi_organism_track_mask()[(organism_index,)]
700
+ return track_mask[:, None, None, :]
701
+
702
+ def loss(
703
+ self,
704
+ predictions: PyTree[Float[Array, 'B ...']],
705
+ batch: schemas.DataBatch,
706
+ ) -> PyTree[Float[Array, '']]:
707
+ """Returns the loss for the head."""
708
+ if (targets := batch.contact_maps) is None:
709
+ raise ValueError('contact_maps target not in batch.')
710
+
711
+ contact_predictions = predictions['predictions']
712
+ chex.assert_equal_shape([contact_predictions, targets])
713
+
714
+ # Mask out NaN targets (which happens when balancing a missing slice).
715
+ targets_mask = self._get_targets_mask(batch.get_organism_index())
716
+ targets_mask = jnp.where(jnp.isnan(targets), False, targets_mask)
717
+ targets = jnp.where(jnp.isnan(targets), 0.0, targets)
718
+
719
+ loss = losses.mse(
720
+ y_pred=contact_predictions, y_true=targets, mask=targets_mask
721
+ )
722
+ return {'loss': loss}
723
+
724
+
725
+ class SpliceSitesClassificationHead(Head):
726
+ """A model head that predicts splice site classification."""
727
+
728
+ @typing.jaxtyped
729
+ @hk.transparent
730
+ def _predict_logits(
731
+ self, x: Float[Array, 'B S D'], organism_index: Int[Array, 'B']
732
+ ) -> Float[Array, 'B S {self.num_tracks}']:
733
+ """Splice site classification."""
734
+ return _MultiOrganismLinear(self.num_tracks, self._num_organisms)(
735
+ x, organism_index
736
+ )
737
+
738
+ def predict(
739
+ self,
740
+ embeddings: embeddings_module.Embeddings,
741
+ organism_index: Int[Array, 'B'],
742
+ **kwargs,
743
+ ) -> PyTree[Float[Array, 'B ...'] | None]:
744
+ """Predicts splice site classification from embeddings."""
745
+ embeddings_1bp = embeddings.get_sequence_embeddings(1)
746
+ logits = self._predict_logits(embeddings_1bp, organism_index)
747
+ probs = jax.nn.softmax(logits.astype(jnp.float32), axis=-1)
748
+ return {'logits': logits, 'predictions': probs}
749
+
750
+ def loss(
751
+ self,
752
+ predictions: PyTree[Float[Array, 'B ...']],
753
+ batch: schemas.DataBatch,
754
+ ) -> PyTree[Float[Array, '']]:
755
+ """Returns the loss for the head."""
756
+ if (splice_sites := batch.splice_sites) is None:
757
+ raise ValueError('splice_sites target not in batch.')
758
+ logits = predictions['logits']
759
+ chex.assert_equal_shape([splice_sites, logits])
760
+
761
+ classification_mask = jnp.any(splice_sites, axis=-1, keepdims=True)
762
+ loss = losses.cross_entropy_loss_from_logits(
763
+ y_pred_logits=logits,
764
+ # Label smoothing with FP32 machine precision (~1e-7) for 5 classes.
765
+ y_true=(1.0 - 1e-7) * splice_sites.astype(jnp.float32)
766
+ + 1e-7 / self.num_tracks,
767
+ mask=classification_mask,
768
+ axis=-1,
769
+ )
770
+ return {'loss': loss}
771
+
772
+
773
+ class SpliceSitesUsageHead(Head):
774
+ """A model head that predicts splice site usage."""
775
+
776
+ @typing.jaxtyped
777
+ @hk.transparent
778
+ def _predict_logits(
779
+ self, x: Float[Array, 'B S D'], organism_index: Int[Array, 'B']
780
+ ) -> Float[Array, 'B S {self.num_tracks}']:
781
+ """Splice site usage."""
782
+ return _MultiOrganismLinear(self.num_tracks, self._num_organisms)(
783
+ x, organism_index
784
+ )
785
+
786
+ def predict(
787
+ self,
788
+ embeddings: embeddings_module.Embeddings,
789
+ organism_index: Int[Array, 'B'],
790
+ **kwargs,
791
+ ) -> PyTree[Float[Array, 'B ...'] | None]:
792
+ """Predicts splice site usage from embeddings."""
793
+ embeddings_1bp = embeddings.get_sequence_embeddings(1)
794
+ logits = self._predict_logits(embeddings_1bp, organism_index)
795
+ splice_site_usage = jax.nn.sigmoid(logits.astype(jnp.float32)).astype(
796
+ jnp.float16
797
+ )
798
+ return {'logits': logits, 'predictions': splice_site_usage}
799
+
800
+ @typing.jaxtyped
801
+ def _get_targets_mask(
802
+ self,
803
+ organism_index: Int[Array, 'B'],
804
+ ) -> Bool[Array, 'B 1 {self.num_tracks}']:
805
+ """Returns a mask for padding channels."""
806
+ track_mask = self.get_multi_organism_track_mask()[(organism_index,)]
807
+ return track_mask[:, None, :]
808
+
809
+ def loss(
810
+ self,
811
+ predictions: PyTree[Float[Array, 'B ...']],
812
+ batch: schemas.DataBatch,
813
+ ) -> PyTree[Float[Array, '']]:
814
+ """Returns the loss for the head."""
815
+ if (splice_site_usage := batch.splice_site_usage) is None:
816
+ raise ValueError('splice_site_usage target not in batch.')
817
+ logits = predictions['logits']
818
+ chex.assert_equal_shape([splice_site_usage, logits])
819
+ loss = losses.binary_crossentropy_from_logits(
820
+ y_pred=logits,
821
+ y_true=jnp.clip(splice_site_usage, 1e-7, 1.0 - 1e-7),
822
+ mask=self._get_targets_mask(batch.get_organism_index()),
823
+ )
824
+ return {'loss': loss}
825
+
826
+
827
+ class SpliceSitesJunctionHead(Head):
828
+ """A model head that predicts splice site junctions."""
829
+
830
+ def __init__(
831
+ self,
832
+ *,
833
+ name: str,
834
+ output_type: dna_output.OutputType,
835
+ metadata: Mapping[
836
+ dna_model.Organism,
837
+ metadata_lib.AlphaGenomeOutputMetadata,
838
+ ],
839
+ num_organisms: int | None = None,
840
+ ):
841
+ """Initializes the SpliceSitesJunctionHead module."""
842
+ super().__init__(
843
+ name=name,
844
+ output_type=output_type,
845
+ metadata=metadata,
846
+ num_organisms=num_organisms,
847
+ )
848
+ self._hidden_dim = 768
849
+ self._max_position_encoding_distance = int(2**20)
850
+
851
+ def get_num_tissues(self, organism: dna_model.Organism) -> int:
852
+ """Returns the number of tissues for the given organism."""
853
+ metadata = self.get_metadata(organism)
854
+ if metadata is None:
855
+ raise ValueError(f'Metadata not found for organism {organism}.')
856
+ return len(metadata)
857
+
858
+ @property
859
+ def max_num_tissues(self) -> int:
860
+ """Returns the maximum number of tissues across all organisms from the metadata."""
861
+
862
+ return max(self.get_num_tissues(organism) for organism in self._metadata)
863
+
864
+ def _get_num_tracks(self) -> int:
865
+ """Returns the number of tracks.
866
+
867
+ Splice junctions metadata contains the tissues per organism, rather than the
868
+ tracks. The number of tracks is twice the number of tissues accounting for
869
+ the two strands.
870
+ """
871
+ return 2 * self.max_num_tissues
872
+
873
+ def get_multi_organism_track_mask(
874
+ self,
875
+ ) -> Bool[Array, '{self._num_organisms} {self.num_tracks}']:
876
+ """Returns the track mask for the head for human and mouse.
877
+
878
+ Splice junctions metadata contains the tissues per organism, rather than the
879
+ tracks.
880
+ """
881
+ track_masks = []
882
+ for organism in self._metadata:
883
+ num_tissues = self.get_num_tissues(organism)
884
+ tissue_mask = np.arange(self.max_num_tissues) < num_tissues
885
+ # Repeat the mask for the two strands.
886
+ track_mask = np.concatenate([tissue_mask, tissue_mask])
887
+ track_masks.append(track_mask)
888
+ return jnp.stack(track_masks).astype(bool)
889
+
890
+ @typing.jaxtyped
891
+ @hk.transparent
892
+ def _predict(
893
+ self,
894
+ x: Float[Array, 'B S D'],
895
+ splice_site_positions: Int[Array, 'B 4 P'],
896
+ organism_index: Int[Array, 'B'],
897
+ ) -> tuple[
898
+ Float[Array, 'B P P {self.num_tracks}'],
899
+ Bool[Array, 'B P P {self.num_tracks}'],
900
+ ]:
901
+ """Splice site junctions."""
902
+
903
+ chex.assert_shape(splice_site_positions, (None, 4, None))
904
+ pos_donor_idx = splice_site_positions[:, 0, :]
905
+ pos_accept_idx = splice_site_positions[:, 1, :]
906
+ neg_donor_idx = splice_site_positions[:, 2, :]
907
+ neg_accept_idx = splice_site_positions[:, 3, :]
908
+
909
+ def _index_embedding(embedding, indices):
910
+ return jax.vmap(functools.partial(jnp.take, axis=0))(embedding, indices)
911
+
912
+ shape = (self._num_organisms, 2, self.max_num_tissues, self._hidden_dim)
913
+
914
+ def _apply_rope(x, indices):
915
+ x = _index_embedding(x, indices).astype(jnp.float32)
916
+ params = hk.get_parameter(
917
+ 'embeddings',
918
+ (shape[0], math.prod(shape[1:])),
919
+ dtype=x.dtype,
920
+ init=jnp.zeros,
921
+ ).reshape(*shape)
922
+ params = _get_param_for_index(params, organism_index)
923
+ # scale and offset have shape [B, 1, num_tissues, C].
924
+ scale, offset = params[:, [0], :, :], params[:, [1], :, :]
925
+ x = scale * x[:, :, None, :] + offset # [B, num_indices, num_tissues, C]
926
+ return attention.apply_rope(
927
+ x, indices, self._max_position_encoding_distance
928
+ )
929
+
930
+ splice_site_logits = _MultiOrganismLinear(
931
+ self._hidden_dim, self._num_organisms
932
+ )(x, organism_index)
933
+
934
+ with hk.name_scope('pos_acceptor_logits'):
935
+ pos_accept_logits = _apply_rope(splice_site_logits, pos_accept_idx)
936
+ with hk.name_scope('pos_donor_logits'):
937
+ pos_donor_logits = _apply_rope(splice_site_logits, pos_donor_idx)
938
+ with hk.name_scope('neg_acceptor_logits'):
939
+ neg_accept_logits = _apply_rope(splice_site_logits, neg_accept_idx)
940
+ with hk.name_scope('neg_donor_logits'):
941
+ neg_donor_logits = _apply_rope(splice_site_logits, neg_donor_idx)
942
+ pos_counts = jax.nn.softplus(
943
+ jnp.einsum(
944
+ 'bdtc,batc->bdat',
945
+ pos_donor_logits,
946
+ pos_accept_logits,
947
+ # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
948
+ precision=jax.lax.Precision.DEFAULT,
949
+ )
950
+ )
951
+ neg_counts = jax.nn.softplus(
952
+ jnp.einsum(
953
+ 'bdtc,batc->bdat',
954
+ neg_donor_logits,
955
+ neg_accept_logits,
956
+ # precision=jax.lax.DotAlgorithmPreset.BF16_BF16_F32,
957
+ precision=jax.lax.Precision.DEFAULT,
958
+ )
959
+ )
960
+ pos_mask = jnp.einsum('bd,ba->bda', pos_donor_idx >= 0, pos_accept_idx >= 0)
961
+ neg_mask = jnp.einsum('bd,ba->bda', neg_donor_idx >= 0, neg_accept_idx >= 0)
962
+ track_mask = self.get_multi_organism_track_mask()[(
963
+ organism_index,
964
+ )] # [B, 2 * num_tissues]
965
+ pos_mask = (
966
+ pos_mask[:, :, :, None]
967
+ * track_mask[:, None, None, : self.max_num_tissues]
968
+ )
969
+ neg_mask = (
970
+ neg_mask[:, :, :, None]
971
+ * track_mask[:, None, None, self.max_num_tissues :]
972
+ )
973
+ # Shape [B, D, A, 2 * num_tissues]
974
+ splice_junction_mask = jnp.concatenate([pos_mask, neg_mask], axis=-1)
975
+ pred_counts = jnp.concatenate((pos_counts, neg_counts), axis=-1)
976
+ pred_counts = jnp.where(splice_junction_mask, pred_counts, 0)
977
+ return pred_counts, splice_junction_mask
978
+
979
+ def predict(
980
+ self,
981
+ embeddings: embeddings_module.Embeddings,
982
+ organism_index: Int[Array, 'B'],
983
+ **kwargs,
984
+ ) -> PyTree[Shaped[Array, 'B ...'] | None]:
985
+ """Predicts splice site junctions from embeddings."""
986
+ if (splice_site_positions := kwargs.get('splice_site_positions')) is None:
987
+ raise ValueError(
988
+ 'splice_site_positions is required for junctions predictions.'
989
+ )
990
+ embeddings_1bp = embeddings.get_sequence_embeddings(1)
991
+ splice_site_junction, splice_junction_mask = self._predict(
992
+ embeddings_1bp, splice_site_positions, organism_index
993
+ )
994
+ return {
995
+ 'predictions': splice_site_junction,
996
+ 'splice_site_positions': splice_site_positions,
997
+ 'splice_junction_mask': splice_junction_mask,
998
+ }
999
+
1000
+ def loss(
1001
+ self,
1002
+ predictions: PyTree[Shaped[Array, 'B ...']],
1003
+ batch: schemas.DataBatch,
1004
+ ) -> PyTree[Float[Array, '']]:
1005
+ """Returns the loss for the head."""
1006
+ if (count_target := batch.splice_junctions) is None:
1007
+ raise ValueError('splice_junctions target not in batch.')
1008
+
1009
+ pred_pair = predictions['predictions']
1010
+ pairs_mask = predictions['splice_junction_mask']
1011
+ # Junctions shape is [batch, donors, acceptors, 2 * num_tissues].
1012
+ chex.assert_equal_shape([pred_pair, count_target, pairs_mask])
1013
+ chex.assert_rank(pred_pair, 4)
1014
+
1015
+ def _scale_junction_counts(counts):
1016
+ return jnp.where(
1017
+ counts > _SOFT_CLIP_VALUE,
1018
+ 2.0 * jnp.sqrt(counts * _SOFT_CLIP_VALUE) - _SOFT_CLIP_VALUE,
1019
+ counts,
1020
+ )
1021
+
1022
+ accept_total_loss = losses.poisson_loss(
1023
+ y_true=_scale_junction_counts(
1024
+ count_target.sum(axis=-2, dtype=jnp.float32, where=pairs_mask)
1025
+ ),
1026
+ y_pred=pred_pair.sum(axis=-2, dtype=jnp.float32, where=pairs_mask),
1027
+ mask=jnp.any(pairs_mask, axis=-2),
1028
+ )
1029
+ donor_total_loss = losses.poisson_loss(
1030
+ y_true=_scale_junction_counts(
1031
+ count_target.sum(axis=-3, dtype=jnp.float32, where=pairs_mask)
1032
+ ),
1033
+ y_pred=pred_pair.sum(axis=-3, dtype=jnp.float32, where=pairs_mask),
1034
+ mask=jnp.any(pairs_mask, axis=-3),
1035
+ )
1036
+
1037
+ # Ratios with cross entropy loss.
1038
+ donor_ratios_loss = losses.cross_entropy_loss(
1039
+ y_true=count_target,
1040
+ y_pred=pred_pair,
1041
+ mask=pairs_mask,
1042
+ axis=-3,
1043
+ )
1044
+ acceptor_ratios_loss = losses.cross_entropy_loss(
1045
+ y_true=count_target,
1046
+ y_pred=pred_pair,
1047
+ mask=pairs_mask,
1048
+ axis=-2,
1049
+ )
1050
+ loss = (
1051
+ donor_ratios_loss
1052
+ + acceptor_ratios_loss
1053
+ + 0.2 * (accept_total_loss + donor_total_loss)
1054
+ )
1055
+ return {'loss': loss}
flax_model/alphagenome/model/heads_test.py ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any
16
+
17
+ from absl.testing import absltest
18
+ from absl.testing import parameterized
19
+ from flax_model.alphagenome._sdk import typing
20
+ from flax_model.alphagenome._sdk.data import junction_data
21
+ from flax_model.alphagenome._sdk.data import track_data
22
+ from flax_model.alphagenome._sdk.models import dna_model
23
+ from flax_model.alphagenome._sdk.models import dna_output
24
+ from flax_model.alphagenome.io import bundles
25
+ from flax_model.alphagenome.model import embeddings
26
+ from flax_model.alphagenome.model import heads
27
+ from flax_model.alphagenome.model import schemas
28
+ from flax_model.alphagenome.model.metadata import metadata as metadata_lib
29
+ import chex
30
+ import haiku as hk
31
+ import jax
32
+ import jax.numpy as jnp
33
+ import numpy as np
34
+ import pandas as pd
35
+
36
+
37
+ _EMBEDDING_DIM_PAIR = 128
38
+ _EMBEDDING_DIM_1BP = 1536
39
+ _EMBEDDING_DIM_128BP = 3072
40
+
41
+ # Number of tracks for human and mouse.
42
+ _MOCK_ATAC_NUM_TRACKS = (9, 7)
43
+ _MOCK_CHIP_TF_NUM_TRACKS = (11, 10)
44
+ _MOCK_CONTACT_MAPS_NUM_TRACKS = (8, 7)
45
+ _MOCK_SPLICE_SITES_NUM_TRACKS = (5, 5)
46
+ _MOCK_SPLICE_SITES_USAGE_NUM_TRACKS = (10, 9)
47
+ _MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES = (15, 12) # Tissues, not tracks.
48
+
49
+
50
+ _ORGANSIM_INDEX = {
51
+ dna_model.Organism.HOMO_SAPIENS: 0,
52
+ dna_model.Organism.MUS_MUSCULUS: 1,
53
+ }
54
+
55
+
56
+ def get_mock_output_metadata(
57
+ organism: dna_model.Organism,
58
+ ) -> metadata_lib.AlphaGenomeOutputMetadata:
59
+ """Returns mock output metadata for the given organisms."""
60
+
61
+ def _make_metadata_df(total_tracks, num_tracks) -> track_data.TrackMetadata:
62
+ df_tracks = pd.DataFrame({
63
+ 'name': [f'track_{i}' for i in range(num_tracks)],
64
+ 'nonzero_mean': [1.0] * num_tracks,
65
+ })
66
+ df_padding = pd.DataFrame({
67
+ 'name': ['padding'] * (total_tracks - num_tracks),
68
+ 'nonzero_mean': [0.0] * (total_tracks - num_tracks),
69
+ })
70
+ return pd.concat([df_tracks, df_padding], ignore_index=True)
71
+
72
+ def _make_junction_metadata_df(num_tissues) -> junction_data.JunctionMetadata:
73
+ return pd.DataFrame({
74
+ 'name': [f'tissue_{i}' for i in range(num_tissues)],
75
+ })
76
+
77
+ organism_idx = _ORGANSIM_INDEX[organism]
78
+ return metadata_lib.AlphaGenomeOutputMetadata(
79
+ atac=_make_metadata_df(
80
+ max(_MOCK_ATAC_NUM_TRACKS), _MOCK_ATAC_NUM_TRACKS[organism_idx]
81
+ ),
82
+ chip_tf=_make_metadata_df(
83
+ max(_MOCK_CHIP_TF_NUM_TRACKS),
84
+ _MOCK_CHIP_TF_NUM_TRACKS[organism_idx],
85
+ ),
86
+ contact_maps=_make_metadata_df(
87
+ max(_MOCK_CONTACT_MAPS_NUM_TRACKS),
88
+ _MOCK_CONTACT_MAPS_NUM_TRACKS[organism_idx],
89
+ ),
90
+ splice_sites=_make_metadata_df(
91
+ max(_MOCK_SPLICE_SITES_NUM_TRACKS),
92
+ _MOCK_SPLICE_SITES_NUM_TRACKS[organism_idx],
93
+ ),
94
+ splice_site_usage=_make_metadata_df(
95
+ max(_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS),
96
+ _MOCK_SPLICE_SITES_USAGE_NUM_TRACKS[organism_idx],
97
+ ),
98
+ splice_junctions=_make_junction_metadata_df(
99
+ _MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES[organism_idx],
100
+ ),
101
+ )
102
+
103
+
104
+ @typing.jaxtyped
105
+ def get_mock_embeddings(
106
+ batch_size: int,
107
+ sequence_length: int,
108
+ ) -> embeddings.Embeddings:
109
+ """Returns mock embeddings for testing."""
110
+ return embeddings.Embeddings(
111
+ embeddings_pair=jnp.zeros(
112
+ (
113
+ batch_size,
114
+ sequence_length // 2048,
115
+ sequence_length // 2048,
116
+ _EMBEDDING_DIM_PAIR,
117
+ ),
118
+ dtype=jnp.bfloat16,
119
+ ),
120
+ embeddings_1bp=jnp.zeros(
121
+ (batch_size, sequence_length, _EMBEDDING_DIM_1BP), dtype=jnp.bfloat16
122
+ ),
123
+ embeddings_128bp=jnp.zeros(
124
+ (batch_size, sequence_length // 128, _EMBEDDING_DIM_128BP),
125
+ dtype=jnp.bfloat16,
126
+ ),
127
+ )
128
+
129
+
130
+ @typing.jaxtyped
131
+ def get_mock_batch(
132
+ batch_size: int,
133
+ sequence_length: int,
134
+ num_splice_sites: int,
135
+ organism_index: int = 0,
136
+ ) -> schemas.DataBatch:
137
+ """Returns mock target data for testing."""
138
+ return schemas.DataBatch(
139
+ organism_index=jnp.ones((batch_size,), dtype=jnp.int32) * organism_index,
140
+ atac=jnp.zeros(
141
+ (batch_size, sequence_length, max(_MOCK_ATAC_NUM_TRACKS)),
142
+ dtype=jnp.float32,
143
+ ),
144
+ atac_mask=jnp.ones(
145
+ (batch_size, 1, max(_MOCK_ATAC_NUM_TRACKS)),
146
+ dtype=bool,
147
+ ),
148
+ chip_tf=jnp.zeros(
149
+ (batch_size, sequence_length // 128, max(_MOCK_CHIP_TF_NUM_TRACKS)),
150
+ dtype=jnp.float32,
151
+ ),
152
+ chip_tf_mask=jnp.ones(
153
+ (batch_size, 1, max(_MOCK_CHIP_TF_NUM_TRACKS)),
154
+ dtype=bool,
155
+ ),
156
+ contact_maps=jnp.zeros(
157
+ (
158
+ batch_size,
159
+ sequence_length // 16 // 128,
160
+ sequence_length // 16 // 128,
161
+ max(_MOCK_CONTACT_MAPS_NUM_TRACKS),
162
+ ),
163
+ dtype=jnp.float32,
164
+ ),
165
+ splice_junctions=jnp.zeros(
166
+ (
167
+ batch_size,
168
+ num_splice_sites,
169
+ num_splice_sites,
170
+ max(_MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES) * 2,
171
+ ),
172
+ dtype=jnp.float32,
173
+ ),
174
+ splice_site_positions=jnp.zeros(
175
+ (batch_size, 4, num_splice_sites), dtype=jnp.int32
176
+ ),
177
+ splice_site_usage=jnp.zeros(
178
+ (
179
+ batch_size,
180
+ sequence_length,
181
+ max(_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS),
182
+ ),
183
+ dtype=jnp.float32,
184
+ ),
185
+ splice_sites=jnp.ones(
186
+ (batch_size, sequence_length, max(_MOCK_SPLICE_SITES_NUM_TRACKS)),
187
+ dtype=bool,
188
+ ),
189
+ )
190
+
191
+
192
+ class HeadsTest(parameterized.TestCase):
193
+
194
+ def setUp(self):
195
+ super().setUp()
196
+ self.batch_size = 1
197
+ # Set >= multinomial resolution of 2^17.
198
+ self.sequence_length = int(2**17)
199
+ self.num_splice_sites = 128
200
+
201
+ def test_head_num_tracks_with_default_metadata(self):
202
+ metadata = {
203
+ dna_model.Organism.HOMO_SAPIENS: metadata_lib.load(
204
+ dna_model.Organism.HOMO_SAPIENS
205
+ ),
206
+ dna_model.Organism.MUS_MUSCULUS: metadata_lib.load(
207
+ dna_model.Organism.MUS_MUSCULUS
208
+ ),
209
+ }
210
+ expected_num_tracks = {
211
+ heads.HeadName.ATAC: 256,
212
+ heads.HeadName.DNASE: 384,
213
+ heads.HeadName.PROCAP: 128,
214
+ heads.HeadName.CAGE: 640,
215
+ heads.HeadName.RNA_SEQ: 768,
216
+ heads.HeadName.CHIP_TF: 1664,
217
+ heads.HeadName.CHIP_HISTONE: 1152,
218
+ heads.HeadName.CONTACT_MAPS: 28,
219
+ heads.HeadName.SPLICE_SITES_CLASSIFICATION: 5,
220
+ heads.HeadName.SPLICE_SITES_USAGE: 734,
221
+ heads.HeadName.SPLICE_SITES_JUNCTION: 734,
222
+ }
223
+ for head_name in heads.HeadName:
224
+ with self.subTest(head_name.value):
225
+ config = heads.get_head_config(head_name)
226
+ head = heads.create_head(config, metadata)
227
+ self.assertEqual(head.num_tracks, expected_num_tracks[head_name])
228
+
229
+ def test_genome_tracks_head_no_metadata_raises_error(self):
230
+ metadata = {
231
+ dna_model.Organism.HOMO_SAPIENS: (
232
+ metadata_lib.AlphaGenomeOutputMetadata()
233
+ ),
234
+ }
235
+ with self.assertRaisesRegex(
236
+ ValueError, 'No metadata found for any organism'
237
+ ):
238
+ _ = heads.GenomeTracksHead(
239
+ name='test_head',
240
+ output_type=dna_output.OutputType.ATAC,
241
+ apply_squashing=True,
242
+ resolutions=[1],
243
+ bundle=bundles.BundleName.ATAC,
244
+ metadata=metadata,
245
+ )
246
+
247
+ def test_genome_tracks_head_inconsistent_num_tracks_raises_error(self):
248
+ def _make_metadata_df(num_tracks) -> track_data.TrackMetadata:
249
+ return pd.DataFrame({
250
+ 'name': [f'track_{i}' for i in range(num_tracks)],
251
+ 'nonzero_mean': [1.0] * num_tracks,
252
+ })
253
+
254
+ metadata = {
255
+ dna_model.Organism.HOMO_SAPIENS: metadata_lib.AlphaGenomeOutputMetadata(
256
+ atac=_make_metadata_df(10)
257
+ ),
258
+ dna_model.Organism.MUS_MUSCULUS: metadata_lib.AlphaGenomeOutputMetadata(
259
+ atac=_make_metadata_df(11)
260
+ ),
261
+ }
262
+ with self.assertRaisesRegex(
263
+ ValueError,
264
+ 'Number of tracks is not the same for all organisms',
265
+ ):
266
+ _ = heads.GenomeTracksHead(
267
+ name='test_head',
268
+ output_type=dna_output.OutputType.ATAC,
269
+ apply_squashing=True,
270
+ resolutions=[1],
271
+ bundle=bundles.BundleName.ATAC,
272
+ metadata=metadata,
273
+ )
274
+
275
+ def _test_head(
276
+ self,
277
+ head: heads.Head,
278
+ expected_params_shape: Any,
279
+ expected_output_shape: Any,
280
+ ):
281
+ @hk.transform
282
+ def forward(embeddings_input, batch):
283
+ kwargs = {}
284
+ if isinstance(head, heads.SpliceSitesJunctionHead):
285
+ kwargs['splice_site_positions'] = batch.splice_site_positions
286
+ output = head(embeddings_input, batch.organism_index, **kwargs)
287
+ loss = head.loss(output, batch)
288
+ return output, loss
289
+
290
+ rng = jax.random.PRNGKey(42)
291
+ embeddings_input = get_mock_embeddings(
292
+ self.batch_size, self.sequence_length
293
+ )
294
+ batch = get_mock_batch(
295
+ self.batch_size, self.sequence_length, self.num_splice_sites
296
+ )
297
+
298
+ params = forward.init(rng, embeddings_input, batch)
299
+ output, loss = forward.apply(params, rng, embeddings_input, batch)
300
+
301
+ to_shape = lambda t: jax.tree.map(lambda x: x.shape, t)
302
+ chex.assert_trees_all_equal(to_shape(params), expected_params_shape)
303
+ chex.assert_trees_all_equal(to_shape(output), expected_output_shape)
304
+ self.assertTrue(np.isfinite(loss['loss']).all())
305
+
306
+ @parameterized.named_parameters(
307
+ dict(
308
+ testcase_name='one_organism',
309
+ organisms=(dna_model.Organism.HOMO_SAPIENS,),
310
+ ),
311
+ dict(
312
+ testcase_name='two_organisms',
313
+ organisms=(
314
+ dna_model.Organism.HOMO_SAPIENS,
315
+ dna_model.Organism.MUS_MUSCULUS,
316
+ ),
317
+ ),
318
+ )
319
+ def test_genome_tracks_head(self, organisms: tuple[dna_model.Organism, ...]):
320
+ metadata = {
321
+ organism: get_mock_output_metadata(organism) for organism in organisms
322
+ }
323
+ head = heads.GenomeTracksHead(
324
+ name='test_head',
325
+ output_type=dna_output.OutputType.ATAC,
326
+ apply_squashing=True,
327
+ resolutions=[1, 128],
328
+ bundle=bundles.BundleName.ATAC,
329
+ metadata=metadata,
330
+ )
331
+ with self.subTest('num_organisms'):
332
+ self.assertLen(head.get_multi_organism_track_mask(), len(metadata))
333
+ with self.subTest('num_tracks'):
334
+ self.assertEqual(head.num_tracks, max(_MOCK_ATAC_NUM_TRACKS))
335
+ with self.subTest('track_mask'):
336
+ for i, organism in enumerate(organisms):
337
+ organism_idx = _ORGANSIM_INDEX[organism]
338
+ self.assertEqual(
339
+ np.sum(head.get_multi_organism_track_mask()[i]),
340
+ _MOCK_ATAC_NUM_TRACKS[organism_idx],
341
+ )
342
+
343
+ num_organisms = len(metadata)
344
+ num_tracks = head.num_tracks
345
+ expected_params_shape = {
346
+ 'test_head/resolution_1': {'learnt_scale': (num_organisms, num_tracks)},
347
+ 'test_head/resolution_1/multi_organism_linear': {
348
+ 'b': (num_organisms, num_tracks),
349
+ 'w': (num_organisms, _EMBEDDING_DIM_1BP, num_tracks),
350
+ },
351
+ 'test_head/resolution_128': {
352
+ 'learnt_scale': (num_organisms, num_tracks)
353
+ },
354
+ 'test_head/resolution_128/multi_organism_linear': {
355
+ 'b': (num_organisms, num_tracks),
356
+ 'w': (num_organisms, _EMBEDDING_DIM_128BP, num_tracks),
357
+ },
358
+ }
359
+ expected_output_shape = {
360
+ 'scaled_predictions_1bp': (
361
+ self.batch_size,
362
+ self.sequence_length,
363
+ num_tracks,
364
+ ),
365
+ 'predictions_1bp': (self.batch_size, self.sequence_length, num_tracks),
366
+ 'scaled_predictions_128bp': (
367
+ self.batch_size,
368
+ self.sequence_length // 128,
369
+ num_tracks,
370
+ ),
371
+ 'predictions_128bp': (
372
+ self.batch_size,
373
+ self.sequence_length // 128,
374
+ num_tracks,
375
+ ),
376
+ }
377
+ with self.subTest('params_shape'):
378
+ self._test_head(
379
+ head,
380
+ expected_params_shape,
381
+ expected_output_shape,
382
+ )
383
+
384
+ @parameterized.named_parameters(
385
+ dict(
386
+ testcase_name='one_organism',
387
+ organisms=(dna_model.Organism.HOMO_SAPIENS,),
388
+ ),
389
+ dict(
390
+ testcase_name='two_organisms',
391
+ organisms=(
392
+ dna_model.Organism.HOMO_SAPIENS,
393
+ dna_model.Organism.MUS_MUSCULUS,
394
+ ),
395
+ ),
396
+ )
397
+ def test_contact_maps_head(self, organisms: tuple[dna_model.Organism, ...]):
398
+ metadata = {
399
+ organism: get_mock_output_metadata(organism) for organism in organisms
400
+ }
401
+ config = heads.get_head_config(heads.HeadName.CONTACT_MAPS)
402
+ head = heads.create_head(config, metadata)
403
+
404
+ with self.subTest('num_organisms'):
405
+ self.assertLen(head.get_multi_organism_track_mask(), len(metadata))
406
+ with self.subTest('num_tracks'):
407
+ self.assertEqual(head.num_tracks, max(_MOCK_CONTACT_MAPS_NUM_TRACKS))
408
+ with self.subTest('track_mask'):
409
+ for i, organism in enumerate(organisms):
410
+ organism_idx = _ORGANSIM_INDEX[organism]
411
+ self.assertEqual(
412
+ np.sum(head.get_multi_organism_track_mask()[i]),
413
+ _MOCK_CONTACT_MAPS_NUM_TRACKS[organism_idx],
414
+ )
415
+
416
+ num_organisms = len(metadata)
417
+ num_tracks = head.num_tracks
418
+ prefix = config.name
419
+ expected_params_shape = {
420
+ f'{prefix}/multi_organism_linear': {
421
+ 'b': (num_organisms, num_tracks),
422
+ 'w': (num_organisms, _EMBEDDING_DIM_PAIR, num_tracks),
423
+ },
424
+ }
425
+ expected_output_shape = {
426
+ 'predictions': (
427
+ self.batch_size,
428
+ self.sequence_length // 2048,
429
+ self.sequence_length // 2048,
430
+ num_tracks,
431
+ ),
432
+ }
433
+ with self.subTest('params_shape'):
434
+ self._test_head(
435
+ head,
436
+ expected_params_shape,
437
+ expected_output_shape,
438
+ )
439
+
440
+ @parameterized.named_parameters(
441
+ dict(
442
+ testcase_name='one_organism',
443
+ organisms=(dna_model.Organism.HOMO_SAPIENS,),
444
+ ),
445
+ dict(
446
+ testcase_name='two_organisms',
447
+ organisms=(
448
+ dna_model.Organism.HOMO_SAPIENS,
449
+ dna_model.Organism.MUS_MUSCULUS,
450
+ ),
451
+ ),
452
+ )
453
+ def test_splice_sites_classification_head(
454
+ self, organisms: tuple[dna_model.Organism, ...]
455
+ ):
456
+ metadata = {
457
+ organism: get_mock_output_metadata(organism) for organism in organisms
458
+ }
459
+ config = heads.get_head_config(heads.HeadName.SPLICE_SITES_CLASSIFICATION)
460
+ head = heads.create_head(config, metadata)
461
+
462
+ with self.subTest('num_organisms'):
463
+ self.assertLen(head.get_multi_organism_track_mask(), len(metadata))
464
+ with self.subTest('num_tracks'):
465
+ self.assertEqual(head.num_tracks, max(_MOCK_SPLICE_SITES_NUM_TRACKS))
466
+ with self.subTest('track_mask'):
467
+ for i, organism in enumerate(organisms):
468
+ organism_idx = _ORGANSIM_INDEX[organism]
469
+ self.assertEqual(
470
+ np.sum(head.get_multi_organism_track_mask()[i]),
471
+ _MOCK_SPLICE_SITES_NUM_TRACKS[organism_idx],
472
+ )
473
+
474
+ num_organisms = len(metadata)
475
+ num_tracks = head.num_tracks
476
+ prefix = config.name
477
+ expected_params_shape = {
478
+ f'{prefix}/multi_organism_linear': {
479
+ 'b': (num_organisms, num_tracks),
480
+ 'w': (num_organisms, _EMBEDDING_DIM_1BP, num_tracks),
481
+ },
482
+ }
483
+ expected_output_shape = {
484
+ 'predictions': (
485
+ self.batch_size,
486
+ self.sequence_length,
487
+ num_tracks,
488
+ ),
489
+ 'logits': (
490
+ self.batch_size,
491
+ self.sequence_length,
492
+ num_tracks,
493
+ ),
494
+ }
495
+ self._test_head(
496
+ head,
497
+ expected_params_shape,
498
+ expected_output_shape,
499
+ )
500
+
501
+ @parameterized.named_parameters(
502
+ dict(
503
+ testcase_name='one_organism',
504
+ organisms=(dna_model.Organism.HOMO_SAPIENS,),
505
+ ),
506
+ dict(
507
+ testcase_name='two_organisms',
508
+ organisms=(
509
+ dna_model.Organism.HOMO_SAPIENS,
510
+ dna_model.Organism.MUS_MUSCULUS,
511
+ ),
512
+ ),
513
+ )
514
+ def test_splice_sites_usage_head(
515
+ self, organisms: tuple[dna_model.Organism, ...]
516
+ ):
517
+ metadata = {
518
+ organism: get_mock_output_metadata(organism) for organism in organisms
519
+ }
520
+ config = heads.get_head_config(heads.HeadName.SPLICE_SITES_USAGE)
521
+ head = heads.create_head(config, metadata)
522
+
523
+ with self.subTest('num_organisms'):
524
+ self.assertLen(head.get_multi_organism_track_mask(), len(metadata))
525
+ with self.subTest('num_tracks'):
526
+ self.assertEqual(
527
+ head.num_tracks, max(_MOCK_SPLICE_SITES_USAGE_NUM_TRACKS)
528
+ )
529
+ with self.subTest('track_mask'):
530
+ for i, organism in enumerate(organisms):
531
+ organism_idx = _ORGANSIM_INDEX[organism]
532
+ self.assertEqual(
533
+ np.sum(head.get_multi_organism_track_mask()[i]),
534
+ _MOCK_SPLICE_SITES_USAGE_NUM_TRACKS[organism_idx],
535
+ )
536
+
537
+ num_organisms = len(metadata)
538
+ num_tracks = head.num_tracks
539
+ prefix = config.name
540
+ expected_params_shape = {
541
+ f'{prefix}/multi_organism_linear': {
542
+ 'b': (num_organisms, num_tracks),
543
+ 'w': (num_organisms, _EMBEDDING_DIM_1BP, num_tracks),
544
+ },
545
+ }
546
+ expected_output_shape = {
547
+ 'predictions': (
548
+ self.batch_size,
549
+ self.sequence_length,
550
+ num_tracks,
551
+ ),
552
+ 'logits': (
553
+ self.batch_size,
554
+ self.sequence_length,
555
+ num_tracks,
556
+ ),
557
+ }
558
+ self._test_head(
559
+ head,
560
+ expected_params_shape,
561
+ expected_output_shape,
562
+ )
563
+
564
+ @parameterized.named_parameters(
565
+ dict(
566
+ testcase_name='one_organism',
567
+ organisms=(dna_model.Organism.HOMO_SAPIENS,),
568
+ ),
569
+ dict(
570
+ testcase_name='two_organisms',
571
+ organisms=(
572
+ dna_model.Organism.HOMO_SAPIENS,
573
+ dna_model.Organism.MUS_MUSCULUS,
574
+ ),
575
+ ),
576
+ )
577
+ def test_splice_sites_junction_head(
578
+ self, organisms: tuple[dna_model.Organism, ...]
579
+ ):
580
+ metadata = {
581
+ organism: get_mock_output_metadata(organism) for organism in organisms
582
+ }
583
+ config = heads.get_head_config(heads.HeadName.SPLICE_SITES_JUNCTION)
584
+ head = heads.create_head(config, metadata)
585
+ assert isinstance(head, heads.SpliceSitesJunctionHead)
586
+
587
+ with self.subTest('num_organisms'):
588
+ self.assertLen(head.get_multi_organism_track_mask(), len(metadata))
589
+ with self.subTest('num_tracks'):
590
+ self.assertEqual(
591
+ head.num_tracks, 2 * max(_MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES)
592
+ )
593
+ with self.subTest('track_mask'):
594
+ for i, organism in enumerate(organisms):
595
+ organism_idx = _ORGANSIM_INDEX[organism]
596
+ self.assertEqual(
597
+ np.sum(head.get_multi_organism_track_mask()[i]),
598
+ 2 * _MOCK_SPLICE_SITES_JUNCTION_NUM_TISSUES[organism_idx],
599
+ )
600
+
601
+ num_organisms = len(metadata)
602
+ num_tracks = head.num_tracks
603
+ num_tissues = head.max_num_tissues
604
+ hidden_dim = 768
605
+ prefix = config.name
606
+ expected_params_shape = {
607
+ f'{prefix}/pos_acceptor_logits': {
608
+ 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim),
609
+ },
610
+ f'{prefix}/pos_donor_logits': {
611
+ 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim),
612
+ },
613
+ f'{prefix}/neg_acceptor_logits': {
614
+ 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim),
615
+ },
616
+ f'{prefix}/neg_donor_logits': {
617
+ 'embeddings': (num_organisms, 2 * num_tissues * hidden_dim),
618
+ },
619
+ f'{prefix}/multi_organism_linear': {
620
+ 'b': (num_organisms, hidden_dim),
621
+ 'w': (num_organisms, _EMBEDDING_DIM_1BP, hidden_dim),
622
+ },
623
+ }
624
+ expected_output_shape = {
625
+ 'predictions': (
626
+ self.batch_size,
627
+ self.num_splice_sites,
628
+ self.num_splice_sites,
629
+ num_tracks,
630
+ ),
631
+ 'splice_site_positions': (
632
+ self.batch_size,
633
+ 4,
634
+ self.num_splice_sites,
635
+ ),
636
+ 'splice_junction_mask': (
637
+ self.batch_size,
638
+ self.num_splice_sites,
639
+ self.num_splice_sites,
640
+ num_tracks,
641
+ ),
642
+ }
643
+ self._test_head(
644
+ head,
645
+ expected_params_shape,
646
+ expected_output_shape,
647
+ )
648
+
649
+ @parameterized.named_parameters(
650
+ dict(testcase_name='with_squashing', apply_squashing=True),
651
+ dict(testcase_name='without_squashing', apply_squashing=False),
652
+ )
653
+ def test_scaling_and_unscaling(self, apply_squashing: bool):
654
+ batch_size, sequence_length, num_tracks, resolution = 3, 2048, 10, 1
655
+ key = jax.random.PRNGKey(42)
656
+ key_data, key_means = jax.random.split(key)
657
+ track_means = jax.random.uniform(key_means, (batch_size, num_tracks)) + 0.01
658
+ input_data = jax.random.uniform(
659
+ key_data, (batch_size, sequence_length, num_tracks), minval=0, maxval=99
660
+ )
661
+ scaled_data = heads.targets_scaling(
662
+ input_data,
663
+ track_means=track_means,
664
+ resolution=resolution,
665
+ apply_squashing=apply_squashing,
666
+ )
667
+ unscaled_data = heads.predictions_scaling(
668
+ scaled_data,
669
+ track_means=track_means,
670
+ resolution=resolution,
671
+ apply_squashing=apply_squashing,
672
+ )
673
+ chex.assert_trees_all_close(input_data, unscaled_data, rtol=1e-5, atol=1e-5)
674
+
675
+
676
+ if __name__ == '__main__':
677
+ absltest.main()
flax_model/alphagenome/model/interval_scoring/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome Interval Scoring."""
flax_model/alphagenome/model/interval_scoring/gene_mask.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Implementation of gene mask interval scoring."""
16
+
17
+ from collections.abc import Mapping
18
+
19
+ from flax_model.alphagenome._sdk import typing
20
+ from flax_model.alphagenome._sdk.data import genome
21
+ from flax_model.alphagenome._sdk.data import track_data
22
+ from flax_model.alphagenome._sdk.models import dna_output
23
+ from flax_model.alphagenome._sdk.models import interval_scorers
24
+ from flax_model.alphagenome.model.interval_scoring import interval_scoring
25
+ from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor as gene_mask_extractor_lib
26
+ from flax_model.alphagenome.model.variant_scoring import variant_scoring
27
+ import anndata
28
+ import jax.numpy as jnp
29
+ from jaxtyping import Array, Bool, Float32 # pylint: disable=g-multiple-import, g-importing-member
30
+ import numpy as np
31
+ import pandas as pd
32
+
33
+
34
+ class GeneIntervalScorer(
35
+ interval_scoring.IntervalScorer[
36
+ Bool[np.ndarray | Array, 'M G'],
37
+ pd.DataFrame,
38
+ interval_scorers.GeneMaskScorer,
39
+ ]
40
+ ):
41
+ """Interval scorer that aggregates intervals across different genes."""
42
+
43
+ def __init__(
44
+ self, gene_mask_extractor: gene_mask_extractor_lib.GeneMaskExtractor
45
+ ):
46
+ """Initializes the GeneIntervalScorer.
47
+
48
+ Args:
49
+ gene_mask_extractor: Gene mask extractor to use.
50
+ """
51
+ self._gene_mask_extractor = gene_mask_extractor
52
+
53
+ def get_masks_and_metadata(
54
+ self,
55
+ interval: genome.Interval,
56
+ *,
57
+ settings: interval_scorers.GeneMaskScorer,
58
+ track_metadata: dna_output.OutputMetadata,
59
+ ) -> tuple[Bool[np.ndarray | Array, 'S G'], pd.DataFrame]:
60
+ """Get gene masks and metadata for the given interval.
61
+
62
+ Args:
63
+ interval: Genomic interval to extract gene masks for.
64
+ settings: The variant scorer settings.
65
+ track_metadata: Track metadata for the variant.
66
+
67
+ Returns:
68
+ Tuple of (gene variant masks, mask metadata). The mask metadata is the
69
+ part of the GTF pandas dataframe that was used to construct the gene
70
+ masks.
71
+ """
72
+ del track_metadata
73
+ if interval.negative_strand:
74
+ raise ValueError(
75
+ 'IntervalScorers do not support negative strands (negative strand'
76
+ ' predictions should already be reverse-complemented prior to'
77
+ ' scoring and thus masks should be generated on the positive strand).'
78
+ )
79
+ if settings.width is not None and settings.width > interval.width:
80
+ raise ValueError('Interval width must be >= the center mask width.')
81
+ resolution = variant_scoring.get_resolution(settings.requested_output)
82
+ target_interval = (
83
+ interval.resize(width=settings.width)
84
+ if settings.width is not None
85
+ else interval
86
+ )
87
+
88
+ gene_mask, metadata = self._gene_mask_extractor.extract(target_interval)
89
+ interval_padding = interval.width - target_interval.width
90
+ gene_mask = np.pad(
91
+ gene_mask,
92
+ ((interval_padding // 2, (interval_padding + 1) // 2), (0, 0)),
93
+ )
94
+ if resolution > 1:
95
+ gene_mask = gene_mask.reshape(
96
+ (gene_mask.shape[0] // resolution, resolution, -1)
97
+ ).max(axis=1)
98
+ return gene_mask, metadata
99
+
100
+ @typing.jaxtyped
101
+ def score_interval(
102
+ self,
103
+ predictions: Mapping[dna_output.OutputType, Float32[Array, 'S T']],
104
+ *,
105
+ masks: Bool[Array | np.ndarray, 'M G'],
106
+ settings: interval_scorers.GeneMaskScorer,
107
+ interval: genome.Interval | None = None,
108
+ ) -> interval_scoring.ScoreIntervalOutput:
109
+ """See base class."""
110
+ del interval
111
+ tracks = predictions[settings.requested_output]
112
+
113
+ match settings.aggregation_type:
114
+ case interval_scorers.IntervalAggregationType.MEAN:
115
+ output = jnp.einsum('lt,lg->gt', tracks, masks) / jnp.expand_dims(
116
+ masks.sum(axis=0), axis=-1
117
+ )
118
+ case interval_scorers.IntervalAggregationType.SUM:
119
+ output = jnp.einsum('lt,lg->gt', tracks, masks)
120
+ case _:
121
+ raise ValueError(
122
+ f'Unsupported aggregation type: {self._aggregation_type}.'
123
+ )
124
+
125
+ return {'score': output}
126
+
127
+ def finalize_interval(
128
+ self,
129
+ scores: interval_scoring.ScoreIntervalResult,
130
+ *,
131
+ track_metadata: dna_output.OutputMetadata,
132
+ mask_metadata: pd.DataFrame,
133
+ settings: interval_scorers.GeneMaskScorer,
134
+ ) -> anndata.AnnData:
135
+ """Returns summarized scores for the given scores and metadata."""
136
+ output_metadata = track_metadata.get(settings.requested_output)
137
+ assert isinstance(output_metadata, track_data.TrackMetadata)
138
+ return variant_scoring.create_anndata(
139
+ scores['score'],
140
+ obs=mask_metadata,
141
+ var=output_metadata,
142
+ )
flax_model/alphagenome/model/interval_scoring/gene_mask_test.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from absl.testing import absltest
16
+ from absl.testing import parameterized
17
+ from flax_model.alphagenome._sdk.data import genome
18
+ from flax_model.alphagenome._sdk.models import dna_output
19
+ from flax_model.alphagenome._sdk.models import interval_scorers
20
+ from flax_model.alphagenome.model.interval_scoring import gene_mask
21
+ from flax_model.alphagenome.model.variant_scoring import gene_mask_extractor
22
+ from flax_model.alphagenome.model.variant_scoring import variant_scoring
23
+ import anndata
24
+ import jax.numpy as jnp
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+
29
+ def _load_gtf():
30
+ return pd.DataFrame({
31
+ 'End': [306, 303, 305, 138, 15],
32
+ 'Start': [301, 302, 303, 0, 5],
33
+ 'Strand': ['+', '+', '+', '-', '-'],
34
+ 'transcript_id': ['', 'T1', 'T2', '', 'T3'],
35
+ 'gene_id': ['G1', 'G1', 'G1', 'G2', 'G2'],
36
+ 'Feature': [
37
+ 'gene',
38
+ 'transcript',
39
+ 'transcript',
40
+ 'gene',
41
+ 'transcript',
42
+ ],
43
+ # Fixed Fields
44
+ 'Chromosome': 'chr1',
45
+ 'Score': '.',
46
+ 'Frame': '.',
47
+ 'Source': 'ENSEMBL',
48
+ 'gene_type': 'protein_coding',
49
+ 'gene_name': 'GX_name',
50
+ 'transcript_type': 'protein_coding',
51
+ })
52
+
53
+
54
+ class GeneIntervalScorerTest(parameterized.TestCase):
55
+
56
+ @parameterized.product(
57
+ aggregation_type=[
58
+ interval_scorers.IntervalAggregationType.SUM,
59
+ interval_scorers.IntervalAggregationType.MEAN,
60
+ ],
61
+ output_type=[dna_output.OutputType.RNA_SEQ, dna_output.OutputType.DNASE],
62
+ )
63
+ def test_gene_scorer_get_masks_and_metadata(
64
+ self, aggregation_type, output_type
65
+ ):
66
+ gtf = _load_gtf()
67
+
68
+ settings = interval_scorers.GeneMaskScorer(
69
+ requested_output=output_type,
70
+ aggregation_type=aggregation_type,
71
+ width=501,
72
+ )
73
+
74
+ interval = genome.Interval('chr1', 0, 2048)
75
+ interval_scorer = gene_mask.GeneIntervalScorer(
76
+ gene_mask_extractor.GeneMaskExtractor(
77
+ gtf=gtf,
78
+ gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS,
79
+ )
80
+ )
81
+
82
+ track_metadata = dna_output.OutputMetadata(**{
83
+ output_type.name.lower(): pd.DataFrame({
84
+ 'name': np.arange(9).astype(str),
85
+ 'strand': '.',
86
+ })
87
+ })
88
+ masks, metadata = interval_scorer.get_masks_and_metadata(
89
+ interval, settings=settings, track_metadata=track_metadata
90
+ )
91
+ self.assertIsInstance(metadata, pd.DataFrame)
92
+ self.assertContainsSubset(
93
+ ['strand', 'gene_name', 'gene_id', 'gene_type'], metadata.columns
94
+ )
95
+
96
+ self.assertEqual(masks.shape[0], interval.width)
97
+
98
+ def test_gene_scorer_get_masks_and_metadata_negative_strand(self):
99
+ gtf = _load_gtf()
100
+ interval_scorer = gene_mask.GeneIntervalScorer(
101
+ gene_mask_extractor.GeneMaskExtractor(
102
+ gtf=gtf,
103
+ gene_mask_type=gene_mask_extractor.GeneMaskType.EXONS,
104
+ )
105
+ )
106
+ settings = interval_scorers.GeneMaskScorer(
107
+ requested_output=dna_output.OutputType.RNA_SEQ,
108
+ aggregation_type=interval_scorers.IntervalAggregationType.SUM,
109
+ width=501,
110
+ )
111
+ with self.assertRaisesRegex(
112
+ ValueError, 'IntervalScorers do not support negative strands'
113
+ ):
114
+ _ = interval_scorer.get_masks_and_metadata(
115
+ genome.Interval('chr1', 0, 2048, strand='-'),
116
+ settings=settings,
117
+ track_metadata=dna_output.OutputMetadata(),
118
+ )
119
+
120
+ @parameterized.product(
121
+ aggregation_type=[
122
+ interval_scorers.IntervalAggregationType.SUM,
123
+ interval_scorers.IntervalAggregationType.MEAN,
124
+ ],
125
+ output_type=[dna_output.OutputType.RNA_SEQ, dna_output.OutputType.DNASE],
126
+ )
127
+ def test_gene_scorer_score_interval(
128
+ self,
129
+ aggregation_type,
130
+ output_type,
131
+ ):
132
+ # Score a simple example for an interval of length 10, consisting of 100
133
+ # tracks, all of values 0..9 depending on the position. The mask
134
+ # includes positions 4-6.
135
+ tracks = jnp.arange(10, dtype=jnp.float32).repeat(100).reshape((10, 100))
136
+ mask = np.zeros((10, 3), dtype=bool)
137
+ mask[4:7] = True
138
+
139
+ gtf = _load_gtf()
140
+ settings = interval_scorers.GeneMaskScorer(
141
+ requested_output=output_type,
142
+ aggregation_type=aggregation_type,
143
+ width=501,
144
+ )
145
+ interval_scorer = gene_mask.GeneIntervalScorer(
146
+ gene_mask_extractor.GeneMaskExtractor(
147
+ gtf=gtf, gene_mask_type=gene_mask_extractor.GeneMaskType.BODY
148
+ ),
149
+ )
150
+ scores = interval_scorer.score_interval(
151
+ {output_type: tracks}, settings=settings, masks=mask
152
+ )
153
+
154
+ expected_num_tracks = 100
155
+ match aggregation_type:
156
+ case interval_scorers.IntervalAggregationType.SUM:
157
+ expected_score = 15.0
158
+ case interval_scorers.IntervalAggregationType.MEAN:
159
+ expected_score = 5.0
160
+ case _:
161
+ raise ValueError(f'Unknown aggregation type: {aggregation_type}')
162
+
163
+ np.testing.assert_almost_equal(
164
+ scores['score'][0],
165
+ np.full((expected_num_tracks,), expected_score, dtype=jnp.float32),
166
+ )
167
+
168
+ @parameterized.product(
169
+ center_mask_width=[501],
170
+ output_type=[
171
+ dna_output.OutputType.RNA_SEQ,
172
+ dna_output.OutputType.CHIP_TF,
173
+ ],
174
+ )
175
+ def test_gene_scorer_with_center_mask_width(
176
+ self,
177
+ center_mask_width,
178
+ output_type,
179
+ ):
180
+ gtf = _load_gtf()
181
+ interval = genome.Interval('chr1', 0, 1024)
182
+ interval_scorer = gene_mask.GeneIntervalScorer(
183
+ gene_mask_extractor.GeneMaskExtractor(
184
+ gtf=gtf,
185
+ gene_mask_type=gene_mask_extractor.GeneMaskType.BODY,
186
+ ),
187
+ )
188
+ settings = interval_scorers.GeneMaskScorer(
189
+ requested_output=output_type,
190
+ aggregation_type=interval_scorers.IntervalAggregationType.MEAN,
191
+ width=center_mask_width,
192
+ )
193
+ resolution = variant_scoring.get_resolution(output_type)
194
+ num_bins = interval.width // resolution
195
+ tracks = (
196
+ jnp.arange(num_bins, dtype=jnp.float32).repeat(4).reshape((num_bins, 4))
197
+ )
198
+
199
+ track_metadata = dna_output.OutputMetadata(**{
200
+ output_type.name.lower(): pd.DataFrame(
201
+ {'name': np.arange(4).astype(str), 'strand': '.'}
202
+ )
203
+ })
204
+ masks, metadata = interval_scorer.get_masks_and_metadata(
205
+ interval, settings=settings, track_metadata=track_metadata
206
+ )
207
+ scores = interval_scorer.score_interval(
208
+ {output_type: tracks}, settings=settings, masks=masks
209
+ )
210
+
211
+ expected_genes = ['G1']
212
+ expected_mask = np.zeros([num_bins, len(expected_genes)], dtype=bool)
213
+ expected_scores = np.full(
214
+ (len(expected_genes), 4), np.nan, dtype=jnp.float32
215
+ )
216
+
217
+ if resolution == 1:
218
+ expected_mask[301:306, 0] = True # G1
219
+ expected_scores[0] = 303.0
220
+ else:
221
+ expected_mask[2, 0] = True # G1
222
+ expected_scores[0] = 2.0
223
+ np.testing.assert_array_equal(masks, expected_mask)
224
+ np.testing.assert_almost_equal(scores['score'], expected_scores)
225
+ np.testing.assert_array_equal(metadata['gene_id'].values, expected_genes)
226
+
227
+ def test_gene_scorer_finalize(self):
228
+ interval = genome.Interval('chr1', 0, 2048)
229
+ track_metadata = dna_output.OutputMetadata(
230
+ rna_seq=pd.DataFrame({
231
+ 'name': np.arange(9).astype(str),
232
+ 'strand': '.',
233
+ })
234
+ )
235
+ expected_scores = np.full((1, 9), 15.0, dtype=jnp.float32)
236
+ scores = {'score': expected_scores}
237
+
238
+ gtf = _load_gtf()
239
+ interval_scorer = gene_mask.GeneIntervalScorer(
240
+ gene_mask_extractor.GeneMaskExtractor(
241
+ gtf=gtf, gene_mask_type=gene_mask_extractor.GeneMaskType.BODY
242
+ )
243
+ )
244
+
245
+ settings = interval_scorers.GeneMaskScorer(
246
+ requested_output=dna_output.OutputType.RNA_SEQ,
247
+ aggregation_type=interval_scorers.IntervalAggregationType.SUM,
248
+ width=2001,
249
+ )
250
+
251
+ _, mask_metadata = interval_scorer.get_masks_and_metadata(
252
+ interval, track_metadata=track_metadata, settings=settings
253
+ )
254
+ finalized_score = interval_scorer.finalize_interval(
255
+ scores,
256
+ track_metadata=track_metadata,
257
+ mask_metadata=mask_metadata,
258
+ settings=settings,
259
+ )
260
+
261
+ self.assertIsInstance(finalized_score, anndata.AnnData)
262
+ np.testing.assert_array_almost_equal(finalized_score.X, expected_scores)
263
+
264
+
265
+ if __name__ == '__main__':
266
+ absltest.main()
flax_model/alphagenome/model/interval_scoring/interval_scoring.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Base class for interval scorers."""
16
+
17
+ import abc
18
+ from collections.abc import Mapping
19
+ from typing import Generic, TypeVar
20
+
21
+ from flax_model.alphagenome._sdk.data import genome
22
+ from flax_model.alphagenome._sdk.models import dna_output
23
+ import anndata
24
+ import jax
25
+ from jaxtyping import Array, Float32 # pylint: disable=g-multiple-import, g-importing-member
26
+ import numpy as np
27
+
28
+ IntervalMaskT = TypeVar('IntervalMaskT')
29
+ IntervalMetadataT = TypeVar('IntervalMetadataT')
30
+ IntervalSettingsT = TypeVar('IntervalSettingsT')
31
+
32
+ ScoreIntervalOutput = Mapping[str, jax.Array | np.ndarray]
33
+ ScoreIntervalResult = Mapping[str, np.ndarray]
34
+
35
+
36
+ class IntervalScorer(
37
+ Generic[IntervalMaskT, IntervalMetadataT, IntervalSettingsT],
38
+ metaclass=abc.ABCMeta,
39
+ ):
40
+ """Abstract class for interval scorers."""
41
+
42
+ @abc.abstractmethod
43
+ def get_masks_and_metadata(
44
+ self,
45
+ interval: genome.Interval,
46
+ *,
47
+ settings: IntervalSettingsT,
48
+ track_metadata: dna_output.OutputMetadata,
49
+ ) -> tuple[IntervalMaskT, IntervalMetadataT]:
50
+ """Returns masks and metadata for the given interval and metadata.
51
+
52
+ The generated masks and metadata will be passed to `score_interval` and
53
+ `finalize_interval` respectively.
54
+
55
+ Args:
56
+ interval: The interval to score.
57
+ settings: The interval scorer settings.
58
+ track_metadata: The model's track metadata.
59
+
60
+ Returns:
61
+ A tuple of (masks, metadata), where:
62
+ masks: The masks required to score the interval, such as gene or TSS or
63
+ strand masks. These will be passed into the jitted `score_interval`
64
+ function.
65
+ metadata: The metadata required to finalize the interval. These will
66
+ be passed into the `finalize_interval` function.
67
+
68
+ The formats/shapes of masks and metadata will vary across interval scorers
69
+ depending on their individual needs.
70
+ """
71
+
72
+ @abc.abstractmethod
73
+ def score_interval(
74
+ self,
75
+ predictions: Mapping[dna_output.OutputType, Float32[Array, 'S T']],
76
+ *,
77
+ masks: IntervalMaskT,
78
+ settings: IntervalSettingsT,
79
+ interval: genome.Interval | None = None,
80
+ ) -> ScoreIntervalOutput:
81
+ """Generates a score per track for the provided predictions.
82
+
83
+ Args:
84
+ predictions: Model predictions for the interval.
85
+ masks: The masks for scoring the interval.
86
+ settings: The interval scorer settings.
87
+ interval: The interval to score.
88
+
89
+ Returns:
90
+ Dictionary of scores to be passed to `finalize_interval`.
91
+ """
92
+
93
+ @abc.abstractmethod
94
+ def finalize_interval(
95
+ self,
96
+ scores: ScoreIntervalResult,
97
+ *,
98
+ track_metadata: dna_output.OutputMetadata,
99
+ mask_metadata: IntervalMetadataT,
100
+ settings: IntervalSettingsT,
101
+ ) -> anndata.AnnData:
102
+ """Returns finalized scores for the given scores and metadata.
103
+
104
+ Args:
105
+ scores: Dictionary of scores generated from `score_interval` function.
106
+ track_metadata: Metadata describing the tracks for each output_type.
107
+ mask_metadata: Metadata describing the masks.
108
+ settings: The interval scorer settings.
109
+
110
+ Returns:
111
+ An AnnData object containing the final interval outputs. The entries will
112
+ vary across scorers depending on their individual needs.
113
+ """
flax_model/alphagenome/model/layers.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Common layers."""
16
+
17
+ from flax_model.alphagenome._sdk import typing
18
+ import haiku as hk
19
+ import jax
20
+ import jax.numpy as jnp
21
+ from jaxtyping import Array, Float # pylint: disable=g-importing-member, g-multiple-import
22
+
23
+
24
+ def gelu(x: jax.Array) -> jax.Array:
25
+ """Gaussian Error Linear Unit activation function."""
26
+ coef = jax.lax.convert_element_type(1.702, x.dtype)
27
+ return jax.nn.sigmoid(coef * x) * x
28
+
29
+
30
+ @typing.jaxtyped
31
+ def pool(
32
+ x: Float[Array, '... S D'], by: int = 2, reduce: str = 'max'
33
+ ) -> Float[Array, '... S/{by} D']:
34
+ """Applies pooling to the sequence dimension of the input.
35
+
36
+ Args:
37
+ x: The input sequence, where the second to last dimension is the sequence
38
+ dimension.
39
+ by: The pooling window size.
40
+ reduce: The pooling reduction method.
41
+
42
+ Returns:
43
+ The pooled sequence.
44
+ Raises:
45
+ NotImplementedError: If the reduce method is not supported.
46
+ """
47
+ if reduce == 'max':
48
+ return hk.MaxPool(window_shape=(by, 1), strides=(by, 1), padding='SAME')(x)
49
+ elif reduce in ['avg', 'mean']:
50
+ return hk.AvgPool(window_shape=(by, 1), strides=(by, 1), padding='SAME')(x)
51
+ else:
52
+ raise NotImplementedError(f'Reduce method={reduce} unknown.')
53
+
54
+
55
+ class RMSBatchNorm(hk.Module):
56
+ r"""Root Mean Square Batch Normalization.
57
+
58
+ Normalization is applied to the last dimension of the input as
59
+ `x -> x * scale / sqrt(var + epsilon) + offset`.
60
+ The scale and offset are learned parameters. The variance is tracked
61
+ as an exponential moving average.
62
+
63
+ Variance is computed across the batch and sequence dimension.
64
+
65
+ Note: only support inference mode (i.e. no training).
66
+ """
67
+
68
+ def __call__(self, x: Float[Array, '... D']) -> Float[Array, '... D']:
69
+ param_shape = (1,) * (x.ndim - 1) + (x.shape[-1],)
70
+ variance = hk.get_state(
71
+ 'var_ema', param_shape, dtype=jnp.float32, init=jnp.ones
72
+ )
73
+ scale = hk.get_parameter(
74
+ 'scale', param_shape, dtype=x.dtype, init=jnp.ones
75
+ ).astype(x.dtype)
76
+ offset = hk.get_parameter(
77
+ 'offset', param_shape, dtype=x.dtype, init=jnp.zeros
78
+ )
79
+ inv = scale * jax.lax.rsqrt(variance + 1e-5).astype(x.dtype)
80
+ return x * inv + offset
81
+
82
+
83
+ class LayerNorm(hk.Module):
84
+ """Layer Normalization."""
85
+
86
+ def __init__(
87
+ self, rms_norm: bool = False, axis: int = -1, name: str | None = None
88
+ ) -> None:
89
+ """Initializes the LayerNorm module.
90
+
91
+ Args:
92
+ rms_norm: If False, the input is centered before computing the
93
+ mean-squared for normalization. If True, the mean-squared is computed
94
+ directly on the uncentered input.
95
+ axis: The axis to apply the normalization to.
96
+ name: The name of the module.
97
+ """
98
+ super().__init__(name=name)
99
+ self._rms_norm = rms_norm
100
+ self._axis = axis
101
+
102
+ def __call__(self, x: Float[Array, '... D']) -> Float[Array, '... D']:
103
+ dtype = x.dtype
104
+ scale = hk.get_parameter(
105
+ 'scale', (x.shape[-1],), dtype, init=jnp.ones
106
+ ).astype(dtype)
107
+ offset = hk.get_parameter(
108
+ 'offset', (x.shape[-1],), dtype, init=jnp.zeros
109
+ ).astype(dtype)
110
+ scale = jax.lax.broadcast_to_rank(scale, x.ndim)
111
+ offset = jax.lax.broadcast_to_rank(offset, x.ndim)
112
+
113
+ if not self._rms_norm:
114
+ mean = jnp.mean(
115
+ x, axis=self._axis, dtype=jnp.float32, keepdims=True
116
+ ).astype(dtype)
117
+ x = x - mean
118
+
119
+ variance = jnp.mean(
120
+ jnp.square(x), axis=self._axis, dtype=jnp.float32, keepdims=True
121
+ )
122
+ inv = scale * jax.lax.rsqrt(variance + 1e-5).astype(dtype)
123
+ return inv * x + offset
flax_model/alphagenome/model/layers_test.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from absl.testing import absltest
16
+ from absl.testing import parameterized
17
+ from flax_model.alphagenome.model import layers
18
+ import chex
19
+ import haiku as hk
20
+ import jax.numpy as jnp
21
+
22
+
23
+ def _get_pool_layer(by: int):
24
+ """Helper function to create the pool layer."""
25
+
26
+ def pool_fn(x):
27
+ return layers.pool(x, by=by)
28
+
29
+ pool_mod = hk.transform(pool_fn)
30
+ return pool_mod
31
+
32
+
33
+ class LayersTest(parameterized.TestCase):
34
+
35
+ def setUp(self):
36
+ super().setUp()
37
+ self._batch_size = 4
38
+ self._sequence_length = 16
39
+ self._num_channels = 8
40
+ self._by = 2
41
+
42
+ def test_pool_shape(self):
43
+ """Tests that the pool layer returns the expected shape."""
44
+ x = jnp.ones((self._batch_size, self._sequence_length, self._num_channels))
45
+ pool_mod = _get_pool_layer(by=self._by)
46
+ params = pool_mod.init(None, x)
47
+ out = pool_mod.apply(params, None, x)
48
+ chex.assert_shape(
49
+ out,
50
+ (
51
+ self._batch_size,
52
+ self._sequence_length // self._by,
53
+ self._num_channels,
54
+ ),
55
+ )
56
+
57
+ def test_pool_type_error(self):
58
+ """Tests that the pool layer raises a type error with invalid input."""
59
+ with self.subTest('wrong_dtype'):
60
+ x = jnp.ones(
61
+ (self._batch_size, self._sequence_length, self._num_channels),
62
+ dtype=jnp.int32, # Provide wrong type.
63
+ )
64
+ with self.assertRaises(TypeError):
65
+ pool_mod = _get_pool_layer(by=self._by)
66
+ params = pool_mod.init(None, x)
67
+ pool_mod.apply(params, None, x)
68
+
69
+
70
+ if __name__ == '__main__':
71
+ absltest.main()
flax_model/alphagenome/model/losses.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Losses for AlphaGenome."""
16
+
17
+ from flax_model.alphagenome._sdk import typing
18
+ import chex
19
+ from einshape import jax_einshape as einshape # pylint: disable=g-importing-member
20
+ import jax
21
+ import jax.numpy as jnp
22
+ from jaxtyping import Array, Bool, Float, PyTree # pylint: disable=g-importing-member, g-multiple-import
23
+
24
+
25
+ @typing.jaxtyped
26
+ def _safe_masked_mean(
27
+ x: Float[Array, '*dims'],
28
+ mask: Bool[Array, '#*dims'] | None = None,
29
+ ) -> Float[Array, '']:
30
+ """Safe jnp.mean that handles completely masked arrays."""
31
+ if mask is None:
32
+ masked = x
33
+ mask = jnp.ones_like(x)
34
+ else:
35
+ # We need to broadcast mask to compute correct mean.
36
+ mask = jnp.broadcast_to(mask, x.shape)
37
+ masked = x * mask
38
+
39
+ return jnp.sum(jnp.asarray(masked), dtype=jnp.float32) / jnp.maximum(
40
+ 1.0, jnp.sum(mask, dtype=jnp.float32)
41
+ )
42
+
43
+
44
+ @typing.jaxtyped
45
+ def poisson_loss(
46
+ *,
47
+ y_true: Float[Array, '*dims'],
48
+ y_pred: Float[Array, '*dims'],
49
+ mask: Bool[Array, '#*dims'],
50
+ ) -> Float[Array, '']:
51
+ """Poisson loss."""
52
+ y_true = jnp.abs(y_true).astype(jnp.float32)
53
+ y_pred = y_pred.astype(jnp.float32)
54
+ y_pred_logits = jnp.log(y_pred + 1e-7)
55
+ # Substract the minimum value such that loss is zero at optimal prediction.
56
+ min_value = y_true - y_true * jnp.log(y_true + 1e-7)
57
+ loss = (y_pred - y_true * y_pred_logits) - min_value
58
+ return _safe_masked_mean(loss, mask)
59
+
60
+
61
+ @typing.jaxtyped
62
+ def multinomial_loss(
63
+ *,
64
+ y_true: Float[Array, '... S C'],
65
+ y_pred: Float[Array, '... S C'],
66
+ mask: Bool[Array, '... 1 C'],
67
+ multinomial_resolution: int,
68
+ positional_weight: float,
69
+ ) -> PyTree[Float[Array, '']]:
70
+ """Returns sum of multinomial losses and Poison loss on total count.
71
+
72
+ Args:
73
+ y_true: Target values.
74
+ y_pred: Model predictions.
75
+ mask: Array of bools.
76
+ multinomial_resolution: We split the input into sub-sequences and compute a
77
+ separate multinomial loss over each sub-sequence.
78
+ positional_weight: Weight of the positional loss.
79
+ """
80
+ chex.assert_equal_shape([y_true, y_pred])
81
+ if y_pred.shape[-2] % multinomial_resolution != 0:
82
+ raise ValueError(
83
+ f'{y_pred.shape[-2]=} must be divisible by {multinomial_resolution=}.'
84
+ )
85
+
86
+ num_segments = y_pred.shape[-2] // multinomial_resolution
87
+
88
+ # Remove the masked out bins from the totals sum.
89
+ y_true = jnp.maximum(y_true, 0) * mask
90
+ y_pred = y_pred * mask
91
+
92
+ # Split sequence into n sub-sequences of size multinomial_resolution.
93
+ y_true = einshape('...(ns)c->...nsc', y_true, n=num_segments)
94
+ y_pred = einshape('...(ns)c->...nsc', y_pred, n=num_segments)
95
+
96
+ total_pred = jnp.sum(y_pred, axis=-2, keepdims=True, dtype=jnp.float32)
97
+ total_true = jnp.sum(y_true, axis=-2, keepdims=True, dtype=jnp.float32)
98
+ mask = mask[..., None, :] # broadcast over segments.
99
+
100
+ loss_total_count = poisson_loss(
101
+ y_true=total_true,
102
+ y_pred=total_pred,
103
+ mask=mask,
104
+ )
105
+ # Magnitude of poisson loss is linear with the number of bins involved in the
106
+ # `total_count` prediction/target window. Normalization keeps overall loss
107
+ # magnitude invariant to input `multinomial_resolution`.
108
+ loss_total_count /= multinomial_resolution
109
+
110
+ prob_predictions = y_pred.astype(jnp.float32) / (total_pred + 1e-7)
111
+ loss_positional = -y_true * jnp.log(prob_predictions + 1e-7)
112
+ loss_positional = _safe_masked_mean(loss_positional, mask=mask)
113
+
114
+ return {
115
+ 'loss': loss_total_count + positional_weight * loss_positional,
116
+ 'loss_total': loss_total_count,
117
+ 'loss_positional': loss_positional,
118
+ 'max_sum_preds': jnp.max(total_pred),
119
+ 'max_preds': jnp.max(y_pred),
120
+ 'max_targets': jnp.max(y_true).astype(jnp.float32),
121
+ }
122
+
123
+
124
+ def mse(
125
+ y_pred: Float[Array, '*dims'],
126
+ y_true: Float[Array, '*dims'],
127
+ mask: Bool[Array, '#*dims'],
128
+ ) -> Float[Array, '']:
129
+ """Mean squared error."""
130
+ return _safe_masked_mean(jnp.square(y_pred - y_true), mask)
131
+
132
+
133
+ @typing.jaxtyped
134
+ def cross_entropy_loss_from_logits(
135
+ *,
136
+ y_pred_logits: Float[Array, '*dims'],
137
+ y_true: Float[Array, '*dims'],
138
+ mask: Bool[Array, '#*dims'],
139
+ axis: int,
140
+ ) -> Float[Array, '']:
141
+ """Cross-entropy loss from logits."""
142
+ log_softmax_preds = jax.nn.log_softmax(
143
+ y_pred_logits.astype(jnp.float32), axis=axis
144
+ )
145
+ loss = -jnp.sum(y_true.astype(jnp.float32) * log_softmax_preds, axis=axis)
146
+ mask = jnp.any(mask, axis=axis)
147
+ return _safe_masked_mean(loss, mask)
148
+
149
+
150
+ @typing.jaxtyped
151
+ def binary_crossentropy_from_logits(
152
+ *,
153
+ y_pred: Float[Array, '*dims'],
154
+ y_true: Float[Array, '*dims'],
155
+ mask: Bool[Array, '#*dims'],
156
+ ) -> Float[Array, '']:
157
+ """Binary cross-entropy loss from sigmoid logits."""
158
+ loss = (
159
+ jnp.maximum(y_pred, 0)
160
+ - y_pred * y_true
161
+ + jnp.log1p(jnp.exp(-jnp.abs(y_pred)))
162
+ )
163
+ return _safe_masked_mean(loss, mask)
164
+
165
+
166
+ @typing.jaxtyped
167
+ def cross_entropy_loss(
168
+ *,
169
+ y_true: Float[Array, '*dims'],
170
+ y_pred: Float[Array, '*dims'],
171
+ mask: Bool[Array, '#*dims'],
172
+ axis: int,
173
+ eps: float = 1e-7,
174
+ ) -> Float[Array, '']:
175
+ """Cross entropy loss on counts."""
176
+ mask = jnp.broadcast_to(mask, y_true.shape)
177
+ chex.assert_equal_shape([y_true, y_pred, mask])
178
+ y_true = jnp.where(mask, y_true.astype(jnp.float32), 0)
179
+ p_true = y_true / jnp.maximum(y_true.sum(axis=axis, keepdims=True), eps)
180
+
181
+ log_normalizer = jnp.log((jnp.where(mask, y_pred, 0) + eps).sum(axis=axis))
182
+ log_likelihood = (p_true * jnp.log(y_pred + eps)).sum(axis=axis)
183
+ log_loss = log_normalizer - log_likelihood
184
+ return _safe_masked_mean(log_loss, mask.any(axis=axis))
flax_model/alphagenome/model/losses_test.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from absl.testing import absltest
16
+ from absl.testing import parameterized
17
+ from flax_model.alphagenome.model import losses
18
+ import jax.numpy as jnp
19
+ import numpy as np
20
+
21
+
22
+ class LossesTest(parameterized.TestCase):
23
+
24
+ def test_multinomial_loss_masking(self):
25
+ """Tests that masking correctly zeros out predictions and targets."""
26
+ y_true = jnp.array([[[10.0, 1.0, 3.0], [5.0, 2.0, 20.0]]])
27
+ y_pred = jnp.array([[[0.5, 2.5, 1.0], [2.5, 0.5, 1.0]]])
28
+ loss_full = losses.multinomial_loss(
29
+ y_true=y_true,
30
+ y_pred=y_pred,
31
+ mask=jnp.array([[[True, True, True]]]),
32
+ multinomial_resolution=1,
33
+ positional_weight=1.0,
34
+ )['loss']
35
+ loss_masked = losses.multinomial_loss(
36
+ y_true=y_true,
37
+ y_pred=y_pred,
38
+ mask=jnp.array([[[True, True, False]]]),
39
+ multinomial_resolution=1,
40
+ positional_weight=1.0,
41
+ )['loss']
42
+ y_true_zero = jnp.array([[[10.0, 1.0], [5.0, 2.0]]])
43
+ y_pred_zero = jnp.array([[[0.5, 2.5], [2.5, 0.5]]])
44
+ loss_truncated = losses.multinomial_loss(
45
+ y_true=y_true_zero,
46
+ y_pred=y_pred_zero,
47
+ mask=jnp.array([[[True, True]]]),
48
+ multinomial_resolution=1,
49
+ positional_weight=1.0,
50
+ )['loss']
51
+ np.testing.assert_almost_equal(loss_masked, loss_truncated, decimal=5)
52
+ np.testing.assert_array_less(loss_masked, loss_full)
53
+
54
+ def test_multinomial_loss_resolution_aggregation(self):
55
+ """Tests the resolution aggregation logic."""
56
+ # Seq length 4, all 1s.
57
+ y_true = jnp.ones((1, 4, 1))
58
+ y_pred = jnp.ones((1, 4, 1))
59
+ mask = jnp.ones((1, 1, 1), dtype=bool)
60
+ out_res1 = losses.multinomial_loss(
61
+ y_true=y_true,
62
+ y_pred=y_pred,
63
+ mask=mask,
64
+ multinomial_resolution=1,
65
+ positional_weight=1.0,
66
+ )
67
+ out_res4 = losses.multinomial_loss(
68
+ y_true=y_true,
69
+ y_pred=y_pred,
70
+ mask=mask,
71
+ multinomial_resolution=4,
72
+ positional_weight=1.0,
73
+ )
74
+ self.assertTrue(np.all(np.isfinite(out_res1['loss'])))
75
+ self.assertTrue(np.all(np.isfinite(out_res4['loss'])))
76
+ np.testing.assert_almost_equal(out_res1['max_sum_preds'], 1.0)
77
+ np.testing.assert_almost_equal(out_res4['max_sum_preds'], 4.0)
78
+
79
+
80
+ if __name__ == '__main__':
81
+ absltest.main()
flax_model/alphagenome/model/metadata/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome Model Metadata."""
flax_model/alphagenome/model/metadata/metadata.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome output metadata."""
16
+
17
+ from importlib import resources
18
+ from collections.abc import Collection, Mapping
19
+ import dataclasses
20
+ import functools
21
+ import pathlib
22
+
23
+ from flax_model.alphagenome._sdk import typing
24
+ from flax_model.alphagenome._sdk.data import ontology
25
+ from flax_model.alphagenome._sdk.data import track_data
26
+ from flax_model.alphagenome._sdk.models import dna_client
27
+ from flax_model.alphagenome._sdk.models import dna_model
28
+ from flax_model.alphagenome._sdk.models import dna_output
29
+ from flax_model.alphagenome._sdk.protos import dna_model_service_pb2
30
+ from google.protobuf import text_format
31
+ from jaxtyping import Bool, Int32 # pylint: disable=g-importing-member, g-multiple-import
32
+ import numpy as np
33
+
34
+ _PATH_METADATA = 'model/metadata/'
35
+ _PADDING_TRACK_NAME = 'padding'
36
+
37
+
38
+ def _create_output_strand_reindexing(
39
+ metadata: track_data.TrackMetadata,
40
+ num_tracks: int,
41
+ ) -> Int32[np.ndarray, '_']:
42
+ """Creates the strand reindexing for a given output type's track metadata."""
43
+ strands = metadata['strand'].values
44
+ reindex_array = np.arange(num_tracks, dtype=np.int32)
45
+ positive_indices = np.flatnonzero(strands == '+')
46
+ negative_indices = np.flatnonzero(strands == '-')
47
+ reindex_array[positive_indices] = negative_indices
48
+ reindex_array[negative_indices] = positive_indices
49
+ return reindex_array
50
+
51
+
52
+ @typing.jaxtyped
53
+ @dataclasses.dataclass(frozen=True, kw_only=True)
54
+ class AlphaGenomeOutputMetadata(dna_output.OutputMetadata):
55
+ """AlphaGenome output metadata."""
56
+
57
+ def resolution(self, output: dna_output.OutputType) -> int:
58
+ """Returns the resolution of the given output type."""
59
+ match output:
60
+ case dna_output.OutputType.ATAC:
61
+ return 1
62
+ case dna_output.OutputType.CAGE:
63
+ return 1
64
+ case dna_output.OutputType.DNASE:
65
+ return 1
66
+ case dna_output.OutputType.RNA_SEQ:
67
+ return 1
68
+ case dna_output.OutputType.CHIP_HISTONE:
69
+ return 128
70
+ case dna_output.OutputType.CHIP_TF:
71
+ return 128
72
+ case dna_output.OutputType.SPLICE_SITES:
73
+ return 1
74
+ case dna_output.OutputType.SPLICE_SITE_USAGE:
75
+ return 1
76
+ case dna_output.OutputType.SPLICE_JUNCTIONS:
77
+ return 1
78
+ case dna_output.OutputType.CONTACT_MAPS:
79
+ return 2048
80
+ case dna_output.OutputType.PROCAP:
81
+ return 1
82
+ case _:
83
+ raise ValueError(f'Unknown {output=}')
84
+
85
+ @functools.cached_property
86
+ def padding(self) -> Mapping[dna_output.OutputType, Bool[np.ndarray, '_']]:
87
+ """Returns mapping of output type to padding mask."""
88
+ padding = {}
89
+ for output_type in dna_output.OutputType:
90
+ if (metadata := self.get(output_type)) is not None:
91
+ padding[output_type] = (
92
+ metadata['name'].str.lower() == _PADDING_TRACK_NAME
93
+ ).values
94
+ return padding
95
+
96
+ @functools.cached_property
97
+ def strand_reindexing(
98
+ self,
99
+ ) -> Mapping[dna_output.OutputType, Int32[np.ndarray, '_']]:
100
+ """Return mapping of output type to negative strand reindexing."""
101
+ result = {}
102
+ for output_type in dna_output.OutputType:
103
+ if (metadata := self.get(output_type)) is not None:
104
+ num_tracks = len(metadata)
105
+ if output_type == dna_output.OutputType.SPLICE_JUNCTIONS:
106
+ # Splice junction metadata is strand agnostic, but predictions are
107
+ # structured as all positive followed by all negative strands.
108
+ result[output_type] = np.concatenate((
109
+ np.arange(num_tracks, num_tracks * 2),
110
+ np.arange(num_tracks),
111
+ ))
112
+ else:
113
+ result[output_type] = _create_output_strand_reindexing(
114
+ metadata, num_tracks
115
+ )
116
+ return result
117
+
118
+
119
+ @typing.jaxtyped
120
+ def create_track_masks(
121
+ metadata: AlphaGenomeOutputMetadata,
122
+ *,
123
+ requested_outputs: Collection[dna_output.OutputType],
124
+ requested_ontologies: Collection[ontology.OntologyTerm] | None,
125
+ ) -> Mapping[dna_output.OutputType, Bool[np.ndarray, '_']]:
126
+ """Creates track masks for the requested output types and ontologies."""
127
+ track_masks = {}
128
+ for output_type in requested_outputs:
129
+ if (output_metadata := metadata.get(output_type)) is None:
130
+ continue
131
+
132
+ if (
133
+ requested_ontologies is not None
134
+ # Splice sites are tissue agnostic.
135
+ and output_type != dna_output.OutputType.SPLICE_SITES
136
+ ):
137
+ ontology_curies = {o.ontology_curie for o in requested_ontologies}
138
+ mask = np.asarray(
139
+ [o in ontology_curies for o in output_metadata['ontology_curie']]
140
+ )
141
+ else:
142
+ mask = ~np.array(metadata.padding[output_type])
143
+
144
+ track_masks[output_type] = mask
145
+
146
+ return track_masks
147
+
148
+
149
+ def load(organism: dna_model.Organism) -> AlphaGenomeOutputMetadata:
150
+ """Loads the metadata for a given organism."""
151
+ file_name = f'OutputMetadataResponse_ORGANISM_{organism.name}.textproto'
152
+ path = pathlib.Path(_PATH_METADATA, file_name)
153
+ content = resources.files('flax_model.alphagenome').joinpath(path).read_text()
154
+ metadata_response = text_format.Parse(
155
+ content, dna_model_service_pb2.MetadataResponse()
156
+ )
157
+ return AlphaGenomeOutputMetadata(
158
+ **vars(dna_client.construct_output_metadata(iter((metadata_response,))))
159
+ )
flax_model/alphagenome/model/model.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 Google LLC.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AlphaGenome model."""
16
+
17
+ from collections.abc import Mapping
18
+
19
+ from flax_model.alphagenome._sdk import typing
20
+ from flax_model.alphagenome._sdk.models import dna_model
21
+ from flax_model.alphagenome.model import attention
22
+ from flax_model.alphagenome.model import convolutions
23
+ from flax_model.alphagenome.model import embeddings as embeddings_module
24
+ from flax_model.alphagenome.model import heads as heads_module
25
+ from flax_model.alphagenome.model import layers
26
+ from flax_model.alphagenome.model import schemas
27
+ from flax_model.alphagenome.model import splicing
28
+ from flax_model.alphagenome.model.metadata import metadata as metadata_lib
29
+ import haiku as hk
30
+ import jax
31
+ from jaxtyping import Array, Float, Int, PyTree, Shaped # pylint: disable=g-importing-member, g-multiple-import
32
+
33
+
34
+ DEFAULT_NUM_SPLICE_SITES = 512
35
+ DEFAULT_SPLICE_SITE_THRESHOLD = 0.1
36
+
37
+
38
+ class SequenceEncoder(hk.Module):
39
+ """Encodes a sequence of DNA into embeddings."""
40
+
41
+ @typing.jaxtyped
42
+ def __call__(
43
+ self, dna_sequence: Float[Array, 'B S 4']
44
+ ) -> tuple[Float[Array, 'B S//128 D'], dict[str, Array]]:
45
+ intermediates = {}
46
+ x = convolutions.DnaEmbedder()(dna_sequence)
47
+ intermediates['bin_size_1'] = x
48
+ x = layers.pool(x)
49
+ for block_idx, bin_size in enumerate([2, 4, 8, 16, 32, 64]):
50
+ x = convolutions.DownResBlock(f'downres_block_{block_idx}')(x)
51
+ intermediates[f'bin_size_{bin_size}'] = x
52
+ x = layers.pool(x)
53
+ return x, intermediates
54
+
55
+
56
+ class SequenceDecoder(hk.Module):
57
+ """Decodes a sequence of embeddings."""
58
+
59
+ @typing.jaxtyped
60
+ def __call__(
61
+ self, x: Float[Array, 'B S D'], intermediates: dict[str, Array]
62
+ ) -> Float[Array, 'B S_final D_final']:
63
+ for bin_size in [64, 32, 16, 8, 4, 2, 1]:
64
+ x = convolutions.UpResBlock()(x, intermediates[f'bin_size_{bin_size}'])
65
+ return x
66
+
67
+
68
+ class TransformerTower(hk.Module):
69
+ """Transformer tower with interleaved pairwise updates."""
70
+
71
+ @typing.jaxtyped
72
+ def __call__(
73
+ self, x: Float[Array, 'B S C']
74
+ ) -> tuple[Float[Array, 'B S C'], Float[Array, 'B S//16 S//16 F'] | None]:
75
+ pair_x = None
76
+ for i in range(9):
77
+ if i % 2 == 0:
78
+ pair_x = attention.PairUpdateBlock()(x, pair_x)
79
+ mha_bias = attention.AttentionBiasBlock()(pair_x)
80
+ x += attention.MHABlock()(x, mha_bias)
81
+ x += attention.MLPBlock()(x)
82
+ return x, pair_x
83
+
84
+
85
+ class AlphaGenome(hk.Module):
86
+ """Main AlphaGenome model.
87
+
88
+ The model architecture consists of a sequence encoder, a transformer tower,
89
+ and a sequence decoder. The output of the decoder is used to generate
90
+ embeddings at 1bp resolution, while the output of the transformer tower
91
+ is used to generate embeddings at 128bp resolution and pair embeddings.
92
+ These embeddings are then passed to various heads to make predictions.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ output_metadata: Mapping[
98
+ dna_model.Organism, metadata_lib.AlphaGenomeOutputMetadata
99
+ ],
100
+ *,
101
+ num_splice_sites: int = DEFAULT_NUM_SPLICE_SITES,
102
+ splice_site_threshold: float = DEFAULT_SPLICE_SITE_THRESHOLD,
103
+ freeze_trunk_embeddings: bool = False,
104
+ num_organisms: int = 2,
105
+ name: str | None = None,
106
+ ):
107
+ """Initializes the AlphaGenome model.
108
+
109
+ Args:
110
+ output_metadata: Metadata for the output tracks for each organism.
111
+ num_splice_sites: The maximum number of splice sites that are extracted
112
+ from the splice site classification predictions.
113
+ splice_site_threshold: The threshold to use for splice site prediction.
114
+ freeze_trunk_embeddings: Whether to stop the gradient to the embeddings.
115
+ This is useful for training only the heads in fine-tuning.
116
+ num_organisms: The number of organisms. This is used to initialize the
117
+ organism embedding layer. Default is 2, for human and mouse. Leave at 2
118
+ to load pre-trained weights.
119
+ name: The name of the module.
120
+ """
121
+
122
+ super().__init__(name=name or 'alphagenome')
123
+ self._output_metadata = output_metadata
124
+ self._num_splice_sites = num_splice_sites
125
+ self._splice_site_threshold = splice_site_threshold
126
+ self._freeze_trunk_embeddings = freeze_trunk_embeddings
127
+ self._num_organisms = num_organisms
128
+ self._heads: dict[heads_module.HeadName, heads_module.Head] = {}
129
+ for head in heads_module.HeadName:
130
+ output_type = heads_module.get_head_config(head).output_type
131
+ organisms_with_metadata = [
132
+ organism
133
+ for organism, metadata in output_metadata.items()
134
+ if metadata.get(output_type) is not None
135
+ ]
136
+ if not organisms_with_metadata:
137
+ # None of the organisms have metadata for this output type. Skip.
138
+ continue
139
+ missing_organisms = set(self._output_metadata.keys()) - set(
140
+ organisms_with_metadata
141
+ )
142
+ if missing_organisms:
143
+ raise ValueError(
144
+ f'No metadata found for output type "{output_type.name}" for the'
145
+ f' following organisms: {missing_organisms}. We expect the same set'
146
+ ' of output types for all organisms. Use padding to account for'
147
+ ' missing tracks.'
148
+ )
149
+ self._heads[head] = heads_module.create_head(
150
+ heads_module.get_head_config(head),
151
+ self._output_metadata,
152
+ num_organisms=num_organisms,
153
+ )
154
+
155
+ @hk.name_like('__call__')
156
+ def predict_junctions(
157
+ self,
158
+ trunk_embeddings: Float[Array, 'B S D'],
159
+ splice_site_positions: Int[Array, 'B 4 K'],
160
+ organism_index: Int[Array, 'B'],
161
+ ) -> PyTree[Float[Array, 'B ...'] | None]:
162
+ """Predicts splice site junctions from embeddings and splice site positions.
163
+
164
+ Args:
165
+ trunk_embeddings: The trunk embeddings to use for predictions.
166
+ splice_site_positions: The splice site positions. Format: [batch, 4,
167
+ num_splice_sites] with order: [donor_pos_idx, accept_pos_idx,
168
+ donor_neg_idx, accept_neg_idx]
169
+ organism_index: The organism index.
170
+
171
+ Returns:
172
+ The predictions for splice site junctions.
173
+ """
174
+ junction_head = self._heads.get(heads_module.HeadName.SPLICE_SITES_JUNCTION)
175
+ if junction_head is None:
176
+ raise ValueError('Junction head is not supported by this model.')
177
+ with hk.name_scope('head'):
178
+ return junction_head(
179
+ embeddings_module.Embeddings(embeddings_1bp=trunk_embeddings),
180
+ organism_index,
181
+ splice_site_positions=splice_site_positions,
182
+ )
183
+
184
+ @typing.jaxtyped
185
+ def __call__(
186
+ self,
187
+ dna_sequence: Float[Array, 'B S 4'],
188
+ organism_index: Int[Array, 'B'],
189
+ ) -> tuple[PyTree[Shaped[Array, 'B ...']], embeddings_module.Embeddings]:
190
+ """Encodes a sequence of DNA and makes predictions for various heads.
191
+
192
+ Args:
193
+ dna_sequence: The sequence of DNA to encode.
194
+ organism_index: The organism index.
195
+
196
+ Returns:
197
+ A tuple of (predictions, embeddings), where predictions is a dictionary
198
+ of predictions for various heads.
199
+ """
200
+ trunk, intermediates = SequenceEncoder()(dna_sequence)
201
+ if self._num_organisms >= 1:
202
+ organism_embedding_trunk = hk.Embed(self._num_organisms, trunk.shape[-1])(
203
+ organism_index
204
+ )
205
+ trunk += organism_embedding_trunk[:, None, :]
206
+ trunk, pair_activations = TransformerTower()(trunk)
207
+
208
+ x = SequenceDecoder()(trunk, intermediates)
209
+
210
+ embeddings_128bp = embeddings_module.OutputEmbedder(self._num_organisms)(
211
+ trunk, organism_index
212
+ )
213
+ embeddings_1bp = embeddings_module.OutputEmbedder(self._num_organisms)(
214
+ x, organism_index, embeddings_128bp
215
+ )
216
+ embeddings_pair = embeddings_module.OutputPair(self._num_organisms)(
217
+ pair_activations, organism_index
218
+ )
219
+
220
+ embeddings = embeddings_module.Embeddings(
221
+ embeddings_1bp=embeddings_1bp,
222
+ embeddings_128bp=embeddings_128bp,
223
+ embeddings_pair=embeddings_pair,
224
+ )
225
+ if self._freeze_trunk_embeddings:
226
+ embeddings = jax.lax.stop_gradient(embeddings)
227
+ predictions = {
228
+ 'embeddings_1bp': embeddings_1bp,
229
+ }
230
+ with hk.name_scope('head'):
231
+ for head_name, head_fn in self._heads.items():
232
+ if head_name == heads_module.HeadName.SPLICE_SITES_JUNCTION:
233
+ # This head is handled separately (see below).
234
+ continue
235
+ predictions[head_name.value] = head_fn(
236
+ embeddings,
237
+ organism_index,
238
+ )
239
+
240
+ # Handle the splice junction head separately. It requires splice site
241
+ # positions as input, which are derived from the splice site
242
+ # classification predictions.
243
+ if (
244
+ junction_head := heads_module.HeadName.SPLICE_SITES_JUNCTION
245
+ ) in self._heads:
246
+ if heads_module.HeadName.SPLICE_SITES_CLASSIFICATION not in self._heads:
247
+ raise ValueError(
248
+ 'SPLICE_SITES_CLASSIFICATION head is required for junctions'
249
+ ' predictions.'
250
+ )
251
+ splice_sites_probabilities = predictions[
252
+ heads_module.HeadName.SPLICE_SITES_CLASSIFICATION.value
253
+ ]['predictions']
254
+ splice_site_positions = splicing.generate_splice_site_positions(
255
+ splice_sites_probabilities,
256
+ alt=None,
257
+ splice_sites=None,
258
+ k=self._num_splice_sites,
259
+ pad_to_length=self._num_splice_sites,
260
+ threshold=self._splice_site_threshold,
261
+ )
262
+ predictions[junction_head.value] = self.predict_junctions(
263
+ embeddings.embeddings_1bp, splice_site_positions, organism_index
264
+ )
265
+ return predictions, embeddings
266
+
267
+ @typing.jaxtyped
268
+ def loss(
269
+ self, batch: schemas.DataBatch
270
+ ) -> tuple[
271
+ Float[Array, ''], PyTree[Float[Array, '']], PyTree[Shaped[Array, 'B ...']]
272
+ ]:
273
+ """Returns the loss for the model."""
274
+ predictions, _ = self(batch.dna_sequence, batch.get_organism_index())
275
+ total_loss, all_scalars = 0.0, {}
276
+ for head_name, head_fn in self._heads.items():
277
+ scalars = head_fn.loss(predictions[head_name.value], batch)
278
+ all_scalars.update(
279
+ {f'{head_name.value}_{k}': v for k, v in scalars.items()}
280
+ )
281
+ total_loss += scalars['loss']
282
+ return total_loss, all_scalars, predictions