├── .gitignore
├── .gitmodules
├── LICENSE.MD
├── README.md
├── evo2-backend
├── evo2
│ ├── .gitmodules
│ ├── AUTHORS
│ ├── LICENSE
│ ├── MANIFEST.in
│ ├── NOTICE
│ ├── README.md
│ ├── evo2.jpg
│ ├── evo2
│ │ ├── __init__.py
│ │ ├── configs
│ │ │ ├── evo2-1b-8k.yml
│ │ │ ├── evo2-40b-1m.yml
│ │ │ ├── evo2-40b-8k.yml
│ │ │ ├── evo2-7b-1m.yml
│ │ │ └── evo2-7b-8k.yml
│ │ ├── models.py
│ │ ├── scoring.py
│ │ ├── utils.py
│ │ └── version.py
│ ├── notebooks
│ │ ├── brca1
│ │ │ ├── 41586_2018_461_MOESM3_ESM.xlsx
│ │ │ ├── GRCh37.p13_chr17.fna.gz
│ │ │ └── brca1_zero_shot_vep.ipynb
│ │ └── generation
│ │ │ └── generation_notebook.ipynb
│ ├── requirements.txt
│ ├── setup.py
│ └── test
│ │ ├── test_evo2.py
│ │ └── test_evo2_generation.py
├── main.py
└── requirements.txt
├── evo2-frontend
├── .env.example
├── .gitignore
├── README.md
├── components.json
├── eslint.config.js
├── next.config.js
├── package-lock.json
├── package.json
├── postcss.config.js
├── prettier.config.js
├── public
│ └── favicon.ico
├── src
│ ├── app
│ │ ├── layout.tsx
│ │ └── page.tsx
│ ├── components
│ │ ├── gene-information.tsx
│ │ ├── gene-sequence.tsx
│ │ ├── gene-viewer.tsx
│ │ ├── known-variants.tsx
│ │ ├── ui
│ │ │ ├── button.tsx
│ │ │ ├── card.tsx
│ │ │ ├── input.tsx
│ │ │ ├── select.tsx
│ │ │ ├── table.tsx
│ │ │ └── tabs.tsx
│ │ ├── variant-analysis.tsx
│ │ └── variant-comparison-modal.tsx
│ ├── env.js
│ ├── lib
│ │ └── utils.ts
│ ├── styles
│ │ └── globals.css
│ └── utils
│ │ ├── coloring-utils.ts
│ │ └── genome-api.ts
└── tsconfig.json
├── evo2.excalidraw
└── thumbnail.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # macOS
2 | .DS_Store
3 | .AppleDouble
4 | .LSOverride
5 |
6 | # Log files
7 | *.log
8 | npm-debug.log*
9 | yarn-debug.log*
10 | yarn-error.log*
11 | pnpm-debug.log*
12 |
13 | # Temporary files
14 | *.tmp
15 | *.swp
16 | *.swo
17 | *.swn
18 |
19 | # Editor directories and files
20 | .vscode/*
21 | !.vscode/settings.json
22 | !.vscode/tasks.json
23 | !.vscode/launch.json
24 | !.vscode/extensions.json
25 | *.sublime-workspace
26 |
27 | # Frontend (evo2-frontend - Next.js)
28 | evo2-frontend/node_modules/
29 | evo2-frontend/.next/
30 | evo2-frontend/out/
31 | evo2-frontend/.env*.local
32 | evo2-frontend/*.tsbuildinfo
33 | evo2-frontend/next-env.d.ts
34 |
35 | # Backend (evo2-backend - Python/Modal)
36 | evo2-backend/__pycache__/
37 | evo2-backend/*.pyc
38 | evo2-backend/*.pyo
39 | evo2-backend/*.pyd
40 | evo2-backend/.venv/
41 | evo2-backend/venv/
42 | evo2-backend/env/
43 | evo2-backend/*.env
44 | evo2-backend/.env
45 | evo2-backend/.modal*
46 | evo2-backend/brca1_analysis_plot.png
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "evo2-backend/evo2"]
2 | path = evo2-backend/evo2
3 | url = https://github.com/ArcInstitute/evo2
4 |
--------------------------------------------------------------------------------
/LICENSE.MD:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) [2025] [Andreas Trolle]
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | [Link to video](https://youtu.be/3dCZxmd5bvs)
4 |
5 | [Discord and more](https://www.andreastrolle.com/)
6 |
7 | ## Overview
8 |
9 | Hi 🤙 In this project, you'll build a web app that can classify how likely specific mutations in DNA are to cause diseases (variant effect prediction). We will deploy and use the state-of-the-art Evo2 large language model, and use it to predict the pathogenicity of single nucleotide variants (SNVs). You'll deploy a Python backend on an H100 serverless GPU with Modal, exposing a FastAPI endpoint for analysis. After deploying the backend, you'll build a web app around it where users can select a genome assembly, browse its chromosomes or search for specific genes like BRCA1, and view the gene's reference genome sequence. The user can input a mutation in the gene and predict its pathogenicity with AI, but the user can also pick from a list of existing known variations, and compare the Evo2 prediction (pathogenic/benign) against existing ClinVar classifications. The web app is built with Next.js, React, TypeScript, Tailwind CSS, and Shadcn UI and is based off of the T3 Stack. You'll be able to build along with me from start to finish.
10 |
11 | Everything (including GPU's) is free, and no biological background is needed, since I'll walk you through all the theory needed.
12 |
13 | TL;DR / Simpler Version\
14 | DNA is like a long code made of A, T, G, and C. Small changes (mutations) in specific parts of this code, like in genes responsible for preventing cancer, can increase a person's risk of developing the disease. For instance, if an 'A' appears where a 'T' should be at a particular spot, that's a mutation. These changes can vary in how harmful they are, and we'll build a tool to analyze these different variations' harmfulness.
15 |
16 | Features:
17 |
18 | - 🧬 Evo2 model for variant effect prediction
19 | - 🩺 Predict pathogenicity of single nucleotide variants (pathogenic/benign)
20 | - ⚖️ Comparison view for existing ClinVar classification vs. Evo2 prediction
21 | - 💯 Prediction confidence estimation
22 | - 🌍 Genome assembly selector (e.g., hg38)
23 | - 🗺️ Select genes from chromosome browsing or searching (e.g., BRCA1)
24 | - 🌐 See full reference genome sequence (UCSC API)
25 | - 🧬 Explore gene and variants data (NCBI ClinVar/E-utilities)
26 | - 💻 Python backend deployed with Modal
27 | - 🚀 FastAPI endpoint for variant analysis requests
28 | - ⚡ GPU-accelerated (H100) variant scoring via Modal
29 | - 📱 Responsive Next.js web interface
30 | - 🎨 Modern UI with Tailwind CSS & Shadcn UI
31 |
32 | ## Evo2 Model
33 |
34 | Check out the paper behind the model.
35 |
36 | - [Paper](https://www.biorxiv.org/content/10.1101/2025.02.18.638918v1)
37 | - [GitHub Repository](https://github.com/ArcInstitute/evo2)
38 |
39 | ## Setup
40 |
41 | Follow these steps to install and set up the project.
42 |
43 | ### Clone the Repository
44 |
45 | ```bash
46 | git clone --recurse-submodules https://github.com/Andreaswt/variant-analysis-evo2.git
47 | ```
48 |
49 | ### Install Python
50 |
51 | Download and install Python if not already installed. Use the link below for guidance on installation:
52 | [Python Download](https://www.python.org/downloads/)
53 |
54 | Create a virtual environment for each folder, except elevenlabs-clone-frontend, with **Python 3.10**.
55 |
56 | ### Backend
57 |
58 | Navigate to backend folder:
59 |
60 | ```bash
61 | cd evo2-backend
62 | ```
63 |
64 | Install dependencies:
65 |
66 | ```bash
67 | pip install -r requirements.txt
68 | ```
69 |
70 | Modal setup:
71 |
72 | ```bash
73 | modal setup
74 | ```
75 |
76 | Run on Modal:
77 |
78 | ```bash
79 | modal run main.py
80 | ```
81 |
82 | Deploy backend:
83 |
84 | ```bash
85 | modal deploy main.py
86 | ```
87 |
88 | ### Frontend
89 |
90 | Install dependencies:
91 |
92 | ```bash
93 | cd evo2-frontend
94 | npm i
95 | ```
96 |
97 | Run:
98 |
99 | ```bash
100 | npm run dev
101 | ```
102 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "vortex"]
2 | path = vortex
3 | url = https://github.com/Zymrael/vortex.git
4 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/AUTHORS:
--------------------------------------------------------------------------------
1 | Garyk Brixi
2 | Matthew G. Durrant
3 | Jerome Ku
4 | Michael Poli
5 | Greg Brockman
6 | Daniel Chang
7 | Gabriel A. Gonzalez
8 | Samuel H. King
9 | David B. Li
10 | Aditi T. Merchant
11 | Mohsen Naghipourfar
12 | Eric Nguyen
13 | Chiara Ricci-Tam
14 | David W. Romero
15 | Gwanggyu Sun
16 | Ali Taghibakshi
17 | Anton Vorontsov
18 | Brandon Yang
19 | Myra Deng
20 | Liv Gorton
21 | Nam Nguyen
22 | Nicholas K. Wang
23 | Etowah Adams
24 | Stephen A. Baccus
25 | Steven Dillmann
26 | Stefano Ermon
27 | Daniel Guo
28 | Rajesh Ilango
29 | Ken Janik
30 | Amy X. Lu
31 | Reshma Mehta
32 | Mohammad R.K. Mofrad
33 | Madelena Y. Ng
34 | Jaspreet Pannu
35 | Christopher Ré
36 | Jonathan C. Schmok
37 | John St. John
38 | Jeremy Sullivan
39 | Kevin Zhu
40 | Greg Zynda
41 | Daniel Balsam
42 | Patrick Collison
43 | Anthony B. Costa
44 | Tina Hernandez-Boussard
45 | Eric Ho
46 | Ming-Yu Liu
47 | Thomas McGrath
48 | Kimberly Powell
49 | Dave P. Burke
50 | Hani Goodarzi
51 | Patrick D. Hsu
52 | Brian L. Hie
--------------------------------------------------------------------------------
/evo2-backend/evo2/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 | include NOTICE
3 | include README.md
4 | include requirements.txt
5 | include pyproject.toml
6 | recursive-include evo2/configs *.yml
7 | recursive-include vortex/vortex *
8 | recursive-exclude vortex/vortex *.pyc
9 | recursive-exclude vortex/vortex/__pycache__ *
--------------------------------------------------------------------------------
/evo2-backend/evo2/NOTICE:
--------------------------------------------------------------------------------
1 | Copyright 2024 Arc Institute. All rights reserved
2 | Copyright 2024 Michael Poli. All rights reserved
3 | Copyright 2024 Stanford University. All rights reserved
4 |
5 | This project incorporates and modifies the components below:
6 |
7 |
8 | - Added training and inference support for Hyena2
9 | - Scaled model training (up to 40B) and context windows (up to 1M)
10 | - Biological/genomic inference and generation evals/tasks
11 |
12 | See AUTHORS file for list of contributing authors.
13 |
14 | See LICENSE file for software license. This software is licensed under the Apache License, Version 2.0.
15 | ======================================================================
16 |
17 | StripedHyena
18 | Copyright 2023-2024 Together
19 | Project URL: https://github.com/togethercomputer/stripedhyena
20 |
21 | This project includes software developed at Together for deep signal processing, hybrid architecture composed of rotary (grouped) attention and gated convolutions arranged in Hyena blocks, with improved scaling over decoder-only Transformers.
22 |
23 | ======================================================================
24 |
25 | GPT-NeoX
26 | Copyright 2021-2024 EleutherAI and contributors
27 | Project URL: https://github.com/EleutherAI/gpt-neox
28 |
29 | This project includes software developed at EleutherAI for large-scale language model training and inference.
30 |
31 | ======================================================================
32 |
33 | Megatron-LM
34 | Copyright 2019-2024 NVIDIA Corporation
35 | Project URL: https://github.com/NVIDIA/Megatron-LM
36 |
37 | This project includes software developed at NVIDIA Corporation for large-scale transformer model training.
38 |
39 | ======================================================================
40 |
41 | DeepSpeed
42 | Copyright 2020-2024 Microsoft Corporation
43 | Project URL: https://github.com/microsoft/DeepSpeed
44 |
45 | This project includes software developed at Microsoft Corporation as part of the DeepSpeed deep learning optimization library.
46 |
47 | ======================================================================
--------------------------------------------------------------------------------
/evo2-backend/evo2/README.md:
--------------------------------------------------------------------------------
1 | # Evo 2: Genome modeling and design across all domains of life
2 |
3 | 
4 |
5 | Evo 2 is a state of the art DNA language model for long context modeling and design. Evo 2 models DNA sequences at single-nucleotide resolution at up to 1 million base pair context length using the [StripedHyena 2](https://github.com/Zymrael/savanna/blob/main/paper.pdf) architecture. Evo 2 was pretrained using [Savanna](https://github.com/Zymrael/savanna). Evo 2 was trained autoregressively on [OpenGenome2](https://huggingface.co/datasets/arcinstitute/opengenome2), a dataset containing 8.8 trillion tokens from all domains of life.
6 |
7 | We describe Evo 2 in the preprint:
8 | ["Genome modeling and design across all domains of life with Evo 2"](https://www.biorxiv.org/content/10.1101/2025.02.18.638918v1).
9 |
10 | ## Contents
11 |
12 | - [Setup](#setup)
13 | - [Requirements](#requirements)
14 | - [Installation](#installation)
15 | - [Checkpoints](#checkpoints)
16 | - [Usage](#usage)
17 | - [Forward](#forward)
18 | - [Embeddings](#embeddings)
19 | - [Generation](#generation)
20 | - [Notebooks](#notebooks)
21 | - [Nvidia NIM](#nvidia-nim)
22 | - [Dataset](#dataset)
23 | - [Training and Finetuning](#training-and-finetuning)
24 | - [Citation](#citation)
25 |
26 | ## Setup
27 |
28 | This repo is for running Evo 2 locally for inference or generation, using our [Vortex](https://github.com/Zymrael/vortex) inference code. For training and finetuning, see the section [here](#training-and-finetuning).
29 | You can run Evo 2 without any installation using the [Nvidia Hosted API](https://build.nvidia.com/arc/evo2-40b).
30 | You can also self-host an instance using Nvidia NIM. See the [Nvidia NIM](#nvidia-nim) section for more
31 | information.
32 |
33 | ### Requirements
34 |
35 | Evo 2 is based on [StripedHyena 2](https://github.com/Zymrael/vortex) which requires python>=3.11. Evo 2 uses [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) FP8 for some layers which requires an H100 (or other GPU with compute capability ≥8.9). We are actively investigating ways to avoid this requirement.
36 |
37 | ### Installation
38 |
39 | To install Evo 2 for inference or generation, please clone and install from GitHub. We recommend using a new conda environment with python>=3.11.
40 |
41 | ```bash
42 | git clone --recurse-submodules git@github.com:ArcInstitute/evo2.git
43 | cd evo2
44 | pip install .
45 | ```
46 |
47 | If this did not work for whatever reason, you can also install from [Vortex](https://github.com/Zymrael/vortex) and follow the instructions there. PyPi support coming soon!
48 |
49 | You can check that the installation was correct by running a test.
50 |
51 | ```
52 | python ./test/test_evo2.py --model_name evo2_7b
53 | ```
54 |
55 | ## Checkpoints
56 |
57 | We provide the following model checkpoints, hosted on [HuggingFace](https://huggingface.co/arcinstitute):
58 | | Checkpoint Name | Description |
59 | |----------------------------------------|-------------|
60 | | `evo2_40b` | A model pretrained with 1 million context obtained through context extension of `evo2_40b_base`.|
61 | | `evo2_7b` | A model pretrained with 1 million context obtained through context extension of `evo2_7b_base`.|
62 | | `evo2_40b_base` | A model pretrained with 8192 context length.|
63 | | `evo2_7b_base` | A model pretrained with 8192 context length.|
64 | | `evo2_1b_base` | A smaller model pretrained with 8192 context length.|
65 |
66 | To use Evo 2 40B, you will need multiple GPUs. Vortex automatically handles device placement, splitting the model across available cuda devices.
67 |
68 | ## Usage
69 |
70 | Below are simple examples of how to download Evo 2 and use it locally in Python.
71 |
72 | ### Forward
73 |
74 | Evo 2 can be used to score the likelihoods across a DNA sequence.
75 |
76 | ```python
77 | import torch
78 | from evo2 import Evo2
79 |
80 | evo2_model = Evo2('evo2_7b')
81 |
82 | sequence = 'ACGT'
83 | input_ids = torch.tensor(
84 | evo2_model.tokenizer.tokenize(sequence),
85 | dtype=torch.int,
86 | ).unsqueeze(0).to('cuda:0')
87 |
88 | outputs, _ = evo2_model(input_ids)
89 | logits = outputs[0]
90 |
91 | print('Logits: ', logits)
92 | print('Shape (batch, length, vocab): ', logits.shape)
93 | ```
94 |
95 | ### Embeddings
96 |
97 | Evo 2 embeddings can be saved for use downstream. We find that intermediate embeddings work better than final embeddings, see our paper for details.
98 |
99 | ```python
100 | import torch
101 | from evo2 import Evo2
102 |
103 | evo2_model = Evo2('evo2_7b')
104 |
105 | sequence = 'ACGT'
106 | input_ids = torch.tensor(
107 | evo2_model.tokenizer.tokenize(sequence),
108 | dtype=torch.int,
109 | ).unsqueeze(0).to('cuda:0')
110 |
111 | layer_name = 'blocks.28.mlp.l3'
112 |
113 | outputs, embeddings = evo2_model(input_ids, return_embeddings=True, layer_names=[layer_name])
114 |
115 | print('Embeddings shape: ', embeddings[layer_name].shape)
116 | ```
117 |
118 | ### Generation
119 |
120 | Evo 2 can generate DNA sequences based on prompts.
121 |
122 | ```python
123 | from evo2 import Evo2
124 |
125 | evo2_model = Evo2('evo2_7b')
126 |
127 | output = evo2_model.generate(prompt_seqs=["ACGT"], n_tokens=400, temperature=1.0, top_k=4)
128 |
129 | print(output.sequences[0])
130 | ```
131 |
132 | ### Notebooks
133 |
134 | We provide example notebooks.
135 |
136 | The [BRCA1 notebook](https://github.com/ArcInstitute/evo2/blob/main/notebooks/brca1/brca1_zero_shot_vep.ipynb) shows zero-shot *BRCA1* variant effect prediction. This example includes a walkthrough of:
137 | - Performing zero-shot *BRCA1* variant effect predictions using Evo 2
138 | - Reference vs alternative allele normalization
139 |
140 | The [generation notebook](https://github.com/ArcInstitute/evo2/blob/main/notebooks/generation/generation_notebook.ipynb) shows DNA sequence completion with Evo 2. This example shows:
141 | - DNA prompt based generation and 'DNA autocompletion'
142 | - How to get and prompt using phylogenetic species tags for generation
143 |
144 | ### Nvidia NIM
145 |
146 | Evo 2 is available on [Nvidia NIM](https://catalog.ngc.nvidia.com/containers?filters=&orderBy=scoreDESC&query=evo2&page=&pageSize=) and [hosted API](https://build.nvidia.com/arc/evo2-40b).
147 |
148 | - [Documentation](https://docs.nvidia.com/nim/bionemo/evo2/latest/overview.html)
149 | - [Quickstart](https://docs.nvidia.com/nim/bionemo/evo2/latest/quickstart-guide.html)
150 |
151 | The quickstart guides users through running Evo 2 on the NVIDIA NIM using a python or shell client after starting NIM. An example python client script is shown below. This is the same way you would interact with the [Nvidia hosted API](https://build.nvidia.com/arc/evo2-40b?snippet_tab=Python).
152 |
153 | ```python
154 | #!/usr/bin/env python3
155 | import requests
156 | import os
157 | import json
158 | from pathlib import Path
159 |
160 | key = os.getenv("NVCF_RUN_KEY") or input("Paste the Run Key: ")
161 |
162 | r = requests.post(
163 | url=os.getenv("URL", "https://health.api.nvidia.com/v1/biology/arc/evo2-40b/generate"),
164 | headers={"Authorization": f"Bearer {key}"},
165 | json={
166 | "sequence": "ACTGACTGACTGACTG",
167 | "num_tokens": 8,
168 | "top_k": 1,
169 | "enable_sampled_probs": True,
170 | },
171 | )
172 |
173 | if "application/json" in r.headers.get("Content-Type", ""):
174 | print(r, "Saving to output.json:\n", r.text[:200], "...")
175 | Path("output.json").write_text(r.text)
176 | elif "application/zip" in r.headers.get("Content-Type", ""):
177 | print(r, "Saving large response to data.zip")
178 | Path("data.zip").write_bytes(r.content)
179 | else:
180 | print(r, r.headers, r.content)
181 | ```
182 |
183 |
184 | ### Very long sequences
185 |
186 | We are actively working on optimizing performance for long sequence processing in Vortex. Vortex can currently compute over very long sequences via teacher prompting. However please note that forward pass on long sequences may currently be slow. You can instead use [Savanna](https://github.com/Zymrael/savanna) or [Nvidia BioNemo](https://github.com/NVIDIA/bionemo-framework) for embedding long sequences.
187 |
188 | ### Dataset
189 |
190 | The OpenGenome2 dataset used for pretraining Evo2 is available on [HuggingFace ](https://huggingface.co/datasets/arcinstitute/opengenome2). Data is available either as raw fastas or as JSONL files which include preprocessing and data augmentation.
191 |
192 | ### Training and Finetuning
193 |
194 | Evo 2 was trained using [Savanna](https://github.com/Zymrael/savanna), an open source framework for training alternative architectures.
195 |
196 | To train or finetune Evo 2, you can use [Savanna](https://github.com/Zymrael/savanna) or [Nvidia BioNemo](https://github.com/NVIDIA/bionemo-framework) which provides a [Evo 2 finetuning tutorial here](https://github.com/NVIDIA/bionemo-framework/blob/ca16c2acf9bf813d020b6d1e2d4e1240cfef6a69/docs/docs/user-guide/examples/bionemo-evo2/fine-tuning-tutorial.ipynb).
197 |
198 | ## Citation
199 |
200 | If you find these models useful for your research, please cite the relevant papers
201 |
202 | ```
203 | @article {Brixi2025.02.18.638918,
204 | author = {Brixi, Garyk and Durrant, Matthew G and Ku, Jerome and Poli, Michael and Brockman, Greg and Chang, Daniel and Gonzalez, Gabriel A and King, Samuel H and Li, David B and Merchant, Aditi T and Naghipourfar, Mohsen and Nguyen, Eric and Ricci-Tam, Chiara and Romero, David W and Sun, Gwanggyu and Taghibakshi, Ali and Vorontsov, Anton and Yang, Brandon and Deng, Myra and Gorton, Liv and Nguyen, Nam and Wang, Nicholas K and Adams, Etowah and Baccus, Stephen A and Dillmann, Steven and Ermon, Stefano and Guo, Daniel and Ilango, Rajesh and Janik, Ken and Lu, Amy X and Mehta, Reshma and Mofrad, Mohammad R.K. and Ng, Madelena Y and Pannu, Jaspreet and Re, Christopher and Schmok, Jonathan C and St. John, John and Sullivan, Jeremy and Zhu, Kevin and Zynda, Greg and Balsam, Daniel and Collison, Patrick and Costa, Anthony B. and Hernandez-Boussard, Tina and Ho, Eric and Liu, Ming-Yu and McGrath, Tom and Powell, Kimberly and Burke, Dave P. and Goodarzi, Hani and Hsu, Patrick D and Hie, Brian},
205 | title = {Genome modeling and design across all domains of life with Evo 2},
206 | elocation-id = {2025.02.18.638918},
207 | year = {2025},
208 | doi = {10.1101/2025.02.18.638918},
209 | publisher = {Cold Spring Harbor Laboratory},
210 | URL = {https://www.biorxiv.org/content/early/2025/02/21/2025.02.18.638918},
211 | eprint = {https://www.biorxiv.org/content/early/2025/02/21/2025.02.18.638918.full.pdf},
212 | journal = {bioRxiv}
213 | }
214 | ```
215 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Andreaswt/variant-analysis-evo2/55741e31ae0bf3327cc97202be842f37e3fd7e6e/evo2-backend/evo2/evo2.jpg
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/__init__.py:
--------------------------------------------------------------------------------
1 | from .models import Evo2
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/configs/evo2-1b-8k.yml:
--------------------------------------------------------------------------------
1 | model_name: shc-evo2-1b-8k-2T-v2
2 |
3 | vocab_size: 512
4 | hidden_size: 1920
5 | # Number of independent filters in Hyena-LI
6 | num_filters: 1920
7 | attn_layer_idxs: [3,10,17,24]
8 | hcl_layer_idxs: [2,6,9,13,16,20,23]
9 | hcm_layer_idxs: [1,5,8,12,15,19,22]
10 | hcs_layer_idxs: [0,4,7,11,14,18,21]
11 |
12 | hcm_filter_length: 128
13 | hcl_filter_groups: 1920
14 | hcm_filter_groups: 128
15 | hcs_filter_groups: 128
16 | hcs_filter_length: 7
17 | num_layers: 25
18 |
19 | # Length of the short, depthwise FIR applied to input projections
20 | short_filter_length: 3
21 | num_attention_heads: 15
22 | short_filter_bias: false # add bias to FIR
23 | mlp_init_method: torch.nn.init.zeros_
24 | mlp_output_init_method: torch.nn.init.zeros_
25 | eps: 0.000001
26 | state_size: 16
27 | rotary_emb_base: 10000
28 | make_vocab_size_divisible_by: 8
29 | inner_size_multiple_of: 16 # force GLU inner_size to be a multiple of
30 | inner_mlp_size: 5120
31 | log_intermediate_values: False
32 | # Number of groups in GQA
33 | proj_groups: 1
34 | # Number of groups in grouped
35 | hyena_filter_groups: 1
36 | # Split strategy for channels
37 | column_split_hyena: False
38 | column_split: True
39 | interleave: True
40 | # Layer > 0 nn.identity activation
41 | evo2_style_activations: True
42 |
43 | # Legacy options for MP / PP inference
44 | model_parallel_size: 1
45 | pipe_parallel_size: 1
46 | tie_embeddings: True
47 | mha_out_proj_bias: True
48 | hyena_out_proj_bias: True
49 | hyena_flip_x1x2: False
50 | qkv_proj_bias: False
51 | use_fp8_input_projections: True
52 | max_seqlen: 8192
53 | max_batch_size: 1
54 | final_norm: True
55 | use_flash_attn: True
56 | use_flash_rmsnorm: False
57 | use_flash_depthwise: False
58 | use_flashfft: False
59 | use_laughing_hyena: False
60 | inference_mode: True
61 | tokenizer_type: CharLevelTokenizer
62 | prefill_style: fft
63 | mlp_activation: gelu
64 | print_activations: False
65 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/configs/evo2-40b-1m.yml:
--------------------------------------------------------------------------------
1 | model_name: shc-evo2-40b-8k-11T-v2
2 |
3 | vocab_size: 512
4 | hidden_size: 8192
5 | # Number of independent filters in Hyena-LI
6 | num_filters: 8192
7 | hcl_layer_idxs: [2,6,9,13,16,20,23,27,30,34,38,41,45,48]
8 | hcm_layer_idxs: [1,5,8,12,15,19,22,26,29,33,37,40,44,47]
9 | hcs_layer_idxs: [0,4,7,11,14,18,21,25,28,32,36,39,43,46]
10 | attn_layer_idxs: [3,10,17,24,31,35,42,49]
11 | hcm_filter_length: 128
12 | hcl_filter_groups: 8192
13 | hcm_filter_groups: 512
14 | hcs_filter_groups: 512
15 | hcs_filter_length: 7
16 | num_layers: 50
17 |
18 | # Length of the short, depthwise FIR applied to input projections
19 | short_filter_length: 3
20 | num_attention_heads: 64
21 | short_filter_bias: false # add bias to FIR
22 | mlp_init_method: torch.nn.init.zeros_
23 | mlp_output_init_method: torch.nn.init.zeros_
24 | eps: 0.000001
25 | state_size: 16
26 | rotary_emb_base: 100000000000
27 | rotary_emb_scaling_factor: 128
28 | use_interpolated_rotary_pos_emb: True
29 | make_vocab_size_divisible_by: 8
30 | inner_size_multiple_of: 128 # force GLU inner_size to be a multiple of
31 | inner_mlp_size: 22528
32 | log_intermediate_values: False
33 | # Number of groups in GQA
34 | proj_groups: 1
35 | # Number of groups in grouped
36 | hyena_filter_groups: 1
37 | # Split strategy for channels
38 | column_split_hyena: False
39 | column_split: True
40 | interleave: True
41 | # Layer > 0 nn.identity activation
42 | evo2_style_activations: True
43 |
44 | use_fp8_input_projections: True
45 |
46 | # Legacy options for MP / PP inference
47 | model_parallel_size: 1
48 | pipe_parallel_size: 1
49 | tie_embeddings: True
50 | mha_out_proj_bias: True
51 | hyena_out_proj_bias: True
52 | hyena_flip_x1x2: False
53 | qkv_proj_bias: False
54 | max_seqlen: 1048576
55 | max_batch_size: 1
56 | final_norm: True
57 | use_flash_attn: True
58 | use_flash_rmsnorm: False
59 | use_flash_depthwise: False
60 | use_flashfft: False
61 | use_laughing_hyena: False
62 | inference_mode: True
63 | tokenizer_type: CharLevelTokenizer
64 | prefill_style: fft
65 | mlp_activation: gelu
66 | print_activations: False
67 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/configs/evo2-40b-8k.yml:
--------------------------------------------------------------------------------
1 | model_name: shc-evo2-40b-8k-11T-v2
2 |
3 | vocab_size: 512
4 | hidden_size: 8192
5 | num_filters: 8192
6 | hcl_layer_idxs: [2,6,9,13,16,20,23,27,30,34,38,41,45,48]
7 | hcm_layer_idxs: [1,5,8,12,15,19,22,26,29,33,37,40,44,47]
8 | hcs_layer_idxs: [0,4,7,11,14,18,21,25,28,32,36,39,43,46]
9 | attn_layer_idxs: [3,10,17,24,31,35,42,49]
10 | hcm_filter_length: 128
11 | hcl_filter_groups: 8192
12 | hcm_filter_groups: 512
13 | hcs_filter_groups: 512
14 | hcs_filter_length: 7
15 | num_layers: 50
16 |
17 | # Length of the short, depthwise FIR applied to input projections
18 | short_filter_length: 3
19 | num_attention_heads: 64
20 | short_filter_bias: false # add bias to FIR
21 | mlp_init_method: torch.nn.init.zeros_
22 | mlp_output_init_method: torch.nn.init.zeros_
23 | eps: 0.000001
24 | state_size: 16
25 | rotary_emb_base: 1000000
26 | make_vocab_size_divisible_by: 8
27 | inner_size_multiple_of: 128 # force GLU inner_size to be a multiple of
28 | inner_mlp_size: 21888
29 | log_intermediate_values: False
30 | # Number of groups in GQA
31 | proj_groups: 1
32 | # Number of groups in grouped
33 | hyena_filter_groups: 1
34 | # Split strategy for channels
35 | column_split_hyena: False
36 | column_split: True
37 | interleave: True
38 | # Layer > 0 nn.identity activation
39 | evo2_style_activations: True
40 |
41 | use_fp8_input_projections: True
42 |
43 | # Legacy options for MP / PP inference
44 | model_parallel_size: 1
45 | pipe_parallel_size: 1
46 | tie_embeddings: True
47 | mha_out_proj_bias: True
48 | hyena_out_proj_bias: True
49 | hyena_flip_x1x2: False
50 | qkv_proj_bias: False
51 | max_seqlen: 8192
52 | max_batch_size: 1
53 | final_norm: True
54 | use_flash_attn: True
55 | use_flash_rmsnorm: False
56 | use_flash_depthwise: False
57 | use_flashfft: False
58 | use_laughing_hyena: False
59 | inference_mode: True
60 | tokenizer_type: CharLevelTokenizer
61 | prefill_style: fft
62 | mlp_activation: gelu
63 | print_activations: False
64 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/configs/evo2-7b-1m.yml:
--------------------------------------------------------------------------------
1 | model_name: shc-evo2-7b-8k-2T-v2
2 |
3 | vocab_size: 512
4 | hidden_size: 4096
5 | # Number of long convolution filters in each hyena block. Can be smaller than `hidden_size`
6 | num_filters: 4096
7 | hcl_layer_idxs: [2,6,9,13,16,20,23,27,30]
8 | hcm_layer_idxs: [1,5,8,12,15,19,22,26,29]
9 | hcs_layer_idxs: [0,4,7,11,14,18,21,25,28]
10 | attn_layer_idxs: [3,10,17,24,31]
11 |
12 | hcm_filter_length: 128
13 | hcl_filter_groups: 4096
14 | hcm_filter_groups: 256
15 | hcs_filter_groups: 256
16 | hcs_filter_length: 7
17 | num_layers: 32
18 |
19 | # Length of the short, depthwise FIR applied to input projections
20 | short_filter_length: 3
21 | num_attention_heads: 32
22 | short_filter_bias: false # add bias to FIR
23 | mlp_init_method: torch.nn.init.zeros_
24 | mlp_output_init_method: torch.nn.init.zeros_
25 | eps: 0.000001
26 | state_size: 16
27 | rotary_emb_base: 100000000000
28 | rotary_emb_scaling_factor: 128
29 | use_interpolated_rotary_pos_emb: True
30 | make_vocab_size_divisible_by: 8
31 | inner_size_multiple_of: 16 # force GLU inner_size to be a multiple of
32 | inner_mlp_size: 11264
33 | log_intermediate_values: False
34 | # Number of groups in GQA
35 | proj_groups: 1
36 | # Number of groups in grouped
37 | hyena_filter_groups: 1
38 | # Split strategy for channels
39 | column_split_hyena: False
40 | column_split: True
41 | interleave: True
42 | # Layer > 0 nn.identity activation
43 | evo2_style_activations: True
44 | # Legacy options for MP / PP inference
45 | model_parallel_size: 1
46 | pipe_parallel_size: 1
47 | tie_embeddings: True
48 | mha_out_proj_bias: True
49 | hyena_out_proj_bias: True
50 | hyena_flip_x1x2: False
51 | qkv_proj_bias: False
52 | use_fp8_input_projections: True
53 | max_seqlen: 1048576
54 | max_batch_size: 1
55 | final_norm: True
56 | use_flash_attn: True
57 | use_flash_rmsnorm: False
58 | use_flash_depthwise: False
59 | use_flashfft: False
60 | use_laughing_hyena: False
61 | inference_mode: True
62 | tokenizer_type: CharLevelTokenizer
63 | prefill_style: fft
64 | mlp_activation: gelu
65 | print_activations: False
66 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/configs/evo2-7b-8k.yml:
--------------------------------------------------------------------------------
1 | model_name: shc-evo2-7b-8k-2T-v2
2 |
3 | vocab_size: 512
4 | hidden_size: 4096
5 | num_filters: 4096
6 | hcl_layer_idxs: [2,6,9,13,16,20,23,27,30]
7 | hcm_layer_idxs: [1,5,8,12,15,19,22,26,29]
8 | hcs_layer_idxs: [0,4,7,11,14,18,21,25,28]
9 | attn_layer_idxs: [3,10,17,24,31]
10 |
11 | # Number of unique convolution filters in each hyena block. Can be smaller than `hidden_size`
12 | hcm_filter_length: 128
13 | hcl_filter_groups: 4096
14 | hcm_filter_groups: 256
15 | hcs_filter_groups: 256
16 | hcs_filter_length: 7
17 | num_layers: 32
18 |
19 | # Length of the short, depthwise FIR applied to input projections
20 | short_filter_length: 3
21 | num_attention_heads: 32
22 | short_filter_bias: false # add bias to FIR
23 | mlp_init_method: torch.nn.init.zeros_
24 | mlp_output_init_method: torch.nn.init.zeros_
25 | eps: 0.000001
26 | state_size: 16
27 | rotary_emb_base: 10000
28 | make_vocab_size_divisible_by: 8
29 | inner_size_multiple_of: 16 # force GLU inner_size to be a multiple of
30 | inner_mlp_size: 11008
31 | log_intermediate_values: False
32 | # Number of groups in GQA
33 | proj_groups: 1
34 | # Number of groups in grouped
35 | hyena_filter_groups: 1
36 | # Split strategy for channels
37 | column_split_hyena: False
38 | column_split: True
39 | interleave: True
40 | # Layer > 0 nn.identity activation
41 | evo2_style_activations: True
42 | # Legacy options for MP / PP inference
43 | model_parallel_size: 1
44 | pipe_parallel_size: 1
45 | tie_embeddings: True
46 | mha_out_proj_bias: True
47 | hyena_out_proj_bias: True
48 | hyena_flip_x1x2: False
49 | qkv_proj_bias: False
50 | use_fp8_input_projections: False
51 | max_seqlen: 32768
52 | max_batch_size: 1
53 | final_norm: True
54 | use_flash_attn: True
55 | use_flash_rmsnorm: False
56 | use_flash_depthwise: False
57 | use_flashfft: False
58 | use_laughing_hyena: False
59 | inference_mode: True
60 | tokenizer_type: CharLevelTokenizer
61 | prefill_style: fft
62 | mlp_activation: gelu
63 | print_activations: False
64 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/models.py:
--------------------------------------------------------------------------------
1 | from functools import partial
2 | import huggingface_hub
3 | from huggingface_hub import snapshot_download, constants, hf_hub_download
4 | import os
5 | import pkgutil
6 | import torch
7 | from typing import List, Tuple, Dict, Union
8 | import yaml
9 |
10 |
11 | from vortex.model.generation import generate as vortex_generate
12 | from vortex.model.model import StripedHyena
13 | from vortex.model.tokenizer import CharLevelTokenizer
14 | from vortex.model.utils import dotdict, print_rank_0, load_checkpoint
15 |
16 | from evo2.scoring import score_sequences, score_sequences_rc
17 | from evo2.utils import MODEL_NAMES, HF_MODEL_NAME_MAP, CONFIG_MAP
18 |
19 | class Evo2:
20 | def __init__(self, model_name: str = MODEL_NAMES[1], local_path: str = None):
21 | """
22 | Load an Evo 2 checkpoint.
23 |
24 | Uses local_path if specified, otherwise checks if in local HuggingFace ~cache.
25 | Automatically downloads checkpoint from HuggingFace if it does not exist locally.
26 |
27 | Vortex automatically handles device placement on CUDA, and splits model across
28 | multiple GPUs if available.
29 | For models split across multiple GPUs, you can specify which GPUs to use with
30 | CUDA_VISIBLE_DEVICES. If using multi-gpu, do not use .to(device) manually.
31 |
32 | Notes:
33 | Evo 2 40b is too large to fit on a single H100 GPU, so needs multiple GPUs.
34 | You can change where HuggingFace downloads to by setting the HF_HOME environment
35 | variable.
36 | """
37 | if model_name not in MODEL_NAMES:
38 | raise ValueError(
39 | f'Invalid model name {model_name}. Should be one of: '
40 | f'{", ".join(MODEL_NAMES)}.'
41 | )
42 |
43 | config_path = CONFIG_MAP[model_name]
44 |
45 | if local_path is not None:
46 | self.model = self.load_evo2_model(None, config_path, local_path)
47 | else:
48 | self.model = self.load_evo2_model(model_name, config_path)
49 |
50 | self.tokenizer = CharLevelTokenizer(512)
51 |
52 | def forward(
53 | self,
54 | input_ids: torch.Tensor,
55 | return_embeddings: bool = False,
56 | layer_names=None,
57 | ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
58 | """
59 | Forward pass with optional embedding extraction.
60 |
61 | Args:
62 | input_ids: Input token IDs
63 | return_embeddings: If True, returns embeddings from specified layers
64 | layer_names: List of layer names to extract embeddings from. Required if
65 | return_embeddings=True
66 |
67 | Returns:
68 | Tuple of (logits, embeddings_dict) if return_embeddings=True
69 | Tuple of (logits, None) otherwise
70 | """
71 | embeddings = {}
72 | handles = []
73 |
74 | if return_embeddings:
75 | if layer_names is None:
76 | raise ValueError(
77 | "layer_names must be specified when return_embeddings=True. Look at "
78 | "evo2_model.model.state_dict().keys() to see available layers."
79 | )
80 |
81 | def hook_fn(layer_name):
82 | def hook(_, __, output):
83 | if isinstance(output, tuple):
84 | output = output[0]
85 | embeddings[layer_name] = output.detach()
86 | return hook
87 |
88 | # Register hooks for requested layers
89 | for name in layer_names:
90 | layer = self.model.get_submodule(name)
91 | handles.append(layer.register_forward_hook(hook_fn(name)))
92 |
93 | try:
94 | # Original forward pass
95 | with torch.no_grad():
96 | logits = self.model.forward(input_ids)
97 |
98 | if return_embeddings:
99 | return logits, embeddings
100 | return logits, None
101 |
102 | finally:
103 | for handle in handles:
104 | handle.remove()
105 |
106 | def __call__(self, input_ids, return_embeddings=False, layer_names=None):
107 | return self.forward(input_ids, return_embeddings, layer_names)
108 |
109 | def score_sequences(
110 | self,
111 | seqs: List[str],
112 | batch_size: int = 1,
113 | prepend_bos: bool = False,
114 | reduce_method: str = 'mean',
115 | average_reverse_complement: bool = False,
116 | ) -> List[float]:
117 | scoring_func = partial(
118 | score_sequences_rc if average_reverse_complement else score_sequences,
119 | model=self.model,
120 | tokenizer=self.tokenizer,
121 | batch_size=batch_size,
122 | prepend_bos=prepend_bos,
123 | reduce_method=reduce_method,
124 | )
125 |
126 | with torch.no_grad():
127 | try:
128 | scores = scoring_func(seqs)
129 | except Exception as e:
130 | raise RuntimeError(f"Error during sequence scoring: {str(e)}") from e
131 |
132 | return scores
133 |
134 | def generate(
135 | self,
136 | prompt_seqs: List[str],
137 | n_tokens: int = 500,
138 | temperature: float = 1.0,
139 | top_k: int = 4,
140 | top_p: float = 1.0,
141 | batched: bool = True,
142 | cached_generation: bool = True,
143 | verbose: int = 1,
144 | force_prompt_threshold: int = None,
145 | ) -> Tuple[List[str], List[float]]:
146 | """
147 | Generate sequences from a list of prompts.
148 |
149 | force_prompt_threshold: If specified, avoids OOM errors through teacher forcing if the prompt is longer than this threshold.
150 |
151 | If force_prompt_threshold is none, sets default assuming 1xH100 (evo2_7b) and 2xH100 (evo2_40b) to help avoid OOM errors.
152 | """
153 |
154 | with torch.no_grad():
155 | output = vortex_generate(
156 | prompt_seqs=prompt_seqs,
157 | model=self.model,
158 | tokenizer=self.tokenizer,
159 | n_tokens=n_tokens,
160 | temperature=temperature,
161 | top_k=top_k,
162 | top_p=top_p,
163 | batched=batched,
164 | cached_generation=cached_generation,
165 | verbose=verbose,
166 | force_prompt_threshold=force_prompt_threshold,
167 | )
168 | return output
169 |
170 |
171 | def load_evo2_model(
172 | self,
173 | model_name: str = MODEL_NAMES[1],
174 | config_path: str = None,
175 | local_path: str = None,
176 | remove_shards: bool = True,
177 | ):
178 | """
179 | Load HuggingFace checkpoint using StripedHyena 2.
180 |
181 | If local_path is specified, loads from local_path.
182 | Otherwise, downloads from HuggingFace.
183 | If remove_shards is True, removes HF checkpoint shards after merging to .pt file.
184 | """
185 | if local_path is not None:
186 | print(f"Loading model from {local_path}...")
187 | print(f"Loading config from {config_path}...")
188 | config = dotdict(yaml.load(open(config_path), Loader=yaml.FullLoader))
189 | model = StripedHyena(config)
190 | load_checkpoint(model, local_path)
191 | return model
192 |
193 | hf_model_name = HF_MODEL_NAME_MAP[model_name]
194 | filename = f"{model_name}.pt"
195 |
196 | final_weights_path = os.path.join(os.path.dirname(constants.HF_HUB_CACHE), filename)
197 | if os.path.exists(final_weights_path):
198 | print(f"Found existing merged file: {final_weights_path}")
199 | weights_path = final_weights_path
200 |
201 | hf_hub_download(
202 | repo_id=hf_model_name,
203 | filename="config.json"
204 | )
205 | else:
206 | repo_dir = snapshot_download(
207 | repo_id=hf_model_name,
208 | )
209 |
210 | # Check if the complete file already exists in the repo
211 | repo_weights_path = os.path.join(repo_dir, filename)
212 | if os.path.exists(repo_weights_path):
213 | print(f"Found complete file in repo: {filename}")
214 | weights_path = repo_weights_path
215 | else:
216 | print(f"Looking for checkpoint shards for {filename}")
217 | parts = []
218 | part_num = 0
219 |
220 | while True:
221 | part_path = os.path.join(repo_dir, f"{filename}.part{part_num}")
222 | if os.path.exists(part_path):
223 | parts.append(part_path)
224 | part_num += 1
225 | else:
226 | break
227 |
228 | if parts:
229 | print(f"Found {len(parts)} shards, merging them...")
230 | with open(final_weights_path, 'wb') as outfile:
231 | for part in parts:
232 | print(f"Merging shard: {os.path.basename(part)}")
233 | with open(part, 'rb') as infile:
234 | while True:
235 | chunk = infile.read(8192*1024)
236 | if not chunk:
237 | break
238 | outfile.write(chunk)
239 |
240 | print(f"Successfully merged all shards into {final_weights_path}")
241 | weights_path = final_weights_path
242 | if remove_shards and os.path.exists(final_weights_path):
243 | for part in parts:
244 | real_path = os.path.realpath(part)
245 | if os.path.exists(real_path):
246 | os.remove(real_path)
247 | if os.path.exists(part):
248 | os.remove(part)
249 | else:
250 | raise FileNotFoundError(f"Could not find {filename} or any of its shards in {repo_dir}")
251 |
252 | config = yaml.safe_load(pkgutil.get_data(__name__, config_path))
253 | global_config = dotdict(config, Loader=yaml.FullLoader)
254 |
255 | model = StripedHyena(global_config)
256 | load_checkpoint(model, weights_path)
257 |
258 | return model
259 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/scoring.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from typing import List, Tuple, Union
3 | from Bio.Seq import Seq
4 | from tqdm import tqdm
5 |
6 | import torch
7 | from vortex.model.model import StripedHyena
8 |
9 |
10 | def prepare_batch(
11 | seqs: List[str],
12 | tokenizer: object,
13 | prepend_bos: bool = False,
14 | device: str = 'cuda:0'
15 | ) -> Tuple[torch.Tensor, List[int]]:
16 | """
17 | Takes in a list of sequences, tokenizes them, and puts them in a tensor batch.
18 | If the sequences have differing lengths, then pad up to the maximum sequence length.
19 | """
20 | seq_lengths = [ len(seq) for seq in seqs ]
21 | max_seq_length = max(seq_lengths)
22 |
23 | input_ids = []
24 | for seq in seqs:
25 | padding = [tokenizer.pad_id] * (max_seq_length - len(seq))
26 | input_ids.append(
27 | torch.tensor(
28 | ([tokenizer.eod_id] * int(prepend_bos)) + tokenizer.tokenize(seq) + padding,
29 | dtype=torch.long,
30 | ).to(device).unsqueeze(0)
31 | )
32 | input_ids = torch.cat(input_ids, dim=0)
33 |
34 | return input_ids, seq_lengths
35 |
36 |
37 | def logits_to_logprobs(
38 | logits: torch.Tensor,
39 | input_ids: torch.Tensor,
40 | ) -> torch.Tensor:
41 | """
42 | Takes in a tensor of logits of dimension (batch, length, vocab).
43 | Computes the log-likelihoods using a softmax along the vocab dimension.
44 | Uses the `input_ids` to index into the log-likelihoods and returns the likelihood
45 | of the provided sequence at each position with dimension (batch, length).
46 | """
47 | softmax_logprobs = torch.log_softmax(logits, dim=-1)
48 | softmax_logprobs = softmax_logprobs[:, :-1]
49 | input_ids = input_ids[:, 1:]
50 | assert softmax_logprobs.shape[1] == input_ids.shape[1]
51 |
52 | logprobs = torch.gather(
53 | softmax_logprobs, # Gather likelihoods...
54 | 2, # along the vocab dimension...
55 | input_ids.unsqueeze(-1) # using the token ids to index.
56 | ).squeeze(-1)
57 |
58 | return logprobs
59 |
60 |
61 | def _score_sequences(
62 | seqs: List[str],
63 | model: StripedHyena,
64 | tokenizer: object,
65 | prepend_bos: bool = False,
66 | reduce_method: str = 'mean',
67 | device: str = 'cuda:0',
68 | ) -> List[float]:
69 | """Helper function to score a list of sequences based on their logprobs."""
70 | input_ids, seq_lengths = prepare_batch(seqs, tokenizer, device=device, prepend_bos=prepend_bos)
71 | assert len(seq_lengths) == input_ids.shape[0]
72 |
73 | with torch.inference_mode():
74 | logits, _ = model(input_ids) # (batch, length, vocab)
75 |
76 | logprobs = logits_to_logprobs(logits, input_ids)
77 | logprobs = logprobs.float().cpu().numpy()
78 |
79 | if reduce_method == 'sum': # PLL
80 | reduce_func = np.sum
81 | elif reduce_method == 'mean': # mean PLL
82 | reduce_func = np.mean
83 | else:
84 | raise ValueError(f'Invalid reduce_method {reduce_method}')
85 |
86 | return [
87 | reduce_func(logprobs[idx][:seq_lengths[idx]])
88 | for idx in range(len(seq_lengths))
89 | ]
90 |
91 |
92 | def score_sequences(
93 | seqs: List[str],
94 | model: StripedHyena,
95 | tokenizer: object,
96 | batch_size: int = None,
97 | prepend_bos: bool = False,
98 | reduce_method: str = 'mean',
99 | device: str = 'cuda:0',
100 | ) -> List[float]:
101 | """
102 | Computes the model log-likelihood scores for sequences in `seqs`.
103 | Uses `reduce_method` to take the mean or sum across the likelihoods at each
104 | position (default: `'mean'`).
105 |
106 | Returns a list of scalar scores corresponding to the reduced log-likelihoods for
107 | each sequence.
108 | """
109 | if batch_size is None:
110 | batch_size = len(seqs)
111 |
112 | scores = []
113 | for i in tqdm(range(0, len(seqs), batch_size)):
114 | batch_seqs = seqs[i:i + batch_size]
115 | batch_scores = _score_sequences(
116 | batch_seqs,
117 | model,
118 | tokenizer,
119 | prepend_bos=prepend_bos,
120 | reduce_method=reduce_method,
121 | device=device,
122 | )
123 | scores.extend(batch_scores)
124 | return scores
125 |
126 |
127 | def score_sequences_rc(
128 | seqs: List[str],
129 | model: StripedHyena,
130 | tokenizer: object,
131 | batch_size: int,
132 | prepend_bos: bool = False,
133 | reduce_method: str = 'mean',
134 | device: str = 'cuda:0',
135 | ) -> List[float]:
136 | """
137 | Computes the model log-likelihood scores for sequences in `seqs` and for their
138 | reverse complements.
139 | Takes the mean score for the forward and reverse-complemented sequence.
140 | Uses `reduce_method` to take the mean or sum across the likelihoods at each
141 | position (default: `'mean'`).
142 |
143 | Returns a list of scalar scores corresponding to the reduced log-likelihoods for
144 | each sequence.
145 | """
146 | scores = []
147 | for i in tqdm(range(0, len(seqs), batch_size)):
148 | batch_seqs = seqs[i:i + batch_size]
149 | batch_seqs_rc = [ str(Seq(seq).reverse_complement()) for seq in batch_seqs ]
150 |
151 | batch_scores = _score_sequences(
152 | batch_seqs,
153 | model,
154 | tokenizer,
155 | prepend_bos=prepend_bos,
156 | reduce_method=reduce_method,
157 | device=device,
158 | )
159 | batch_scores_rc = _score_sequences(
160 | batch_seqs_rc,
161 | model,
162 | tokenizer,
163 | prepend_bos=prepend_bos,
164 | reduce_method=reduce_method,
165 | device=device,
166 | )
167 | batch_scores = (np.array(batch_scores) + np.array(batch_scores_rc)) * 0.5
168 |
169 | scores.extend(list(batch_scores))
170 | return scores
171 |
172 |
173 | def positional_entropies(
174 | seqs: List[str],
175 | model: StripedHyena,
176 | tokenizer: object,
177 | prepend_bos: bool = False,
178 | device: str = 'cuda:0',
179 | ) -> List[np.array]:
180 | """
181 | Computes the positional entropies for sequences in `seqs`.
182 |
183 | Returns a list of arrays, where each array is the same length as the
184 | corresponding sequence length. Each array contains the per-position entropy
185 | across the vocab dimension.
186 | """
187 | input_ids, seq_lengths = prepare_batch(seqs, tokenizer, device=device, prepend_bos=prepend_bos)
188 | assert len(seq_lengths) == input_ids.shape[0]
189 |
190 | with torch.inference_mode():
191 | logits, _ = model(input_ids) # (batch, length, vocab)
192 |
193 | softmax_logprobs = torch.log_softmax(logits, dim=-1)
194 | if prepend_bos:
195 | softmax_logprobs = softmax_logprobs[:, 1:, :] # Remove BOS entropy.
196 |
197 | entropies = -torch.sum(torch.exp(softmax_logprobs) * softmax_logprobs, dim=-1)
198 | entropies = entropies.float().cpu().numpy()
199 |
200 | sequence_entropies = [
201 | entropies[idx][:seq_lengths[idx]] for idx in range(len(seq_lengths))
202 | ]
203 | assert all(
204 | len(seq) == len(entropy) for seq, entropy in zip(seqs, sequence_entropies)
205 | )
206 |
207 | return sequence_entropies
208 |
209 |
210 | def score_perplexity_along_sequence(
211 | model: StripedHyena,
212 | seq: str,
213 | reverse_complement: bool = True,
214 | entropy: bool = False
215 | ) -> np.array:
216 | '''
217 | Get forward and reverse RC of dna sequence, pass both through model, and return average entropy or perplexity.
218 | '''
219 | seq_rc = str(Seq(seq).reverse_complement())
220 |
221 | entropy_forward = positional_entropies([seq], model.model, model.tokenizer)[0]
222 |
223 | if reverse_complement:
224 | entropy_reverse = positional_entropies([seq_rc], model.model, model.tokenizer)[0]
225 | entropy_reverse = entropy_reverse[::-1]
226 |
227 | average_entropy = (entropy_forward + entropy_reverse) / 2
228 | else:
229 | average_entropy = entropy_forward
230 |
231 | if entropy:
232 | return average_entropy
233 | else:
234 | return np.exp(average_entropy)
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/utils.py:
--------------------------------------------------------------------------------
1 | MODEL_NAMES = [
2 | 'evo2_40b',
3 | 'evo2_7b',
4 | 'evo2_40b_base',
5 | 'evo2_7b_base',
6 | 'evo2_1b_base',
7 | ]
8 |
9 | HF_MODEL_NAME_MAP = {
10 | 'evo2_40b': 'arcinstitute/evo2_40b',
11 | 'evo2_7b': 'arcinstitute/evo2_7b',
12 | 'evo2_40b_base': 'arcinstitute/evo2_40b_base',
13 | 'evo2_7b_base': 'arcinstitute/evo2_7b_base',
14 | 'evo2_1b_base': 'arcinstitute/evo2_1b_base',
15 | }
16 |
17 | CONFIG_MAP = {
18 | 'evo2_7b': 'configs/evo2-7b-1m.yml',
19 | 'evo2_40b': 'configs/evo2-40b-1m.yml',
20 | 'evo2_7b_base': 'configs/evo2-7b-8k.yml',
21 | 'evo2_40b_base': 'configs/evo2-40b-8k.yml',
22 | 'evo2_1b_base': 'configs/evo2-1b-8k.yml',
23 | }
24 |
25 |
26 | def make_phylotag_from_gbif(
27 | species_name: str,
28 | ) -> dict:
29 | """
30 | Returns phylogenetic tags for a given species, to get new tags not in the metadata
31 | """
32 |
33 | import requests
34 | def get_taxonomy_from_gbif(species_name):
35 | url = f"https://api.gbif.org/v1/species/match?name={species_name}"
36 | response = requests.get(url)
37 | if response.status_code == 200:
38 | data = response.json()
39 | return {
40 | "kingdom": data.get("kingdom"),
41 | "phylum": data.get("phylum"),
42 | "class": data.get("class"),
43 | "order": data.get("order"),
44 | "family": data.get("family"),
45 | "genus": data.get("genus"),
46 | "species": data.get("species")
47 | }
48 | else:
49 | print(f"Could not find taxonomy for {species_name}")
50 |
51 | taxonomy = get_taxonomy_from_gbif(species_name)
52 | if taxonomy:
53 | phylo_tag = (
54 | f'd__{taxonomy["kingdom"]};'
55 | f'p__{taxonomy["phylum"]};'
56 | f'c__{taxonomy["class"]};'
57 | f'o__{taxonomy["order"]};'
58 | f'f__{taxonomy["family"]};'
59 | f'g__{taxonomy["genus"]};'
60 | f's__{taxonomy["species"]}'
61 | ).upper()
62 | phylo_tag = '|'+phylo_tag+'|'
63 | else:
64 | print(f"Could not find taxonomy for {species_name}")
65 |
66 | return phylo_tag.upper()
67 |
68 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/evo2/version.py:
--------------------------------------------------------------------------------
1 | version = '0.1.0'
2 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/notebooks/brca1/41586_2018_461_MOESM3_ESM.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Andreaswt/variant-analysis-evo2/55741e31ae0bf3327cc97202be842f37e3fd7e6e/evo2-backend/evo2/notebooks/brca1/41586_2018_461_MOESM3_ESM.xlsx
--------------------------------------------------------------------------------
/evo2-backend/evo2/notebooks/brca1/GRCh37.p13_chr17.fna.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Andreaswt/variant-analysis-evo2/55741e31ae0bf3327cc97202be842f37e3fd7e6e/evo2-backend/evo2/notebooks/brca1/GRCh37.p13_chr17.fna.gz
--------------------------------------------------------------------------------
/evo2-backend/evo2/requirements.txt:
--------------------------------------------------------------------------------
1 | biopython
2 | huggingface_hub
--------------------------------------------------------------------------------
/evo2-backend/evo2/setup.py:
--------------------------------------------------------------------------------
1 | import os
2 | import subprocess
3 | import sys
4 | from setuptools import setup, find_packages
5 | from setuptools.command.build import build as _build # use the top-level build command
6 | from setuptools.command.develop import develop as _develop
7 | from wheel.bdist_wheel import bdist_wheel as _bdist_wheel
8 |
9 |
10 | def update_submodules():
11 | base_dir = os.path.dirname(__file__)
12 | # Check if the .git folder exists
13 | if os.path.exists(os.path.join(base_dir, '.git')):
14 | print("Updating git submodules...")
15 | # Run submodule init and update for 'vortex'
16 | subprocess.check_call(['git', 'submodule', 'init', 'vortex'], cwd=base_dir)
17 | subprocess.check_call(['git', 'submodule', 'update', 'vortex'], cwd=base_dir)
18 | else:
19 | print("No .git directory found; skipping submodule update.")
20 |
21 | def run_make_setup_full():
22 | base_dir = os.path.dirname(__file__)
23 | vortex_dir = os.path.join(base_dir, 'vortex')
24 | original_dir = os.getcwd()
25 |
26 | # Ensure submodules are updated before running the Makefile
27 | update_submodules()
28 |
29 | # Ensure the Makefile uses the current Python interpreter
30 | env = os.environ.copy()
31 | env["PYTHON"] = sys.executable
32 | print(f"Running 'make setup-full' in {vortex_dir} with PYTHON={sys.executable} ...")
33 |
34 | try:
35 | os.chdir(vortex_dir)
36 | subprocess.check_call(['make', 'setup-full'], env=env)
37 | finally:
38 | os.chdir(original_dir)
39 |
40 | class CustomBuild(_build):
41 | def run(self):
42 | # Run egg_info to ensure metadata is available
43 | self.run_command('egg_info')
44 | # Update submodules and run the Makefile before building anything else
45 | run_make_setup_full()
46 | # Continue with the normal build process
47 | _build.run(self)
48 |
49 | class CustomDevelop(_develop):
50 | def run(self):
51 | update_submodules()
52 | run_make_setup_full()
53 | _develop.run(self)
54 |
55 | class CustomBDistWheel(_bdist_wheel):
56 | def run(self):
57 | self.run_command('egg_info')
58 | _bdist_wheel.run(self)
59 |
60 | def parse_requirements(filename):
61 | requirements = []
62 | with open(filename) as f:
63 | for line in f:
64 | line = line.strip()
65 | if line and not line.startswith('#'):
66 | requirements.append(line)
67 | return requirements
68 |
69 |
70 | with open('evo2/version.py') as infile:
71 | exec(infile.read())
72 |
73 | with open('README.md') as f:
74 | readme = f.read()
75 |
76 | requirements = parse_requirements("requirements.txt")
77 |
78 | setup(
79 | name='evo2',
80 | version=version,
81 | # Only include the evo2 package; the vortex submodule is used for build purposes.
82 | packages=find_packages(include=["evo2", "vortex/vortex"]),
83 | install_requires=requirements,
84 | cmdclass={
85 | 'build': CustomBuild,
86 | 'develop': CustomDevelop,
87 | 'bdist_wheel': CustomBDistWheel,
88 | },
89 | package_data={'evo2': ['evo2/configs/*.yml']},
90 | include_package_data=True,
91 | python_requires='>=3.11',
92 | license="Apache-2.0",
93 | description='Genome modeling across all domains of life',
94 | long_description=readme,
95 | long_description_content_type='text/markdown',
96 | author='Team Evo 2',
97 | url='https://github.com/arcinstitute/evo2',
98 | )
99 |
--------------------------------------------------------------------------------
/evo2-backend/evo2/test/test_evo2.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import csv
3 | from pathlib import Path
4 | from typing import List, Optional, Union
5 | import numpy as np
6 | import torch
7 | import torch.nn.functional as F
8 |
9 | from evo2 import Evo2
10 |
11 | def read_prompts(input_file: Path) -> Union[List[List[str]]]:
12 | """Read prompts from input file."""
13 | promptseqs: List[str] = []
14 |
15 | with open(input_file, encoding='utf-8-sig', newline='') as csvfile:
16 | reader = csv.reader(csvfile)
17 | next(reader) # Skip header
18 | for row in reader:
19 | promptseqs.append(row[0])
20 |
21 | return promptseqs
22 |
23 | def test_forward_pass(*, model, sequences):
24 | """Test model forward pass accuracy on sequences."""
25 | losses = []
26 | accuracies = []
27 |
28 | for seq in sequences:
29 | # Convert sequence to model input format
30 | input_ids = torch.tensor(model.tokenizer.tokenize(seq), dtype=int).to('cuda:0')
31 |
32 | with torch.inference_mode():
33 | # Forward pass
34 | logits, _ = model.model.forward(input_ids.unsqueeze(0))
35 |
36 | # Calculate loss and accuracy
37 | target_ids = input_ids[1:] # Shift right for next token prediction
38 | pred_logits = logits[0, :-1, :]
39 |
40 | # Cross entropy loss
41 | loss = F.cross_entropy(
42 | pred_logits,
43 | target_ids.long()
44 | )
45 |
46 | # Get predictions
47 | pred_tokens = torch.argmax(pred_logits, dim=-1)
48 |
49 | # Calculate accuracy
50 | accuracy = (target_ids == pred_tokens).float().mean().item()
51 |
52 | losses.append(loss.item())
53 | accuracies.append(accuracy)
54 |
55 | # Print sequence results
56 | print("\nSequence Results:")
57 | for i, (loss, acc) in enumerate(zip(losses, accuracies)):
58 | print(f"Sequence {i+1}: Loss = {loss:.3f}, Accuracy = {acc:.2%}")
59 | if acc < 0.5:
60 | print("WARNING: Forward pass accuracy is below 50% on test sequence. Model may be broken, trained models should have >80% accuracy.")
61 |
62 | return accuracies, losses
63 |
64 | def main():
65 | """
66 | Test sequence prediction accuracy using Evo2 models.
67 | Expected results for forward pass:
68 | - Evo 2 40B 1m: Loss ~0.216, Accuracy ~91.67%
69 | - Evo 2 7B 1m: Loss ~0.348, Accuracy ~86.35%
70 | - Evo 2 1B base: Loss ~0.502, Accuracy ~79.56%
71 | """
72 | parser = argparse.ArgumentParser(description="Test Evo2 Model Forward Pass")
73 | parser.add_argument("--model_name", choices=['evo2_7b', 'evo2_40b', 'evo2_7b_base', 'evo2_40b_base', 'evo2_1b_base'],
74 | default='evo2_7b',
75 | help="Model to test")
76 |
77 | args = parser.parse_args()
78 |
79 | # Set random seeds
80 | torch.manual_seed(1)
81 | torch.cuda.manual_seed(1)
82 |
83 | # Initialize model
84 | model = Evo2(args.model_name)
85 |
86 | # Read sequences
87 | sequences = read_prompts('vortex/test/data/prompts.csv')
88 |
89 | # Test forward pass
90 | accuracies, losses = test_forward_pass(
91 | model=model,
92 | sequences=sequences
93 | )
94 |
95 | # Calculate and validate results
96 | mean_loss = np.mean(losses)
97 | mean_accuracy = np.mean(accuracies) * 100
98 | print(f"\nMean Loss: {mean_loss:.3f}")
99 | print(f"Mean Accuracy: {mean_accuracy:.3f}%")
100 |
101 | # Validate against expected scores
102 | eps = 1e-3 # epsilon for float comparison
103 | expected_metrics = {
104 | 'evo2_40b': {'loss': 0.2159424, 'acc': 91.673},
105 | 'evo2_7b': {'loss': 0.3476563, 'acc': 86.346},
106 | 'evo2_40b_base': {'loss': 0.2149658, 'acc': 91.741},
107 | 'evo2_7b_base': {'loss': 0.3520508, 'acc': 85.921},
108 | 'evo2_1b_base': {'loss': 0.501953125, 'acc': 79.556}
109 | }
110 |
111 | expected = expected_metrics[args.model_name]
112 | if abs(mean_loss - expected['loss']) < eps:
113 | print(f"\nTest Passed! Loss matches expected {expected['loss']:.3f}")
114 | else:
115 | print(f"\nTest Failed: Expected loss {expected['loss']:.3f}, got {mean_loss:.3f}")
116 |
117 | if __name__ == "__main__":
118 | main()
--------------------------------------------------------------------------------
/evo2-backend/evo2/test/test_evo2_generation.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import csv
3 | from pathlib import Path
4 | from typing import List, Optional, Union
5 | import numpy as np
6 | import torch
7 |
8 | from evo2 import Evo2
9 |
10 | def read_prompts(input_file: Path) -> Union[List[List[str]]]:
11 | """Read prompts from input file."""
12 | promptseqs: List[str] = []
13 |
14 | with open(input_file, encoding='utf-8-sig', newline='') as csvfile:
15 | reader = csv.reader(csvfile)
16 | next(reader) # Skip header
17 | for row in reader:
18 | promptseqs.append(row[0])
19 |
20 | return promptseqs
21 |
22 | def mid_point_split(*, seq, num_tokens):
23 | """Split sequence at midpoint for prompt and target."""
24 | mid_point = 2*(len(seq)//4)
25 | prompt = seq[:mid_point]
26 | target = seq[mid_point:mid_point+num_tokens]
27 | return prompt, target
28 |
29 | def calculate_sequence_identity(seq1: str, seq2: str) -> Optional[float]:
30 | """Calculate sequence identity between two sequences through direct comparison."""
31 | if not seq1 or not seq2:
32 | return None
33 |
34 | min_length = min(len(seq1), len(seq2))
35 | matches = sum(a == b for a, b in zip(seq1[:min_length], seq2[:min_length]))
36 | return (matches / min_length) * 100
37 |
38 | def generate_and_score(*, sequences, model, generations_per_prompt=5, n_tokens=500,
39 | temperature=1.0, top_k=1, top_p=1.0):
40 | """Prompt with first half, generate and score on 2nd half."""
41 | scores = []
42 | prompts = []
43 | targets = []
44 |
45 | # Prepare all prompts and targets
46 | for seq in sequences:
47 | prompt, target = mid_point_split(seq=seq, num_tokens=n_tokens)
48 | prompts.extend([prompt] * generations_per_prompt)
49 | targets.extend([target] * generations_per_prompt)
50 |
51 | for i in range(len(prompts)):
52 | prompt = prompts[i]
53 | target = targets[i]
54 |
55 | with torch.inference_mode():
56 | generated = model.generate(
57 | prompt_seqs=[prompt],
58 | n_tokens=n_tokens,
59 | temperature=temperature,
60 | top_k=top_k,
61 | top_p=top_p,
62 | )
63 |
64 | decoded_seq = generated.sequences[0] # Assuming generate returns list of sequences
65 | score = calculate_sequence_identity(decoded_seq, target)
66 | scores.append(score)
67 |
68 | # Reshape scores to group by original sequence
69 | reshaped_scores = [scores[i:i + generations_per_prompt]
70 | for i in range(0, len(scores), generations_per_prompt)]
71 |
72 | return reshaped_scores
73 |
74 | def main():
75 | """
76 | Test sequence generation and scoring using the evo2 models
77 | Expected results (direct comparison w/o alignment):
78 | - Evo 2 40B 1m: 91.15%
79 | - Evo 2 7B 1m: 89.25%
80 | - Evo 2 1B base: 68.0%
81 | """
82 | parser = argparse.ArgumentParser(description="Test Evo2 Model Generation")
83 | parser.add_argument("--model_name", choices=['evo2_7b', 'evo2_40b', 'evo2_1b_base'], default='evo2_7b',
84 | help="Model to test (supports evo2_7b, evo2_40b, evo2_1b_base)")
85 |
86 | args = parser.parse_args()
87 |
88 | # Set random seeds
89 | torch.manual_seed(1)
90 | torch.cuda.manual_seed(1)
91 |
92 | model = Evo2(args.model_name)
93 |
94 | # Test parameters: greedy sampling of 500 tokens
95 | test_params = {
96 | 'n_tokens': 500,
97 | 'temperature': 1.0,
98 | 'top_k': 1,
99 | 'top_p': 1.0,
100 | 'generations_per_prompt': 1,
101 | }
102 |
103 | # Read and process sequences
104 | sequences = read_prompts('vortex/test/data/prompts.csv')
105 | scores = generate_and_score(
106 | sequences=sequences,
107 | model=model,
108 | **test_params
109 | )
110 |
111 | # Calculate and validate results
112 | mean_score = np.mean(scores)
113 | print("\nTest Results:")
114 | print("% Matching Nucleotides:", mean_score)
115 |
116 | # Validate against expected scores
117 | eps = 3 # large epsilon for direct comparison, since there are numeric differences by versions
118 | expected_scores = {
119 | 'evo2_40b': 91.15,
120 | 'evo2_7b': 89.25,
121 | 'evo2_1b_base': 68.0
122 | }
123 |
124 | expected_score = expected_scores[args.model_name]
125 | if abs(mean_score - expected_score) < eps:
126 | print(f"\nTest Passed! Score matches expected {expected_score}%")
127 | else:
128 | print(f"\nTest Failed: Expected {expected_score}%, got {mean_score}%")
129 |
130 | if __name__ == "__main__":
131 | main()
--------------------------------------------------------------------------------
/evo2-backend/main.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | import modal
4 |
5 | from pydantic import BaseModel
6 |
7 | class VariantRequest(BaseModel):
8 | variant_position: int
9 | alternative: str
10 | genome: str
11 | chromosome: str
12 |
13 | evo2_image = (
14 | modal.Image.from_registry(
15 | "nvidia/cuda:12.4.0-devel-ubuntu22.04", add_python="3.12"
16 | )
17 | .apt_install(
18 | ["build-essential", "cmake", "ninja-build",
19 | "libcudnn8", "libcudnn8-dev", "git", "gcc", "g++"]
20 | )
21 | .env({
22 | "CC": "/usr/bin/gcc",
23 | "CXX": "/usr/bin/g++",
24 | })
25 | .run_commands("git clone --recurse-submodules https://github.com/ArcInstitute/evo2.git && cd evo2 && pip install .")
26 | .run_commands("pip uninstall -y transformer-engine transformer_engine")
27 | .run_commands("pip install 'transformer_engine[pytorch]==1.13' --no-build-isolation")
28 | .pip_install_from_requirements("requirements.txt")
29 | )
30 |
31 | app = modal.App("variant-analysis-evo2", image=evo2_image)
32 |
33 | volume = modal.Volume.from_name("hf_cache", create_if_missing=True)
34 | mount_path = "/root/.cache/huggingface"
35 |
36 |
37 | @app.function(gpu="H100", volumes={mount_path: volume}, timeout=1000)
38 | def run_brca1_analysis():
39 | import base64
40 | from io import BytesIO
41 | from Bio import SeqIO
42 | import gzip
43 | import matplotlib.pyplot as plt
44 | import numpy as np
45 | import pandas as pd
46 | import os
47 | import seaborn as sns
48 | from sklearn.metrics import roc_auc_score, roc_curve
49 |
50 | from evo2 import Evo2
51 |
52 | WINDOW_SIZE = 8192
53 |
54 | print("Loading evo2 model...")
55 | model = Evo2('evo2_7b')
56 | print("Evo2 model loaded")
57 |
58 | brca1_df = pd.read_excel(
59 | '/evo2/notebooks/brca1/41586_2018_461_MOESM3_ESM.xlsx',
60 | header=2,
61 | )
62 | brca1_df = brca1_df[[
63 | 'chromosome', 'position (hg19)', 'reference', 'alt', 'function.score.mean', 'func.class',
64 | ]]
65 |
66 | brca1_df.rename(columns={
67 | 'chromosome': 'chrom',
68 | 'position (hg19)': 'pos',
69 | 'reference': 'ref',
70 | 'alt': 'alt',
71 | 'function.score.mean': 'score',
72 | 'func.class': 'class',
73 | }, inplace=True)
74 |
75 | # Convert to two-class system
76 | brca1_df['class'] = brca1_df['class'].replace(['FUNC', 'INT'], 'FUNC/INT')
77 |
78 | with gzip.open('/evo2/notebooks/brca1/GRCh37.p13_chr17.fna.gz', "rt") as handle:
79 | for record in SeqIO.parse(handle, "fasta"):
80 | seq_chr17 = str(record.seq)
81 | break
82 |
83 | # Build mappings of unique reference sequences
84 | ref_seqs = []
85 | ref_seq_to_index = {}
86 |
87 | # Parse sequences and store indexes
88 | ref_seq_indexes = []
89 | var_seqs = []
90 |
91 | brca1_subset = brca1_df.iloc[:500].copy()
92 |
93 | for _, row in brca1_subset.iterrows():
94 | p = row["pos"] - 1 # Convert to 0-indexed position
95 | full_seq = seq_chr17
96 |
97 | ref_seq_start = max(0, p - WINDOW_SIZE//2)
98 | ref_seq_end = min(len(full_seq), p + WINDOW_SIZE//2)
99 | ref_seq = seq_chr17[ref_seq_start:ref_seq_end]
100 | snv_pos_in_ref = min(WINDOW_SIZE//2, p)
101 | var_seq = ref_seq[:snv_pos_in_ref] + \
102 | row["alt"] + ref_seq[snv_pos_in_ref+1:]
103 |
104 | # Get or create index for reference sequence
105 | if ref_seq not in ref_seq_to_index:
106 | ref_seq_to_index[ref_seq] = len(ref_seqs)
107 | ref_seqs.append(ref_seq)
108 |
109 | ref_seq_indexes.append(ref_seq_to_index[ref_seq])
110 | var_seqs.append(var_seq)
111 |
112 | ref_seq_indexes = np.array(ref_seq_indexes)
113 |
114 | print(
115 | f'Scoring likelihoods of {len(ref_seqs)} reference sequences with Evo 2...')
116 | ref_scores = model.score_sequences(ref_seqs)
117 |
118 | print(
119 | f'Scoring likelihoods of {len(var_seqs)} variant sequences with Evo 2...')
120 | var_scores = model.score_sequences(var_seqs)
121 |
122 | # Subtract score of corresponding reference sequences from scores of variant sequences
123 | delta_scores = np.array(var_scores) - np.array(ref_scores)[ref_seq_indexes]
124 |
125 | # Add delta scores to dataframe
126 | brca1_subset[f'evo2_delta_score'] = delta_scores
127 |
128 | y_true = (brca1_subset['class'] == 'LOF')
129 | auroc = roc_auc_score(y_true, -brca1_subset['evo2_delta_score'])
130 |
131 | # --- Calculate threshold START
132 | y_true = (brca1_subset["class"] == "LOF")
133 |
134 | fpr, tpr, thresholds = roc_curve(y_true, -brca1_subset["evo2_delta_score"])
135 |
136 | optimal_idx = (tpr - fpr).argmax()
137 |
138 | optimal_threshold = -thresholds[optimal_idx]
139 |
140 | lof_scores = brca1_subset.loc[brca1_subset["class"]
141 | == "LOF", "evo2_delta_score"]
142 | func_scores = brca1_subset.loc[brca1_subset["class"]
143 | == "FUNC/INT", "evo2_delta_score"]
144 |
145 | lof_std = lof_scores.std()
146 | func_std = func_scores.std()
147 |
148 | confidence_params = {
149 | "threshold": optimal_threshold,
150 | "lof_std": lof_std,
151 | "func_std": func_std
152 | }
153 |
154 | print("Confidence params:", confidence_params)
155 |
156 | # --- Calculate threshold END
157 |
158 | plt.figure(figsize=(4, 2))
159 |
160 | # Plot stripplot of distributions
161 | p = sns.stripplot(
162 | data=brca1_subset,
163 | x='evo2_delta_score',
164 | y='class',
165 | hue='class',
166 | order=['FUNC/INT', 'LOF'],
167 | palette=['#777777', 'C3'],
168 | size=2,
169 | jitter=0.3,
170 | )
171 |
172 | # Mark medians from each distribution
173 | sns.boxplot(showmeans=True,
174 | meanline=True,
175 | meanprops={'visible': False},
176 | medianprops={'color': 'k', 'ls': '-', 'lw': 2},
177 | whiskerprops={'visible': False},
178 | zorder=10,
179 | x="evo2_delta_score",
180 | y="class",
181 | data=brca1_subset,
182 | showfliers=False,
183 | showbox=False,
184 | showcaps=False,
185 | ax=p)
186 | plt.xlabel('Delta likelihood score, Evo 2')
187 | plt.ylabel('BRCA1 SNV class')
188 | plt.tight_layout()
189 |
190 | buffer = BytesIO()
191 | plt.savefig(buffer, format="png")
192 | buffer.seek(0)
193 | plot_data = base64.b64encode(buffer.getvalue()).decode("utf-8")
194 |
195 | return {'variants': brca1_subset.to_dict(orient="records"), "plot": plot_data, "auroc": auroc}
196 |
197 |
198 | @app.function()
199 | def brca1_example():
200 | import base64
201 | from io import BytesIO
202 | import matplotlib.pyplot as plt
203 | import matplotlib.image as mpimg
204 |
205 | print("Running BRCA1 variant analysis with Evo2...")
206 |
207 | # Run inference
208 | result = run_brca1_analysis.remote()
209 |
210 | if "plot" in result:
211 | plot_data = base64.b64decode(result["plot"])
212 | with open("brca1_analysis_plot.png", "wb") as f:
213 | f.write(plot_data)
214 |
215 | img = mpimg.imread(BytesIO(plot_data))
216 | plt.figure(figsize=(10, 5))
217 | plt.imshow(img)
218 | plt.axis("off")
219 | plt.show()
220 |
221 |
222 | def get_genome_sequence(position, genome: str, chromosome: str, window_size=8192):
223 | import requests
224 |
225 | half_window = window_size // 2
226 | start = max(0, position - 1 - half_window)
227 | end = position - 1 + half_window + 1
228 |
229 | print(
230 | f"Fetching {window_size}bp window around position {position} from UCSC API..")
231 | print(f"Coordinates: {chromosome}:{start}-{end} ({genome})")
232 |
233 | api_url = f"https://api.genome.ucsc.edu/getData/sequence?genome={genome};chrom={chromosome};start={start};end={end}"
234 | response = requests.get(api_url)
235 |
236 | if response.status_code != 200:
237 | raise Exception(
238 | f"Failed to fetch genome sequence from UCSC API: {response.status_code}")
239 |
240 | genome_data = response.json()
241 |
242 | if "dna" not in genome_data:
243 | error = genome_data.get("error", "Unknown error")
244 | raise Exception(f"UCSC API errpr: {error}")
245 |
246 | sequence = genome_data.get("dna", "").upper()
247 | expected_length = end - start
248 | if len(sequence) != expected_length:
249 | print(
250 | f"Warning: received sequence length ({len(sequence)}) differs from expected ({expected_length})")
251 |
252 | print(
253 | f"Loaded reference genome sequence window (length: {len(sequence)} bases)")
254 |
255 | return sequence, start
256 |
257 |
258 | def analyze_variant(relative_pos_in_window, reference, alternative, window_seq, model):
259 | var_seq = window_seq[:relative_pos_in_window] + \
260 | alternative + window_seq[relative_pos_in_window+1:]
261 |
262 | ref_score = model.score_sequences([window_seq])[0]
263 | var_score = model.score_sequences([var_seq])[0]
264 |
265 | delta_score = var_score - ref_score
266 |
267 | threshold = -0.0009178519
268 | lof_std = 0.0015140239
269 | func_std = 0.0009016589
270 |
271 | if delta_score < threshold:
272 | prediction = "Likely pathogenic"
273 | confidence = min(1.0, abs(delta_score - threshold) / lof_std)
274 | else:
275 | prediction = "Likely benign"
276 | confidence = min(1.0, abs(delta_score - threshold) / func_std)
277 |
278 | return {
279 | "reference": reference,
280 | "alternative": alternative,
281 | "delta_score": float(delta_score),
282 | "prediction": prediction,
283 | "classification_confidence": float(confidence)
284 | }
285 |
286 |
287 | @app.cls(gpu="H100", volumes={mount_path: volume}, max_containers=3, retries=2, scaledown_window=120)
288 | class Evo2Model:
289 | @modal.enter()
290 | def load_evo2_model(self):
291 | from evo2 import Evo2
292 | print("Loading evo2 model...")
293 | self.model = Evo2('evo2_7b')
294 | print("Evo2 model loaded")
295 |
296 | # @modal.method()
297 | @modal.fastapi_endpoint(method="POST")
298 | def analyze_single_variant(self, request: VariantRequest):
299 | variant_position = request.variant_position
300 | alternative = request.alternative
301 | genome = request.genome
302 | chromosome = request.chromosome
303 |
304 | print("Genome:", genome)
305 | print("Chromosome:", chromosome)
306 | print("Variant position:", variant_position)
307 | print("Variant alternative:", alternative)
308 |
309 | WINDOW_SIZE = 8192
310 |
311 | window_seq, seq_start = get_genome_sequence(
312 | position=variant_position,
313 | genome=genome,
314 | chromosome=chromosome,
315 | window_size=WINDOW_SIZE
316 | )
317 |
318 | print(f"Fetched genome seauence window, first 100: {window_seq[:100]}")
319 |
320 | relative_pos = variant_position - 1 - seq_start
321 | print(f"Relative position within window: {relative_pos}")
322 |
323 | if relative_pos < 0 or relative_pos >= len(window_seq):
324 | raise ValueError(
325 | f"Variant position {variant_position} is outside the fetched window (start={seq_start+1}, end={seq_start+len(window_seq)})")
326 |
327 | reference = window_seq[relative_pos]
328 | print("Reference is: " + reference)
329 |
330 | # Analyze the variant
331 | result = analyze_variant(
332 | relative_pos_in_window=relative_pos,
333 | reference=reference,
334 | alternative=alternative,
335 | window_seq=window_seq,
336 | model=self.model
337 | )
338 |
339 | result["position"] = variant_position
340 |
341 | return result
342 |
343 |
344 | @app.local_entrypoint()
345 | def main():
346 | # Example of how you'd call the deployed Modal Function from your client
347 | import requests
348 | import json # brca1_example.remote()
349 |
350 | evo2Model = Evo2Model()
351 |
352 | url = evo2Model.analyze_single_variant.web_url
353 |
354 | payload = {
355 | "variant_position": 43119628,
356 | "alternative": "G",
357 | "genome": "hg38",
358 | "chromosome": "chr17"
359 | }
360 |
361 | headers = {
362 | "Content-Type": "application/json"
363 | }
364 |
365 | response = requests.post(url, json=payload, headers=headers)
366 | response.raise_for_status()
367 | result = response.json()
368 | print(result)
369 |
--------------------------------------------------------------------------------
/evo2-backend/requirements.txt:
--------------------------------------------------------------------------------
1 | fastapi[standard]
2 | modal
3 | matplotlib
4 | pandas
5 | seaborn
6 | scikit-learn
7 | openpyxl
--------------------------------------------------------------------------------
/evo2-frontend/.env.example:
--------------------------------------------------------------------------------
1 | # Since the ".env" file is gitignored, you can use the ".env.example" file to
2 | # build a new ".env" file when you clone the repo. Keep this file up-to-date
3 | # when you add new variables to `.env`.
4 |
5 | # This file will be committed to version control, so make sure not to have any
6 | # secrets in it. If you are cloning this repo, create a copy of this file named
7 | # ".env" and populate it with your secrets.
8 |
9 | # When adding additional environment variables, the schema in "/src/env.js"
10 | # should be updated accordingly.
11 |
12 | # Example:
13 | # SERVERVAR="foo"
14 | # NEXT_PUBLIC_CLIENTVAR="bar"
15 |
--------------------------------------------------------------------------------
/evo2-frontend/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # database
12 | /prisma/db.sqlite
13 | /prisma/db.sqlite-journal
14 | db.sqlite
15 |
16 | # next.js
17 | /.next/
18 | /out/
19 | next-env.d.ts
20 |
21 | # production
22 | /build
23 |
24 | # misc
25 | .DS_Store
26 | *.pem
27 |
28 | # debug
29 | npm-debug.log*
30 | yarn-debug.log*
31 | yarn-error.log*
32 | .pnpm-debug.log*
33 |
34 | # local env files
35 | # do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables
36 | .env
37 | .env*.local
38 |
39 | # vercel
40 | .vercel
41 |
42 | # typescript
43 | *.tsbuildinfo
44 |
45 | # idea files
46 | .idea
--------------------------------------------------------------------------------
/evo2-frontend/README.md:
--------------------------------------------------------------------------------
1 | # Create T3 App
2 |
3 | This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`.
4 |
5 | ## What's next? How do I make an app with this?
6 |
7 | We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary.
8 |
9 | If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help.
10 |
11 | - [Next.js](https://nextjs.org)
12 | - [NextAuth.js](https://next-auth.js.org)
13 | - [Prisma](https://prisma.io)
14 | - [Drizzle](https://orm.drizzle.team)
15 | - [Tailwind CSS](https://tailwindcss.com)
16 | - [tRPC](https://trpc.io)
17 |
18 | ## Learn More
19 |
20 | To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources:
21 |
22 | - [Documentation](https://create.t3.gg/)
23 | - [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials
24 |
25 | You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome!
26 |
27 | ## How do I deploy this?
28 |
29 | Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel), [Netlify](https://create.t3.gg/en/deployment/netlify) and [Docker](https://create.t3.gg/en/deployment/docker) for more information.
30 |
--------------------------------------------------------------------------------
/evo2-frontend/components.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://ui.shadcn.com/schema.json",
3 | "style": "new-york",
4 | "rsc": true,
5 | "tsx": true,
6 | "tailwind": {
7 | "config": "",
8 | "css": "src/styles/globals.css",
9 | "baseColor": "neutral",
10 | "cssVariables": true,
11 | "prefix": ""
12 | },
13 | "aliases": {
14 | "components": "~/components",
15 | "utils": "~/lib/utils",
16 | "ui": "~/components/ui",
17 | "lib": "~/lib",
18 | "hooks": "~/hooks"
19 | },
20 | "iconLibrary": "lucide"
21 | }
--------------------------------------------------------------------------------
/evo2-frontend/eslint.config.js:
--------------------------------------------------------------------------------
1 | import { FlatCompat } from "@eslint/eslintrc";
2 | import tseslint from "typescript-eslint";
3 |
4 | const compat = new FlatCompat({
5 | baseDirectory: import.meta.dirname,
6 | });
7 |
8 | export default tseslint.config(
9 | {
10 | ignores: [".next"],
11 | },
12 | ...compat.extends("next/core-web-vitals"),
13 | {
14 | files: ["**/*.ts", "**/*.tsx"],
15 | extends: [
16 | ...tseslint.configs.recommended,
17 | ...tseslint.configs.recommendedTypeChecked,
18 | ...tseslint.configs.stylisticTypeChecked,
19 | ],
20 | rules: {
21 | "@typescript-eslint/array-type": "off",
22 | "@typescript-eslint/consistent-type-definitions": "off",
23 | "@typescript-eslint/consistent-type-imports": [
24 | "warn",
25 | { prefer: "type-imports", fixStyle: "inline-type-imports" },
26 | ],
27 | "@typescript-eslint/no-unused-vars": [
28 | "warn",
29 | { argsIgnorePattern: "^_" },
30 | ],
31 | "@typescript-eslint/require-await": "off",
32 | "@typescript-eslint/no-misused-promises": [
33 | "error",
34 | { checksVoidReturn: { attributes: false } },
35 | ],
36 | },
37 | },
38 | {
39 | linterOptions: {
40 | reportUnusedDisableDirectives: true,
41 | },
42 | languageOptions: {
43 | parserOptions: {
44 | projectService: true,
45 | },
46 | },
47 | },
48 | );
49 |
--------------------------------------------------------------------------------
/evo2-frontend/next.config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially useful
3 | * for Docker builds.
4 | */
5 | import "./src/env.js";
6 |
7 | /** @type {import("next").NextConfig} */
8 | const config = {
9 | reactStrictMode: false,
10 | };
11 |
12 | export default config;
13 |
--------------------------------------------------------------------------------
/evo2-frontend/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "variant-analysis-evo2-frontend",
3 | "version": "0.1.0",
4 | "private": true,
5 | "type": "module",
6 | "scripts": {
7 | "build": "next build",
8 | "check": "next lint && tsc --noEmit",
9 | "dev": "next dev --turbo",
10 | "format:check": "prettier --check \"**/*.{ts,tsx,js,jsx,mdx}\" --cache",
11 | "format:write": "prettier --write \"**/*.{ts,tsx,js,jsx,mdx}\" --cache",
12 | "lint": "next lint",
13 | "lint:fix": "next lint --fix",
14 | "preview": "next build && next start",
15 | "start": "next start",
16 | "typecheck": "tsc --noEmit"
17 | },
18 | "dependencies": {
19 | "@radix-ui/react-select": "^2.2.2",
20 | "@radix-ui/react-slot": "^1.2.0",
21 | "@radix-ui/react-tabs": "^1.1.8",
22 | "@t3-oss/env-nextjs": "^0.12.0",
23 | "class-variance-authority": "^0.7.1",
24 | "clsx": "^2.1.1",
25 | "lucide-react": "^0.501.0",
26 | "next": "^15.2.3",
27 | "react": "^19.0.0",
28 | "react-dom": "^19.0.0",
29 | "tailwind-merge": "^3.2.0",
30 | "zod": "^3.24.2"
31 | },
32 | "devDependencies": {
33 | "@eslint/eslintrc": "^3.3.1",
34 | "@tailwindcss/postcss": "^4.0.15",
35 | "@types/node": "^20.14.10",
36 | "@types/react": "^19.0.0",
37 | "@types/react-dom": "^19.0.0",
38 | "eslint": "^9.23.0",
39 | "eslint-config-next": "^15.2.3",
40 | "postcss": "^8.5.3",
41 | "prettier": "^3.5.3",
42 | "prettier-plugin-tailwindcss": "^0.6.11",
43 | "tailwindcss": "^4.0.15",
44 | "tw-animate-css": "^1.2.5",
45 | "typescript": "^5.8.2",
46 | "typescript-eslint": "^8.27.0"
47 | },
48 | "ct3aMetadata": {
49 | "initVersion": "7.39.3"
50 | },
51 | "packageManager": "npm@10.2.4"
52 | }
53 |
--------------------------------------------------------------------------------
/evo2-frontend/postcss.config.js:
--------------------------------------------------------------------------------
1 | export default {
2 | plugins: {
3 | "@tailwindcss/postcss": {},
4 | },
5 | };
6 |
--------------------------------------------------------------------------------
/evo2-frontend/prettier.config.js:
--------------------------------------------------------------------------------
1 | /** @type {import('prettier').Config & import('prettier-plugin-tailwindcss').PluginOptions} */
2 | export default {
3 | plugins: ["prettier-plugin-tailwindcss"],
4 | };
5 |
--------------------------------------------------------------------------------
/evo2-frontend/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Andreaswt/variant-analysis-evo2/55741e31ae0bf3327cc97202be842f37e3fd7e6e/evo2-frontend/public/favicon.ico
--------------------------------------------------------------------------------
/evo2-frontend/src/app/layout.tsx:
--------------------------------------------------------------------------------
1 | import "~/styles/globals.css";
2 |
3 | import { type Metadata } from "next";
4 | import { Geist } from "next/font/google";
5 |
6 | export const metadata: Metadata = {
7 | title: "Evo2 Variant Analysis",
8 | description: "Evo2 Variant Analysis",
9 | icons: [{ rel: "icon", url: "/favicon.ico" }],
10 | };
11 |
12 | const geist = Geist({
13 | subsets: ["latin"],
14 | variable: "--font-geist-sans",
15 | });
16 |
17 | export default function RootLayout({
18 | children,
19 | }: Readonly<{ children: React.ReactNode }>) {
20 | return (
21 |
22 |
{children}
23 |
24 | );
25 | }
26 |
--------------------------------------------------------------------------------
/evo2-frontend/src/app/page.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 |
3 | import { Clapperboard, Search, SearchCodeIcon } from "lucide-react";
4 | import { useEffect, useState } from "react";
5 | import GeneViewer from "~/components/gene-viewer";
6 | import { Button } from "~/components/ui/button";
7 | import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
8 | import { Input } from "~/components/ui/input";
9 | import {
10 | Select,
11 | SelectContent,
12 | SelectItem,
13 | SelectTrigger,
14 | SelectValue,
15 | } from "~/components/ui/select";
16 | import {
17 | Table,
18 | TableBody,
19 | TableCell,
20 | TableHead,
21 | TableHeader,
22 | TableRow,
23 | } from "~/components/ui/table";
24 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
25 | import {
26 | type ChromosomeFromSeach,
27 | type GeneFromSearch,
28 | type GenomeAssemblyFromSearch,
29 | getAvailableGenomes,
30 | getGenomeChromosomes,
31 | searchGenes,
32 | } from "~/utils/genome-api";
33 |
34 | type Mode = "browse" | "search";
35 |
36 | export default function HomePage() {
37 | const [genomes, setGenomes] = useState([]);
38 | const [selectedGenome, setSelectedGenome] = useState("hg38");
39 | const [chromosomes, setChromosomes] = useState([]);
40 | const [selectedChromosome, setSelectedChromosome] = useState("chr1");
41 | const [selectedGene, setSelectedGene] = useState(null);
42 | const [searchQuery, setSearchQuery] = useState("");
43 | const [searchResults, setSearchResults] = useState([]);
44 | const [isLoading, setIsLoading] = useState(false);
45 | const [error, setError] = useState(null);
46 | const [mode, setMode] = useState("search");
47 |
48 | useEffect(() => {
49 | const fetchGenomes = async () => {
50 | try {
51 | setIsLoading(true);
52 | const data = await getAvailableGenomes();
53 | if (data.genomes && data.genomes["Human"]) {
54 | setGenomes(data.genomes["Human"]);
55 | }
56 | } catch (err) {
57 | setError("Failed to load genome data");
58 | } finally {
59 | setIsLoading(false);
60 | }
61 | };
62 | fetchGenomes();
63 | }, []);
64 |
65 | useEffect(() => {
66 | const fetchChromosomes = async () => {
67 | try {
68 | setIsLoading(true);
69 | const data = await getGenomeChromosomes(selectedGenome);
70 | setChromosomes(data.chromosomes);
71 | console.log(data.chromosomes);
72 | if (data.chromosomes.length > 0) {
73 | setSelectedChromosome(data.chromosomes[0]!.name);
74 | }
75 | } catch (err) {
76 | setError("Failed to load chromosome data");
77 | } finally {
78 | setIsLoading(false);
79 | }
80 | };
81 | fetchChromosomes();
82 | }, [selectedGenome]);
83 |
84 | const performGeneSearch = async (
85 | query: string,
86 | genome: string,
87 | filterFn?: (gene: GeneFromSearch) => boolean,
88 | ) => {
89 | try {
90 | setIsLoading(true);
91 | const data = await searchGenes(query, genome);
92 | const results = filterFn ? data.results.filter(filterFn) : data.results;
93 |
94 | setSearchResults(results);
95 | } catch (err) {
96 | setError("Faield to search genes");
97 | } finally {
98 | setIsLoading(false);
99 | }
100 | };
101 |
102 | useEffect(() => {
103 | if (!selectedChromosome || mode !== "browse") return;
104 | performGeneSearch(
105 | selectedChromosome,
106 | selectedGenome,
107 | (gene: GeneFromSearch) => gene.chrom === selectedChromosome,
108 | );
109 | }, [selectedChromosome, selectedGenome, mode]);
110 |
111 | const handleGenomeChange = (value: string) => {
112 | setSelectedGenome(value);
113 | setSearchResults([]);
114 | setSelectedGene(null);
115 | };
116 |
117 | const switchMode = (newMode: Mode) => {
118 | if (newMode === mode) return;
119 |
120 | setSearchResults([]);
121 | setSelectedGene(null);
122 | setError(null);
123 |
124 | if (newMode === "browse" && selectedChromosome) {
125 | performGeneSearch(
126 | selectedChromosome,
127 | selectedGenome,
128 | (gene: GeneFromSearch) => gene.chrom === selectedChromosome,
129 | );
130 | }
131 |
132 | setMode(newMode);
133 | };
134 |
135 | const handleSearch = async (e?: React.FormEvent) => {
136 | if (e) e.preventDefault();
137 | if (!searchQuery.trim()) return;
138 |
139 | performGeneSearch(searchQuery, selectedGenome);
140 | };
141 |
142 | const loadBRCA1Example = () => {
143 | setMode("search");
144 | setSearchQuery("BRCA1");
145 | performGeneSearch("BRCA1", selectedGenome);
146 | };
147 |
148 | return (
149 |
150 |
151 |
152 |
153 |
154 |
155 | EVO
156 | 2
157 |
158 |
159 |
160 |
161 | Variant Analysis
162 |
163 |
164 |
165 |
166 |
167 |
168 | {selectedGene ? (
169 | setSelectedGene(null)}
173 | />
174 | ) : (
175 | <>
176 |
177 |
178 |
179 |
180 | Genome Assembly
181 |
182 |
183 | Organism: Human
184 |
185 |
186 |
187 |
188 |
193 |
194 |
195 |
196 |
197 | {genomes.map((genome) => (
198 |
199 | {genome.id} - {genome.name}
200 | {genome.active ? " (active)" : ""}
201 |
202 | ))}
203 |
204 |
205 | {selectedGenome && (
206 |
207 | {
208 | genomes.find((genome) => genome.id === selectedGenome)
209 | ?.sourceName
210 | }
211 |
212 | )}
213 |
214 |
215 |
216 |
217 |
218 |
219 | Browse
220 |
221 |
222 |
223 | switchMode(value as Mode)}
226 | >
227 |
228 |
232 | Search Genes
233 |
234 |
238 | Browse Chromosomes
239 |
240 |
241 |
242 |
243 |
244 |
267 |
272 | Try BRCA1 example
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 | {chromosomes.map((chrom) => (
281 | setSelectedChromosome(chrom.name)}
287 | >
288 | {chrom.name}
289 |
290 | ))}
291 |
292 |
293 |
294 |
295 |
296 | {isLoading && (
297 |
300 | )}
301 |
302 | {error && (
303 |
304 | {error}
305 |
306 | )}
307 |
308 | {searchResults.length > 0 && !isLoading && (
309 |
310 |
311 |
312 | {mode === "search" ? (
313 | <>
314 | Search Results:{" "}
315 |
316 | {searchResults.length} genes
317 |
318 | >
319 | ) : (
320 | <>
321 | Genes on {selectedChromosome}:{" "}
322 |
323 | {searchResults.length} found
324 |
325 | >
326 | )}
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 | Symbol
336 |
337 |
338 | Name
339 |
340 |
341 | Location
342 |
343 |
344 |
345 |
346 | {searchResults.map((gene, index) => (
347 | setSelectedGene(gene)}
351 | >
352 |
353 | {gene.symbol}
354 |
355 |
356 | {gene.name}
357 |
358 |
359 | {gene.chrom}
360 |
361 |
362 | ))}
363 |
364 |
365 |
366 |
367 | )}
368 |
369 | {!isLoading && !error && searchResults.length === 0 && (
370 |
371 |
372 |
373 | {mode === "search"
374 | ? "Enter a gene or symbol and click search"
375 | : selectedChromosome
376 | ? "No genes found on this chromosome"
377 | : "Select a chromosome to view genes"}
378 |
379 |
380 | )}
381 |
382 |
383 | >
384 | )}
385 |
386 |
387 | );
388 | }
389 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/gene-information.tsx:
--------------------------------------------------------------------------------
1 | import type {
2 | GeneBounds,
3 | GeneDetailsFromSearch,
4 | GeneFromSearch,
5 | } from "~/utils/genome-api";
6 | import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
7 | import { ExternalLink } from "lucide-react";
8 |
9 | export function GeneInformation({
10 | gene,
11 | geneDetail,
12 | geneBounds,
13 | }: {
14 | gene: GeneFromSearch;
15 | geneDetail: GeneDetailsFromSearch | null;
16 | geneBounds: GeneBounds | null;
17 | }) {
18 | return (
19 |
20 |
21 |
22 | Gene Information
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | Symbol:
31 |
32 | {gene.symbol}
33 |
34 |
35 |
36 | Name:
37 |
38 | {gene.name}
39 |
40 | {gene.description && gene.description !== gene.name && (
41 |
42 |
43 | Description:
44 |
45 | {gene.description}
46 |
47 | )}
48 |
49 |
50 | Chromosome:
51 |
52 | {gene.chrom}
53 |
54 | {geneBounds && (
55 |
56 |
57 | Position:
58 |
59 |
60 | {Math.min(geneBounds.min, geneBounds.max).toLocaleString()} -{" "}
61 | {Math.max(geneBounds.min, geneBounds.max).toLocaleString()} (
62 | {Math.abs(
63 | geneBounds.max - geneBounds.min + 1,
64 | ).toLocaleString()}{" "}
65 | bp)
66 | {geneDetail?.genomicinfo?.[0]?.strand === "-" &&
67 | " (reverse strand)"}
68 |
69 |
70 | )}
71 |
72 |
73 | {gene.gene_id && (
74 |
89 | )}
90 | {geneDetail?.organism && (
91 |
92 |
93 | Organism:
94 |
95 |
96 | {geneDetail.organism.scientificname}{" "}
97 | {geneDetail.organism.commonname &&
98 | ` (${geneDetail.organism.commonname})`}
99 |
100 |
101 | )}
102 |
103 | {geneDetail?.summary && (
104 |
105 |
106 | Summary:
107 |
108 |
109 | {geneDetail.summary}
110 |
111 |
112 | )}
113 |
114 |
115 |
116 |
117 | );
118 | }
119 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/gene-sequence.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 |
3 | import type { GeneBounds, GeneDetailsFromSearch } from "~/utils/genome-api";
4 | import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
5 | import {
6 | startTransition,
7 | useCallback,
8 | useEffect,
9 | useMemo,
10 | useRef,
11 | useState,
12 | type JSX,
13 | } from "react";
14 | import { Input } from "./ui/input";
15 | import { Button } from "./ui/button";
16 | import { getNucleotideColorClass } from "~/utils/coloring-utils";
17 |
18 | export function GeneSequence({
19 | geneBounds,
20 | geneDetail,
21 | startPosition,
22 | endPosition,
23 | onStartPositionChange,
24 | onEndPositionChange,
25 | sequenceData,
26 | sequenceRange,
27 | isLoading,
28 | error,
29 | onSequenceLoadRequest,
30 | onSequenceClick,
31 | maxViewRange,
32 | }: {
33 | geneBounds: GeneBounds | null;
34 | geneDetail: GeneDetailsFromSearch | null;
35 | startPosition: string;
36 | endPosition: string;
37 | onStartPositionChange: (value: string) => void;
38 | onEndPositionChange: (value: string) => void;
39 | sequenceData: string;
40 | sequenceRange: { start: number; end: number } | null;
41 | isLoading: boolean;
42 | error: string | null;
43 | onSequenceLoadRequest: () => void;
44 | onSequenceClick: (position: number, nucleotide: string) => void;
45 | maxViewRange: number;
46 | }) {
47 | const [sliderValues, setSliderValues] = useState({ start: 60, end: 70 });
48 | const [isDraggingStart, setIsDraggingStart] = useState(false);
49 | const [isDraggingEnd, setIsDraggingEnd] = useState(false);
50 | const [isDraggingRange, setIsDraggingRange] = useState(false);
51 | const sliderRef = useRef(null);
52 | const dragStartX = useRef<{
53 | x: number;
54 | startPos: number;
55 | endPos: number;
56 | } | null>(null);
57 | const [hoverPosition, setHoverPosition] = useState(null);
58 | const [mousePosition, setMousePosition] = useState<{
59 | x: number;
60 | y: number;
61 | } | null>(null);
62 |
63 | const currentRangeSize = useMemo(() => {
64 | const start = parseInt(startPosition);
65 | const end = parseInt(endPosition);
66 | return isNaN(start) || isNaN(end) || end < start ? 0 : end - start + 1;
67 | }, [startPosition, endPosition]);
68 |
69 | useEffect(() => {
70 | if (!geneBounds) return;
71 |
72 | const minBound = Math.min(geneBounds.min, geneBounds.max);
73 | const maxBound = Math.max(geneBounds.min, geneBounds.max);
74 | const totalSize = maxBound - minBound;
75 |
76 | const startNum = parseInt(startPosition);
77 | const endNum = parseInt(endPosition);
78 |
79 | if (isNaN(startNum) || isNaN(endNum) || totalSize <= 0) {
80 | setSliderValues({ start: 0, end: 100 });
81 | return;
82 | }
83 |
84 | const startPercent = ((startNum - minBound) / totalSize) * 100;
85 | const endPercent = ((endNum - minBound) / totalSize) * 100;
86 |
87 | setSliderValues({
88 | start: Math.max(0, Math.min(startPercent, 100)),
89 | end: Math.max(0, Math.min(endPercent, 100)),
90 | });
91 | }, [startPosition, endPosition, geneBounds]);
92 |
93 | useEffect(() => {
94 | const handleMouseMove = (e: MouseEvent) => {
95 | if (!isDraggingStart && !isDraggingEnd && !isDraggingRange) return;
96 | if (!sliderRef.current || !geneBounds) return;
97 |
98 | const sliderRect = sliderRef.current.getBoundingClientRect();
99 | const relativeX = e.clientX - sliderRect.left;
100 | const sliderWidth = sliderRect.width;
101 | let newPercent = (relativeX / sliderWidth) * 100;
102 | newPercent = Math.max(0, Math.min(newPercent, 100));
103 |
104 | const minBound = Math.min(geneBounds.min, geneBounds.max);
105 | const maxBound = Math.max(geneBounds.min, geneBounds.max);
106 | const geneSize = maxBound - minBound;
107 |
108 | const newPosition = Math.round(minBound + (geneSize * newPercent) / 100);
109 | const currentStartNum = parseInt(startPosition);
110 | const currentEndNum = parseInt(endPosition);
111 |
112 | if (isDraggingStart) {
113 | if (!isNaN(currentEndNum)) {
114 | if (currentEndNum - newPosition + 1 > maxViewRange) {
115 | onStartPositionChange(String(currentEndNum - maxViewRange + 1));
116 | } else if (newPosition < currentEndNum) {
117 | onStartPositionChange(String(newPosition));
118 | }
119 | }
120 | } else if (isDraggingEnd) {
121 | if (!isNaN(currentStartNum)) {
122 | if (newPosition - currentStartNum + 1 > maxViewRange) {
123 | onEndPositionChange(String(currentStartNum + maxViewRange - 1));
124 | } else if (newPosition > currentStartNum) {
125 | onEndPositionChange(String(newPosition));
126 | }
127 | }
128 | } else if (isDraggingRange) {
129 | if (!dragStartX.current) return;
130 | const pixelsPerBase = sliderWidth / geneSize;
131 | const dragDeltaPixels = relativeX - dragStartX.current.x;
132 | const dragDeltaBases = Math.round(dragDeltaPixels / pixelsPerBase);
133 |
134 | let newStart = dragStartX.current.startPos + dragDeltaBases;
135 | let newEnd = dragStartX.current.endPos + dragDeltaBases;
136 | const rangeSize =
137 | dragStartX.current.endPos - dragStartX.current.startPos;
138 |
139 | if (newStart < minBound) {
140 | newStart = minBound;
141 | newEnd = minBound + rangeSize;
142 | }
143 | if (newEnd > maxBound) {
144 | newEnd = maxBound;
145 | newStart = maxBound - rangeSize;
146 | }
147 |
148 | onStartPositionChange(String(newStart));
149 | onEndPositionChange(String(newEnd));
150 | }
151 | };
152 |
153 | const handleMouseUp = () => {
154 | if (
155 | (isDraggingStart || isDraggingEnd || isDraggingRange) &&
156 | startPosition &&
157 | endPosition
158 | ) {
159 | onSequenceLoadRequest();
160 | }
161 | setIsDraggingStart(false);
162 | setIsDraggingEnd(false);
163 | setIsDraggingRange(false);
164 | dragStartX.current = null;
165 | };
166 |
167 | window.addEventListener("mousemove", handleMouseMove);
168 | window.addEventListener("mouseup", handleMouseUp);
169 | return () => {
170 | window.removeEventListener("mousemove", handleMouseMove);
171 | window.removeEventListener("mouseup", handleMouseUp);
172 | };
173 | }, [
174 | isDraggingStart,
175 | isDraggingEnd,
176 | isDraggingRange,
177 | geneBounds,
178 | startPosition,
179 | endPosition,
180 | onStartPositionChange,
181 | onEndPositionChange,
182 | maxViewRange,
183 | onSequenceLoadRequest,
184 | ]);
185 |
186 | const handleMouseDown = useCallback(
187 | (e: React.MouseEvent, handle: "start" | "end") => {
188 | e.preventDefault();
189 | if (handle === "start") setIsDraggingStart(true);
190 | else setIsDraggingEnd(true);
191 | },
192 | [],
193 | );
194 |
195 | const handleRangeMouseDown = useCallback(
196 | (e: React.MouseEvent) => {
197 | e.preventDefault();
198 |
199 | if (!sliderRef.current) return;
200 |
201 | const startNum = parseInt(startPosition);
202 | const endNum = parseInt(endPosition);
203 | if (isNaN(startNum) || isNaN(endNum)) return;
204 |
205 | setIsDraggingRange(true);
206 | const sliderRect = sliderRef.current.getBoundingClientRect();
207 | const relativeX = e.clientX - sliderRect.left;
208 | dragStartX.current = {
209 | x: relativeX,
210 | startPos: startNum,
211 | endPos: endNum,
212 | };
213 | },
214 | [startPosition, endPosition],
215 | );
216 |
217 | const formattedSequence = useMemo(() => {
218 | if (!sequenceData || !sequenceRange) return null;
219 |
220 | const start = sequenceRange.start;
221 | const BASES_PER_LINE = 200;
222 | const lines: JSX.Element[] = [];
223 |
224 | for (let i = 0; i < sequenceData.length; i += BASES_PER_LINE) {
225 | const lineStartPos = start + i;
226 | const chunk = sequenceData.substring(i, i + BASES_PER_LINE);
227 | const colorizedChars: JSX.Element[] = [];
228 |
229 | for (let j = 0; j < chunk.length; j++) {
230 | const nucleotide = chunk[j] || "";
231 | const nucleotidePosition = lineStartPos + j;
232 | const color = getNucleotideColorClass(nucleotide);
233 | colorizedChars.push(
234 | onSequenceClick(nucleotidePosition, nucleotide)}
237 | onMouseEnter={(e) => {
238 | setHoverPosition(nucleotidePosition);
239 | setMousePosition({ x: e.clientX, y: e.clientY });
240 | }}
241 | onMouseLeave={(e) => {
242 | setHoverPosition(null);
243 | setMousePosition(null);
244 | }}
245 | className={`${color} group relative cursor-pointer`}
246 | >
247 | {nucleotide}
248 | ,
249 | );
250 | }
251 |
252 | lines.push(
253 |
254 |
255 | {lineStartPos.toLocaleString()}
256 |
257 |
{colorizedChars}
258 |
,
259 | );
260 | }
261 |
262 | return lines;
263 | }, [sequenceData, sequenceRange, onSequenceClick]);
264 |
265 | return (
266 |
267 |
268 |
269 | Gene Sequence
270 |
271 |
272 |
273 |
274 | {geneBounds && (
275 |
276 |
277 |
278 | From:
279 |
280 | {Math.min(geneBounds.min, geneBounds.max).toLocaleString()}
281 |
282 |
283 |
284 | Selected: {parseInt(startPosition || "0").toLocaleString()} -{" "}
285 | {parseInt(endPosition || "0").toLocaleString()} (
286 | {currentRangeSize.toLocaleString()} bp)
287 |
288 |
289 | To:
290 |
291 | {Math.max(geneBounds.min, geneBounds.max).toLocaleString()}
292 |
293 |
294 |
295 |
296 | {/* Slider component */}
297 |
298 |
299 |
303 | {/* Track background */}
304 |
305 |
306 | {/* Selected range */}
307 |
315 |
316 | {/* Start handle */}
317 |
handleMouseDown(e, "start")}
321 | >
322 |
323 |
324 |
325 | {/* End handle */}
326 |
handleMouseDown(e, "end")}
330 | >
331 |
332 |
333 |
334 |
335 |
336 | {/* Position controls */}
337 |
338 |
339 | Start:
340 | onStartPositionChange(e.target.value)}
343 | type="text"
344 | inputMode="numeric"
345 | pattern="[0-9]*"
346 | className="h-7 w-full border-[#3c4f3d]/10 text-xs sm:w-28"
347 | />
348 |
349 |
355 | {isLoading ? "Loading..." : "Load sequence"}
356 |
357 |
358 | End:
359 | onEndPositionChange(e.target.value)}
362 | type="text"
363 | inputMode="numeric"
364 | pattern="[0-9]*"
365 | className="h-7 w-full border-[#3c4f3d]/10 text-xs sm:w-28"
366 | />
367 |
368 |
369 |
370 |
371 | )}
372 |
373 |
374 |
375 | {geneDetail?.genomicinfo?.[0]?.strand === "+"
376 | ? "Forward strand (5' -> 3')"
377 | : geneDetail?.genomicinfo?.[0]?.strand === "-"
378 | ? "Reverse strand (3' <- 5')"
379 | : "Strand information not available"}
380 |
381 |
382 | Maximum window size: {maxViewRange.toLocaleString()} bp
383 |
384 |
385 |
386 | {error && (
387 |
388 | {error}
389 |
390 | )}
391 |
392 |
393 | {isLoading ? (
394 |
397 | ) : sequenceData ? (
398 |
399 |
400 | {formattedSequence}
401 |
402 |
403 | ) : (
404 |
405 | {error ? "Error loading sequence" : "No sequence data loaded."}
406 |
407 | )}
408 |
409 |
410 | {hoverPosition !== null && mousePosition !== null && (
411 |
419 | Position: {hoverPosition.toLocaleString()}
420 |
421 | )}
422 |
423 |
424 |
428 |
432 |
436 |
440 |
441 |
442 |
443 | );
444 | }
445 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/gene-viewer.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 |
3 | import {
4 | fetchGeneDetails,
5 | fetchGeneSequence as apiFetchGeneSequence,
6 | fetchClinvarVariants as apiFetchClinvarVariants,
7 | type GeneBounds,
8 | type GeneDetailsFromSearch,
9 | type GeneFromSearch,
10 | type ClinvarVariant,
11 | } from "~/utils/genome-api";
12 | import { Button } from "./ui/button";
13 | import { ArrowLeft } from "lucide-react";
14 | import { useCallback, useEffect, useRef, useState } from "react";
15 | import { GeneInformation } from "./gene-information";
16 | import { GeneSequence } from "./gene-sequence";
17 | import KnownVariants from "./known-variants";
18 | import { VariantComparisonModal } from "./variant-comparison-modal";
19 | import VariantAnalysis, {
20 | type VariantAnalysisHandle,
21 | } from "./variant-analysis";
22 |
23 | export default function GeneViewer({
24 | gene,
25 | genomeId,
26 | onClose,
27 | }: {
28 | gene: GeneFromSearch;
29 | genomeId: string;
30 | onClose: () => void;
31 | }) {
32 | const [geneSequence, setGeneSequence] = useState("");
33 | const [geneDetail, setGeneDetail] = useState(
34 | null,
35 | );
36 | const [geneBounds, setGeneBounds] = useState(null);
37 | const [isLoading, setIsLoading] = useState(false);
38 | const [error, setError] = useState(null);
39 |
40 | const [startPosition, setStartPosition] = useState("");
41 | const [endPosition, setEndPosition] = useState("");
42 | const [isLoadingSequence, setIsLoadingSequence] = useState(false);
43 |
44 | const [clinvarVariants, setClinvarVariants] = useState([]);
45 | const [isLoadingClinvar, setIsLoadingClinvar] = useState(false);
46 | const [clinvarError, setClinvarError] = useState(null);
47 |
48 | const [actualRange, setActualRange] = useState<{
49 | start: number;
50 | end: number;
51 | } | null>(null);
52 |
53 | const [comparisonVariant, setComparisonVariant] =
54 | useState(null);
55 |
56 | const [activeSequencePosition, setActiveSequencePosition] = useState<
57 | number | null
58 | >(null);
59 | const [activeReferenceNucleotide, setActiveReferenceNucleotide] = useState<
60 | string | null
61 | >(null);
62 |
63 | const variantAnalysisRef = useRef(null);
64 |
65 | const updateClinvarVariant = (
66 | clinvar_id: string,
67 | updateVariant: ClinvarVariant,
68 | ) => {
69 | setClinvarVariants((currentVariants) =>
70 | currentVariants.map((v) =>
71 | v.clinvar_id == clinvar_id ? updateVariant : v,
72 | ),
73 | );
74 | };
75 |
76 | const fetchGeneSequence = useCallback(
77 | async (start: number, end: number) => {
78 | try {
79 | setIsLoadingSequence(true);
80 | setError(null);
81 |
82 | const {
83 | sequence,
84 | actualRange: fetchedRange,
85 | error: apiError,
86 | } = await apiFetchGeneSequence(gene.chrom, start, end, genomeId);
87 |
88 | setGeneSequence(sequence);
89 | setActualRange(fetchedRange);
90 |
91 | if (apiError) {
92 | setError(apiError);
93 | }
94 | } catch (err) {
95 | setError("Failed to load sequence data");
96 | } finally {
97 | setIsLoadingSequence(false);
98 | }
99 | },
100 | [gene.chrom, genomeId],
101 | );
102 |
103 | useEffect(() => {
104 | const initializeGeneData = async () => {
105 | setIsLoading(true);
106 |
107 | if (!gene.gene_id) {
108 | setError("Gene ID is missing, cannot fetch details");
109 | setIsLoading(false);
110 | return;
111 | }
112 |
113 | try {
114 | const {
115 | geneDetails: fetchedDetail,
116 | geneBounds: fetchedGeneBounds,
117 | initialRange: fetchedRange,
118 | } = await fetchGeneDetails(gene.gene_id);
119 |
120 | setGeneDetail(fetchedDetail);
121 | setGeneBounds(fetchedGeneBounds);
122 |
123 | if (fetchedRange) {
124 | setStartPosition(String(fetchedRange.start));
125 | setEndPosition(String(fetchedRange.end));
126 | await fetchGeneSequence(fetchedRange.start, fetchedRange.end);
127 | }
128 | } catch {
129 | setError("Faield to load gene information. Please try again.");
130 | } finally {
131 | setIsLoading(false);
132 | }
133 | };
134 |
135 | initializeGeneData();
136 | }, [gene, genomeId]);
137 |
138 | const handleSequenceClick = useCallback(
139 | (position: number, nucleotide: string) => {
140 | setActiveSequencePosition(position);
141 | setActiveReferenceNucleotide(nucleotide);
142 | window.scrollTo({ top: 0, behavior: "smooth" });
143 | if (variantAnalysisRef.current) {
144 | variantAnalysisRef.current.focusAlternativeInput();
145 | }
146 | },
147 | [],
148 | );
149 |
150 | const handleLoadSequence = useCallback(() => {
151 | const start = parseInt(startPosition);
152 | const end = parseInt(endPosition);
153 | let validationError: string | null = null;
154 |
155 | if (isNaN(start) || isNaN(end)) {
156 | validationError = "Please enter valid start and end positions";
157 | } else if (start >= end) {
158 | validationError = "Start position must be less than end position";
159 | } else if (geneBounds) {
160 | const minBound = Math.min(geneBounds.min, geneBounds.max);
161 | const maxBound = Math.max(geneBounds.min, geneBounds.max);
162 | if (start < minBound) {
163 | validationError = `Start position (${start.toLocaleString()}) is below the minimum value (${minBound.toLocaleString()})`;
164 | } else if (end > maxBound) {
165 | validationError = `End position (${end.toLocaleString()}) exceeds the maximum value (${maxBound.toLocaleString()})`;
166 | }
167 |
168 | if (end - start > 10000) {
169 | validationError = `Selected range exceeds maximum view range of 10.000 bp.`;
170 | }
171 | }
172 |
173 | if (validationError) {
174 | setError(validationError);
175 | return;
176 | }
177 |
178 | setError(null);
179 | fetchGeneSequence(start, end);
180 | }, [startPosition, endPosition, fetchGeneSequence, geneBounds]);
181 |
182 | const fetchClinvarVariants = async () => {
183 | if (!gene.chrom || !geneBounds) return;
184 |
185 | setIsLoadingClinvar(true);
186 | setClinvarError(null);
187 |
188 | try {
189 | const variants = await apiFetchClinvarVariants(
190 | gene.chrom,
191 | geneBounds,
192 | genomeId,
193 | );
194 | setClinvarVariants(variants);
195 | console.log(variants);
196 | } catch (error) {
197 | setClinvarError("Failed to fetch ClinVar variants");
198 | setClinvarVariants([]);
199 | } finally {
200 | setIsLoadingClinvar(false);
201 | }
202 | };
203 |
204 | useEffect(() => {
205 | if (geneBounds) {
206 | fetchClinvarVariants();
207 | }
208 | }, [geneBounds]);
209 |
210 | const showComparison = (variant: ClinvarVariant) => {
211 | if (variant.evo2Result) {
212 | setComparisonVariant(variant);
213 | }
214 | };
215 |
216 | if (isLoading) {
217 | return (
218 |
221 | );
222 | }
223 |
224 | return (
225 |
226 |
232 |
233 | Back to results
234 |
235 |
236 |
246 |
247 |
257 |
258 |
273 |
274 |
279 |
280 |
setComparisonVariant(null)}
283 | />
284 |
285 | );
286 | }
287 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/known-variants.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 |
3 | import {
4 | analyzeVariantWithAPI,
5 | type ClinvarVariant,
6 | type GeneFromSearch,
7 | } from "~/utils/genome-api";
8 | import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
9 | import { Button } from "./ui/button";
10 | import {
11 | Table,
12 | TableBody,
13 | TableCell,
14 | TableHead,
15 | TableHeader,
16 | TableRow,
17 | } from "./ui/table";
18 | import { Viaoda_Libre } from "next/font/google";
19 | import {
20 | BarChart2,
21 | ExternalLink,
22 | RefreshCw,
23 | Search,
24 | Shield,
25 | Zap,
26 | } from "lucide-react";
27 | import { getClassificationColorClasses } from "~/utils/coloring-utils";
28 |
29 | export default function KnownVariants({
30 | refreshVariants,
31 | showComparison,
32 | updateClinvarVariant,
33 | clinvarVariants,
34 | isLoadingClinvar,
35 | clinvarError,
36 | genomeId,
37 | gene,
38 | }: {
39 | refreshVariants: () => void;
40 | showComparison: (variant: ClinvarVariant) => void;
41 | updateClinvarVariant: (id: string, newVariant: ClinvarVariant) => void;
42 | clinvarVariants: ClinvarVariant[];
43 | isLoadingClinvar: boolean;
44 | clinvarError: string | null;
45 | genomeId: string;
46 | gene: GeneFromSearch;
47 | }) {
48 | const analyzeVariant = async (variant: ClinvarVariant) => {
49 | let variantDetails = null;
50 | const position = variant.location
51 | ? parseInt(variant.location.replaceAll(",", ""))
52 | : null;
53 |
54 | const refAltMatch = variant.title.match(/(\w)>(\w)/);
55 |
56 | if (refAltMatch && refAltMatch.length === 3) {
57 | variantDetails = {
58 | position,
59 | reference: refAltMatch[1],
60 | alternative: refAltMatch[2],
61 | };
62 | }
63 |
64 | if (
65 | !variantDetails ||
66 | !variantDetails.position ||
67 | !variantDetails.reference ||
68 | !variantDetails.alternative
69 | ) {
70 | return;
71 | }
72 |
73 | updateClinvarVariant(variant.clinvar_id, {
74 | ...variant,
75 | isAnalyzing: true,
76 | });
77 |
78 | try {
79 | const data = await analyzeVariantWithAPI({
80 | position: variantDetails.position,
81 | alternative: variantDetails.alternative,
82 | genomeId: genomeId,
83 | chromosome: gene.chrom,
84 | });
85 |
86 | const updatedVariant: ClinvarVariant = {
87 | ...variant,
88 | isAnalyzing: false,
89 | evo2Result: data,
90 | };
91 |
92 | updateClinvarVariant(variant.clinvar_id, updatedVariant);
93 |
94 | showComparison(updatedVariant);
95 | } catch (error) {
96 | updateClinvarVariant(variant.clinvar_id, {
97 | ...variant,
98 | isAnalyzing: false,
99 | evo2Error: error instanceof Error ? error.message : "Analysis failed",
100 | });
101 | }
102 | };
103 | return (
104 |
105 |
106 |
107 | Known Variants in Gene from ClinVar
108 |
109 |
116 |
117 | Refresh
118 |
119 |
120 |
121 | {clinvarError && (
122 |
123 | {clinvarError}
124 |
125 | )}
126 |
127 | {isLoadingClinvar ? (
128 |
131 | ) : clinvarVariants.length > 0 ? (
132 |
133 |
134 |
135 |
136 |
137 | Variant
138 |
139 |
140 | Type
141 |
142 |
143 | Clinical Significance
144 |
145 |
146 | Actions
147 |
148 |
149 |
150 |
151 | {clinvarVariants.map((variant) => (
152 |
156 |
157 |
158 | {variant.title}
159 |
160 |
161 |
Location: {variant.location}
162 |
167 | window.open(
168 | `https://www.ncbi.nlm.nih.gov/clinvar/variation/${variant.clinvar_id}`,
169 | "_blank",
170 | )
171 | }
172 | >
173 | View in ClinVar
174 |
175 |
176 |
177 |
178 |
179 | {variant.variation_type}
180 |
181 |
182 |
185 | {variant.classification || "Unknown"}
186 |
187 | {variant.evo2Result && (
188 |
189 |
192 |
193 | Evo2: {variant.evo2Result.prediction}
194 |
195 |
196 | )}
197 |
198 |
199 |
200 | {variant.variation_type
201 | .toLowerCase()
202 | .includes("single nucleotide") ? (
203 | !variant.evo2Result ? (
204 | analyzeVariant(variant)}
210 | >
211 | {variant.isAnalyzing ? (
212 | <>
213 |
214 | Analyzing...
215 | >
216 | ) : (
217 | <>
218 |
219 | Analyze with Evo2
220 | >
221 | )}
222 |
223 | ) : (
224 | showComparison(variant)}
229 | >
230 |
231 | Compare Results
232 |
233 | )
234 | ) : null}
235 |
236 |
237 |
238 | ))}
239 |
240 |
241 |
242 | ) : (
243 |
244 |
245 |
246 | No ClinVar variants found for this gene.
247 |
248 |
249 | )}
250 |
251 |
252 | );
253 | }
254 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/ui/button.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react"
2 | import { Slot } from "@radix-ui/react-slot"
3 | import { cva, type VariantProps } from "class-variance-authority"
4 |
5 | import { cn } from "~/lib/utils"
6 |
7 | const buttonVariants = cva(
8 | "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
9 | {
10 | variants: {
11 | variant: {
12 | default:
13 | "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
14 | destructive:
15 | "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
16 | outline:
17 | "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
18 | secondary:
19 | "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
20 | ghost:
21 | "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
22 | link: "text-primary underline-offset-4 hover:underline",
23 | },
24 | size: {
25 | default: "h-9 px-4 py-2 has-[>svg]:px-3",
26 | sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
27 | lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
28 | icon: "size-9",
29 | },
30 | },
31 | defaultVariants: {
32 | variant: "default",
33 | size: "default",
34 | },
35 | }
36 | )
37 |
38 | function Button({
39 | className,
40 | variant,
41 | size,
42 | asChild = false,
43 | ...props
44 | }: React.ComponentProps<"button"> &
45 | VariantProps & {
46 | asChild?: boolean
47 | }) {
48 | const Comp = asChild ? Slot : "button"
49 |
50 | return (
51 |
56 | )
57 | }
58 |
59 | export { Button, buttonVariants }
60 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/ui/card.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react"
2 |
3 | import { cn } from "~/lib/utils"
4 |
5 | function Card({ className, ...props }: React.ComponentProps<"div">) {
6 | return (
7 |
15 | )
16 | }
17 |
18 | function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
19 | return (
20 |
28 | )
29 | }
30 |
31 | function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
32 | return (
33 |
38 | )
39 | }
40 |
41 | function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
42 | return (
43 |
48 | )
49 | }
50 |
51 | function CardAction({ className, ...props }: React.ComponentProps<"div">) {
52 | return (
53 |
61 | )
62 | }
63 |
64 | function CardContent({ className, ...props }: React.ComponentProps<"div">) {
65 | return (
66 |
71 | )
72 | }
73 |
74 | function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
75 | return (
76 |
81 | )
82 | }
83 |
84 | export {
85 | Card,
86 | CardHeader,
87 | CardFooter,
88 | CardTitle,
89 | CardAction,
90 | CardDescription,
91 | CardContent,
92 | }
93 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/ui/input.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react"
2 |
3 | import { cn } from "~/lib/utils"
4 |
5 | function Input({ className, type, ...props }: React.ComponentProps<"input">) {
6 | return (
7 |
18 | )
19 | }
20 |
21 | export { Input }
22 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/ui/select.tsx:
--------------------------------------------------------------------------------
1 | "use client"
2 |
3 | import * as React from "react"
4 | import * as SelectPrimitive from "@radix-ui/react-select"
5 | import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
6 |
7 | import { cn } from "~/lib/utils"
8 |
9 | function Select({
10 | ...props
11 | }: React.ComponentProps) {
12 | return
13 | }
14 |
15 | function SelectGroup({
16 | ...props
17 | }: React.ComponentProps) {
18 | return
19 | }
20 |
21 | function SelectValue({
22 | ...props
23 | }: React.ComponentProps) {
24 | return
25 | }
26 |
27 | function SelectTrigger({
28 | className,
29 | size = "default",
30 | children,
31 | ...props
32 | }: React.ComponentProps & {
33 | size?: "sm" | "default"
34 | }) {
35 | return (
36 |
45 | {children}
46 |
47 |
48 |
49 |
50 | )
51 | }
52 |
53 | function SelectContent({
54 | className,
55 | children,
56 | position = "popper",
57 | ...props
58 | }: React.ComponentProps) {
59 | return (
60 |
61 |
72 |
73 |
80 | {children}
81 |
82 |
83 |
84 |
85 | )
86 | }
87 |
88 | function SelectLabel({
89 | className,
90 | ...props
91 | }: React.ComponentProps) {
92 | return (
93 |
98 | )
99 | }
100 |
101 | function SelectItem({
102 | className,
103 | children,
104 | ...props
105 | }: React.ComponentProps) {
106 | return (
107 |
115 |
116 |
117 |
118 |
119 |
120 | {children}
121 |
122 | )
123 | }
124 |
125 | function SelectSeparator({
126 | className,
127 | ...props
128 | }: React.ComponentProps) {
129 | return (
130 |
135 | )
136 | }
137 |
138 | function SelectScrollUpButton({
139 | className,
140 | ...props
141 | }: React.ComponentProps) {
142 | return (
143 |
151 |
152 |
153 | )
154 | }
155 |
156 | function SelectScrollDownButton({
157 | className,
158 | ...props
159 | }: React.ComponentProps) {
160 | return (
161 |
169 |
170 |
171 | )
172 | }
173 |
174 | export {
175 | Select,
176 | SelectContent,
177 | SelectGroup,
178 | SelectItem,
179 | SelectLabel,
180 | SelectScrollDownButton,
181 | SelectScrollUpButton,
182 | SelectSeparator,
183 | SelectTrigger,
184 | SelectValue,
185 | }
186 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/ui/table.tsx:
--------------------------------------------------------------------------------
1 | "use client"
2 |
3 | import * as React from "react"
4 |
5 | import { cn } from "~/lib/utils"
6 |
7 | function Table({ className, ...props }: React.ComponentProps<"table">) {
8 | return (
9 |
19 | )
20 | }
21 |
22 | function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
23 | return (
24 |
29 | )
30 | }
31 |
32 | function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
33 | return (
34 |
39 | )
40 | }
41 |
42 | function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
43 | return (
44 | tr]:last:border-b-0",
48 | className
49 | )}
50 | {...props}
51 | />
52 | )
53 | }
54 |
55 | function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
56 | return (
57 |
65 | )
66 | }
67 |
68 | function TableHead({ className, ...props }: React.ComponentProps<"th">) {
69 | return (
70 | [role=checkbox]]:translate-y-[2px]",
74 | className
75 | )}
76 | {...props}
77 | />
78 | )
79 | }
80 |
81 | function TableCell({ className, ...props }: React.ComponentProps<"td">) {
82 | return (
83 | [role=checkbox]]:translate-y-[2px]",
87 | className
88 | )}
89 | {...props}
90 | />
91 | )
92 | }
93 |
94 | function TableCaption({
95 | className,
96 | ...props
97 | }: React.ComponentProps<"caption">) {
98 | return (
99 |
104 | )
105 | }
106 |
107 | export {
108 | Table,
109 | TableHeader,
110 | TableBody,
111 | TableFooter,
112 | TableHead,
113 | TableRow,
114 | TableCell,
115 | TableCaption,
116 | }
117 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/ui/tabs.tsx:
--------------------------------------------------------------------------------
1 | "use client"
2 |
3 | import * as React from "react"
4 | import * as TabsPrimitive from "@radix-ui/react-tabs"
5 |
6 | import { cn } from "~/lib/utils"
7 |
8 | function Tabs({
9 | className,
10 | ...props
11 | }: React.ComponentProps) {
12 | return (
13 |
18 | )
19 | }
20 |
21 | function TabsList({
22 | className,
23 | ...props
24 | }: React.ComponentProps) {
25 | return (
26 |
34 | )
35 | }
36 |
37 | function TabsTrigger({
38 | className,
39 | ...props
40 | }: React.ComponentProps) {
41 | return (
42 |
50 | )
51 | }
52 |
53 | function TabsContent({
54 | className,
55 | ...props
56 | }: React.ComponentProps) {
57 | return (
58 |
63 | )
64 | }
65 |
66 | export { Tabs, TabsList, TabsTrigger, TabsContent }
67 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/variant-analysis.tsx:
--------------------------------------------------------------------------------
1 | "use client";
2 |
3 | import {
4 | type AnalysisResult,
5 | analyzeVariantWithAPI,
6 | type ClinvarVariant,
7 | type GeneBounds,
8 | type GeneFromSearch,
9 | } from "~/utils/genome-api";
10 | import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
11 | import { Input } from "./ui/input";
12 | import React, {
13 | forwardRef,
14 | useEffect,
15 | useImperativeHandle,
16 | useRef,
17 | useState,
18 | } from "react";
19 | import {
20 | getClassificationColorClasses,
21 | getNucleotideColorClass,
22 | } from "~/utils/coloring-utils";
23 | import { Button } from "./ui/button";
24 | import { match } from "node:assert";
25 | import { Zap } from "lucide-react";
26 |
27 | export interface VariantAnalysisHandle {
28 | focusAlternativeInput: () => void;
29 | }
30 |
31 | interface VariantAnalysisProps {
32 | gene: GeneFromSearch;
33 | genomeId: string;
34 | chromosome: string;
35 | clinvarVariants: Array;
36 | referenceSequence: string | null;
37 | sequencePosition: number | null;
38 | geneBounds: GeneBounds | null;
39 | }
40 |
41 | const VariantAnalysis = forwardRef(
42 | (
43 | {
44 | gene,
45 | genomeId,
46 | chromosome,
47 | clinvarVariants = [],
48 | referenceSequence,
49 | sequencePosition,
50 | geneBounds,
51 | }: VariantAnalysisProps,
52 | ref,
53 | ) => {
54 | const [variantPosition, setVariantPosition] = useState(
55 | geneBounds?.min?.toString() || "",
56 | );
57 | const [variantReference, setVariantReference] = useState("");
58 | const [variantAlternative, setVariantAlternative] = useState("");
59 | const [variantResult, setVariantResult] = useState(
60 | null,
61 | );
62 | const [isAnalyzing, setIsAnalyzing] = useState(false);
63 | const [variantError, setVariantError] = useState(null);
64 | const alternativeInputRef = useRef(null);
65 |
66 | useImperativeHandle(ref, () => ({
67 | focusAlternativeInput: () => {
68 | if (alternativeInputRef.current) {
69 | alternativeInputRef.current.focus();
70 | }
71 | },
72 | }));
73 |
74 | useEffect(() => {
75 | if (sequencePosition && referenceSequence) {
76 | setVariantPosition(String(sequencePosition));
77 | setVariantReference(referenceSequence);
78 | }
79 | }, [sequencePosition, referenceSequence]);
80 |
81 | const handlePositionChange = (e: React.ChangeEvent) => {
82 | setVariantPosition(e.target.value);
83 | setVariantReference("");
84 | };
85 |
86 | const handleVariantSubmit = async (pos: string, alt: string) => {
87 | const position = parseInt(pos);
88 | if (isNaN(position)) {
89 | setVariantError("Please enter a valid position number");
90 | return;
91 | }
92 |
93 | const validNucleotides = /^[ATGC]$/;
94 | if (!validNucleotides.test(alt)) {
95 | setVariantError("Nucleotides must be A, C, G or T");
96 | return;
97 | }
98 |
99 | setIsAnalyzing(true);
100 | setVariantError(null);
101 |
102 | try {
103 | const data = await analyzeVariantWithAPI({
104 | position,
105 | alternative: alt,
106 | genomeId,
107 | chromosome,
108 | });
109 | setVariantResult(data);
110 | } catch (err) {
111 | console.error(err);
112 | setVariantError("Failed to analyze variant");
113 | } finally {
114 | setIsAnalyzing(false);
115 | }
116 | };
117 |
118 | return (
119 |
120 |
121 |
122 | Variant Analysis
123 |
124 |
125 |
126 |
127 | Predict the impact of genetic variants using the Evo2 deep learning
128 | model.
129 |
130 |
131 |
132 |
133 | Position
134 |
135 |
140 |
141 |
142 |
143 | Alternative (variant)
144 |
145 |
149 | setVariantAlternative(e.target.value.toUpperCase())
150 | }
151 | className="h-8 w-32 border-[#3c4f3d]/10 text-xs"
152 | placeholder="e.g., T"
153 | maxLength={1}
154 | />
155 |
156 | {variantReference && (
157 |
158 | Substitution
159 |
162 | {variantReference}
163 |
164 | →
165 |
168 | {variantAlternative ? variantAlternative : "?"}
169 |
170 |
171 | )}
172 |
176 | handleVariantSubmit(
177 | variantPosition.replaceAll(",", ""),
178 | variantAlternative,
179 | )
180 | }
181 | >
182 | {isAnalyzing ? (
183 | <>
184 |
185 | Analyzing...
186 | >
187 | ) : (
188 | "Analyze variant"
189 | )}
190 |
191 |
192 |
193 | {variantPosition &&
194 | clinvarVariants
195 | .filter(
196 | (variant) =>
197 | variant?.variation_type
198 | ?.toLowerCase()
199 | .includes("single nucleotide") &&
200 | parseInt(variant?.location?.replaceAll(",", "")) ===
201 | parseInt(variantPosition.replaceAll(",", "")),
202 | )
203 | .map((matchedVariant) => {
204 | const refAltMatch = matchedVariant.title.match(/(\w)>(\w)/);
205 |
206 | let ref = null;
207 | let alt = null;
208 | if (refAltMatch && refAltMatch.length === 3) {
209 | ref = refAltMatch[1];
210 | alt = refAltMatch[2];
211 | }
212 |
213 | if (!ref || !alt) return null;
214 |
215 | return (
216 |
220 |
221 |
222 | Known Variant Detected
223 |
224 |
225 | Position: {matchedVariant.location}
226 |
227 |
228 |
229 |
230 |
231 |
232 | Variant Details
233 |
234 |
{matchedVariant.title}
235 |
236 | {gene?.symbol} {variantPosition}{" "}
237 |
238 |
239 | {ref}
240 |
241 | {">"}
242 |
243 | {alt}
244 |
245 |
246 |
247 |
248 | ClinVar classification
249 |
252 | {matchedVariant.classification || "Unknown"}
253 |
254 |
255 |
256 |
257 | {
263 | setVariantAlternative(alt);
264 | handleVariantSubmit(
265 | variantPosition.replaceAll(",", ""),
266 | alt,
267 | );
268 | }}
269 | >
270 | {isAnalyzing ? (
271 | <>
272 |
273 | Analyzing...
274 | >
275 | ) : (
276 | <>
277 |
278 | Analyze this Variant
279 | >
280 | )}
281 |
282 |
283 |
284 |
285 | );
286 | })[0]}
287 | {variantError && (
288 |
289 | {variantError}
290 |
291 | )}
292 | {variantResult && (
293 |
294 |
295 | Analysis Result
296 |
297 |
298 |
299 |
300 |
301 | Variant
302 |
303 |
304 | {gene?.symbol} {variantResult.position}{" "}
305 |
306 | {variantResult.reference}
307 | {">"}
308 | {variantResult.alternative}
309 |
310 |
311 |
312 |
313 |
314 | Delta likelihood score
315 |
316 |
317 | {variantResult.delta_score.toFixed(6)}
318 |
319 |
320 | Negative score indicates loss of function
321 |
322 |
323 |
324 |
325 |
326 | Prediction
327 |
328 |
331 | {variantResult.prediction}
332 |
333 |
334 |
335 | Confidence
336 |
337 |
345 |
346 | {Math.round(
347 | variantResult.classification_confidence * 100,
348 | )}
349 | %
350 |
351 |
352 |
353 |
354 |
355 | )}
356 |
357 |
358 | );
359 | },
360 | );
361 |
362 | export default VariantAnalysis;
363 |
--------------------------------------------------------------------------------
/evo2-frontend/src/components/variant-comparison-modal.tsx:
--------------------------------------------------------------------------------
1 | import type { ClinvarVariant } from "~/utils/genome-api";
2 | import { Button } from "./ui/button";
3 | import { Check, ExternalLink, Shield, X } from "lucide-react";
4 | import {
5 | getClassificationColorClasses,
6 | getNucleotideColorClass,
7 | } from "~/utils/coloring-utils";
8 |
9 | export function VariantComparisonModal({
10 | comparisonVariant,
11 | onClose,
12 | }: {
13 | comparisonVariant: ClinvarVariant | null;
14 | onClose: () => void;
15 | }) {
16 | if (!comparisonVariant || !comparisonVariant.evo2Result) return null;
17 |
18 | return (
19 |
20 |
21 | {/* Modal header */}
22 |
23 |
24 |
25 | Variant Analysis Comparison
26 |
27 |
33 |
34 |
35 |
36 |
37 |
38 | {/* Modal content */}
39 |
40 | {comparisonVariant && comparisonVariant.evo2Result && (
41 |
42 |
43 |
44 | Variant Information
45 |
46 |
47 |
48 |
49 |
50 |
51 | Position:
52 |
53 |
54 | {comparisonVariant.location}
55 |
56 |
57 |
58 |
59 | Type:
60 |
61 |
62 | {comparisonVariant.variation_type}
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 | Variant:
73 |
74 |
75 | {(() => {
76 | const match =
77 | comparisonVariant.title.match(/(\w)>(\w)/);
78 | if (match && match.length === 3) {
79 | const [_, ref, alt] = match;
80 | return (
81 | <>
82 |
85 | {ref}
86 |
87 | {">"}
88 |
91 | {alt}
92 |
93 | >
94 | );
95 | }
96 | return comparisonVariant.title;
97 | })()}
98 |
99 |
100 |
113 |
114 |
115 |
116 |
117 |
118 | {/* Variant results */}
119 |
120 |
121 | Analysis Comparison
122 |
123 |
124 |
125 | {/* ClinVar Assesment */}
126 |
127 |
128 |
129 |
130 |
131 | ClinVar Assessment
132 |
133 |
134 |
137 | {comparisonVariant.classification ||
138 | "Unknown significance"}
139 |
140 |
141 |
142 |
143 | {/* Evo2 Prediction */}
144 |
145 |
146 |
147 |
148 |
149 | Evo2 Prediction
150 |
151 |
152 |
155 |
156 | {comparisonVariant.evo2Result.prediction}
157 |
158 |
159 | {/* Delta score */}
160 |
161 |
162 | Delta Likelihood Score:
163 |
164 |
165 | {comparisonVariant.evo2Result.delta_score.toFixed(6)}
166 |
167 |
168 | {comparisonVariant.evo2Result.delta_score < 0
169 | ? "Negative score indicates loss of function"
170 | : "Positive score indicated gain/neutral function"}
171 |
172 |
173 | {/* Confidence bar */}
174 |
175 |
176 | Confidence:
177 |
178 |
186 |
187 | {Math.round(
188 | comparisonVariant.evo2Result
189 | .classification_confidence * 100,
190 | )}
191 | %
192 |
193 |
194 |
195 |
196 |
197 | {/* Assesment Agreement */}
198 |
199 |
200 |
203 | {comparisonVariant.classification.toLowerCase() ===
204 | comparisonVariant.evo2Result.prediction.toLowerCase() ? (
205 |
206 | ) : (
207 |
208 | !
209 |
210 | )}
211 |
212 |
213 | {comparisonVariant.classification.toLowerCase() ===
214 | comparisonVariant.evo2Result.prediction.toLowerCase()
215 | ? "Evo2 prediction agrees with ClinVar classification"
216 | : "Evo2 prediction differs from ClinVar classification"}
217 |
218 |
219 |
220 |
221 |
222 |
223 | )}
224 |
225 |
226 | {/* Modal footer */}
227 |
228 |
233 | Close
234 |
235 |
236 |
237 |
238 | );
239 | }
240 |
--------------------------------------------------------------------------------
/evo2-frontend/src/env.js:
--------------------------------------------------------------------------------
1 | import { createEnv } from "@t3-oss/env-nextjs";
2 | import { z } from "zod";
3 |
4 | export const env = createEnv({
5 | /**
6 | * Specify your server-side environment variables schema here. This way you can ensure the app
7 | * isn't built with invalid env vars.
8 | */
9 | server: {
10 | NODE_ENV: z.enum(["development", "test", "production"]),
11 | },
12 |
13 | /**
14 | * Specify your client-side environment variables schema here. This way you can ensure the app
15 | * isn't built with invalid env vars. To expose them to the client, prefix them with
16 | * `NEXT_PUBLIC_`.
17 | */
18 | client: {
19 | NEXT_PUBLIC_ANALYZE_SINGLE_VARIANT_BASE_URL: z.string(),
20 | },
21 |
22 | /**
23 | * You can't destruct `process.env` as a regular object in the Next.js edge runtimes (e.g.
24 | * middlewares) or client-side so we need to destruct manually.
25 | */
26 | runtimeEnv: {
27 | NODE_ENV: process.env.NODE_ENV,
28 | NEXT_PUBLIC_ANALYZE_SINGLE_VARIANT_BASE_URL:
29 | process.env.NEXT_PUBLIC_ANALYZE_SINGLE_VARIANT_BASE_URL,
30 | },
31 | /**
32 | * Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
33 | * useful for Docker builds.
34 | */
35 | skipValidation: !!process.env.SKIP_ENV_VALIDATION,
36 | /**
37 | * Makes it so that empty strings are treated as undefined. `SOME_VAR: z.string()` and
38 | * `SOME_VAR=''` will throw an error.
39 | */
40 | emptyStringAsUndefined: true,
41 | });
42 |
--------------------------------------------------------------------------------
/evo2-frontend/src/lib/utils.ts:
--------------------------------------------------------------------------------
1 | import { clsx, type ClassValue } from "clsx"
2 | import { twMerge } from "tailwind-merge"
3 |
4 | export function cn(...inputs: ClassValue[]) {
5 | return twMerge(clsx(inputs))
6 | }
7 |
--------------------------------------------------------------------------------
/evo2-frontend/src/styles/globals.css:
--------------------------------------------------------------------------------
1 | @import "tailwindcss";
2 | @import "tw-animate-css";
3 |
4 | @custom-variant dark (&:is(.dark *));
5 |
6 | @theme {
7 | --font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif,
8 | "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
9 | }
10 |
11 | @theme inline {
12 | --radius-sm: calc(var(--radius) - 4px);
13 | --radius-md: calc(var(--radius) - 2px);
14 | --radius-lg: var(--radius);
15 | --radius-xl: calc(var(--radius) + 4px);
16 | --color-background: var(--background);
17 | --color-foreground: var(--foreground);
18 | --color-card: var(--card);
19 | --color-card-foreground: var(--card-foreground);
20 | --color-popover: var(--popover);
21 | --color-popover-foreground: var(--popover-foreground);
22 | --color-primary: var(--primary);
23 | --color-primary-foreground: var(--primary-foreground);
24 | --color-secondary: var(--secondary);
25 | --color-secondary-foreground: var(--secondary-foreground);
26 | --color-muted: var(--muted);
27 | --color-muted-foreground: var(--muted-foreground);
28 | --color-accent: var(--accent);
29 | --color-accent-foreground: var(--accent-foreground);
30 | --color-destructive: var(--destructive);
31 | --color-border: var(--border);
32 | --color-input: var(--input);
33 | --color-ring: var(--ring);
34 | --color-chart-1: var(--chart-1);
35 | --color-chart-2: var(--chart-2);
36 | --color-chart-3: var(--chart-3);
37 | --color-chart-4: var(--chart-4);
38 | --color-chart-5: var(--chart-5);
39 | --color-sidebar: var(--sidebar);
40 | --color-sidebar-foreground: var(--sidebar-foreground);
41 | --color-sidebar-primary: var(--sidebar-primary);
42 | --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
43 | --color-sidebar-accent: var(--sidebar-accent);
44 | --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
45 | --color-sidebar-border: var(--sidebar-border);
46 | --color-sidebar-ring: var(--sidebar-ring);
47 | }
48 |
49 | :root {
50 | --radius: 0.625rem;
51 | --card: oklch(1 0 0);
52 | --card-foreground: oklch(0.145 0 0);
53 | --popover: oklch(1 0 0);
54 | --popover-foreground: oklch(0.145 0 0);
55 | --primary: oklch(0.205 0 0);
56 | --primary-foreground: oklch(0.985 0 0);
57 | --secondary: oklch(0.97 0 0);
58 | --secondary-foreground: oklch(0.205 0 0);
59 | --muted: oklch(0.97 0 0);
60 | --muted-foreground: oklch(0.556 0 0);
61 | --accent: oklch(0.97 0 0);
62 | --accent-foreground: oklch(0.205 0 0);
63 | --destructive: oklch(0.577 0.245 27.325);
64 | --border: oklch(0.922 0 0);
65 | --input: oklch(0.922 0 0);
66 | --ring: oklch(0.708 0 0);
67 | --chart-1: oklch(0.646 0.222 41.116);
68 | --chart-2: oklch(0.6 0.118 184.704);
69 | --chart-3: oklch(0.398 0.07 227.392);
70 | --chart-4: oklch(0.828 0.189 84.429);
71 | --chart-5: oklch(0.769 0.188 70.08);
72 | --sidebar: oklch(0.985 0 0);
73 | --sidebar-foreground: oklch(0.145 0 0);
74 | --sidebar-primary: oklch(0.205 0 0);
75 | --sidebar-primary-foreground: oklch(0.985 0 0);
76 | --sidebar-accent: oklch(0.97 0 0);
77 | --sidebar-accent-foreground: oklch(0.205 0 0);
78 | --sidebar-border: oklch(0.922 0 0);
79 | --sidebar-ring: oklch(0.708 0 0);
80 | --background: oklch(1 0 0);
81 | --foreground: oklch(0.145 0 0);
82 | }
83 |
84 | .dark {
85 | --background: oklch(0.145 0 0);
86 | --foreground: oklch(0.985 0 0);
87 | --card: oklch(0.205 0 0);
88 | --card-foreground: oklch(0.985 0 0);
89 | --popover: oklch(0.205 0 0);
90 | --popover-foreground: oklch(0.985 0 0);
91 | --primary: oklch(0.922 0 0);
92 | --primary-foreground: oklch(0.205 0 0);
93 | --secondary: oklch(0.269 0 0);
94 | --secondary-foreground: oklch(0.985 0 0);
95 | --muted: oklch(0.269 0 0);
96 | --muted-foreground: oklch(0.708 0 0);
97 | --accent: oklch(0.269 0 0);
98 | --accent-foreground: oklch(0.985 0 0);
99 | --destructive: oklch(0.704 0.191 22.216);
100 | --border: oklch(1 0 0 / 10%);
101 | --input: oklch(1 0 0 / 15%);
102 | --ring: oklch(0.556 0 0);
103 | --chart-1: oklch(0.488 0.243 264.376);
104 | --chart-2: oklch(0.696 0.17 162.48);
105 | --chart-3: oklch(0.769 0.188 70.08);
106 | --chart-4: oklch(0.627 0.265 303.9);
107 | --chart-5: oklch(0.645 0.246 16.439);
108 | --sidebar: oklch(0.205 0 0);
109 | --sidebar-foreground: oklch(0.985 0 0);
110 | --sidebar-primary: oklch(0.488 0.243 264.376);
111 | --sidebar-primary-foreground: oklch(0.985 0 0);
112 | --sidebar-accent: oklch(0.269 0 0);
113 | --sidebar-accent-foreground: oklch(0.985 0 0);
114 | --sidebar-border: oklch(1 0 0 / 10%);
115 | --sidebar-ring: oklch(0.556 0 0);
116 | }
117 |
118 | @layer base {
119 | * {
120 | @apply border-border outline-ring/50;
121 | }
122 | body {
123 | @apply bg-background text-foreground;
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/evo2-frontend/src/utils/coloring-utils.ts:
--------------------------------------------------------------------------------
1 | export function getNucleotideColorClass(nucleotide: string): string {
2 | switch (nucleotide.toUpperCase()) {
3 | case "A":
4 | return "text-red-600";
5 | case "T":
6 | return "text-blue-600";
7 | case "G":
8 | return "text-green-600";
9 | case "C":
10 | return "text-amber-600";
11 | default:
12 | return "text-gray-500";
13 | }
14 | }
15 |
16 | export function getClassificationColorClasses(classification: string): string {
17 | if (!classification) return "bg-yellow-100 text-yellow-800";
18 | const lowercaseClass = classification.toLowerCase();
19 |
20 | if (lowercaseClass.includes("pathogenic")) {
21 | return "bg-red-100 text-red-800";
22 | } else if (lowercaseClass.includes("benign")) {
23 | return "bg-green-100 text-green-800";
24 | } else {
25 | return "bg-yellow-100 text-yellow-800";
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/evo2-frontend/src/utils/genome-api.ts:
--------------------------------------------------------------------------------
1 | import { Viaoda_Libre } from "next/font/google";
2 | import { env } from "~/env";
3 |
4 | export interface GenomeAssemblyFromSearch {
5 | id: string;
6 | name: string;
7 | sourceName: string;
8 | active: boolean;
9 | }
10 |
11 | export interface ChromosomeFromSeach {
12 | name: string;
13 | size: number;
14 | }
15 |
16 | export interface GeneFromSearch {
17 | symbol: string;
18 | name: string;
19 | chrom: string;
20 | description: string;
21 | gene_id?: string;
22 | }
23 |
24 | export interface GeneDetailsFromSearch {
25 | genomicinfo?: {
26 | chrstart: number;
27 | chrstop: number;
28 | strand?: string;
29 | }[];
30 | summary?: string;
31 | organism?: {
32 | scientificname: string;
33 | commonname: string;
34 | };
35 | }
36 |
37 | export interface GeneBounds {
38 | min: number;
39 | max: number;
40 | }
41 |
42 | export interface ClinvarVariant {
43 | clinvar_id: string;
44 | title: string;
45 | variation_type: string;
46 | classification: string;
47 | gene_sort: string;
48 | chromosome: string;
49 | location: string;
50 | evo2Result?: {
51 | prediction: string;
52 | delta_score: number;
53 | classification_confidence: number;
54 | };
55 | isAnalyzing?: boolean;
56 | evo2Error?: string;
57 | }
58 |
59 | export interface AnalysisResult {
60 | position: number;
61 | reference: string;
62 | alternative: string;
63 | delta_score: number;
64 | prediction: string;
65 | classification_confidence: number;
66 | }
67 |
68 | export async function getAvailableGenomes() {
69 | const apiUrl = "https://api.genome.ucsc.edu/list/ucscGenomes";
70 | const response = await fetch(apiUrl);
71 | if (!response.ok) {
72 | throw new Error("Failed to fetch genome list from UCSC API");
73 | }
74 |
75 | const genomeData = await response.json();
76 | if (!genomeData.ucscGenomes) {
77 | throw new Error("UCSC API error: missing ucscGenomes");
78 | }
79 |
80 | const genomes = genomeData.ucscGenomes;
81 | const structuredGenomes: Record = {};
82 |
83 | for (const genomeId in genomes) {
84 | const genomeInfo = genomes[genomeId];
85 | const organism = genomeInfo.organism || "Other";
86 |
87 | if (!structuredGenomes[organism]) structuredGenomes[organism] = [];
88 | structuredGenomes[organism].push({
89 | id: genomeId,
90 | name: genomeInfo.description || genomeId,
91 | sourceName: genomeInfo.sourceName || genomeId,
92 | active: !!genomeInfo.active,
93 | });
94 | }
95 |
96 | return { genomes: structuredGenomes };
97 | }
98 |
99 | export async function getGenomeChromosomes(genomeId: string) {
100 | const apiUrl = `https://api.genome.ucsc.edu/list/chromosomes?genome=${genomeId}`;
101 | const response = await fetch(apiUrl);
102 | if (!response.ok) {
103 | throw new Error("Failed to fetch chromosome list from UCSC API");
104 | }
105 |
106 | const chromosomeData = await response.json();
107 | if (!chromosomeData.chromosomes) {
108 | throw new Error("UCSC API error: missing chromosomes");
109 | }
110 |
111 | const chromosomes: ChromosomeFromSeach[] = [];
112 | for (const chromId in chromosomeData.chromosomes) {
113 | if (
114 | chromId.includes("_") ||
115 | chromId.includes("Un") ||
116 | chromId.includes("random")
117 | )
118 | continue;
119 | chromosomes.push({
120 | name: chromId,
121 | size: chromosomeData.chromosomes[chromId],
122 | });
123 | }
124 |
125 | // chr1, chr2, ... chrX, chrY
126 | chromosomes.sort((a, b) => {
127 | const anum = a.name.replace("chr", "");
128 | const bnum = b.name.replace("chr", "");
129 | const isNumA = /^\d+$/.test(anum);
130 | const isNumB = /^\d+$/.test(bnum);
131 | if (isNumA && isNumB) return Number(anum) - Number(bnum);
132 | if (isNumA) return -1;
133 | if (isNumB) return 1;
134 | return anum.localeCompare(bnum);
135 | });
136 |
137 | return { chromosomes };
138 | }
139 |
140 | export async function searchGenes(query: string, genome: string) {
141 | const url = "https://clinicaltables.nlm.nih.gov/api/ncbi_genes/v3/search";
142 | const params = new URLSearchParams({
143 | terms: query,
144 | df: "chromosome,Symbol,description,map_location,type_of_gene",
145 | ef: "chromosome,Symbol,description,map_location,type_of_gene,GenomicInfo,GeneID",
146 | });
147 | const response = await fetch(`${url}?${params}`);
148 | if (!response.ok) {
149 | throw new Error("NCBI API Error");
150 | }
151 |
152 | const data = await response.json();
153 | const results: GeneFromSearch[] = [];
154 |
155 | if (data[0] > 0) {
156 | const fieldMap = data[2];
157 | const geneIds = fieldMap.GeneID || [];
158 | for (let i = 0; i < Math.min(10, data[0]); ++i) {
159 | if (i < data[3].length) {
160 | try {
161 | const display = data[3][i];
162 | let chrom = display[0];
163 | if (chrom && !chrom.startsWith("chr")) {
164 | chrom = `chr${chrom}`;
165 | }
166 | results.push({
167 | symbol: display[2],
168 | name: display[3],
169 | chrom,
170 | description: display[3],
171 | gene_id: geneIds[i] || "",
172 | });
173 | } catch {
174 | continue;
175 | }
176 | }
177 | }
178 | }
179 |
180 | return { query, genome, results };
181 | }
182 |
183 | export async function fetchGeneDetails(geneId: string): Promise<{
184 | geneDetails: GeneDetailsFromSearch | null;
185 | geneBounds: GeneBounds | null;
186 | initialRange: { start: number; end: number } | null;
187 | }> {
188 | try {
189 | const detailUrl = `https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=gene&id=${geneId}&retmode=json`;
190 | const detailsResponse = await fetch(detailUrl);
191 |
192 | if (!detailsResponse.ok) {
193 | console.error(
194 | `Failed to fetch gene details: ${detailsResponse.statusText}`,
195 | );
196 | return { geneDetails: null, geneBounds: null, initialRange: null };
197 | }
198 |
199 | const detailData = await detailsResponse.json();
200 |
201 | if (detailData.result && detailData.result[geneId]) {
202 | const detail = detailData.result[geneId];
203 |
204 | if (detail.genomicinfo && detail.genomicinfo.length > 0) {
205 | const info = detail.genomicinfo[0];
206 |
207 | const minPos = Math.min(info.chrstart, info.chrstop);
208 | const maxPos = Math.max(info.chrstart, info.chrstop);
209 | const bounds = { min: minPos, max: maxPos };
210 |
211 | const geneSize = maxPos - minPos;
212 | const seqStart = minPos;
213 | const seqEnd = geneSize > 10000 ? minPos + 10000 : maxPos;
214 | const range = { start: seqStart, end: seqEnd };
215 |
216 | return { geneDetails: detail, geneBounds: bounds, initialRange: range };
217 | }
218 | }
219 |
220 | return { geneDetails: null, geneBounds: null, initialRange: null };
221 | } catch (err) {
222 | return { geneDetails: null, geneBounds: null, initialRange: null };
223 | }
224 | }
225 |
226 | export async function fetchGeneSequence(
227 | chrom: string,
228 | start: number,
229 | end: number,
230 | genomeId: string,
231 | ): Promise<{
232 | sequence: string;
233 | actualRange: { start: number; end: number };
234 | error?: string;
235 | }> {
236 | try {
237 | const chromosome = chrom.startsWith("chr") ? chrom : `chr${chrom}`;
238 |
239 | const apiStart = start - 1;
240 | const apiEnd = end;
241 |
242 | const apiUrl = `https://api.genome.ucsc.edu/getData/sequence?genome=${genomeId};chrom=${chromosome};start=${apiStart};end=${apiEnd}`;
243 | const response = await fetch(apiUrl);
244 | const data = await response.json();
245 |
246 | const actualRange = { start, end };
247 |
248 | if (data.error || !data.dna) {
249 | return { sequence: "", actualRange, error: data.error };
250 | }
251 |
252 | const sequence = data.dna.toUpperCase();
253 |
254 | return { sequence, actualRange };
255 | } catch (err) {
256 | return {
257 | sequence: "",
258 | actualRange: { start, end },
259 | error: "Internal error in fetch gene sequence",
260 | };
261 | }
262 | }
263 |
264 | export async function fetchClinvarVariants(
265 | chrom: string,
266 | geneBound: GeneBounds,
267 | genomeId: string,
268 | ): Promise {
269 | const chromFormatted = chrom.replace(/^chr/i, "");
270 |
271 | const minBound = Math.min(geneBound.min, geneBound.max);
272 | const maxBound = Math.max(geneBound.min, geneBound.max);
273 |
274 | const positionField = genomeId === "hg19" ? "chrpos37" : "chrpos38";
275 | const searchTerm = `${chromFormatted}[chromosome] AND ${minBound}:${maxBound}[${positionField}]`;
276 |
277 | const searchUrl =
278 | "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi";
279 | const searchParams = new URLSearchParams({
280 | db: "clinvar",
281 | term: searchTerm,
282 | retmode: "json",
283 | retmax: "20",
284 | });
285 |
286 | const searchResponse = await fetch(`${searchUrl}?${searchParams.toString()}`);
287 |
288 | if (!searchResponse.ok) {
289 | throw new Error("ClinVar search failed: " + searchResponse.statusText);
290 | }
291 |
292 | const searchData = await searchResponse.json();
293 |
294 | if (
295 | !searchData.esearchresult ||
296 | !searchData.esearchresult.idlist ||
297 | searchData.esearchresult.idlist.length === 0
298 | ) {
299 | console.log("No ClinVar variants found");
300 | return [];
301 | }
302 |
303 | const variantIds = searchData.esearchresult.idlist;
304 |
305 | const summaryUrl =
306 | "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi";
307 | const summaryParams = new URLSearchParams({
308 | db: "clinvar",
309 | id: variantIds.join(","),
310 | retmode: "json",
311 | });
312 |
313 | const summaryResponse = await fetch(
314 | `${summaryUrl}?${summaryParams.toString()}`,
315 | );
316 |
317 | if (!summaryResponse.ok) {
318 | throw new Error(
319 | "Failed to fetch variant details: " + summaryResponse.statusText,
320 | );
321 | }
322 |
323 | const summaryData = await summaryResponse.json();
324 | const variants: ClinvarVariant[] = [];
325 |
326 | if (summaryData.result && summaryData.result.uids) {
327 | for (const id of summaryData.result.uids) {
328 | const variant = summaryData.result[id];
329 | variants.push({
330 | clinvar_id: id,
331 | title: variant.title,
332 | variation_type: (variant.obj_type || "Unknown")
333 | .split(" ")
334 | .map(
335 | (word: string) =>
336 | word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),
337 | )
338 | .join(" "),
339 | classification:
340 | variant.germline_classification.description || "Unknown",
341 | gene_sort: variant.gene_sort || "",
342 | chromosome: chromFormatted,
343 | location: variant.location_sort
344 | ? parseInt(variant.location_sort).toLocaleString()
345 | : "Unknown",
346 | });
347 | }
348 | }
349 |
350 | return variants;
351 | }
352 |
353 | export async function analyzeVariantWithAPI({
354 | position,
355 | alternative,
356 | genomeId,
357 | chromosome,
358 | }: {
359 | position: number;
360 | alternative: string;
361 | genomeId: string;
362 | chromosome: string;
363 | }): Promise {
364 | const queryParams = new URLSearchParams({
365 | variant_position: position.toString(),
366 | alternative: alternative,
367 | genome: genomeId,
368 | chromosome: chromosome,
369 | });
370 |
371 | const url = `${env.NEXT_PUBLIC_ANALYZE_SINGLE_VARIANT_BASE_URL}?${queryParams.toString()}`;
372 |
373 | const response = await fetch(url, { method: "POST" });
374 |
375 | if (!response.ok) {
376 | const errorText = await response.text();
377 | throw new Error("Failed to analyze variant " + errorText);
378 | }
379 |
380 | return await response.json();
381 | }
382 |
--------------------------------------------------------------------------------
/evo2-frontend/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | /* Base Options: */
4 | "esModuleInterop": true,
5 | "skipLibCheck": true,
6 | "target": "es2022",
7 | "allowJs": true,
8 | "resolveJsonModule": true,
9 | "moduleDetection": "force",
10 | "isolatedModules": true,
11 | "verbatimModuleSyntax": true,
12 |
13 | /* Strictness */
14 | "strict": true,
15 | "noUncheckedIndexedAccess": true,
16 | "checkJs": true,
17 |
18 | /* Bundled projects */
19 | "lib": ["dom", "dom.iterable", "ES2022"],
20 | "noEmit": true,
21 | "module": "ESNext",
22 | "moduleResolution": "Bundler",
23 | "jsx": "preserve",
24 | "plugins": [{ "name": "next" }],
25 | "incremental": true,
26 |
27 | /* Path Aliases */
28 | "baseUrl": ".",
29 | "paths": {
30 | "~/*": ["./src/*"]
31 | }
32 | },
33 | "include": [
34 | "next-env.d.ts",
35 | "**/*.ts",
36 | "**/*.tsx",
37 | "**/*.cjs",
38 | "**/*.js",
39 | ".next/types/**/*.ts"
40 | ],
41 | "exclude": ["node_modules"]
42 | }
43 |
--------------------------------------------------------------------------------
/thumbnail.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Andreaswt/variant-analysis-evo2/55741e31ae0bf3327cc97202be842f37e3fd7e6e/thumbnail.png
--------------------------------------------------------------------------------