alterlab-clinvar

$npx mdskill add AlterLab-IEU/AlterLab-Academic-Skills/alterlab-clinvar

Query ClinVar for germline variant pathogenicity and clinical significance.

  • Assess if a variant is pathogenic, benign, or VUS using ACMG classifications.
  • Uses NCBI E-utilities REST API and optional FTP for data access.
  • Interprets review-status star ratings and conflicting classifications.
  • Returns structured clinical significance data for variant annotation.

SKILL.md

.github/skills/alterlab-clinvarView on GitHub ↗
---
name: alterlab-clinvar
description: Query NCBI ClinVar via the E-utilities API or FTP for the clinical significance (pathogenicity) of human germline genetic variants, searching by gene, variant, condition, or genomic position and interpreting ACMG/AMP classifications and review-status star ratings. Use when assessing whether a variant is pathogenic, likely pathogenic, VUS, likely benign, or benign, resolving conflicting interpretations, or annotating a VCF with ClinVar clinical significance. For population allele frequencies by ancestry use alterlab-gnomad; for somatic cancer mutation frequencies use alterlab-cosmic. Part of the AlterLab Academic Skills suite.
license: MIT
allowed-tools: Read WebFetch Bash(curl:*) Bash(python:*)
compatibility: Keyless NCBI E-utilities REST API; optional NCBI API key raises rate limits
metadata:
    skill-author: AlterLab
    version: "1.0.0"
---

# ClinVar Database

## Overview

ClinVar is NCBI's freely accessible archive of reports on relationships between human genetic variants and phenotypes, with supporting evidence. The database aggregates information about genomic variation and its relationship to human health, providing standardized variant classifications used in clinical genetics and research.

## When to Use This Skill

This skill should be used when:

- Searching for variants by gene, condition, or clinical significance
- Interpreting clinical significance classifications (pathogenic, benign, VUS)
- Accessing ClinVar data programmatically via E-utilities API
- Downloading and processing bulk data from FTP
- Understanding review status and star ratings
- Resolving conflicting variant interpretations
- Annotating variant call sets with clinical significance

## Core Capabilities

### 1. Search and Query ClinVar

#### Web Interface Queries

Search ClinVar using the web interface at https://www.ncbi.nlm.nih.gov/clinvar/

**Common search patterns** (field tags verified against the live `einfo` field list — there is **no `[CLNSIG]` or `[RVSTAT]` field**; using them silently falls back to `[All Fields]` and does NOT filter):
- By gene: `BRCA1[gene]`
- By clinical significance: `clinsig_pathogenic[Properties]` (also `clinsig_likely_pathogenic`, `clinsig_benign`, `clinsig_likely_benign`, `clinsig_uncertain`, `clinsig_has_conflicts`)
- By review status: `"reviewed by expert panel"[Review status]`, `"practice guideline"[Review status]`, `"criteria provided, single submitter"[Review status]`
- By condition: `"breast cancer"[Disease/Phenotype]`
- By variant: `"c.1310_1313del"[Variant name]`
- By chromosome: `13[chr]`
- Combined: `BRCA1[gene] AND clinsig_pathogenic[Properties]`

#### Programmatic Access via E-utilities

Access ClinVar programmatically using NCBI's E-utilities API. Refer to `references/api_reference.md` for comprehensive API documentation including:
- **esearch** - Search for variants matching criteria
- **esummary** - Retrieve variant summaries
- **efetch** - Download full XML records
- **elink** - Find related records in other NCBI databases

**Quick example using curl:**
```bash
# Search for pathogenic BRCA1 variants
curl "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=clinvar&term=BRCA1[gene]+AND+clinsig_pathogenic[Properties]&retmode=json"
```
Always inspect the `querytranslation` field in the response: if a `[...]` tag is unknown, NCBI rewrites it to `[All Fields]` and your filter is silently dropped.

**Best practices:**
- Test queries on the web interface before automating
- Use API keys to increase rate limits from 3 to 10 requests/second
- Implement exponential backoff for rate limit errors
- Set `Entrez.email` when using Biopython

### 2. Interpret Clinical Significance

#### Understanding Classifications

ClinVar uses standardized terminology for variant classifications. Refer to `references/clinical_significance.md` for detailed interpretation guidelines.

**Key germline classification terms (ACMG/AMP):**
- **Pathogenic (P)** - Variant causes disease (~99% probability)
- **Likely Pathogenic (LP)** - Variant likely causes disease (~90% probability)
- **Uncertain Significance (VUS)** - Insufficient evidence to classify
- **Likely Benign (LB)** - Variant likely does not cause disease
- **Benign (B)** - Variant does not cause disease

**Review status (star ratings):**
- ★★★★ Practice guideline - Highest confidence
- ★★★ Expert panel review (e.g., ClinGen) - High confidence
- ★★ Multiple submitters, no conflicts - Moderate confidence
- ★ Single submitter with criteria - Standard weight
- ☆ No assertion criteria - Low confidence

**Critical considerations:**
- Always check review status - prefer ★★★ or ★★★★ ratings
- Conflicting interpretations require manual evaluation
- Classifications may change as new evidence emerges
- VUS (uncertain significance) variants lack sufficient evidence for clinical use

### 3. Download Bulk Data from FTP

#### Access ClinVar FTP Site

Download complete datasets from `ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/`

Refer to `references/data_formats.md` for comprehensive documentation on file formats and processing.

**Update schedule:**
- Monthly releases: First Thursday of each month (complete dataset, archived)
- Weekly updates: Every Monday (incremental updates)

#### Available Formats

**XML files** (most comprehensive):
- VCV (Variation) files: `xml/clinvar_variation/` - Variant-centric aggregation
- RCV (Record) files: `xml/RCV/` - Variant-condition pairs
- Include full submission details, evidence, and metadata

**VCF files** (for genomic pipelines):
- GRCh37: `vcf_GRCh37/clinvar.vcf.gz`
- GRCh38: `vcf_GRCh38/clinvar.vcf.gz`
- Limitations: Excludes variants >10kb and complex structural variants

**Tab-delimited files** (for quick analysis):
- `tab_delimited/variant_summary.txt.gz` - Summary of all variants
- `tab_delimited/var_citations.txt.gz` - PubMed citations
- `tab_delimited/cross_references.txt.gz` - Database cross-references

**Example download:**
```bash
# Download latest monthly XML release
wget ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/xml/clinvar_variation/ClinVarVariationRelease_00-latest.xml.gz

# Download VCF for GRCh38
wget ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh38/clinvar.vcf.gz
```

### 4. Process and Analyze ClinVar Data

#### Working with XML Files

Process XML files to extract variant details, classifications, and evidence.

**Python example with xml.etree:**
```python
import gzip
import xml.etree.ElementTree as ET

with gzip.open('ClinVarVariationRelease.xml.gz', 'rt') as f:
    for event, elem in ET.iterparse(f, events=('end',)):
        if elem.tag == 'VariationArchive':
            variation_id = elem.attrib.get('VariationID')
            # Extract clinical significance, review status, etc.
            elem.clear()  # Free memory
```

#### Working with VCF Files

Annotate variant calls or filter by clinical significance using bcftools or Python.

**Using bcftools:**
```bash
# Filter pathogenic variants
bcftools view -i 'INFO/CLNSIG~"Pathogenic"' clinvar.vcf.gz

# Extract specific genes
bcftools view -i 'INFO/GENEINFO~"BRCA"' clinvar.vcf.gz

# Annotate your VCF with ClinVar
bcftools annotate -a clinvar.vcf.gz -c INFO your_variants.vcf
```

**Using pysam in Python** (the old `PyVCF`/`import vcf` package is unmaintained and breaks on Python 3.10+; use `pysam` or `cyvcf2` instead):
```python
import pysam

vcf = pysam.VariantFile("clinvar.vcf.gz")
for rec in vcf:
    # CLNSIG is a comma/pipe-delimited string (e.g. "Pathogenic/Likely_pathogenic");
    # match as substring, not equality.
    clnsig = str(rec.info.get("CLNSIG", ""))
    if "Pathogenic" in clnsig:
        gene = rec.info.get("GENEINFO", "")
        print(f"{rec.chrom}:{rec.pos} {gene} - {clnsig}")
```

#### Working with Tab-Delimited Files

Use pandas or command-line tools for rapid filtering and analysis.

**Using pandas:**
```python
import pandas as pd

# Load variant summary
df = pd.read_csv('variant_summary.txt.gz', sep='\t', compression='gzip')

# Filter pathogenic variants in specific gene
pathogenic_brca = df[
    (df['GeneSymbol'] == 'BRCA1') &
    (df['ClinicalSignificance'].str.contains('Pathogenic', na=False))
]

# Count variants by clinical significance
sig_counts = df['ClinicalSignificance'].value_counts()
```

**Using command-line tools:**
```bash
# Extract pathogenic variants for specific gene
zcat variant_summary.txt.gz | \
  awk -F'\t' '$7=="TP53" && $13~"Pathogenic"' | \
  cut -f1,5,7,13,14
```

### 5. Handle Conflicting Interpretations

When multiple submitters provide different classifications for the same variant, ClinVar reports "Conflicting interpretations of pathogenicity."

**Resolution strategy:**
1. Check review status (star rating) - higher ratings carry more weight
2. Examine evidence and assertion criteria from each submitter
3. Consider submission dates - newer submissions may reflect updated evidence
4. Review population frequency data (e.g., gnomAD) for context
5. Consult expert panel classifications (★★★) when available
6. For clinical use, always defer to a genetics professional

**Search query to exclude conflicts:**
```
TP53[gene] AND clinsig_pathogenic[Properties] NOT clinsig_has_conflicts[Properties]
```

### 6. Track Classification Updates

Variant classifications may change over time as new evidence emerges.

**Why classifications change:**
- New functional studies or clinical data
- Updated population frequency information
- Revised ACMG/AMP guidelines
- Segregation data from additional families

**Best practices:**
- Document ClinVar version and access date for reproducibility
- Re-check classifications periodically for critical variants
- Subscribe to ClinVar mailing list for major updates
- Use monthly archived releases for stable datasets

### 7. Submit Data to ClinVar

Organizations can submit variant interpretations to ClinVar.

**Submission methods:**
- Web submission portal: https://submit.ncbi.nlm.nih.gov/clinvar/
- API submission (requires service account): See `references/api_reference.md`
- Batch submission via Excel templates

**Requirements:**
- Organizational account with NCBI
- Assertion criteria (preferably ACMG/AMP guidelines)
- Supporting evidence for classification

Contact: [email protected] for submission account setup.

## Workflow Examples

### Example 1: Identify High-Confidence Pathogenic Variants in a Gene

**Objective:** Find pathogenic variants in CFTR gene with expert panel review.

**Steps:**
1. Search using web interface or E-utilities:
   ```
   CFTR[gene] AND clinsig_pathogenic[Properties] AND ("reviewed by expert panel"[Review status] OR "practice guideline"[Review status])
   ```
2. Review results, noting review status (should be ★★★ or ★★★★)
3. Export variant list or retrieve full records via efetch
4. Cross-reference with clinical presentation if applicable

### Example 2: Annotate VCF with ClinVar Classifications

**Objective:** Add clinical significance annotations to variant calls.

**Steps:**
1. Download appropriate ClinVar VCF (match genome build: GRCh37 or GRCh38):
   ```bash
   wget ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh38/clinvar.vcf.gz
   wget ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh38/clinvar.vcf.gz.tbi
   ```
2. Annotate using bcftools:
   ```bash
   bcftools annotate -a clinvar.vcf.gz \
     -c INFO/CLNSIG,INFO/CLNDN,INFO/CLNREVSTAT \
     -o annotated_variants.vcf \
     your_variants.vcf
   ```
3. Filter annotated VCF for pathogenic variants:
   ```bash
   bcftools view -i 'INFO/CLNSIG~"Pathogenic"' annotated_variants.vcf
   ```

### Example 3: Analyze Variants for a Specific Disease

**Objective:** Study all variants associated with hereditary breast cancer.

**Steps:**
1. Search by condition:
   ```
   "hereditary breast cancer"[Disease/Phenotype] OR "Breast-ovarian cancer, familial"[Disease/Phenotype]
   ```
2. Download results as CSV or retrieve via E-utilities
3. Filter by review status to prioritize high-confidence variants
4. Analyze distribution across genes (BRCA1, BRCA2, PALB2, etc.)
5. Examine variants with conflicting interpretations separately

### Example 4: Bulk Download and Database Construction

**Objective:** Build a local ClinVar database for analysis pipeline.

**Steps:**
1. Download monthly release for reproducibility:
   ```bash
   wget ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/xml/clinvar_variation/ClinVarVariationRelease_YYYY-MM.xml.gz
   ```
2. Parse XML and load into database (PostgreSQL, MySQL, MongoDB)
3. Index by gene, position, clinical significance, review status
4. Implement version tracking for updates
5. Schedule monthly updates from FTP site

## Important Limitations and Considerations

### Data Quality
- **Not all submissions have equal weight** - Check review status (star ratings)
- **Conflicting interpretations exist** - Require manual evaluation
- **Historical submissions may be outdated** - Newer data may be more accurate
- **VUS classification is not a clinical diagnosis** - Means insufficient evidence

### Scope Limitations
- **Not for direct clinical diagnosis** - Always involve genetics professional
- **Population-specific** - Variant frequencies vary by ancestry
- **Incomplete coverage** - Not all genes or variants are well-studied
- **Version dependencies** - Coordinate genome build (GRCh37/GRCh38) across analyses

### Technical Limitations
- **VCF files exclude large variants** - Variants >10kb not in VCF format
- **Rate limits on API** - 3 req/sec without key, 10 req/sec with API key
- **File sizes** - Full XML releases are multi-GB compressed files
- **No real-time updates** - Website updated weekly, FTP monthly/weekly

## Resources

### Reference Documentation

This skill includes comprehensive reference documentation:

- **`references/api_reference.md`** - Complete E-utilities API documentation with examples for esearch, esummary, efetch, and elink; includes rate limits, authentication, and Python/Biopython code samples

- **`references/clinical_significance.md`** - Detailed guide to interpreting clinical significance classifications, review status star ratings, conflict resolution, and best practices for variant interpretation

- **`references/data_formats.md`** - Documentation for XML, VCF, and tab-delimited file formats; FTP directory structure, processing examples, and format selection guidance

### External Resources

- ClinVar home: https://www.ncbi.nlm.nih.gov/clinvar/
- ClinVar documentation: https://www.ncbi.nlm.nih.gov/clinvar/docs/help/
- E-utilities documentation: https://www.ncbi.nlm.nih.gov/books/NBK25501/
- ACMG variant interpretation guidelines: Richards et al., 2015 (PMID: 25741868)
- ClinGen expert panels: https://clinicalgenome.org/

### Contact

For questions about ClinVar or data submission: [email protected]

## Scripts

`scripts/query_clinvar.py` — runnable helper for ClinVar via NCBI E-utilities (no key; `NCBI_API_KEY` lifts the rate limit):

```bash
python scripts/query_clinvar.py search "BRCA1[gene] AND clinsig_pathogenic[Properties]" --retmax 5
python scripts/query_clinvar.py summary 12345,12346
```

More from AlterLab-IEU/AlterLab-Academic-Skills

SkillDescription
alterlab-abm-mesaBuilds agent-based models of social systems with Mesa 3 — the current AgentSet API (model.agents.shuffle_do('step'), auto-assigned unique_id, mandatory super().__init__(seed=...)), cell spaces (mesa.discrete_space OrthogonalMooreGrid / classic mesa.space grids), the DataCollector, batch_run parameter sweeps, and SolaraViz — for emergence, segregation, diffusion, opinion dynamics, and cooperation models. It uses the Mesa 3.x API (the old mesa.time schedulers like RandomActivation are removed) and treats the model as a generative theory to be validated, not just run. Use when the request mentions an agent-based model, Mesa, simulating interacting agents, or emergent macro behavior from micro rules. For discrete-event (queueing/process) simulation prefer alterlab-simpy; for reinforcement learning prefer alterlab-stable-baselines3. Part of the AlterLab Academic Skills suite.
alterlab-academic-careerPrepares academic career documents and professional-development materials for faculty and researchers. Use when drafting academic CVs, research statements, teaching philosophies, diversity statements, faculty-position cover letters, tenure dossiers, promotion narratives, academic portfolios, or mentorship statements, and when planning conference-networking strategy, building academic web presence, setting up ORCID profiles, or understanding impact metrics. Part of the AlterLab Academic Skills suite.
alterlab-accreditation-aolScaffolds program-level Assurance-of-Learning (AoL) documentation for AACSB (2020 Standard 5) and ABET (Criterion 3 Student Outcomes, Criterion 4 Continuous Improvement) accreditation — program learning outcomes / competency goals, curriculum-to-outcome mapping matrices, direct- and indirect-assessment plans, rubric design, and closing-the-loop continuous-improvement narratives — and validates the structure of an outcome-mapping matrix with scripts/aol_matrix.py. Use when the user needs AACSB or ABET assurance-of-learning material, a program-learning-outcomes set, a curriculum/outcome map or coverage matrix, a direct/indirect assessment plan, a closing-the-loop report, or accreditation self-study text. For single-course design or course rubrics prefer alterlab-teaching-design; for post-award grant reports prefer alterlab-grant-reporting. Part of the AlterLab Academic Skills suite.
alterlab-adaptyvSubmits and tracks protein-testing experiments on the Adaptyv Bio Foundry cloud lab (wet-lab validation), and optimizes protein sequences before submission with computational tools (NetSolP, SoluProt, SolubleMPNN, ESM). Use when designing proteins that need wet-lab validation - binding/affinity screening, expression testing, thermostability, or fluorescence assays - or when submitting experiments to the Foundry API, browsing the target catalog, tracking experiment status, retrieving results, or pre-screening sequences for solubility/expression. Triggers on "Adaptyv", "Foundry API", "cloud lab", "biolayer interferometry / BLI", "wet-lab validation". Part of the AlterLab Academic Skills suite.
alterlab-aeonRuns time series machine learning with the aeon library — classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search via scikit-learn compatible APIs. Use when working with temporal data, sequential patterns, or time-indexed observations (univariate or multivariate) that need specialized algorithms beyond standard ML approaches. Part of the AlterLab Academic Skills suite.
alterlab-akademik-tesvikComputes the annual Turkish academic-incentive (akademik teşvik) score for Devlet (state) university öğretim elemanı (academic staff) from a classified activity list, applying the verified Akademik Teşvik Ödeneği Yönetmeliği (2018/11834) Faaliyet Hesaplama Tablosu headline puanları (Proje 20, Araştırma 15, Yayın 30, Patent 30, Atıf 30, Tebliğ 20, Ödül 20) with the k (author-count), p (Q1 1/Q2 0.8/Q3 0.5/Q4 0.25), and r (project-role) coefficients via türü puanı = Σ(faaliyet oranları) × headline (MADDE 8/2), then enforcing the per-type headline ceilings, the 100 cap (MADDE 8/3), and the net-30 payment gate (MADDE 10/3) in a deterministic scripts/tesvik_score.py. Use when the user wants to calculate akademik teşvik puanı, check the en az 30 (net-30) threshold, apply TABLO 4 ceilings, or estimate teşvik eligibility; keeps its coefficients separate from doçentlik scoring. For doçentlik point eligibility prefer alterlab-docentlik-eligibility. Part of the AlterLab Academic Skills suite.
alterlab-alpha-vantageAccesses real-time and historical stock market data, forex rates, cryptocurrency prices, commodities, economic indicators, and 50+ technical indicators via the Alpha Vantage API (requires a free API key from alphavantage.co). Use when fetching stock prices (OHLCV), company fundamentals (income statement, balance sheet, cash flow), earnings, options data, market news/sentiment, insider transactions, GDP, CPI, treasury yields, gold/silver/oil prices, Bitcoin/crypto prices, forex exchange rates, or calculating technical indicators (SMA, EMA, MACD, RSI, Bollinger Bands). Part of the AlterLab Academic Skills suite.
alterlab-alphafoldPredict protein 3D structures with AlphaFold2 via ColabFold — MMseqs2-accelerated MSAs, monomer and AlphaFold2-Multimer complex folding, and confidence-based validation (pLDDT, pTM/ipTM, PAE). Use when folding a protein sequence or complex from FASTA, generating a predicted structure with confidence metrics, ranking models, or checking self-consistency of a design. For co-folding a protein WITH a small-molecule ligand or predicting binding affinity prefer alterlab-boltz; for antibody–antigen or one-FASTA multi-entity complexes prefer alterlab-chai; to LOOK UP an already-computed structure prefer alterlab-alphafold-db; for ESM embeddings or inverse folding prefer alterlab-esm. Part of the AlterLab Academic Skills suite.
alterlab-alphafold-dbAccess the AlphaFold DB of 200M+ AI-PREDICTED protein structures — retrieve models by UniProt accession, download PDB/mmCIF files, and analyze prediction confidence metrics (pLDDT, PAE). Use when a UniProt ID needs a computationally predicted 3D structure or when no experimental structure exists, for homology modeling, protein engineering, or structure-based drug discovery; for EXPERIMENTALLY determined structures (X-ray, cryo-EM, NMR) prefer alterlab-pdb, and for protein sequences, annotations, or accession ID mapping prefer alterlab-uniprot instead. Part of the AlterLab Academic Skills suite.
alterlab-anndataBuild, slice, concatenate, read, and write AnnData annotated data matrices (obs, var, X, layers, obsm, uns) — the scverse data STRUCTURE, not an analysis pipeline. Use when creating or wrangling .h5ad/zarr files, managing cell and gene annotations, concatenating batches, or handling layers/obsm/backed-mode; for the QC, normalization, clustering, UMAP, and differential-expression analysis pipeline prefer alterlab-scanpy instead, and for RNA velocity from spliced/unspliced layers prefer alterlab-scvelo instead. Part of the AlterLab Academic Skills suite.