Variant Analysis using AlphaGenome
Prerequisites
uv: Read the uv skill and follow its Setup instructions to ensure
uv is installed and on PATH.
User Notification: If
.licenses/alphagenome_single_variant_analysis_LICENSE.txt does not already
exist in the workspace root directory then (1) prominently notify the user
to check the terms at https://deepmind.google.com/science/alphagenome/, then
(2) create the file recording the notification text and timestamp.
.env file: Make sure the .env file exists in your home directory.
Create one if it does not exist.
ALPHAGENOME_API_KEY: This skill requires an API key to function.
You can register for a key at https://deepmind.google.com/science/alphagenome/.
You MUST use the safe credentials protocol in the credentials skill to
check for and request this key if this skill looks relevant to the user's request.
ALPHAGENOME_GTF_PATH (Optional): Accelerate gene/transcript lookup by
pointing to a local copy of the GTF feather file instead of downloading from
GCS:
echo "ALPHAGENOME_GTF_PATH=/path/to/local/gencode.v46.annotation.gtf.gz.feather" >> ~/.env
Core Rules
- NEVER run
python3 or python3 -c directly. The system Python does not
necessarily have pandas, numpy, and other key dependencies. ALWAYS use uv run to run ALL Python code — including scripts, ad-hoc analysis files, and
one-liners. Do not attempt to pip install or create new venvs — uv
manages an isolated environment automatically.
- Offline Only: NEVER use external APIs (e.g., MyGene.info, Ensembl REST)
for gene/transcript lookup. Use
lookup_gene_info.py with the local GTF. If
it fails, fix the environment/paths, do not switch to external APIs.
- API Key is required:
ALPHAGENOME_API_KEY must be set before running
any script.
- Notification: If this skill is used, ensure this is mentioned in the
output.
- Report Format: Always use the templates in
docs/report-templates.md
for generating analysis reports, and ensure to include the table of top hits
from the discovery scan.
Environment Setup & Troubleshooting
Python Environment
All scripts must be executed using uv run, which manages an isolated virtual
environment with the correct dependencies via uv.
uv run <script_name> [args...]
For ad-hoc scripts (e.g., inline analysis code saved to a temp file), pass the
full path instead of a short name:
uv run --project $SKILL_DIR /tmp/my_analysis.py --arg1 val1
[!NOTE] The first invocation resolves and installs dependencies (10s).
Subsequent runs use the cached environment and start instantly. The cache
lives in `/.cache/uv/`.
Common Issues
- Column Names:
tidy_scores and metadata often use gene_name (not
gene_symbol) and output_type (not modality). Always inspect
df.columns before filtering.
- Large Genes: Genes > 500kb (e.g.,
USH2A) break the whole_gene view.
Use --view detail or manual regional windows instead.
- Sashimi Strand Error:
plot_components.Sashimi does NOT accept a
strand argument directly. Filter input tracks instead.
- KeyError: 'ontology_curie': Not all tracks have
ontology_curie. Check
track.metadata.columns before filtering.
- Python Path: If
exec: "python": executable file not found occurs,
ensure you are using uv run instead of bare python/python3.
- NotImplementedError (pandas): "iLocation based boolean indexing on an
integer type is not available". This occurs when using boolean masks with
.iloc on integer-indexed DataFrames in newer pandas versions. Fix:
Convert boolean masks to integer indices using np.flatnonzero(mask).
- GTF Feather Case Sensitivity: The AlphaGenome GTF Feather file uses
Capitalized column names (
Feature, Start, End, Strand) unlike
standard GTF files. Always check df.columns if getting KeyErrors.
score_variant ontology filtering: score_variant does NOT accept
ontology_terms as an argument. You must filter the returned AnnData
objects manually by inspecting adata.var columns. In contrast,
predict_variant DOES accept ontology_terms directly.
- Sashimi Zoom Logic: To ensure "skipping" arcs are visible, expand the
zoom to include the flanking exons rather than relying on junction
overlap alone.
- Junction Scores: Raw
Junction objects from prediction may be simple
Intervals. Use junction_data.get_junctions_to_plot(predictions=..., name=...) to retrieve objects with the .k (abundance/score) attribute.
uv Not Found: If exec: uv: not found, follow the installation
instructions in Prerequisites.
- Registry Authentication Error (401): If
uv fails with 401 Unauthorized
for a private registry, set UV_INDEX_URL=https://pypi.org/simple before
running the script.
References
- alphagenome-api.md — API reference and code
patterns
- interpretation-guide.md — Interpretation
guide, score magnitude rules, ISM, and checklist.
- report-templates.md — Full report templates
scripts/visualize_variant_effects.py
— Single-variant visualization template (Ref/Alt comparisons, Splicing).
- Splicing Zoom Strategy: Uses a Hybrid Approach for optimal
visibility:
- Base Interval: Variant +/- 1 downstream and upstream exon
(Structural Context).
- Junction Expansion: Expands to include the full span of any
significant splicing junction (e.g., exon skipping events that
span multiple exons).
- Anchor Enforcement: Ensures the exons anchoring these long
junctions are fully visible. Lesson: Simple fixed windows (e.g.,
2kb) or nearest-exon logic often fail for skipping events. Always
use the observed junction data to drive zoom levels.
examples/splicing/ — Splicing analysis examples
examples/model_limitation_RNU4ATAC/
— ncRNA structure limitation case study
examples/polyadenylation_HBA2/ — 3'
UTR / Polyadenylation case study
examples/regulatory/ — Regulatory variant
examples
examples/negative_result_GATA4/ —
Negative results (mathematical artefact)
examples/negative_result_TGFB3/ —
Negative results (proxies)
scripts/lookup_gene_info.py — Gene &
transcript lookup
scripts/resolve_ontology_terms.py —
Ontology term resolution (UBERON/CL IDs)
Code Patterns
Broad Discovery Scan
Use score_variant across differential scorers only to discover unexpected
tissue effects.
from alphagenome.models import dna_client
from alphagenome.models import variant_scorers
from alphagenome.data import genome
import os
import pandas as pd
import dotenv
# Load environment variables from ~/.env
dotenv.load_dotenv(os.path.expanduser('~/.env'))
# Setup API Key and Client
dna_model = dna_client.create(api_key=os.environ.get('ALPHAGENOME_API_KEY'),
address='dns:///gdmscience.googleapis.com:443')
# Define Variant (example)
variant_str = "chr2:1234:A>C"
chrom, pos_str, ref_alt = variant_str.split(':')
ref, alt = ref_alt.split('>')
pos = int(pos_str)
# Use supported sequence length (e.g., 2**20 for optimal performance)
SEQ_LENGTH = 2**20
interval = genome.Interval(chrom, pos - SEQ_LENGTH // 2, pos + SEQ_LENGTH // 2)
variant = genome.Variant(chrom, pos, ref, alt)
scorers = [
variant_scorers.RECOMMENDED_VARIANT_SCORERS[m]
for m in variant_scorers.RECOMMENDED_VARIANT_SCORERS
if "ACTIVE" not in m and "CAGE" not in m and "PROCAP" not in m
]
print(f"Scoring variant {variant_str}...")
scores_list = dna_model.score_variant(interval=interval, variant=variant, variant_scorers=scorers)
# Process and Display Results
all_dfs = []
for score_adata in scores_list:
df = variant_scorers.tidy_scores([score_adata], match_gene_strand=True)
if df is not None:
all_dfs.append(df)
if all_dfs:
df = pd.concat(all_dfs)
significant = df[df['quantile_score'].abs() > 0.995]
ranked = significant.sort_values('raw_score', key=abs, ascending=False)
print("Top Significant Hits:")
print(ranked[['biosample_name', 'gene_name', 'output_type', 'quantile_score', 'raw_score']])
Extended Search for Disease-Relevant Tissues
# Define keywords based on disease context
disease_keywords = ["liver", "hepatocyte"]
# Filter for any match
mask = df['biosample_name'].str.contains('|'.join(disease_keywords), case=False, na=False)
relevant_hits = df[mask].sort_values('raw_score', key=abs, ascending=False)
print(f"\n--- Extended Analysis (Keywords: {disease_keywords}) ---")
print(relevant_hits.head(20)[['biosample_name', 'output_type', 'raw_score', 'quantile_score']])
Workflow Checklist
Variant Analysis Progress:
- [ ] Step 0: Review Golden Examples (MANDATORY)
- [ ] Step 1: Create Output Folder and Setup
- [ ] Step 2: Parse User Query & Research
- [ ] Step 3: Resolve Tissues & Modalities
- [ ] Step 4: Visualize & Save Plots
- [ ] Step 5: Analyze Predictions (view plots, no code). MANDATORY: Read [interpretation-guide.md](docs/interpretation-guide.md) before interpreting results.
- [ ] Step 6: Write Report, save it as `report.md` (MANDATORY)
- [ ] Step 7: Self-Critique (view `report.md` to verify links & claims)
- [ ] Step 8: Make artifact out of `report.md`
Multi-Variant Workflow
If multiple variants are specified, spawn sub-agents to run each variant
analysis and then synthesize each report.md into a single report.
Script Reference
| Script |
Purpose |
lookup_gene_info |
Comprehensive gene and transcript lookup using |
| : : GTF data : |
|
resolve_ontology_terms |
Biological terms → UBERON/CL/EFO IDs |
visualize_variant_effects |
REF/ALT visualization (expression, regulatory, |
| : : splicing) : |
|
analyze_ism |
In-Silico Mutagenesis SeqLogo generation |
interpret_splicing |
Quantitative splicing analysis (delta scores, |
| : : junctions) : |
|
visualize_genome_tracks |
Genomic track visualization for a region |
1---
2name: alphagenome-single-variant-analysis
3description: >
4 Analyzes genetic variant effects on gene expression (RNA-seq), chromatin
5 accessibility (DNASE), histone marks (ChIP), and transcription factors
6 using the AlphaGenome API. Use when the user asks about non-coding variant effects,
7 pathogenicity, clinical significance, disease associations, functional
8 effects, gene expression changes, splicing disruption, or regulatory effects
9 in promoters and enhancers. Also use for resolving biological terms to
10 tissue/cell-type ontologies (UBERON/CL) or analyzing variants in
11 chr:pos:ref>alt format.
12metadata:
13 source: https://skillmd.com/skills/google-deepmind/alphagenome-single-variant-analysis
14---
15
16# Variant Analysis using AlphaGenome
17
18## Prerequisites
19
201. **`uv`**: Read the `uv` skill and follow its Setup instructions to ensure
21 `uv` is installed and on PATH.
222. **User Notification**: If
23 .licenses/alphagenome_single_variant_analysis_LICENSE.txt does not already
24 exist in the workspace root directory then (1) prominently notify the user
25 to check the terms at https://deepmind.google.com/science/alphagenome/, then
26 (2) create the file recording the notification text and timestamp.
273. **`.env` file**: Make sure the `.env` file exists in your home directory.
28 Create one if it does not exist.
294. **`ALPHAGENOME_API_KEY`**: This skill requires an API key to function.
30
31 You can register for a key at https://deepmind.google.com/science/alphagenome/.
32 You **MUST** use the safe credentials protocol in the `credentials` skill to
33 check for and request this key if this skill looks relevant to the user's request.
345. **`ALPHAGENOME_GTF_PATH` (Optional)**: Accelerate gene/transcript lookup by
35 pointing to a local copy of the GTF feather file instead of downloading from
36 GCS:
37
38 ```bash
39 echo "ALPHAGENOME_GTF_PATH=/path/to/local/gencode.v46.annotation.gtf.gz.feather" >> ~/.env
40 ```
41
42## Core Rules
43
44- **NEVER run `python3` or `python3 -c` directly.** The system Python does not
45 necessarily have pandas, numpy, and other key dependencies. ALWAYS use `uv
46 run` to run ALL Python code — including scripts, ad-hoc analysis files, and
47 one-liners. Do not attempt to `pip install` or create new venvs — `uv`
48 manages an isolated environment automatically.
49- **Offline Only**: NEVER use external APIs (e.g., MyGene.info, Ensembl REST)
50 for gene/transcript lookup. Use `lookup_gene_info.py` with the local GTF. If
51 it fails, fix the environment/paths, do not switch to external APIs.
52- **API Key is required**: `ALPHAGENOME_API_KEY` must be set before running
53 any script.
54- **Notification**: If this skill is used, ensure this is mentioned in the
55 output.
56- **Report Format**: Always use the templates in `docs/report-templates.md`
57 for generating analysis reports, and ensure to include the table of top hits
58 from the discovery scan.
59
60## Environment Setup & Troubleshooting
61
62### Python Environment
63
64All scripts must be executed using `uv run`, which manages an isolated virtual
65environment with the correct dependencies via `uv`.
66
67```bash
68uv run <script_name> [args...]
69```
70
71For ad-hoc scripts (e.g., inline analysis code saved to a temp file), pass the
72full path instead of a short name:
73
74```bash
75uv run --project $SKILL_DIR /tmp/my_analysis.py --arg1 val1
76```
77
78> [!NOTE] The first invocation resolves and installs dependencies (~10s).
79> Subsequent runs use the cached environment and start instantly. The cache
80> lives in `~/.cache/uv/`.
81
82### Common Issues
83
84- **Column Names**: `tidy_scores` and metadata often use `gene_name` (not
85 `gene_symbol`) and `output_type` (not `modality`). Always inspect
86 `df.columns` before filtering.
87- **Large Genes**: Genes > 500kb (e.g., `USH2A`) break the `whole_gene` view.
88 Use `--view detail` or manual regional windows instead.
89- **Sashimi Strand Error**: `plot_components.Sashimi` does NOT accept a
90 `strand` argument directly. Filter input tracks instead.
91- **KeyError: 'ontology_curie'**: Not all tracks have `ontology_curie`. Check
92 `track.metadata.columns` before filtering.
93- **Python Path**: If `exec: "python": executable file not found` occurs,
94 ensure you are using `uv run` instead of bare `python`/`python3`.
95- **NotImplementedError (pandas)**: "iLocation based boolean indexing on an
96 integer type is not available". This occurs when using boolean masks with
97 `.iloc` on integer-indexed DataFrames in newer pandas versions. **Fix**:
98 Convert boolean masks to integer indices using `np.flatnonzero(mask)`.
99- **GTF Feather Case Sensitivity**: The AlphaGenome GTF Feather file uses
100 **Capitalized** column names (`Feature`, `Start`, `End`, `Strand`) unlike
101 standard GTF files. Always check `df.columns` if getting KeyErrors.
102- **`score_variant` ontology filtering**: `score_variant` does NOT accept
103 `ontology_terms` as an argument. You must filter the returned AnnData
104 objects manually by inspecting `adata.var` columns. In contrast,
105 `predict_variant` DOES accept `ontology_terms` directly.
106- **Sashimi Zoom Logic**: To ensure "skipping" arcs are visible, expand the
107 zoom to include the **flanking exons** rather than relying on junction
108 overlap alone.
109- **Junction Scores**: Raw `Junction` objects from `prediction` may be simple
110 Intervals. Use `junction_data.get_junctions_to_plot(predictions=...,
111 name=...)` to retrieve objects with the `.k` (abundance/score) attribute.
112- **`uv` Not Found**: If `exec: uv: not found`, follow the installation
113 instructions in [Prerequisites](#prerequisites).
114- **Registry Authentication Error (401)**: If `uv` fails with 401 Unauthorized
115 for a private registry, set `UV_INDEX_URL=https://pypi.org/simple` before
116 running the script.
117
118## References
119
120- [alphagenome-api.md](docs/alphagenome-api.md) — API reference and code
121 patterns
122- [interpretation-guide.md](docs/interpretation-guide.md) — Interpretation
123 guide, score magnitude rules, ISM, and checklist.
124- [report-templates.md](docs/report-templates.md) — Full report templates
125- [`scripts/visualize_variant_effects.py`](scripts/visualize_variant_effects.py)
126 — Single-variant visualization template (Ref/Alt comparisons, Splicing).
127 - **Splicing Zoom Strategy**: Uses a **Hybrid Approach** for optimal
128 visibility:
129 1. **Base Interval**: Variant +/- 1 downstream and upstream exon
130 (Structural Context).
131 2. **Junction Expansion**: Expands to include the full span of any
132 **significant splicing junction** (e.g., exon skipping events that
133 span multiple exons).
134 3. **Anchor Enforcement**: Ensures the exons *anchoring* these long
135 junctions are fully visible. *Lesson*: Simple fixed windows (e.g.,
136 2kb) or nearest-exon logic often fail for skipping events. Always
137 use the *observed junction data* to drive zoom levels.
138- [`examples/splicing/`](docs/examples/splicing/) — Splicing analysis examples
139- [`examples/model_limitation_RNU4ATAC/`](docs/examples/model_limitation_RNU4ATAC/)
140 — ncRNA structure limitation case study
141- [`examples/polyadenylation_HBA2/`](docs/examples/polyadenylation_HBA2/) — 3'
142 UTR / Polyadenylation case study
143- [`examples/regulatory/`](docs/examples/regulatory/) — Regulatory variant
144 examples
145- [`examples/negative_result_GATA4/`](docs/examples/negative_result_GATA4/) —
146 Negative results (mathematical artefact)
147- [`examples/negative_result_TGFB3/`](docs/examples/negative_result_TGFB3/) —
148 Negative results (proxies)
149- [`scripts/lookup_gene_info.py`](scripts/lookup_gene_info.py) — Gene &
150 transcript lookup
151- [`scripts/resolve_ontology_terms.py`](scripts/resolve_ontology_terms.py) —
152 Ontology term resolution (UBERON/CL IDs)
153
154--------------------------------------------------------------------------------
155
156## Code Patterns
157
158### Broad Discovery Scan
159
160Use `score_variant` across **differential scorers only** to discover unexpected
161tissue effects.
162
163```python
164from alphagenome.models import dna_client
165from alphagenome.models import variant_scorers
166from alphagenome.data import genome
167import os
168import pandas as pd
169import dotenv
170
171# Load environment variables from ~/.env
172dotenv.load_dotenv(os.path.expanduser('~/.env'))
173
174# Setup API Key and Client
175dna_model = dna_client.create(api_key=os.environ.get('ALPHAGENOME_API_KEY'),
176 address='dns:///gdmscience.googleapis.com:443')
177
178# Define Variant (example)
179variant_str = "chr2:1234:A>C"
180chrom, pos_str, ref_alt = variant_str.split(':')
181ref, alt = ref_alt.split('>')
182pos = int(pos_str)
183
184# Use supported sequence length (e.g., 2**20 for optimal performance)
185SEQ_LENGTH = 2**20
186interval = genome.Interval(chrom, pos - SEQ_LENGTH // 2, pos + SEQ_LENGTH // 2)
187variant = genome.Variant(chrom, pos, ref, alt)
188
189scorers = [
190 variant_scorers.RECOMMENDED_VARIANT_SCORERS[m]
191 for m in variant_scorers.RECOMMENDED_VARIANT_SCORERS
192 if "ACTIVE" not in m and "CAGE" not in m and "PROCAP" not in m
193]
194
195print(f"Scoring variant {variant_str}...")
196scores_list = dna_model.score_variant(interval=interval, variant=variant, variant_scorers=scorers)
197
198# Process and Display Results
199all_dfs = []
200for score_adata in scores_list:
201 df = variant_scorers.tidy_scores([score_adata], match_gene_strand=True)
202 if df is not None:
203 all_dfs.append(df)
204
205if all_dfs:
206 df = pd.concat(all_dfs)
207 significant = df[df['quantile_score'].abs() > 0.995]
208 ranked = significant.sort_values('raw_score', key=abs, ascending=False)
209 print("Top Significant Hits:")
210 print(ranked[['biosample_name', 'gene_name', 'output_type', 'quantile_score', 'raw_score']])
211```
212
213### Extended Search for Disease-Relevant Tissues
214
215```python
216# Define keywords based on disease context
217disease_keywords = ["liver", "hepatocyte"]
218
219# Filter for any match
220mask = df['biosample_name'].str.contains('|'.join(disease_keywords), case=False, na=False)
221
222relevant_hits = df[mask].sort_values('raw_score', key=abs, ascending=False)
223print(f"\n--- Extended Analysis (Keywords: {disease_keywords}) ---")
224print(relevant_hits.head(20)[['biosample_name', 'output_type', 'raw_score', 'quantile_score']])
225```
226
227## Workflow Checklist
228
229```
230Variant Analysis Progress:
231- [ ] Step 0: Review Golden Examples (MANDATORY)
232- [ ] Step 1: Create Output Folder and Setup
233- [ ] Step 2: Parse User Query & Research
234- [ ] Step 3: Resolve Tissues & Modalities
235- [ ] Step 4: Visualize & Save Plots
236- [ ] Step 5: Analyze Predictions (view plots, no code). MANDATORY: Read [interpretation-guide.md](docs/interpretation-guide.md) before interpreting results.
237- [ ] Step 6: Write Report, save it as `report.md` (MANDATORY)
238- [ ] Step 7: Self-Critique (view `report.md` to verify links & claims)
239- [ ] Step 8: Make artifact out of `report.md`
240```
241
242--------------------------------------------------------------------------------
243
244## Multi-Variant Workflow
245
246If multiple variants are specified, spawn sub-agents to run each variant
247analysis and then synthesize each `report.md` into a single report.
248
249### Script Reference
250
251| Script | Purpose |
252| --------------------------- | ---------------------------------------------- |
253| `lookup_gene_info` | Comprehensive gene and transcript lookup using |
254: : GTF data :
255| `resolve_ontology_terms` | Biological terms → UBERON/CL/EFO IDs |
256| `visualize_variant_effects` | REF/ALT visualization (expression, regulatory, |
257: : splicing) :
258| `analyze_ism` | In-Silico Mutagenesis SeqLogo generation |
259| `interpret_splicing` | Quantitative splicing analysis (delta scores, |
260: : junctions) :
261| `visualize_genome_tracks` | Genomic track visualization for a region |