Download dev/code_google-deepmind__science-skills.txt from ag2003/length-extrapolating-architecture-data: direct link, hf CLI and curl.
- Browser
- Download file 94.7 kB
-
https://huggingface.co/datasets/ag2003/length-extrapolating-architecture-data/resolve/main/dev/code_google-deepmind__science-skills.txt
- Command line
-
hf download hf://datasets/ag2003/length-extrapolating-architecture-data/dev/code_google-deepmind__science-skills.txt
-
curl -L -o code_google-deepmind__science-skills.txt https://huggingface.co/datasets/ag2003/length-extrapolating-architecture-data/resolve/main/dev/code_google-deepmind__science-skills.txt
94.7 kB
# ===== file: skills/workflow_skill_creator/references/cli_script_template.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CLI script template for skills that wrap external APIs.
Copy and adapt this pattern when generating a multi-command CLI script for a
new skill. This follows the same structure as clinvar_api.py and screen_api.py.
Key design decisions:
- Uses argparse with subcommands (one per workflow step).
- All subcommands write output to a JSON file via --output.
- Uses stdlib only (urllib, json, argparse) — no requests, no third-party deps.
- Built-in rate limiting with dedicated RateLimitError and retry logic.
"""
import argparse
import json
import sys
import time
from urllib import error as urllib_error
from urllib import parse as urllib_parse
from urllib import request as urllib_request
class RateLimitError(Exception):
"""Raised when the API rate limit is exceeded."""
class MyAPIClient:
"""Client for the Example API with built-in rate limiting.
Replace with your actual API. Adapt this class as follows:
1. Set BASE_URL to your API's base URL.
2. Set REQUESTS_PER_SECOND to the documented rate limit.
3. Implement domain-specific query methods.
"""
BASE_URL = 'https://api.example.com/v1'
REQUESTS_PER_SECOND = 5
def __init__(self):
self.delay = 1.0 / self.REQUESTS_PER_SECOND
self.last_request_time = 0.0
def _wait_for_rate_limit(self):
"""Blocks until enough time has passed since the last request."""
elapsed = time.monotonic() - self.last_request_time
if elapsed < self.delay:
time.sleep(self.delay - elapsed)
def _request(self, path, params=None, retries=3):
"""Makes an HTTP GET request with rate limiting and retry logic.
Args:
path: URL path relative to BASE_URL (e.g., '/search').
params: Optional dict of query parameters.
retries: Number of retry attempts for transient server errors.
Returns:
Parsed JSON response as a Python dict/list.
Raises:
RateLimitError: If the server responds with HTTP 429.
RuntimeError: If the request fails after all retries.
"""
url = f'{self.BASE_URL}{path}'
if params:
url = f'{url}?{urllib_parse.urlencode(params)}'
for attempt in range(retries):
self._wait_for_rate_limit()
try:
req = urllib_request.Request(url)
req.add_header('Accept', 'application/json')
with urllib_request.urlopen(req, timeout=30) as response:
self.last_request_time = time.monotonic()
return json.loads(response.read().decode('utf-8'))
except urllib_error.HTTPError as e:
self.last_request_time = time.monotonic()
if e.code == 429:
# Rate limited — exponential backoff before retry
wait = 2**attempt
print(
f'Rate limited (429), retrying in {wait}s '
f'(attempt {attempt + 1}/{retries})...',
file=sys.stderr,
)
if attempt == retries - 1:
raise RateLimitError(
f'HTTP 429 Too Many Requests from {self.BASE_URL}. '
f'The API rate limit ({self.REQUESTS_PER_SECOND} req/s) has '
f'been exceeded after {retries} retries.'
) from e
time.sleep(wait)
continue
if e.code >= 500:
# Transient server error — exponential backoff
wait = 2**attempt
print(
f'Server error {e.code}, retrying in {wait}s '
f'(attempt {attempt + 1}/{retries})...',
file=sys.stderr,
)
if attempt == retries - 1:
raise RuntimeError(
f'Server error {e.code} from {url} after {retries} retries.'
) from e
time.sleep(wait)
continue
# Non-retriable client error — read the response body for details
try:
body = e.read().decode('utf-8', errors='replace')[:1000]
except OSError:
body = e.reason
raise RuntimeError(f'HTTP {e.code} from {url}: {body}') from e
except urllib_error.URLError as e:
if attempt == retries - 1:
raise RuntimeError(
f'Failed to connect to {url} after {retries} attempts: {e}'
) from e
time.sleep(2**attempt)
def search(self, query, limit=100):
"""Example search method. Replace with your API's search endpoint."""
return self._request('/search', params={'q': query, 'limit': limit})
def get_details(self, item_id):
"""Example detail method. Replace with your API's detail endpoint."""
return self._request(f'/items/{item_id}')
def write_output(data, output_file):
"""Writes data to a JSON file.
Args:
data: The data to serialize (dict or list).
output_file: Path to the output file.
"""
try:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
print(f'Success! Data written to: {output_file}')
except (OSError, TypeError) as e:
print(f'Error writing to file {output_file}: {e}', file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(description='Example API Wrapper Script')
subparsers = parser.add_subparsers(dest='command', required=True)
# --- Subcommand: search ---
p_search = subparsers.add_parser(
'search',
help='Search for items by query',
)
p_search.add_argument(
'--query',
required=True,
help='Search query string',
)
p_search.add_argument(
'--limit',
type=int,
required=True,
help='Maximum number of results to return',
)
p_search.add_argument(
'--output',
required=True,
help='Output JSON file path',
)
# --- Subcommand: details ---
p_details = subparsers.add_parser(
'details',
help='Get detailed information for a specific item',
)
p_details.add_argument(
'--id',
required=True,
dest='item_id',
help='Item ID to retrieve',
)
p_details.add_argument(
'--output',
required=True,
help='Output JSON file path',
)
args = parser.parse_args()
client = MyAPIClient()
if args.command == 'search':
data = client.search(args.query, limit=args.limit)
elif args.command == 'details':
data = client.get_details(args.item_id)
else:
print(f'Unknown command: {args.command}', file=sys.stderr)
sys.exit(1)
write_output(data, args.output)
if __name__ == '__main__':
main()
# ===== file: skills/alphafold_database_fetch_and_analyze/scripts/analyze_pae.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Analyzes Predicted Aligned Error (PAE) and detects domain boundaries."""
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
import argparse
import itertools
import json
import os
def find_sub_domains(pae_matrix, distance_cutoff=7.0, min_domain_size=40):
"""Identifies structurally independent sub-domains based on the PAE matrix."""
n_res = len(pae_matrix)
domains = []
current_domain = []
for i in range(n_res):
if not current_domain:
current_domain.append(i)
continue
window_size = min(20, len(current_domain))
recent_res = current_domain[-window_size:]
pae_sum = sum(pae_matrix[r][i] + pae_matrix[i][r] for r in recent_res)
avg_pae = pae_sum / (2.0 * window_size)
if avg_pae < distance_cutoff:
current_domain.append(i)
else:
if len(current_domain) >= min_domain_size:
domains.append(current_domain)
current_domain = [i]
if len(current_domain) >= min_domain_size:
domains.append(current_domain)
domain_boundaries = []
for comp in domains:
start = comp[0] + 1
end = comp[-1] + 1
domain_boundaries.append([start, end])
return domain_boundaries
def merge_global_domains(boundaries, pae_matrix, merge_cutoff=15.0):
"""Merges sub-domains if the average PAE between them is below cutoff."""
if not boundaries:
return []
if len(boundaries) == 1:
merged = boundaries
else:
merged = [boundaries[0]]
for i in range(1, len(boundaries)):
prev_end = merged[-1][1] - 1
curr_start = boundaries[i][0] - 1
lookback = max(merged[-1][0] - 1, prev_end - 30)
lookfwd = min(boundaries[i][1] - 1, curr_start + 30)
pae_sum = 0
n_pairs = 0
for r1 in range(lookback, prev_end + 1):
for r2 in range(curr_start, lookfwd + 1):
pae_sum += pae_matrix[r1][r2] + pae_matrix[r2][r1]
n_pairs += 2
if n_pairs > 0 and (pae_sum / n_pairs) < merge_cutoff:
merged[-1][1] = boundaries[i][1]
else:
merged.append(boundaries[i])
filtered_merged = [dom for dom in merged if (dom[1] - dom[0] + 1) > 50]
return filtered_merged
def analyze_pae(pae_file):
"""Parses a PAE JSON file and calculates structural domain metrics."""
print(
"\n[*] Analyzing Predicted Aligned Error (PAE) from"
f" {os.path.basename(pae_file)}..."
)
try:
with open(pae_file, "r") as f:
data = json.load(f)[0]
if "predicted_aligned_error" in data:
pae = data["predicted_aligned_error"]
elif "distance" in data:
pae = data["distance"]
else:
print(
" [!] Could not locate PAE matrix in JSON keys:"
f" {list(data.keys())}"
)
return
flat_pae = list(itertools.chain.from_iterable(pae))
if not flat_pae:
print(" [!] PAE matrix is empty.")
return
mean_pae = sum(flat_pae) / len(flat_pae)
max_pae = max(flat_pae)
min_pae = min(flat_pae)
confident_pairs = sum(1 for p in flat_pae if p < 5.0) / len(flat_pae) * 100
print(f" -> PAE Matrix Shape: {len(pae)}x{len(pae[0])}")
print(f" -> Mean Error: {mean_pae:.2f} Å")
print(
f" -> Max Error: {max_pae:.2f} Å (suggests max possible distance"
" between domains)"
)
print(f" -> Min Error: {min_pae:.2f} Å")
print(
" -> Fraction of confident residue pairs (<5Å PAE):"
f" {confident_pairs:.1f}%"
)
sub_domains = find_sub_domains(pae, distance_cutoff=7.0, min_domain_size=40)
global_domains = merge_global_domains(sub_domains, pae, merge_cutoff=15.0)
print("\n[*] Domain Boundary Analysis:")
if not global_domains:
print(" -> No distinct rigidly-folded domains detected (>50 AAs).")
else:
print(
" -> Number of distinct Global Domains detected:"
f" {len(global_domains)}"
)
for i, (start, end) in enumerate(global_domains, 1):
print(
f" Domain {i}: residues {start} - {end} (Length:"
f" {end - start + 1} AAs)"
)
print("\n[*] PAE Structural Conclusion:")
if len(global_domains) == 1:
conclusion = (
"The protein consists of a single well-folded, rigid composite"
" domain."
)
elif len(global_domains) > 1:
conclusion = (
f"The protein has {len(global_domains)} independently positioned"
" global domains separated by truly flexible joints."
)
else:
conclusion = (
"The protein is likely entirely disordered or lacks rigid"
" tertiary structure."
)
print(f" -> {conclusion}")
return {
"pae_file": os.path.basename(pae_file),
"matrix_shape": f"{len(pae)}x{len(pae[0])}",
"mean_pae": round(mean_pae, 2),
"max_pae": round(max_pae, 2),
"min_pae": round(min_pae, 2),
"confident_pairs_pct": round(confident_pairs, 1),
"domains": [
{"start": s, "end": e, "length": e - s + 1}
for s, e in global_domains
],
"conclusion": conclusion,
}
except (IOError, json.JSONDecodeError) as e:
print(f" [!] Failed to analyze PAE file: {e}")
return None
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Analyze PAE matrix and detect domain boundaries from an AlphaFold"
" PAE JSON file"
)
)
parser.add_argument(
"pae_file",
help=(
"Path to the PAE JSON file (e.g.,"
" AF-P04637-F1-predicted_aligned_error_v6.json)"
),
)
args = parser.parse_args()
analyze_pae(args.pae_file)
# ===== file: skills/alphafold_database_fetch_and_analyze/scripts/analyze_plddt.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Analyzes pLDDT confidence metrics from a saved AFDB metadata JSON file."""
# /// script
# requires-python = ">=3.10"
# dependencies = []
# ///
import argparse
import json
import sys
CONFIDENT_THRESHOLD = 0.7
MODERATE_THRESHOLD = 0.4
NOTABLE_DISORDER_THRESHOLD = 0.15
MIXED_DISORDER_THRESHOLD = 0.3
MOSTLY_DISORDERED_THRESHOLD = 0.5
def analyze_plddt(metadata_file):
"""Loads an AFDB metadata JSON and analyzes pLDDT metrics."""
try:
with open(metadata_file, "r") as f:
entry = json.load(f)
except (IOError, json.JSONDecodeError) as e:
print(f"[!] Error reading metadata file: {e}")
sys.exit(1)
return _analyze_entry(entry)
def _analyze_entry(entry):
"""Parses and analyzes pLDDT confidence metrics from the API payload."""
accession = entry.get("uniprotAccession", "Unknown")
print(f"\n[*] AlphaFold pLDDT Metrics for Accession: {accession}")
global_plddt = entry.get("globalMetricValue", 0.0)
frac_vlow = entry.get("fractionPlddtVeryLow", 0.0)
frac_low = entry.get("fractionPlddtLow", 0.0)
frac_conf = entry.get("fractionPlddtConfident", 0.0)
frac_vhigh = entry.get("fractionPlddtVeryHigh", 0.0)
print("-" * 65)
print(f" -> Overall Global pLDDT : {global_plddt:.2f}")
print(f" -> Fraction Very Low (<50): {frac_vlow:.3f} ({frac_vlow*100:.1f}%)")
print(f" -> Fraction Low (50-70) : {frac_low:.3f} ({frac_low*100:.1f}%)")
print(f" -> Fraction Confident : {frac_conf:.3f} ({frac_conf*100:.1f}%)")
print(
f" -> Fraction Very High : {frac_vhigh:.3f} ({frac_vhigh*100:.1f}%)"
)
print("-" * 65)
conf_total = frac_conf + frac_vhigh
print("[*] pLDDT Conclusion:")
if conf_total >= CONFIDENT_THRESHOLD:
if frac_vlow > NOTABLE_DISORDER_THRESHOLD:
conclusion = (
"Protein is mostly confidently predicted, but contains notable"
" disordered regions."
)
else:
conclusion = (
"Protein is confidently predicted and likely fully"
" ordered/structured."
)
elif conf_total >= MODERATE_THRESHOLD:
if frac_vlow >= MIXED_DISORDER_THRESHOLD:
conclusion = (
"Protein has a mixture of confidently predicted structured"
" domains and significant intrinsically disordered regions."
)
else:
conclusion = (
"Protein has moderate prediction confidence. Certain regions"
" might be flexible or poorly predicted."
)
else:
if frac_vlow >= MOSTLY_DISORDERED_THRESHOLD:
conclusion = (
"Protein is mostly poorly predicted, likely being highly"
" intrinsically disordered."
)
else:
conclusion = "Protein prediction is of low confidence overall."
print(f" -> {conclusion}")
print()
return {
"uniprot_id": accession,
"global_plddt": global_plddt,
"fractions": {
"very_low": frac_vlow,
"low": frac_low,
"confident": frac_conf,
"very_high": frac_vhigh,
},
"conclusion": conclusion,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Analyze pLDDT confidence metrics from an AFDB metadata file"
)
parser.add_argument(
"metadata_file",
help="Path to the metadata JSON file (e.g., AF-P04637-F1-metadata.json)",
)
args = parser.parse_args()
analyze_plddt(args.metadata_file)
# ===== file: skills/alphafold_database_fetch_and_analyze/scripts/fetch_structure.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Fetches AlphaFold structure files (mmCIF + PAE) for a UniProt ID."""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "polite-http",
# ]
# ///
import argparse
import json
import os
import sys
from polite_http import http_client
CLIENT = http_client.HttpClient("https://alphafold.ebi.ac.uk", qps=1.0)
def fetch_structure(uniprot_id, output_dir):
"""Downloads the mmCIF file and PAE JSON for a given UniProt ID from AFDB."""
uniprot_id = uniprot_id.strip().upper()
api_url = f"https://alphafold.ebi.ac.uk/api/prediction/{uniprot_id}"
is_fragment = False
os.makedirs(output_dir, exist_ok=True)
print(f"[*] Requesting AlphaFold data for UniProt ID: {uniprot_id}")
try:
data = CLIENT.fetch_json(api_url)
except http_client.HttpError as e:
if e.status_code == 404:
print(
f"\n[!] Error: UniProt ID '{uniprot_id}' was not found in"
" the AlphaFold Database."
)
print(
" Please double-check the ID for typos, or verify it"
" has an AFDB entry."
)
else:
print(f"[!] HTTP error fetching API data: {e}")
sys.exit(1)
if not data:
print(f"[!] No AlphaFold data returned for {uniprot_id}")
sys.exit(1)
# The API may return multiple entries (e.g. isoforms) for a single
# UniProt ID. Prefer the canonical entry whose accession matches exactly.
entry = None
for e in data:
if e.get("uniprotAccession") == uniprot_id:
entry = e
break
# If no canonical entry exists (common for very large proteins like
# Dystrophin), fall back to the longest available isoform so the user
# gets the most complete structure.
if entry is None:
entry = max(data, key=lambda e: e.get("sequenceEnd", 0))
entry_acc = entry.get("uniprotAccession", "unknown")
entry_len = entry.get("sequenceEnd", 0)
print(
"[!] WARNING: No canonical AFDB entry found for"
f" '{uniprot_id}'. Using longest available isoform"
f" '{entry_acc}' ({entry_len} amino acids) instead."
" The full-length protein may not be available in AFDB."
)
max_seq_len = max((e.get("sequenceEnd", 0) for e in data), default=0)
if max_seq_len > 2700:
print(
f"[!] WARNING: Protein {uniprot_id} is massive"
f" ({max_seq_len} amino acids). Only the first entry has"
" been downloaded. The full protein may span many more"
" fragments in AFDB."
)
is_fragment = True
entry_acc = entry.get("uniprotAccession", uniprot_id)
metadata_filename = f"AF-{entry_acc}-F1-metadata.json"
metadata_path = os.path.join(output_dir, metadata_filename)
with open(metadata_path, "w") as f:
json.dump(entry, f, indent=2)
print(f" -> Saved API metadata to: {metadata_path}")
cif_url = entry.get("cifUrl")
pae_url = entry.get("paeDocUrl")
urls_to_fetch = []
if cif_url:
urls_to_fetch.append(cif_url)
if pae_url:
urls_to_fetch.append(pae_url)
success_count = 0
for url in urls_to_fetch:
filename = url.split("/")[-1]
file_path = os.path.join(output_dir, filename)
print(f" -> Fetching {filename}...")
try:
file_bytes = CLIENT.fetch_bytes(url)
with open(file_path, "wb") as f:
f.write(file_bytes)
print(f" [+] Saved to: {file_path}")
success_count += 1
except http_client.HttpError as e:
if e.status_code == 404:
print(f" [!] Error 404: {filename} not found.")
else:
print(f" [!] Download error: {e}")
if success_count == 0:
print(
f"\n[!] Failed to download any data for {uniprot_id}. Please check"
" the ID."
)
sys.exit(1)
else:
print(
f"\n[*] Successfully downloaded {success_count}/{len(urls_to_fetch)}"
" files."
)
return {
"uniprot_id": uniprot_id,
"output_dir": output_dir,
"is_fragment": is_fragment,
"files_downloaded": success_count,
"metadata_file": metadata_path,
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Download AlphaFold structure files for a UniProt ID"
)
parser.add_argument(
"uniprot_id", help="The UniProt ID (e.g., P04637 or A0A1B0GX81)"
)
parser.add_argument(
"-o",
"--output-dir",
help="Output directory to save the files (required)",
required=True,
)
args = parser.parse_args()
fetch_structure(args.uniprot_id, args.output_dir)
# ===== file: skills/alphagenome_atlas_website_links/scripts/alphagenome_atlas_links.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""AlphaGenome Atlas Deep-Link & Track Predictions Generator CLI.
Constructs validated deep-links and multi-modality Ref vs. Alt track predictions
for the AlphaGenome Atlas web application
(https://deepmind.google.com/science/alphagenome/atlas).
Subcommands:
- `variant`: Construct single-variant exploration URLs.
- `locus`: Construct genomic interval / locus exploration URLs.
- `table`: Format variant records into a Markdown table with embedded Atlas
links.
- `track-predictions`: Construct /atlas/track-predictions comparison chart
URLs with paired RNA-seq + splicing.
"""
import argparse
from collections.abc import Mapping, Sequence
import dataclasses
import json
import os
import re
import sys
import urllib.parse
from alphagenome.atlas import atlas
from alphagenome.data import genome
import dotenv
import pandas as pd
BASE_ATLAS_URL = "https://deepmind.google.com/science/alphagenome/atlas"
_DEFAULT_INTERGENIC_FLANK_BP = 20_000
@dataclasses.dataclass(frozen=True, kw_only=True)
class VariantLinkConfig:
"""Configuration for a single-variant Atlas URL.
Attributes:
variant: Genetic variant identifier in `chr:pos:ref>alt` format.
biosample: Optional biosample or cell line name filter.
modalities: Modality layout sections to display in the Atlas UI.
filter_modalities: Scorer modality filters applied to the query (`f=`).
tfs: Transcription factor names for ChIP-TF track filtering.
include_avi: Whether to include the top-level AVI score track.
extra_pinned: Additional track IDs or tokens to pin into the layout.
"""
variant: str
biosample: str | None = None
modalities: Sequence[str] = ("RNA_SEQ", "DNASE", "CHIP_TF")
filter_modalities: Sequence[str] = ()
tfs: Sequence[str] = ()
include_avi: bool = True
extra_pinned: Sequence[str] = ()
@dataclasses.dataclass(frozen=True, kw_only=True)
class LocusLinkConfig:
"""Configuration for a locus/interval Atlas URL.
Attributes:
interval: Genomic coordinate viewport in `chr:start-end` format.
biosample: Optional biosample or cell line name filter.
modalities: Modality layout sections to display in the Atlas UI.
filter_modalities: Scorer modality filters applied to the query (`f=`).
tfs: Transcription factor names for ChIP-TF track filtering.
include_avi: Whether to include the top-level AVI score track.
"""
interval: str
biosample: str | None = None
modalities: Sequence[str] = ("RNA_SEQ", "DNASE", "CHIP_TF")
filter_modalities: Sequence[str] = ()
tfs: Sequence[str] = ()
include_avi: bool = True
@dataclasses.dataclass(frozen=True, kw_only=True)
class GenomicInterval:
"""A genomic coordinate interval.
Attributes:
chrom: Chromosome with 'chr' prefix.
start: 1-based start position (inclusive).
end: 1-based end position (inclusive).
"""
chrom: str
start: int
end: int
def __str__(self) -> str:
return f"{self.chrom}:{self.start}-{self.end}"
@dataclasses.dataclass(frozen=True, kw_only=True)
class GeneInfo:
"""Metadata for a single gene overlapping a genomic region.
Attributes:
gene_name: HGNC gene symbol.
gene_id: Ensembl gene ID (with version).
strand: Strand ('+' or '-').
is_mane: Whether this is a MANE Select transcript.
is_coding: Whether this is protein-coding.
start: Gene start position.
end: Gene end position.
"""
gene_name: str
gene_id: str
strand: str
is_mane: bool
is_coding: bool
start: int
end: int
@dataclasses.dataclass(frozen=True, kw_only=True)
class ScoreRecord:
"""A single track prediction score entry.
Attributes:
modality: Scorer modality (e.g. 'RNA_SEQ', 'DNASE').
track: Resolved track name from the Atlas catalog.
strand: Strand descriptor for display.
gene: Gene identifier or 'None' for unstranded modalities.
score_id: Full score token for the Atlas URL.
"""
modality: str
track: str
strand: str
gene: str
score_id: str
def normalize_variant_str(variant_str: str) -> str:
"""Validates and formats variant into chr:pos:ref>alt."""
v = variant_str.strip()
if not v.startswith("chr"):
v = f"chr{v}"
if ">" not in v:
raise ValueError(
f"Variant '{variant_str}' must contain '>' (format: chr:pos:ref>alt)"
)
return v
def encode_variant_query(variant_str: str) -> str:
"""URL-encodes variant for Atlas query string (ref%3Ealt)."""
norm = normalize_variant_str(variant_str)
return norm.replace(">", "%3E")
def _clean_chrom(chrom_str: str | int) -> str:
"""Ensures chromosome string has chr prefix."""
c = str(chrom_str).strip()
return c if c.startswith("chr") else f"chr{c}"
def parse_variant_components(variant: str) -> genome.Variant:
"""Parses a variant string (e.g. chr1:12345:A>G) into a genome.Variant."""
return genome.Variant.from_str(variant)
def parse_interval(interval: str) -> GenomicInterval:
"""Parses a chr:start-end string into a GenomicInterval."""
m = re.fullmatch(r"(?:chr)?([0-9A-Za-z]+):([0-9,]+)-([0-9,]+)", interval)
if not m:
raise ValueError(
f"Invalid interval format '{interval}'. Expected 'chr:start-end'."
)
return GenomicInterval(
chrom=_clean_chrom(m.group(1)),
start=int(m.group(2).replace(",", "")),
end=int(m.group(3).replace(",", "")),
)
def _select_mane_preferred(df_rows):
"""Returns the MANE_Select-tagged row if available, otherwise the first row."""
mane = df_rows[df_rows["tag"].fillna("").str.contains("MANE_Select")]
return mane.iloc[0] if not mane.empty else df_rows.iloc[0]
def _parse_modality_list(modalities: Sequence[str] | str) -> list[str]:
"""Normalizes modalities input to a list of uppercase modality strings."""
if isinstance(modalities, str):
return [m.strip().upper() for m in modalities.split(",") if m.strip()]
return [m.strip().upper() for m in modalities if m.strip()]
def build_filter_string(
*,
biosample: str | None = None,
modalities: Sequence[str] = (),
tfs: Sequence[str] = (),
) -> str | None:
"""Builds Atlas filter string (f=) enforcing the mandatory Assay group rule."""
filter_parts: list[str] = []
if biosample:
filter_parts.append(f"BIOSAMPLE_NAME:{biosample}")
modality_map: Mapping[str, str] = {
"RNA_SEQ": "RNA-seq",
"DNASE": "DNase",
"ATAC": "ATAC-seq",
"CHIP_TF": "ChIP-TF",
"CHIP_HISTONE": "ChIP-Histone",
"CAGE": "CAGE",
"PROCAP": "PRO-cap",
"POLYADENYLATION": "Polyadenylation",
"SPLICE_JUNCTIONS": "Splice junctions",
"SPLICE_SITE_USAGE": "Splice site usage",
}
for mod in modalities:
mod_upper = mod.upper()
display_name = modality_map.get(mod_upper, mod)
filter_parts.append(f"SCORER_MODALITY:{display_name}")
for tf in tfs:
filter_parts.append(f"ASSAY_TRANSCRIPTOR_FACTOR:{tf}")
return ",".join(filter_parts) if filter_parts else None
def build_layout_items(
*,
include_avi: bool = True,
modalities: Sequence[str] = (),
pinned_tracks: Sequence[str] = (),
) -> str:
"""Builds Atlas layout items (lItems=)."""
items: list[str] = []
if include_avi:
items.append("avi")
for mod in modalities:
mod_upper = mod.upper()
items.append(f"section:{mod_upper}")
for pinned in pinned_tracks:
items.append(pinned)
return ",".join(items) if items else "avi"
def _get_tf_modality_filter_str(
*,
biosample: str | None,
filter_modalities: Sequence[str],
tfs: Sequence[str],
) -> str | None:
"""Computes the filter string (f=) enforcing the mandatory Assay group rule.
When TF filters are present, RNA_SEQ and DNASE modalities are auto-included to
satisfy the Atlas Assay-group OR-logic requirement (see SKILL §2).
Args:
biosample: Optional biosample name.
filter_modalities: Modality filters to apply.
tfs: Transcription factor filters to apply.
Returns:
Formatted Atlas filter string, or None if no filters are active.
"""
active_mods = list(filter_modalities)
if tfs:
for required in ("RNA_SEQ", "DNASE"):
if required not in active_mods:
active_mods.append(required)
return build_filter_string(
biosample=biosample,
modalities=active_mods,
tfs=tfs,
)
def build_variant_url(config: VariantLinkConfig) -> str:
"""Builds full AlphaGenome Atlas URL for a single variant."""
norm_var = normalize_variant_str(config.variant)
l_items = build_layout_items(
include_avi=config.include_avi,
modalities=config.modalities,
pinned_tracks=config.extra_pinned,
)
query: dict[str, str] = {
"q": norm_var,
"m": "variant",
"lItems": l_items,
}
f_str = _get_tf_modality_filter_str(
biosample=config.biosample,
filter_modalities=config.filter_modalities,
tfs=config.tfs,
)
if f_str:
query["f"] = f_str
return f"{BASE_ATLAS_URL}?" + urllib.parse.urlencode(
query, quote_via=urllib.parse.quote, safe=":,-"
)
def build_locus_url(config: LocusLinkConfig) -> str:
"""Builds full AlphaGenome Atlas URL for a genomic interval."""
interval = config.interval.strip()
if not interval.startswith("chr"):
interval = f"chr{interval}"
l_items = build_layout_items(
include_avi=config.include_avi,
modalities=config.modalities,
)
query: dict[str, str] = {
"q": interval,
"m": "locus",
"lItems": l_items,
}
f_str = _get_tf_modality_filter_str(
biosample=config.biosample,
filter_modalities=config.filter_modalities,
tfs=config.tfs,
)
if f_str:
query["f"] = f_str
return f"{BASE_ATLAS_URL}?" + urllib.parse.urlencode(
query, quote_via=urllib.parse.quote, safe=":,-"
)
def build_table_from_records(
records: Sequence[Mapping[str, object]],
*,
biosample: str | None = None,
) -> str:
"""Formats variant records into a Markdown table with embedded Atlas links."""
lines: list[str] = [
(
"| Rank | Variant | AVI Phred | Raw Score | Top Modality | Atlas"
" Deep-Link |"
),
"| :--- | :--- | :--- | :--- | :--- | :--- |",
]
for idx, rec in enumerate(records, start=1):
variant_str = str(rec.get("variant", ""))
phred_val = rec.get("avi_phred", rec.get("phred", ""))
raw_val = rec.get("avi_raw", rec.get("raw_score", ""))
top_mod = rec.get("top_modality", rec.get("top_feature", "N/A"))
phred_display = f"**{float(phred_val):.2f}**" if phred_val else "N/A"
raw_display = f"{float(raw_val):.4f}" if raw_val else "N/A"
if variant_str:
url = build_variant_url(
VariantLinkConfig(
variant=variant_str,
biosample=biosample,
)
)
link_display = f"[View in Atlas]({url})"
else:
link_display = "N/A"
lines.append(
f"| {idx} | `{variant_str}` | {phred_display} | {raw_display} |"
f" `{top_mod}` | {link_display} |"
)
return "\n".join(lines)
# ------------------------------------------------------------------------------
# Track Predictions & GENCODE Splice Junction Resolution (predict subcommand)
# ------------------------------------------------------------------------------
def _get_authenticated_atlas_client():
"""Loads .env and initializes authenticated AlphaGenome Atlas client."""
dotenv.load_dotenv(os.path.expanduser("~/.env"))
api_key = os.environ.get("ALPHAGENOME_API_KEY")
if not api_key:
print(
"Error: ALPHAGENOME_API_KEY is not set.\n\nThe 'predict' subcommand"
" connects to the AlphaGenome Atlas database to resolve\nexact"
" experimental track metadata and splice junction coordinates.\n\nTo"
" set up your API key:\n 1. Retrieve your key and add it to ~/.env:\n "
' echo "ALPHAGENOME_API_KEY=<your_key>" >> ~/.env\n 2. Refer to'
" the 'credentials' skill for the safe credentials protocol,\n or"
" register for an API key at"
" https://deepmind.google.com/science/alphagenome/.\n",
file=sys.stderr,
)
sys.exit(1)
return atlas.create(api_key=api_key)
GTF_URL = (
"https://storage.googleapis.com/alphagenome/reference/gencode/"
"hg38/gencode.v46.annotation.gtf.gz.feather"
)
def load_gtf_dataframe(custom_path: str | None = None):
"""Loads GENCODE v46 GTF annotations, downloading and caching if needed."""
path = custom_path or os.environ.get("ALPHAGENOME_GTF_PATH")
if path and os.path.exists(path):
print(f"Loading GTF from {path}...")
return pd.read_feather(path)
cache_dir = os.path.expanduser("~/.cache/alphagenome")
cache_path = os.path.join(cache_dir, "gencode.v46.annotation.gtf.gz.feather")
if os.path.exists(cache_path):
print(f"Loading GTF from cache {cache_path}...")
return pd.read_feather(cache_path)
target_url = path or GTF_URL
print(f"Loading GTF from {target_url}...")
try:
df = pd.read_feather(target_url)
try:
os.makedirs(cache_dir, exist_ok=True)
df.to_feather(cache_path)
except Exception:
pass
return df
except Exception as e:
raise RuntimeError(
f"Failed to load GENCODE v46 GTF annotations from {target_url}: {e}"
) from e
def _resolve_locus(
*,
gene: str | None,
gene_id: str | None,
interval: str | None,
variant: genome.Variant | None,
gtf_df,
) -> tuple[GenomicInterval, object | None]:
"""Resolves the genomic interval and target gene from inputs.
Resolution priority: gene/gene_id > explicit interval > variant overlap.
Args:
gene: Gene symbol (e.g. 'BRCA1').
gene_id: Ensembl gene ID.
interval: Explicit interval string.
variant: Parsed genome.Variant, or None.
gtf_df: GENCODE v46 GTF DataFrame.
Returns:
Tuple of (GenomicInterval, target_gene_row or None).
Raises:
ValueError: If no input provides enough information to resolve a locus.
"""
if gene or gene_id:
return _resolve_locus_from_gene(
gene=gene,
gene_id=gene_id,
interval=interval,
gtf_df=gtf_df,
)
if interval:
return parse_interval(interval), None
if variant is not None:
return _resolve_locus_from_variant(
variant=variant,
gtf_df=gtf_df,
)
raise ValueError("Must provide at least one of variant, gene, or interval.")
def _resolve_locus_from_gene(
*,
gene: str | None,
gene_id: str | None,
interval: str | None,
gtf_df,
) -> tuple[GenomicInterval, object]:
"""Resolves locus from a gene symbol or Ensembl ID."""
if gene_id:
matches = gtf_df[gtf_df["gene_id"].str.startswith(gene_id.split(".")[0])]
else:
matches = gtf_df[gtf_df["gene_name"].str.upper() == gene.upper()]
if matches.empty:
raise ValueError(f"Gene '{gene or gene_id}' not found in GENCODE v46 GTF.")
target_gene_row = _select_mane_preferred(matches)
chrom = target_gene_row["Chromosome"]
if interval:
return parse_interval(interval), target_gene_row
return (
GenomicInterval(
chrom=chrom,
start=int(matches["Start"].min()),
end=int(matches["End"].max()),
),
target_gene_row,
)
def _resolve_locus_from_variant(
*,
variant: genome.Variant,
gtf_df,
) -> tuple[GenomicInterval, object | None]:
"""Resolves locus by overlapping variant position with gene annotations."""
chrom = variant.chromosome
var_pos = variant.position
c_df = gtf_df[gtf_df["Chromosome"] == chrom]
overlapping = c_df[(c_df["Start"] <= var_pos) & (c_df["End"] >= var_pos)]
if not overlapping.empty:
target_gene_row = _select_mane_preferred(overlapping)
gene_all = c_df[c_df["gene_id"] == target_gene_row["gene_id"]]
return (
GenomicInterval(
chrom=chrom,
start=int(gene_all["Start"].min()),
end=int(gene_all["End"].max()),
),
target_gene_row,
)
return (
GenomicInterval(
chrom=chrom,
start=max(1, var_pos - _DEFAULT_INTERGENIC_FLANK_BP),
end=var_pos + _DEFAULT_INTERGENIC_FLANK_BP,
),
None,
)
def _collect_overlapping_genes(
gtf_df,
interval: GenomicInterval,
) -> tuple[list[GeneInfo], list[GeneInfo]]:
"""Finds genes overlapping an interval, split and ranked by strand."""
c_df = gtf_df[gtf_df["Chromosome"] == interval.chrom]
in_region = c_df[
(c_df["Feature"] == "gene")
& (c_df["Start"] <= interval.end)
& (c_df["End"] >= interval.start)
]
if in_region.empty:
in_region = c_df[
(c_df["Start"] <= interval.end) & (c_df["End"] >= interval.start)
]
unique_genes = in_region.drop_duplicates(subset=["gene_id"])
positive_genes: list[GeneInfo] = []
negative_genes: list[GeneInfo] = []
for _, g in unique_genes.iterrows():
info = GeneInfo(
gene_name=g.get("gene_name") or g["gene_id"],
gene_id=g["gene_id"],
strand=g["Strand"],
is_mane="MANE_Select" in str(g.get("tag", "")),
is_coding=g.get("gene_type") == "protein_coding",
start=int(g["Start"]),
end=int(g["End"]),
)
if info.strand == "+":
positive_genes.append(info)
elif info.strand == "-":
negative_genes.append(info)
rank_key = lambda x: (x.is_mane, x.is_coding, x.end - x.start)
positive_genes.sort(key=rank_key, reverse=True)
negative_genes.sort(key=rank_key, reverse=True)
return positive_genes, negative_genes
def _pick_target_gene_id(
target_gene_row,
positive_genes: Sequence[GeneInfo],
negative_genes: Sequence[GeneInfo],
) -> str | None:
"""Picks the best target gene ID from available sources."""
if target_gene_row is not None:
return target_gene_row["gene_id"]
if positive_genes:
return positive_genes[0].gene_id
if negative_genes:
return negative_genes[0].gene_id
return None
def _junction_from_exon_index(gene_exons, idx: int) -> tuple[int, int]:
"""Returns junction boundaries for a variant within the exon at idx."""
n = len(gene_exons)
if 0 < idx < n - 1:
return (
int(gene_exons.iloc[idx - 1]["End"]),
int(gene_exons.iloc[idx + 1]["Start"]),
)
if idx == 0:
return int(gene_exons.iloc[0]["End"]), int(gene_exons.iloc[1]["Start"])
return int(gene_exons.iloc[-2]["End"]), int(gene_exons.iloc[-1]["Start"])
def _find_junction_for_position(gene_exons, var_pos: int) -> tuple[int, int]:
"""Finds the splice junction flanking a variant position."""
for i, (_, ex) in enumerate(gene_exons.iterrows()):
if int(ex["Start"]) <= var_pos <= int(ex["End"]):
return _junction_from_exon_index(gene_exons, i)
for i in range(len(gene_exons) - 1):
e1 = gene_exons.iloc[i]
e2 = gene_exons.iloc[i + 1]
if int(e1["End"]) < var_pos < int(e2["Start"]):
return int(e1["End"]), int(e2["Start"])
return int(gene_exons.iloc[0]["End"]), int(gene_exons.iloc[1]["Start"])
def _resolve_splice_junction(
*,
gtf_df,
chrom: str,
var_pos: int,
target_gene_row,
positive_genes: Sequence[GeneInfo],
negative_genes: Sequence[GeneInfo],
) -> tuple[int | None, int | None]:
"""Resolves splice junction boundaries nearest to a variant position."""
target_gid = _pick_target_gene_id(
target_gene_row, positive_genes, negative_genes
)
if target_gid is None:
return None, None
c_df = gtf_df[gtf_df["Chromosome"] == chrom]
target_tid = (
target_gene_row.get("transcript_id")
if target_gene_row is not None
else None
)
if target_tid:
gene_exons = c_df[
(c_df["transcript_id"] == target_tid) & (c_df["Feature"] == "exon")
].sort_values("Start")
else:
gene_exons = (
c_df[(c_df["gene_id"] == target_gid) & (c_df["Feature"] == "exon")]
.sort_values("Start")
.drop_duplicates(subset=["Start", "End"])
)
if len(gene_exons) < 2:
return None, None
return _find_junction_for_position(gene_exons, var_pos)
def _resolve_tracks_from_catalog(
*,
requested_modalities: Sequence[str],
biosample: str,
tf: str,
) -> dict[str, str]:
"""Resolves track names from the Atlas API scorer metadata catalog."""
client = _get_authenticated_atlas_client()
scorer_map = client.scorer_metadata()
resolved: dict[str, str] = {}
for scorer_name, s_meta in scorer_map.items():
df_meta = s_meta.track_metadata
if df_meta is None or df_meta.empty:
continue
if scorer_name.endswith("_ACTIVE"):
continue
if scorer_name not in requested_modalities:
continue
if scorer_name in resolved:
continue
for _, row in df_meta.iterrows():
t_name = str(row.get("name", ""))
b_name = str(row.get("biosample_name", ""))
ont_id = str(row.get("ontology_curie", ""))
if scorer_name == "CHIP_TF":
tf_match = tf.upper() in t_name.upper()
bio_match = (
not biosample
or biosample.lower() in b_name.lower()
or biosample.lower() in t_name.lower()
)
if tf_match and (bio_match or "CHIP_TF" not in resolved):
resolved["CHIP_TF"] = t_name
else:
if (
biosample.lower() in b_name.lower()
or biosample.lower() in t_name.lower()
or biosample.lower() in ont_id.lower()
):
resolved[scorer_name] = t_name
break
return resolved
def _build_score_tokens(
*,
target_variant: str,
requested_modalities: Sequence[str],
resolved_tracks: Mapping[str, str],
target_gene_row,
positive_genes: Sequence[GeneInfo],
negative_genes: Sequence[GeneInfo],
interval: GenomicInterval,
junction_start: int | None,
junction_end: int | None,
) -> tuple[list[str], list[ScoreRecord]]:
"""Builds score tokens and records for track prediction URLs."""
tokens: list[str] = []
records: list[ScoreRecord] = []
gene_id = (
_pick_target_gene_id(target_gene_row, positive_genes, negative_genes)
or "0"
)
for mod in requested_modalities:
track_name = resolved_tracks.get(mod)
if not track_name:
continue
if mod == "SPLICE_JUNCTIONS":
start = junction_start if junction_start is not None else interval.start
end = junction_end if junction_end is not None else interval.end
token = (
f"{target_variant}:SPLICE_JUNCTIONS:{track_name}"
f":Unstranded:{gene_id}:{start}:{end}"
)
tokens.append(token)
records.append(
ScoreRecord(
modality="SPLICE_JUNCTIONS",
track=track_name,
strand="Gene (Junction)",
gene=gene_id,
score_id=token,
)
)
elif mod == "RNA_SEQ":
if positive_genes:
g = positive_genes[0]
token = (
f"{target_variant}:RNA_SEQ:{track_name}:Unstranded:{g.gene_id}:0:0"
)
tokens.append(token)
records.append(
ScoreRecord(
modality="RNA_SEQ (+ strand)",
track=track_name,
strand="+ (Forward)",
gene=f"{g.gene_name} ({g.gene_id})",
score_id=token,
)
)
if negative_genes:
g = negative_genes[0]
token = (
f"{target_variant}:RNA_SEQ:{track_name}:Unstranded:{g.gene_id}:0:0"
)
tokens.append(token)
records.append(
ScoreRecord(
modality="RNA_SEQ (- strand)",
track=track_name,
strand="- (Reverse)",
gene=f"{g.gene_name} ({g.gene_id})",
score_id=token,
)
)
elif mod in (
"DNASE",
"ATAC",
"CHIP_TF",
"CHIP_HISTONE",
"CAGE",
"PROCAP",
):
token = f"{target_variant}:{mod}:{track_name}:Unstranded:None:None:None"
tokens.append(token)
records.append(
ScoreRecord(
modality=mod,
track=track_name,
strand="Unstranded",
gene="None",
score_id=token,
)
)
return tokens, records
def generate_track_prediction_link(
*,
variant: str | None = None,
gene: str | None = None,
gene_id: str | None = None,
interval: str | None = None,
biosample: str = "Muscle_Skeletal",
modalities: Sequence[str] | str = (
"SPLICE_JUNCTIONS",
"RNA_SEQ",
"DNASE",
"CHIP_TF",
),
tf: str = "CTCF",
tp_renames: str | None = None,
tp_legend_title: str | None = None,
gtf_path: str | None = None,
) -> dict[str, object]:
"""Constructs Atlas track prediction deep-links and resolves locus structures.
Args:
variant: Variant in chr:pos:ref>alt format.
gene: Target gene symbol.
gene_id: Ensembl gene ID.
interval: Explicit genomic interval viewport (chr:start-end).
biosample: Target biosample or tissue name.
modalities: Modalities to include (comma-separated string or sequence).
tf: Transcription factor name for ChIP-TF tracks.
tp_renames: Custom track rename overrides for the URL.
tp_legend_title: Custom legend title for the track prediction card.
gtf_path: Path or URL to the GTF feather file.
Returns:
Dict with 'url', 'interval', 'variant', 'target_gene',
'positive_strand_genes', 'negative_strand_genes', and 'scores'.
"""
gtf_df = load_gtf_dataframe(gtf_path)
requested_modalities = _parse_modality_list(modalities)
parsed_var = parse_variant_components(variant) if variant else None
locus, target_gene_row = _resolve_locus(
gene=gene,
gene_id=gene_id,
interval=interval,
variant=parsed_var,
gtf_df=gtf_df,
)
positive_genes, negative_genes = _collect_overlapping_genes(gtf_df, locus)
junction_start, junction_end = None, None
if "SPLICE_JUNCTIONS" in requested_modalities and parsed_var is not None:
junction_start, junction_end = _resolve_splice_junction(
gtf_df=gtf_df,
chrom=locus.chrom,
var_pos=parsed_var.position,
target_gene_row=target_gene_row,
positive_genes=positive_genes,
negative_genes=negative_genes,
)
resolved_tracks = _resolve_tracks_from_catalog(
requested_modalities=requested_modalities,
biosample=biosample,
tf=tf,
)
target_var = variant or (
f"{locus.chrom}:{locus.start + (locus.end - locus.start) // 2}:A>G"
)
score_tokens, score_records = _build_score_tokens(
target_variant=target_var,
requested_modalities=requested_modalities,
resolved_tracks=resolved_tracks,
target_gene_row=target_gene_row,
positive_genes=positive_genes,
negative_genes=negative_genes,
interval=locus,
junction_start=junction_start,
junction_end=junction_end,
)
l_items_str = build_layout_items(
include_avi=True,
modalities=requested_modalities,
)
query_dict: dict[str, str] = {
"q": variant or str(locus),
"m": "variant" if variant else "locus",
"lItems": l_items_str,
"scores": ",".join(score_tokens),
"i": str(locus),
}
if tp_renames:
query_dict["tpRenames"] = tp_renames
if tp_legend_title:
query_dict["tpLegendTitle"] = tp_legend_title
final_url = f"{BASE_ATLAS_URL}/track-predictions?" + urllib.parse.urlencode(
query_dict, quote_via=urllib.parse.quote, safe=":,-"
)
return {
"url": final_url,
"interval": str(locus),
"variant": variant,
"target_gene": (
target_gene_row["gene_name"] if target_gene_row is not None else None
),
"positive_strand_genes": [dataclasses.asdict(g) for g in positive_genes],
"negative_strand_genes": [dataclasses.asdict(g) for g in negative_genes],
"scores": [dataclasses.asdict(r) for r in score_records],
}
def main() -> None:
parser = argparse.ArgumentParser(
description=(
"AlphaGenome Atlas Deep-Link & Track Predictions Generator CLI"
),
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
subparsers = parser.add_subparsers(dest="subcommand", required=True)
# Subcommand: variant
p_var = subparsers.add_parser(
"variant",
help="Generate an AlphaGenome Atlas exploration URL for a single variant",
)
p_var.add_argument("variant", help="Variant in chr:pos:ref>alt format")
p_var.add_argument(
"--biosample",
"-b",
help="Biosample or cell line name (e.g. K562, HepG2, Muscle_Skeletal)",
)
p_var.add_argument(
"--modalities",
"-m",
default="RNA_SEQ,DNASE,CHIP_TF",
help="Comma-separated modalities to include in layout",
)
p_var.add_argument(
"--tf",
dest="tfs",
action="append",
default=[],
help="Transcription factor names for ChIP-TF tracks (e.g. GATA1, CTCF)",
)
p_var.add_argument(
"--no_avi",
action="store_true",
help="Exclude top-level AVI score track",
)
# Subcommand: locus
p_loc = subparsers.add_parser(
"locus",
help=(
"Generate an AlphaGenome Atlas locus exploration URL for an interval"
),
)
p_loc.add_argument(
"interval",
help="Genomic coordinate interval (e.g. chr11:5288500-5290500)",
)
p_loc.add_argument(
"--biosample",
"-b",
help="Biosample or cell line filter",
)
p_loc.add_argument(
"--modalities",
"-m",
default="RNA_SEQ,DNASE,CHIP_TF",
help="Comma-separated modalities to include",
)
p_loc.add_argument(
"--tf",
dest="tfs",
action="append",
default=[],
help="Transcription factors for ChIP-TF filters",
)
p_loc.add_argument(
"--no_avi",
action="store_true",
help="Exclude top-level AVI score track",
)
# Subcommand: table
p_tab = subparsers.add_parser(
"table",
help=(
"Format variant records or a JSON file into a Markdown table with"
" embedded Atlas links"
),
)
p_tab.add_argument(
"--input",
"-i",
help="Path to JSON file containing variant records",
)
p_tab.add_argument(
"--variant",
"-v",
action="append",
default=[],
help="Variant string(s) to include in table",
)
p_tab.add_argument(
"--biosample",
"-b",
help="Optional biosample filter to attach to links",
)
# Subcommand: track-predictions (comparison URLs)
p_pred = subparsers.add_parser(
"track-predictions",
help=(
"Construct /atlas/track-predictions comparison chart URLs with paired"
" RNA-seq + splicing"
),
)
p_pred.add_argument(
"--variant",
"-v",
help="Variant string in chr:pos:ref>alt format",
)
p_pred.add_argument(
"--gene",
"-g",
help="Target gene symbol (e.g. CAPN3)",
)
p_pred.add_argument(
"--gene_id",
help="Target Ensembl gene ID (e.g. ENSG00000092529.26)",
)
p_pred.add_argument(
"--interval",
"--region",
"-i",
dest="interval",
help="Genomic interval viewport in chr:start-end format",
)
p_pred.add_argument(
"--biosample",
"-b",
default="Muscle_Skeletal",
help=(
"Target biosample or tissue query (e.g. Muscle_Skeletal, K562,"
" Whole_Blood)"
),
)
p_pred.add_argument(
"--modalities",
"-m",
default="SPLICE_JUNCTIONS,RNA_SEQ,DNASE,CHIP_TF",
help=(
"Comma-separated modalities to include (SPLICE_JUNCTIONS, RNA_SEQ,"
" DNASE, ATAC, CHIP_TF)"
),
)
p_pred.add_argument(
"--tf",
default="CTCF",
help="Transcription factor name for ChIP-TF tracks (e.g. CTCF, GATA1)",
)
p_pred.add_argument(
"--rename",
"--tp_renames",
dest="tp_renames",
help="Custom track rename overrides (e.g. ScoreId:CustomTitle)",
)
p_pred.add_argument(
"--legend_title",
"--tp_legend_title",
dest="tp_legend_title",
help="Custom legend title for the track prediction card",
)
p_pred.add_argument(
"--gtf_path",
help=(
"Path or URL to the GTF feather file (defaults to"
" $ALPHAGENOME_GTF_PATH or the public GCS URL)"
),
)
p_pred.add_argument(
"--format",
choices=["table", "json", "url"],
default="table",
help="Output format",
)
args = parser.parse_args()
def _parse_modalities(raw: str) -> list[str]:
return [m.strip() for m in raw.split(",") if m.strip()]
if args.subcommand == "variant":
modalities = _parse_modalities(args.modalities)
config = VariantLinkConfig(
variant=args.variant,
biosample=args.biosample,
modalities=modalities,
tfs=args.tfs,
include_avi=not args.no_avi,
)
url = build_variant_url(config)
print(url)
elif args.subcommand == "locus":
modalities = _parse_modalities(args.modalities)
config = LocusLinkConfig(
interval=args.interval,
biosample=args.biosample,
modalities=modalities,
tfs=args.tfs,
include_avi=not args.no_avi,
)
url = build_locus_url(config)
print(url)
elif args.subcommand == "table":
records: list[dict[str, object]] = []
if args.input:
with open(args.input, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
records.extend(data)
elif isinstance(data, dict):
records.append(data)
for v in args.variant:
records.append({"variant": v})
if not records:
print(
"Error: No variants provided via --input or --variant.",
file=sys.stderr,
)
sys.exit(1)
table_md = build_table_from_records(
records,
biosample=args.biosample,
)
print(table_md)
elif args.subcommand == "track-predictions":
try:
result = generate_track_prediction_link(
variant=args.variant,
gene=args.gene,
gene_id=args.gene_id,
interval=args.interval,
biosample=args.biosample,
modalities=args.modalities,
tf=args.tf,
tp_renames=args.tp_renames,
tp_legend_title=args.tp_legend_title,
gtf_path=args.gtf_path,
)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if args.format == "url":
print(result["url"])
return
if args.format == "json":
print(json.dumps(result, indent=2))
return
print("\n### AlphaGenome Atlas Track Predictions Deep-Link")
print(f"\n**Generated URL**:\n{result['url']}\n")
print(f"**Genomic Interval Viewport (`i`)**: `{result['interval']}`")
if result["variant"]:
print(f"**Target Variant (`q`)**: `{result['variant']}`")
if result["target_gene"]:
print(f"**Target Gene**: `{result['target_gene']}`")
print()
positive_genes = result["positive_strand_genes"]
negative_genes = result["negative_strand_genes"]
chrom = str(result["interval"]).split(":", maxsplit=1)[0]
print("#### Overlapping Genes in Interval:")
print(f"- **(+) Forward Strand Genes ({len(positive_genes)})**:")
for g in positive_genes[:5]:
mane_tag = " [MANE Select]" if g["is_mane"] else ""
print(
f" - {g['gene_name']} ({g['gene_id']}){mane_tag}:"
f" `{chrom}:{g['start']}-{g['end']}`"
)
if len(positive_genes) > 5:
print(f" - ... and {len(positive_genes) - 5} more (+)-strand genes")
print(f"- **(-) Reverse Strand Genes ({len(negative_genes)})**:")
for g in negative_genes[:5]:
mane_tag = " [MANE Select]" if g["is_mane"] else ""
print(
f" - {g['gene_name']} ({g['gene_id']}){mane_tag}:"
f" `{chrom}:{g['start']}-{g['end']}`"
)
if len(negative_genes) > 5:
print(f" - ... and {len(negative_genes) - 5} more (-)-strand genes")
print()
print("#### Composed Track Prediction Scores (`scores`):")
print("| Modality | Strand | Track Name | Gene ID / Target |")
print("| :--- | :--- | :--- | :--- |")
for r in result["scores"]:
print(
f"| `{r['modality']}` | {r['strand']} | `{r['track']}` |"
f" {r['gene']} |"
)
print()
if __name__ == "__main__":
main()
# ===== file: skills/alphagenome_single_variant_analysis/scripts/analyze_ism.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""Generate ISM Sequence Logo for a variant.
Design Note:
This tool generates ISM Sequence Logos to identify disrupted motifs at the
variant position, helping explain *why* a regulatory or splicing site was
lost or gained (mechanistic cause).
The script extracts the top k-mer and prints its reverse complement.
The agent must use its own knowledge about transcription factor binding
motifs to identify candidate TFs that match the extracted motif or its
reverse complement.
Usage:
uv run analyze_ism.py --chrom=chr17 --pos=7675148 --ref=G --alt=A \
--tissue=liver --ontology=UBERON:0002107 --modality=DNASE
Examples:
uv run analyze_ism.py --chrom=chr17 --pos=7675148 --ref=G --alt=A \
--tissue=liver --ontology=UBERON:0002107 --modality=DNASE
uv run analyze_ism.py --chrom=chr21 --pos=46126238 --ref=G --alt=C \
--tissue='skeletal muscle' --ontology=CL:0002545 --modality=SPLICE_SITE_USAGE \
--gene=COL6A2
uv run analyze_ism.py --chrom=chr7 --pos=5529776 --ref=C --alt=T \
--tissue=HepG2 --ontology=EFO:0001187 --modality=CHIP_TF --gene=ACTB \
--output_dir=./ism_plots
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "alphagenome",
# "numpy",
# "python-dotenv",
# ]
# ///
from __future__ import annotations
import argparse
import os
from typing import Any, Sequence
from alphagenome.data import genome
from alphagenome.interpretation import ism
from alphagenome.models import dna_client
from alphagenome.models import variant_scorers
from alphagenome.visualization import plot_components
import dotenv
import numpy as np
def _reverse_complement(seq: str) -> str:
"""Returns the reverse complement of a DNA sequence."""
return seq[::-1].translate(str.maketrans('ACGTacgt', 'TGCAtgca'))
def extract_ontology_scores(
ism_results: list[tuple[Any, ...]],
ontology_id: str,
gene_name: str | None = None,
) -> tuple[list[float], list[Any]]:
"""Extracts scores for a specific ontology ID from ISM results."""
scores_flat: list[float] = []
variants_flat: list[Any] = []
for adata, *_ in ism_results:
var_obj = adata.uns['variant']
score = 0.0
if 'ontology_curie' in adata.var.columns:
col_mask = adata.var['ontology_curie'] == ontology_id
if col_mask.any():
row_mask = slice(None) # All rows
if gene_name and 'gene_name' in adata.obs.columns:
gene_mask = adata.obs['gene_name'] == gene_name
if gene_mask.any():
row_mask = gene_mask
score = np.nanmean(adata.X[row_mask, col_mask])
else:
print(
'Info: No scores found for ontology term'
f' {ontology_id!r} in ISM result.'
)
scores_flat.append(score)
variants_flat.append(var_obj)
return scores_flat, variants_flat
def interpret_ism_matrix(
ref_ism_mat: np.ndarray,
bases: list[str],
kmer_length: int,
min_threshold: float,
) -> None:
"""Prints interpretation summary from an ISM matrix."""
print('\n--- ISM Interpretation Summary ---')
if not np.any(ref_ism_mat):
print('ISM matrix is all zeros. No relevant tracks or scores found.')
return
max_scores_per_pos = np.max(np.abs(ref_ism_mat), axis=1)
top_pos_idx = int(np.argmax(max_scores_per_pos))
top_score = ref_ism_mat[top_pos_idx, :]
center_idx = ref_ism_mat.shape[0] // 2
print(
f'Top Disrupted Position: {top_pos_idx - center_idx} (Relative to'
' Variant)'
)
print(f'Scores at Top Position: {dict(zip(bases, top_score))}')
# Use relative threshold but ensure it's at least min_threshold
threshold = max(np.max(np.abs(ref_ism_mat)) * 0.1, min_threshold)
consensus_seq: list[str] = []
for i in range(ref_ism_mat.shape[0]):
row = ref_ism_mat[i, :]
best_idx = np.argmax(np.abs(row))
if abs(row[best_idx]) > threshold:
consensus_seq.append(bases[best_idx])
else:
consensus_seq.append('.')
consensus_str = ''.join(consensus_seq)
print(f'Consensus Motif: {consensus_str}')
print(f'Reverse Compl : {_reverse_complement(consensus_str)}')
if ref_ism_mat.shape[0] >= kmer_length:
best_kmer_score = -1.0
best_kmer_seq = ''
best_kmer_start = 0
for i in range(ref_ism_mat.shape[0] - kmer_length + 1):
window = ref_ism_mat[i : i + kmer_length, :]
score = np.sum(np.max(np.abs(window), axis=1))
if score > best_kmer_score:
best_kmer_score = score
best_kmer_start = i
seq = ''
for j in range(kmer_length):
w_row = window[j, :]
seq += bases[np.argmax(np.abs(w_row))]
best_kmer_seq = seq
print(
f'Top {kmer_length}-mer: {best_kmer_seq}'
f' (Start: {best_kmer_start - center_idx},'
f' Score: {best_kmer_score:.3f})'
)
print(f'RevComp {kmer_length}-mer: {_reverse_complement(best_kmer_seq)}')
print('----------------------------------\n')
def analyze_ism(
chrom: str,
pos: int,
ref: str,
alt: str,
tissue: str,
ontology: str,
modality: str,
gene: str,
output_dir: str,
kmer_length: int,
min_threshold: float,
) -> None:
"""Runs In-Silico Mutagenesis (ISM) analysis and plots the results."""
api_key = os.environ.get('ALPHAGENOME_API_KEY')
if not api_key:
raise ValueError('ALPHAGENOME_API_KEY not found.')
print('Initializing AlphaGenome Client...')
dna_model = dna_client.create(
api_key=api_key,
address='dns:///gdmscience.googleapis.com:443',
)
variant = genome.Variant(chrom, pos, ref, alt)
print(f'Variant: {variant}')
ism_interval = variant.reference_interval.resize(32)
sequence_interval = ism_interval.resize(dna_client.SEQUENCE_LENGTH_1MB)
try:
output_type = dna_client.OutputType[modality.upper()]
except KeyError as e:
raise ValueError(
f'Unknown modality: {modality}. Valid options:'
f' {[o.name for o in dna_client.OutputType]}'
) from e
if output_type == dna_client.OutputType.SPLICE_JUNCTIONS:
raise ValueError(
'SPLICE_JUNCTIONS is NOT supported for ISM. Please use'
' SPLICE_SITE_USAGE instead.'
)
print(f'Scoring ISM for {tissue} ({output_type.name})...')
modality_key = modality.upper()
if modality_key in variant_scorers.RECOMMENDED_VARIANT_SCORERS:
ism_scorer = variant_scorers.RECOMMENDED_VARIANT_SCORERS[modality_key]
else:
raise ValueError(
f'No recommended scorer found for modality: {modality_key}. '
'Available recommended scorers: '
f'{list(variant_scorers.RECOMMENDED_VARIANT_SCORERS.keys())}'
)
print('Running ISM on REF background...')
ref_ism_results = dna_model.score_ism_variants(
interval=sequence_interval,
ism_interval=ism_interval,
variant_scorers=[ism_scorer],
)
ref_scores, ref_variants = extract_ontology_scores(
ref_ism_results, ontology, gene_name=gene
)
ref_ism_mat = ism.ism_matrix(ref_scores, variants=ref_variants)
max_score = np.max(np.abs(ref_ism_mat))
if max_score == 0:
print('WARNING: ISM matrix is empty (all zeros). Check ontology ID.')
elif max_score < min_threshold:
print(
f'WARNING: Max ISM score is very low ({max_score:.3f}), below'
f' threshold {min_threshold}. The result may not be reliable.'
)
print('Generating SeqLogo...')
fig = plot_components.plot(
[
plot_components.SeqLogo(
scores=ref_ism_mat,
scores_interval=ism_interval,
ylabel=f'ISM {tissue}\n{output_type.name}',
)
],
interval=ism_interval,
fig_width=15,
title=f'ISM Motif Analysis: {gene} {chrom}:{pos} ({tissue})',
annotations=[plot_components.VariantAnnotation([variant], alpha=0.5)],
)
safe_tissue = tissue.replace(' ', '_').replace('/', '_')
filename = os.path.join(output_dir, f'ism_{safe_tissue}_{modality}.png')
os.makedirs(output_dir, exist_ok=True)
fig.savefig(filename)
print(f'Saved ISM SeqLogo to {filename}')
bases = ['A', 'C', 'G', 'T']
interpret_ism_matrix(ref_ism_mat, bases, kmer_length, min_threshold)
def main(argv: Sequence[str] | None = None) -> None:
"""Main entry point for the ISM analysis CLI tool."""
dotenv.load_dotenv(os.path.expanduser('~/.env'))
parser = argparse.ArgumentParser(
description='Generate ISM Sequence Logo for a variant.'
)
parser.add_argument(
'--chrom',
required=True,
help='Chromosome (e.g., chr17).',
)
parser.add_argument(
'--pos', type=int, required=True, help='Position (1-based).'
)
parser.add_argument('--ref', required=True, help='Reference allele.')
parser.add_argument('--alt', required=True, help='Alternate allele.')
parser.add_argument(
'--tissue', required=True, help='Tissue name for labeling.'
)
parser.add_argument(
'--ontology', required=True, help='Ontology CURIE (e.g., UBERON:0002107).'
)
parser.add_argument(
'--modality',
required=True,
help='Output modality (e.g., DNASE, CHIP_TF).',
)
parser.add_argument(
'--gene', default='Unknown', help='Gene name for plot title.'
)
parser.add_argument('--output_dir', default='.', help='Output directory.')
parser.add_argument(
'--kmer_length',
type=int,
default=8,
help='Length of k-mer to scan for top score.',
)
parser.add_argument(
'--min_threshold',
type=float,
default=0.05,
help='Minimum absolute score threshold for motif extraction.',
)
args = parser.parse_args(argv)
analyze_ism(
args.chrom,
args.pos,
args.ref,
args.alt,
args.tissue,
args.ontology,
args.modality,
args.gene,
args.output_dir,
args.kmer_length,
args.min_threshold,
)
if __name__ == '__main__':
main()
# ===== file: skills/alphagenome_single_variant_analysis/scripts/generate_ontology_mapping.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generates tissue_ontology_mapping.json from the AlphaGenome API.
Usage:
uv run scripts/generate_ontology_mapping.py
Can be imported and called programmatically:
from generate_ontology_mapping import generate_mapping_file
generate_mapping_file('/path/to/output.json')
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "alphagenome",
# "pandas",
# "python-dotenv",
# ]
# ///
import json
import logging
import os
import dotenv
logger = logging.getLogger(__name__)
from alphagenome.models import dna_client
import pandas as pd
def clean_list(series: pd.Series) -> list[str]:
"""Clean a pandas series to a sorted list of unique non-empty values."""
vals = set(series.dropna().astype(str))
vals = {
v
for v in vals
if v.strip() and v.lower() not in ('none', 'nan', 'null', '')
}
return sorted(list(vals))
def prune_empty(d):
"""Recursively remove empty values from nested dicts and lists."""
if not isinstance(d, (dict, list)):
return d
if isinstance(d, list):
return [
v for v in (prune_empty(v) for v in d) if v not in (None, [], {}, '')
]
if isinstance(d, dict):
return {
k: v
for k, v in ((k, prune_empty(v)) for k, v in d.items())
if v not in (None, [], {}, '')
}
def create_biological_mapping(df: pd.DataFrame) -> dict:
"""Create a mapping from ontology CURIEs to biosample metadata."""
df_proc = df.drop(
columns=['genetically_modified', 'nonzero_mean', 'name'], errors='ignore'
).copy()
df_proc['output_type'] = (
df_proc['output_type']
.astype(str)
.str.replace('OutputType.', '', regex=False)
)
mapping = {}
for curie, group in df_proc.groupby('ontology_curie'):
if pd.isna(curie):
continue
entry = {
'biosample': {
'name': group['biosample_name'].iloc[0],
'type': group['biosample_type'].iloc[0],
'life': clean_list(group['biosample_life_stage']),
'sources': clean_list(group['data_source']),
},
'molecular': {
'histones': clean_list(group['histone_mark']),
'tfs': clean_list(group['transcription_factor']),
},
'assays': {
assay: {
'tracks': clean_list(ag['output_type']),
'marks': (
clean_list(ag['histone_mark'])
+ clean_list(ag['transcription_factor'])
),
}
for assay, ag in group.groupby('Assay title')
},
}
mapping[curie] = prune_empty(entry)
return mapping
def generate_mapping_file(output_path: str) -> dict:
"""Fetches AlphaGenome metadata and writes the ontology mapping JSON.
Args:
output_path: Path to write the tissue_ontology_mapping.json file.
Returns:
The generated mapping dictionary.
Raises:
RuntimeError: If ALPHAGENOME_API_KEY is not set.
"""
api_key = os.environ.get('ALPHAGENOME_API_KEY')
if not api_key:
raise RuntimeError(
'ALPHAGENOME_API_KEY not set. '
'Ensure the `.env` file contains ALPHAGENOME_API_KEY=<key> and '
'use uv run to run this script.'
)
logger.info('Fetching output metadata from AlphaGenome API...')
dna_model = dna_client.create(api_key=api_key)
df = dna_model.output_metadata(dna_client.Organism.HOMO_SAPIENS).concatenate()
logger.info('Got %d rows.', len(df))
logger.info('Building ontology mapping...')
mapping = create_biological_mapping(df)
logger.info('Created %d entries.', len(mapping))
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w') as f:
json.dump(mapping, f, indent=2)
logger.info('Wrote mapping to %s', output_path)
return mapping
def get_tissue_ontology_mapping_path(resource_dir: str) -> str:
"""Returns the path to the tissue ontology mapping JSON file.
Args:
resource_dir: Directory where the resources are stored.
Returns:
Absolute path to tissue_ontology_mapping.json.
"""
return os.path.join(resource_dir, 'tissue_ontology_mapping.json')
def main():
dotenv.load_dotenv(os.path.expanduser('~/.env'))
script_dir = os.path.dirname(os.path.abspath(__file__))
resource_dir = os.path.join(script_dir, '..', 'resources')
generate_mapping_file(get_tissue_ontology_mapping_path(resource_dir))
if __name__ == '__main__':
main()
# ===== file: skills/alphagenome_single_variant_analysis/scripts/interpret_splicing.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Quantitative analysis of splicing effects (Splice Sites & Junctions).
This script provides high-resolution, quantitative analysis of splicing changes.
While discovery scans give summary scores, this script analyzes specific
junctions to detect events like exon skipping or cryptic splicing.
Design Note:
This tool provides quantitative analysis of specific splice junctions,
complementary to analyze_ism.py which can be used to analyze motifs affecting
splice site usage. While ISM helps identify *why* a site was lost or gained
(motif disruption), this script reveals *what* structural changes occurred
(e.g., exon skipping or cryptic junction usage). It offloads final judgment
to the agent but provides heuristic flags (e.g., GAIN/LOSS) to guide the analysis.
Usage:
uv run scripts/interpret_splicing.py --chrom=chr21 --pos=46126238 --ref=G --alt=C \
--ontology_id=CL:0002545
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "alphagenome",
# "numpy",
# "pandas",
# "python-dotenv",
# ]
# ///
from __future__ import annotations
import argparse
import os
from typing import Any, Sequence
from alphagenome.data import genome
from alphagenome.models import dna_client
import dotenv
import numpy as np
import pandas as pd
API_ADDRESS = 'dns:///gdmscience.googleapis.com:443'
def get_track(obj: Any, attr: str, curie: str) -> Any:
"""Retrieves a track filtered by ontology CURIE."""
if not hasattr(obj, attr):
print(f"Warning: Object missing attribute '{attr}'.")
return None
data = getattr(obj, attr)
if hasattr(data, 'filter_by_ontology'):
return data.filter_by_ontology(curie)
mask = data.metadata['ontology_curie'] == curie
if not mask.any():
print(f"Info: No data found for ontology term '{curie}' in track '{attr}'.")
return None
return data.filter_tracks(mask.values)
def junctions_to_df(junc_track: Any) -> pd.DataFrame:
"""Converts a JunctionTrack to a DataFrame."""
if junc_track is None or len(junc_track.junctions) == 0:
return pd.DataFrame()
scores = None
if hasattr(junc_track, 'values'):
vals = junc_track.values
# Handle different shapes of values array from API
if vals.shape[0] == len(junc_track.junctions):
scores = vals.mean(axis=1)
elif len(vals.shape) > 1 and vals.shape[1] == len(junc_track.junctions):
scores = vals.mean(axis=0)
elif len(vals.shape) == 1 and len(vals) == len(junc_track.junctions):
scores = vals
if scores is None:
print('Warning: Failed to parse scores for junctions.')
return pd.DataFrame()
rows = []
for junction, score in zip(junc_track.junctions, scores):
rows.append({
'start': junction.start,
'end': junction.end,
'score': float(score),
'strand': junction.strand,
})
return pd.DataFrame(rows)
def analyze_splicing(
chrom: str,
pos: int,
ref: str,
alt: str,
ontology_id: str,
window: int,
) -> None:
"""Runs the splicing analysis for a specific variant."""
api_key = os.environ.get('ALPHAGENOME_API_KEY')
if not api_key:
raise ValueError('ALPHAGENOME_API_KEY environment variable not set.')
dna_model = dna_client.create(api_key=api_key, address=API_ADDRESS)
variant = genome.Variant(chrom, pos, ref, alt)
zoom_interval = genome.Interval(chrom, pos - window // 2, pos + window // 2)
pred_interval = zoom_interval.resize(131072)
print(
f'Quantifying splicing changes for {chrom}:{pos}:{ref}>{alt} in'
f' {ontology_id}...'
)
requested_outputs = [
dna_client.OutputType.SPLICE_JUNCTIONS,
dna_client.OutputType.SPLICE_SITE_USAGE,
dna_client.OutputType.RNA_SEQ,
]
prediction = dna_model.predict_variant(
interval=pred_interval,
variant=variant,
requested_outputs=requested_outputs,
ontology_terms=[ontology_id],
)
print('\n--- Splice Site Usage Analysis ---')
ss_ref = get_track(prediction.reference, 'splice_site_usage', ontology_id)
ss_alt = get_track(prediction.alternate, 'splice_site_usage', ontology_id)
if ss_ref and ss_alt:
start = pred_interval.start
idx = pos - start
for offset in range(-2, 3):
position = pos + offset
index = idx + offset
try:
val_ref = (
ss_ref.values[index].mean()
if ss_ref.values.ndim > 1
else ss_ref.values[index]
)
val_alt = (
ss_alt.values[index].mean()
if ss_alt.values.ndim > 1
else ss_alt.values[index]
)
diff = val_alt - val_ref
if abs(diff) > 0.05:
print(
f'Position {position} (Offset {offset}): REF={val_ref:.3f},'
f' ALT={val_alt:.3f}, Delta={diff:.3f}'
)
if val_ref > 0.5 and val_alt < 0.1:
print(f' -> Loss of strong splice site at {position}!')
elif val_ref < 0.1 and val_alt > 0.5:
print(f' -> Gain of new splice site at {position}!')
except (IndexError, AttributeError, ValueError) as e:
if not isinstance(e, IndexError):
print(f'Warning: Error during splice site diff calculation: {e}')
pass
else:
print('Splice site usage track missing.')
print('\n--- Junction Analysis ---')
junc_ref = prediction.reference.splice_junctions.filter_by_ontology(
ontology_id
)
junc_alt = prediction.alternate.splice_junctions.filter_by_ontology(
ontology_id
)
df_ref = junctions_to_df(junc_ref)
df_alt = junctions_to_df(junc_alt)
if not df_ref.empty and not df_alt.empty:
merged = pd.merge(
df_ref,
df_alt,
on=['start', 'end', 'strand'],
how='outer',
suffixes=('_REF', '_ALT'),
).fillna(0)
merged['delta'] = merged['score_ALT'] - merged['score_REF']
# Junctions overlapping variant
variant_overlapping = merged[
(merged['start'] < pos) & (merged['end'] > pos)
]
print(f'Junctions overlapping variant ({pos}):')
if variant_overlapping.empty:
print(' None found.')
else:
for _, row in variant_overlapping.iterrows():
print(
f" {int(row['start'])}-{int(row['end'])} (Strand {row['strand']}):"
f" REF={row['score_REF']:.2f}, ALT={row['score_ALT']:.2f},"
f" Delta={row['delta']:.2f}"
)
if row['score_REF'] > 5 and row['score_ALT'] < 1:
print(' -> Skipping/Loss of canonical intron (Exon skipping?)')
# Cryptic Junctions (Gain in ALT)
cryptic = merged[(merged['score_ALT'] > 5) & (merged['score_REF'] < 1)]
if not cryptic.empty:
print('\nPotential Cryptic Junctions (Gain in ALT):')
for _, row in cryptic.iterrows():
print(
f" {int(row['start'])}-{int(row['end'])}:"
f" REF={row['score_REF']:.2f} -> ALT={row['score_ALT']:.2f}"
)
print('\nTop 5 Most Changed Junctions:')
top_changes = merged.reindex(
merged['delta'].abs().sort_values(ascending=False).index
).head(5)
print(top_changes[['start', 'end', 'score_REF', 'score_ALT', 'delta']])
else:
print('No junctions found or failed to parse.')
print('\n--- RNA-seq Analysis ---')
rna_ref = get_track(prediction.reference, 'rna_seq', ontology_id)
rna_alt = get_track(prediction.alternate, 'rna_seq', ontology_id)
if rna_ref and rna_alt:
start_idx = pos - pred_interval.start - 50
end_idx = pos - pred_interval.start + 50
def safe_mean(arr: np.ndarray) -> np.ndarray:
if arr.ndim > 1:
return arr.mean(axis=1)
return arr
ref_vals = safe_mean(rna_ref.values)
alt_vals = safe_mean(rna_alt.values)
ref_window = ref_vals[start_idx:end_idx]
alt_window = alt_vals[start_idx:end_idx]
print(
f'Mean RNA Coverage (+/- 50bp): REF={ref_window.mean():.2f},'
f' ALT={alt_window.mean():.2f}'
)
if ref_window.mean() > 0:
log2fc = np.log2((alt_window.mean() + 1e-3) / (ref_window.mean() + 1e-3))
print(f'Log2 Fold Change at variant: {log2fc:.2f}')
else:
print('RNA-seq track missing.')
def main(argv: Sequence[str] | None = None) -> None:
"""Main entry point for the splicing analysis CLI tool."""
dotenv.load_dotenv(os.path.expanduser('~/.env'))
parser = argparse.ArgumentParser(
description='Quantitative analysis of splicing effects.'
)
parser.add_argument(
'--chrom', required=True, help='Chromosome (e.g., chr21).'
)
parser.add_argument(
'--pos', type=int, required=True, help='Position (1-based).'
)
parser.add_argument('--ref', required=True, help='Reference allele.')
parser.add_argument('--alt', required=True, help='Alternate allele.')
parser.add_argument(
'--ontology_id', required=True, help='Ontology CURIE (e.g., CL:0002545).'
)
parser.add_argument(
'--window',
type=int,
default=1500,
help='Window size around variant for analysis.',
)
args = parser.parse_args(argv)
analyze_splicing(
args.chrom,
args.pos,
args.ref,
args.alt,
args.ontology_id,
args.window,
)
if __name__ == '__main__':
main()
# ===== file: skills/alphagenome_single_variant_analysis/scripts/lookup_gene_info.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Comprehensive gene and transcript lookup tool using GTF data.
Usage:
# 1. Lookup gene symbol or coordinate to get ID and location
uv run scripts/lookup_gene_info.py --genes='TP53,BRCA1'
uv run scripts/lookup_gene_info.py --genes='chr17:7675148'
# 2. Find genes near a coordinate
uv run scripts/lookup_gene_info.py --coord='chr17:7675148' --window=50000
# 3. List and filter transcripts for a gene
uv run scripts/lookup_gene_info.py --genes='EGFR' --transcripts --mane
"""
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "alphagenome",
# "pandas",
# "python-dotenv",
# ]
# ///
from __future__ import annotations
import argparse
import os
import re
from typing import Sequence
from alphagenome.data import gene_annotation
import dotenv
import pandas as pd
GTF_URL = (
'https://storage.googleapis.com/alphagenome/reference/gencode/'
'hg38/gencode.v46.annotation.gtf.gz.feather'
)
def load_gtf(gtf_path: str | None = None) -> pd.DataFrame:
"""Loads the GTF feather file from a path or URL."""
path = gtf_path or os.environ.get('ALPHAGENOME_GTF_PATH', GTF_URL)
print(f'Loading GTF from {path}...')
return pd.read_feather(path)
def parse_gene_input(genes: list[str]) -> list[str]:
"""Parses comma-separated gene input and deduplicates."""
parsed = set()
for gene in genes:
parsed |= {x.strip() for x in gene.split(',') if x.strip()}
return sorted(parsed)
def classify_queries(queries: list[str]) -> tuple[list[str], list[str]]:
"""Classifies queries into coordinates and gene symbols."""
coords = []
symbols = []
for query in queries:
if re.match(r'^chr[0-9XYM]+:\d+', query):
coords.append(query)
else:
symbols.append(query)
return coords, symbols
def parse_coord(coord_str: str) -> tuple[str, int, int]:
"""Parses coordinate string like chr1:100-200 or chr1:150."""
chrom, pos_part = coord_str.split(':', 1)
if '-' in pos_part:
start_str, end_str = pos_part.split('-')
return chrom, int(start_str), int(end_str)
else:
pos = int(pos_part)
return chrom, pos, pos
# --- Mode 1: Gene Symbol <-> Coord Lookup (from lookup_ensg_gtf) ---
def run_gene_lookup(gtf: pd.DataFrame, genes_input: list[str]) -> None:
"""Looks up gene symbols or coordinates in GTF."""
genes_of_interest = parse_gene_input(genes_input)
coords_to_lookup, symbols_to_lookup = classify_queries(genes_of_interest)
results = []
# Handle symbols
if symbols_to_lookup:
mask = gtf['gene_name'].isin(symbols_to_lookup)
result_df = gtf[mask][
['gene_name', 'gene_id_nopatch', 'Chromosome', 'Start', 'End', 'Strand']
]
results.append(result_df)
# Handle coordinates
for coord in coords_to_lookup:
chrom, pos, _ = parse_coord(coord)
mask = (
(gtf['Chromosome'] == chrom)
& (gtf['Start'] <= pos)
& (gtf['End'] >= pos)
)
result_df = gtf[mask][
['gene_name', 'gene_id_nopatch', 'Chromosome', 'Start', 'End', 'Strand']
]
results.append(result_df)
if not results:
print('No matches found.')
return
df = pd.concat(results).drop_duplicates()
if df.empty:
print('No matches found.')
else:
print(df.to_string(index=False))
# --- Mode 2: Find Genes at Coordinate (from lookup_gene_at_coord) ---
def run_coord_search(gtf: pd.DataFrame, coord: str, window: int) -> None:
"""Finds genes near a coordinate."""
chrom, start, end = parse_coord(coord)
if start == end:
search_start = start - window
search_end = end + window
else:
search_start, search_end = start, end
print(f'\nSearching for genes at {chrom}:{search_start:,}-{search_end:,}')
print('-' * 50)
mask = (
(gtf['Chromosome'] == chrom)
& (gtf['Start'] <= search_end)
& (gtf['End'] >= search_start)
)
matching_genes = gtf[mask].copy()
if matching_genes.empty:
print('No genes found in this region.')
return
# Calculate distance if it's a single point query
if start == end:
def calc_dist(row):
if row['Start'] <= start <= row['End']:
return 0
return min(abs(row['Start'] - start), abs(row['End'] - start))
matching_genes['Distance'] = matching_genes.apply(calc_dist, axis=1)
matching_genes = matching_genes.sort_values('Distance')
cols = [
'gene_name',
'gene_id_nopatch',
'Chromosome',
'Start',
'End',
'Distance',
]
else:
matching_genes = matching_genes.sort_values('Start')
cols = ['gene_name', 'gene_id_nopatch', 'Chromosome', 'Start', 'End']
# Keep only gene features to avoid duplicate rows for exons/transcripts
feature_col = 'Feature' if 'Feature' in matching_genes.columns else 'feature'
if feature_col in matching_genes.columns:
matching_genes = matching_genes[matching_genes[feature_col] == 'gene']
if matching_genes.empty:
print(
'No gene features found (only exons/transcripts). Showing unique gene'
' names:'
)
print(matching_genes['gene_name'].unique())
else:
print(matching_genes[cols].drop_duplicates().to_string(index=False))
# --- Mode 3: List and Filter Transcripts (from lookup_transcripts) ---
def run_transcript_lookup(
gtf: pd.DataFrame,
genes_input: list[str],
mane: bool,
protein_coding: bool,
transcript_support_level: str | None,
longest: bool,
details: bool,
) -> None:
"""Lists and filters transcripts for genes."""
genes_list = parse_gene_input(genes_input)
filtered = gtf[gtf['gene_name'].isin(genes_list)].copy()
if filtered.empty:
print(f'No data found for genes: {genes_list}')
return
if mane:
print('Filtering to MANE transcripts...')
filtered = gene_annotation.filter_to_mane_select_transcript(filtered)
if protein_coding:
print('Filtering to protein coding transcripts...')
filtered = gene_annotation.filter_to_protein_coding_transcript(filtered)
if transcript_support_level:
print(
f'Filtering to Transcript Support Level: {transcript_support_level}...'
)
tsl_list = [x.strip() for x in transcript_support_level.split(',')]
if 'transcript_support_level' in filtered.columns:
filtered['tsl_clean'] = (
filtered['transcript_support_level'].astype(str).str.extract(r'^(\d)')
)
filtered = filtered[filtered['tsl_clean'].isin(tsl_list)]
else:
print(
'Warning: "transcript_support_level" column not found. Cannot filter'
' by TSL.'
)
if longest:
print('Filtering to longest transcript per gene...')
filtered = gene_annotation.filter_to_longest_transcript(filtered)
cols = ['gene_name', 'transcript_id']
if details:
for column in [
'transcript_type',
'transcript_support_level',
'Chromosome',
'Start',
'End',
]:
if column in filtered.columns:
cols.append(column)
print('\nResults:')
if 'Feature' in filtered.columns:
transcript_features = filtered[filtered['Feature'] == 'transcript']
if not transcript_features.empty:
filtered = transcript_features
print(filtered[cols].drop_duplicates().to_string(index=False))
def main(argv: Sequence[str] | None = None) -> None:
dotenv.load_dotenv(os.path.expanduser('~/.env'))
parser = argparse.ArgumentParser(
description='Lookup gene and transcript info using GTF data.'
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--genes', help='Comma-separated gene symbols or coordinates to lookup.'
)
group.add_argument(
'--coord', help='Genomic coordinate for search (e.g. chr17:7675148).'
)
parser.add_argument(
'--window',
type=int,
default=50000,
help='Window size for coordinate search (default 50kb).',
)
parser.add_argument(
'--transcripts',
action='store_true',
help='List transcripts instead of gene info.',
)
# Transcript filters
parser.add_argument(
'--mane', action='store_true', help='Filter to MANE transcripts.'
)
parser.add_argument(
'--protein_coding',
action='store_true',
help='Filter to protein coding transcripts.',
)
parser.add_argument(
'--transcript_support_level',
help='Filter by Transcript Support Level (e.g. 1,2).',
)
parser.add_argument(
'--longest',
action='store_true',
help='Filter to longest transcript per gene.',
)
parser.add_argument(
'--details', action='store_true', help='Show full transcript details.'
)
parser.add_argument(
'--gtf_path',
type=str,
default=None,
help=(
'Path or URL to the GTF feather file (defaults to'
' $ALPHAGENOME_GTF_PATH or the public GCS URL).'
),
)
args = parser.parse_args(argv)
gtf = load_gtf(args.gtf_path)
if args.coord is not None:
run_coord_search(gtf, args.coord, args.window)
elif args.genes is not None:
genes_list = [x.strip() for x in args.genes.split(',')]
if args.transcripts:
run_transcript_lookup(
gtf,
genes_list,
args.mane,
args.protein_coding,
args.transcript_support_level,
args.longest,
args.details,
)
else:
run_
# ===== file: skills/workflow_skill_creator/references/cli_script_template.py =====
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CLI script template for skills that wrap external APIs.
Copy and adapt this pattern when generating a multi-command CLI script for a
new skill. This follows the same structure as clinvar_api.py and screen_api.py.
Key design decisions:
- Uses argparse with subcommands (one per workflow step).
- All subcommands write output to a JSON file via --output.
- Uses stdlib only (urllib, json, argparse) — no requests, no third-party deps.
- Built-in rate limiting with dedicated RateLimitError and retry logic.
"""
import argparse
import json
import sys
import time
from urllib import error as urllib_error
from urllib import parse as urllib_parse
from urllib import request as urllib_request
class RateLimitError(Exception):
"""Raised when the API rate limit is exceeded."""
class MyAPIClient:
"""Client for the Example API with built-in rate limiting.
Replace with your actual API. Adapt this class as follows:
1. Set BASE_URL to your API's base URL.
2. Set REQUESTS_PER_SECOND to the documented rate limit.
3. Implement domain-specific query methods.
"""
BASE_URL = 'https://api.example.com/v1'
REQUESTS_PER_SECOND = 5
def __init__(self):
self.delay = 1.0 / self.REQUESTS_PER_SECOND
self.last_request_time = 0.0
def _wait_for_rate_limit(self):
"""Blocks until enough time has passed since the last request."""
elapsed = time.monotonic() - self.last_request_time
if elapsed < self.delay:
time.sleep(self.delay - elapsed)
def _request(self, path, params=None, retries=3):
"""Makes an HTTP GET request with rate limiting and retry logic.
Args:
path: URL path relative to BASE_URL (e.g., '/search').
params: Optional dict of query parameters.
retries: Number of retry attempts for transient server errors.
Returns:
Parsed JSON response as a Python dict/list.
Raises:
RateLimitError: If the server responds with HTTP 429.
RuntimeError: If the request fails after all retries.
"""
url = f'{self.BASE_URL}{path}'
if params:
url = f'{url}?{urllib_parse.urlencode(params)}'
for attempt in range(retries):
self._wait_for_rate_limit()
try:
req = urllib_request.Request(url)
req.add_header('Accept', 'application/json')
with urllib_request.urlopen(req, timeout=30) as response:
self.last_request_time = time.monotonic()
return json.loads(response.read().decode('utf-8'))
except urllib_error.HTTPError as e:
self.last_request_time = time.monotonic()
if e.code == 429:
# Rate limited — exponential backoff before retry
wait = 2**attempt
print(
f'Rate limited (429), retrying in {wait}s '
f'(attempt {attempt + 1}/{retries})...',
file=sys.stderr,
)
if attempt == retries - 1: