bio-copy-number-cnv-visualization
Visualize copy number profiles, segments, allele-specific tracks, and cohort patterns from CNVkit, GATK, ASCAT, FACETS, Sequenza, and other callers. Covers genome-wide and per-chromosome log2 scatter plots, B-allele-frequency/minor-allele-fraction tracks, ideograms, cohort heatmaps, circos views, and caller-native plots. Use when creating publication CNV figures, choosing which plot answers a given question, diagnosing a wrong diploid baseline visually, displaying loss of heterozygosity, or deciding what depth-only plots cannot reveal.
What this skill does
## Version Compatibility
Reference examples tested with: matplotlib 3.8+, pandas 2.2+, numpy 1.26+, seaborn 0.13+, CNVkit 0.9.10+, GATK 4.5+; R 4.3+ with ggplot2 3.5+.
Before using code patterns, verify installed versions match. If versions differ:
- Python: `pip show matplotlib pandas` then `help(function)` for signatures
- R: `packageVersion('ggplot2')` then `?function_name`
- CLI: `cnvkit.py version`, `gatk --version`
If code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example rather than retrying.
# CNV Visualization
**"Plot my copy number profile"** -> A CNV figure is an argument, not a picture. The plot type, the y-axis quantity, and where the diploid baseline sits all determine what the reader can conclude. The single most important rule: a depth-only log2 plot cannot show loss of heterozygosity, cannot show tumor purity, and silently misleads if the diploid baseline is centered on a non-diploid mode.
- CLI: `cnvkit.py scatter` / `diagram` / `heatmap`; `gatk PlotModeledSegments`
- Python: `matplotlib` for custom genome-wide and allele-specific tracks
- R: `ggplot2`, `karyoploteR` for publication ideograms
## Plot Selection — What Each View Reveals and Hides
| Plot | Answers | Reveals | Cannot show |
|------|---------|---------|-------------|
| Genome-wide log2 scatter + segments | Where are the gains/losses? | Focal vs broad events, noise level | LOH, purity, allele-specific state |
| Per-chromosome scatter | Is this focal event real and where are its boundaries? | Breakpoints, bin support, weight | Absolute CN without purity |
| BAF / minor-allele-fraction track | Is there allelic imbalance / LOH? | CN-neutral LOH, mirrored imbalance | Total copy number alone |
| Combined log2 + BAF (two-panel) | What is the allele-specific state? | Gains vs CN-LOH vs balanced | — (this is the complete view) |
| Cohort heatmap | What is recurrent across samples? | Shared arm/focal events | Per-sample breakpoint detail |
| Ideogram / diagram | Where do events sit relative to cytobands/genes? | Gene-level context | Quantitative amplitude |
| Circos | Genome-wide CNV + SV breakpoints together | CNV-SV co-localization | Fine amplitude detail |
| Caller-native (GATK/ASCAT/FACETS) | Did the caller fit correctly? | Model fit, segment confidence | — (diagnostic, not publication) |
The decision rule: if the biological question involves LOH, allele-specific gain, or whole-genome doubling, a log2-only plot is insufficient — pair it with a BAF track.
## CNVkit Built-in Plots
```bash
cnvkit.py scatter sample.cnr -s sample.cns -o scatter.png # genome-wide
cnvkit.py scatter sample.cnr -s sample.cns -c chr17 -o chr17.png # one chromosome
cnvkit.py scatter sample.cnr -s sample.cns -v sample.vcf.gz -o baf.png # with BAF panel
cnvkit.py diagram sample.cnr -s sample.cns -o diagram.pdf # ideogram
cnvkit.py heatmap cohort/*.cns -d -o cohort_heatmap.pdf # cohort, desaturated
```
Passing `-v` with a VCF adds a B-allele-frequency panel — use it whenever LOH matters.
## Genome-Wide log2 Profile with Segments
**Goal:** Render a publication genome-wide CNV profile with colored segments.
**Approach:** Map per-bin log2 to cumulative genomic coordinates, plot bins as faint points, overlay segment medians as colored horizontal lines, mark chromosome boundaries.
```python
import pandas as pd
import matplotlib.pyplot as plt
def plot_genome_profile(cnr_file, cns_file, output=None, gain=0.3, loss=-0.3):
'''Genome-wide log2 scatter with segment overlay.'''
cnr = pd.read_csv(cnr_file, sep='\t')
cns = pd.read_csv(cns_file, sep='\t')
chroms = [f'chr{i}' for i in range(1, 23)] + ['chrX', 'chrY']
offsets, cum = {}, 0
for c in chroms:
sub = cnr[cnr['chromosome'] == c]
if sub.empty:
continue
offsets[c] = cum
cum += sub['end'].max()
cnr = cnr[cnr['chromosome'].isin(offsets)].copy()
cnr['x'] = cnr.apply(lambda r: offsets[r['chromosome']] + r['start'], axis=1)
fig, ax = plt.subplots(figsize=(16, 4))
ax.scatter(cnr['x'], cnr['log2'], s=1, c='0.7', alpha=0.5, rasterized=True)
for _, seg in cns.iterrows():
if seg['chromosome'] not in offsets:
continue
x0 = offsets[seg['chromosome']] + seg['start']
x1 = offsets[seg['chromosome']] + seg['end']
color = 'red' if seg['log2'] > gain else 'blue' if seg['log2'] < loss else '0.3'
ax.hlines(seg['log2'], x0, x1, colors=color, linewidth=2.5)
for c, x in offsets.items():
ax.axvline(x, color='0.9', linewidth=0.5)
ax.axhline(0, color='black', linewidth=0.6)
ax.set_ylim(-2, 2)
ax.set_ylabel('log2 copy ratio')
ax.set_xlabel('genomic position')
fig.tight_layout()
if output:
fig.savefig(output, dpi=200)
return fig, ax
```
## Combined log2 + B-Allele-Frequency Panel
**Goal:** Show total copy number and allelic imbalance together so CN-neutral LOH and allele-specific gains are visible.
**Approach:** Stack two axes — log2 on top, BAF below. Mirror BAF about 0.5 so allelic imbalance reads as deviation from the center line.
```python
import numpy as np
def plot_log2_baf(cnr_file, baf_df, output=None):
'''Two-panel plot: log2 copy ratio above, B-allele frequency below.
baf_df: columns chromosome, position, baf (germline-het sites only).'''
cnr = pd.read_csv(cnr_file, sep='\t')
fig, (ax_cn, ax_baf) = plt.subplots(2, 1, figsize=(16, 6), sharex=True)
ax_cn.scatter(range(len(cnr)), cnr['log2'], s=1, c='0.6', alpha=0.5)
ax_cn.axhline(0, color='black', linewidth=0.6)
ax_cn.set_ylabel('log2 ratio')
ax_cn.set_ylim(-2, 2)
# Plot BAF and its mirror; a tight band at 0.5 = balanced, split bands = imbalance/LOH
ax_baf.scatter(range(len(baf_df)), baf_df['baf'], s=2, c='0.4', alpha=0.5)
ax_baf.scatter(range(len(baf_df)), 1 - baf_df['baf'], s=2, c='0.4', alpha=0.5)
ax_baf.axhline(0.5, color='black', linewidth=0.6)
ax_baf.set_ylabel('B-allele frequency')
ax_baf.set_ylim(0, 1)
ax_baf.set_xlabel('het SNP index')
fig.tight_layout()
if output:
fig.savefig(output, dpi=200)
return fig
```
A copy-neutral LOH region shows log2 ~ 0 but BAF splitting away from 0.5 — invisible on any log2-only plot.
## Cohort Heatmap
**Goal:** Show recurrent CNV patterns across a cohort.
**Approach:** Resample every sample's segments onto a common genomic bin grid, stack into a samples-by-bins matrix, render with a diverging colormap centered at zero.
```python
import seaborn as sns
def plot_cohort_heatmap(cns_files, bin_size=1_000_000, output=None):
'''Recurrent-CNV heatmap across a cohort on a uniform bin grid.'''
chroms = [f'chr{i}' for i in range(1, 23)]
columns = []
for c in chroms:
columns += [(c, b) for b in range(0, 250_000_000, bin_size)]
matrix = {}
for f in cns_files:
name = f.split('/')[-1].replace('.cns', '')
cns = pd.read_csv(f, sep='\t')
row = {}
for c, b in columns:
hits = cns[(cns['chromosome'] == c) &
(cns['start'] < b + bin_size) & (cns['end'] > b)]
row[(c, b)] = hits['log2'].mean() if not hits.empty else 0.0
matrix[name] = row
df = pd.DataFrame(matrix).T
fig, ax = plt.subplots(figsize=(14, max(4, 0.3 * len(cns_files))))
sns.heatmap(df, cmap='RdBu_r', center=0, vmin=-1.5, vmax=1.5,
xticklabels=False, ax=ax)
ax.set_xlabel('genomic bin')
ax.set_ylabel('sample')
if output:
fig.savefig(output, dpi=200, bbox_inches='tight')
return fig
```
## Caller-Native Diagnostic Plots
```bash
# GATK: denoised ratios + modeled segments with allelic info
gatk PlotModeledSegments --denoised-copy-ratios tumor.denoisedCR.tsv \
--allelic-counts tumor.hets.tsv --segments tumor.modelFinal.seg \
--sequence-dictionary reference.dict --output-prefix tumor -O plots/
``Related in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.