[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73G567X03GAZYS5EJQSP2NH":3,"skill-same:01M73G567X03GAZYS5EJQSP2NH":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73G567X03GAZYS5EJQSP2NH","cnvkit-copy-number",null,"Detect somatic CNVs from WES\u002FWGS\u002Ftargeted BAMs (CNVkit v0.9.x). Bin coverage in target\u002Fantitarget regions, normalize vs reference, segment with CBS\u002FHMM, call amps\u002Fdels, scatter\u002Fdiagram plots, purity\u002Fploidy, VCF\u002FSEG export. CLI plus Python API (cnvlib). Use GATK CNV for deep WGS with population controls; use CNVkit for targeted\u002Fexome where antitarget bins matter.","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fcnvkit-copy-number\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"cnvkit-copy-number\"\ndescription: \"Detect somatic CNVs from WES\u002FWGS\u002Ftargeted BAMs (CNVkit v0.9.x). Bin coverage in target\u002Fantitarget regions, normalize vs reference, segment with CBS\u002FHMM, call amps\u002Fdels, scatter\u002Fdiagram plots, purity\u002Fploidy, VCF\u002FSEG export. CLI plus Python API (cnvlib). Use GATK CNV for deep WGS with population controls; use CNVkit for targeted\u002Fexome where antitarget bins matter.\"\nlicense: \"Apache-2.0\"\n---\n\n# CNVkit Copy Number Analysis\n\n## Overview\n\nCNVkit detects somatic copy number variants (CNVs) from whole-exome sequencing (WES), whole-genome sequencing (WGS), or targeted panel BAM files. It calculates read depth in both on-target (capture) bins and off-target (antitarget) bins, corrects for GC bias and library depth, segments the log2 copy ratio profile with circular binary segmentation (CBS) or a hidden Markov model (HMM), and calls amplifications and deletions. CNVkit provides both a CLI (`cnvkit.py`) and a Python API (`cnvlib`) for integration into analysis pipelines, and produces scatter plots, chromosome diagrams, heatmaps, and export files in VCF, BED, and SEG formats.\n\n## When to Use\n\n- Calling somatic copy number variants from tumor-normal paired exome (WES) or targeted panel sequencing\n- Detecting copy number alterations in tumor-only samples using a pooled normal reference\n- Running CNV analysis on whole-genome sequencing (WGS) data with the `--method wgs` mode\n- Estimating tumor purity and ploidy for samples where purity is unknown, to interpret copy ratio calls\n- Generating SEG format copy number files for GISTIC2, cBioPortal, or IGV visualization\n- Identifying focal amplifications (e.g., ERBB2, MYC) or homozygous deletions (e.g., CDKN2A, RB1)\n- Use **omics-plotting** SKILL for generic coverage\u002Flog2-ratio figures from exported tables; genome-wide CNV views use `cnvkit.py scatter\u002Fdiagram`\n- Use **GATK CNV** (`gatk DenoiseReadCounts` \u002F `gatk ModelSegments`) instead for deep WGS cohorts with large matched panel-of-normals (PoN); CNVkit is better suited for targeted\u002Fexome data\n- Use **Control-FREEC** instead when you need allele-frequency-based B-allele fraction modeling alongside CNV calling\n\n## Prerequisites\n\n- **Software**: CNVkit v0.9.x, Python 3.8+, R (for CBS segmentation), samtools\n- **Python packages**: `cnvlib` (installed as part of CNVkit), `matplotlib`, `pandas`\n- **Input files**: sorted, indexed BAM files (tumor ± matched normal); BED file of capture targets; reference genome FASTA; access to R with DNAcopy package for CBS\n- **Data requirements**: minimum ~50× mean target coverage for WES; WGS works at 20-30×\n\n> **Check before installing**: The tool may already be available in the current environment (e.g., inside a `pixi` \u002F `conda` env). Run `command -v cnvkit.py` first and skip the install commands below if it returns a path. When running inside a pixi project, invoke the tool via `pixi run cnvkit.py` rather than bare `cnvkit.py`.\n\n```bash\n# Install CNVkit via conda (recommended — handles R\u002FDNAcopy dependency)\nconda install -c bioconda cnvkit\n\n# Or via pip (requires R + DNAcopy already installed)\npip install cnvkit\n\n# Verify\ncnvkit.py version\n# cnvkit 0.9.10\n\n# Install R DNAcopy (for CBS segmentation)\nRscript -e 'if (!requireNamespace(\"BiocManager\")) install.packages(\"BiocManager\"); BiocManager::install(\"DNAcopy\")'\n\n# Index BAM files if not already indexed\nsamtools index tumor.bam\nsamtools index normal.bam\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: sequencingMethod\n    kind: required\n    source: data\n    ask: \"Was this whole-genome, hybrid-capture exome, or amplicon sequencing?\"\n    default: null\n\n  - id: D2\n    param: referenceNormals\n    kind: required\n    source: user\n    ask: \"Which normal samples should define the expected coverage baseline?\"\n    default: null\n\n  - id: D3\n    param: targetRegions\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"Which BED file describes the captured regions?\"\n    default: null\n    skip_if: \"whole-genome sequencing - there are no capture targets\"\n\n  - id: D4\n    param: tumorPurity\n    kind: required\n    source: user\n    ask: \"What fraction of the sample is tumour rather than contaminating normal tissue?\"\n    default: \"1.0 - assumes a pure sample, which understates every copy-number change\"\n\n  - id: D5\n    param: ploidy\n    kind: required\n    source: user\n    ask: \"What baseline ploidy should absolute copy number be called against?\"\n    default: 2\n\n  - id: D6\n    param: segmentMethod\n    kind: optional\n    source: user\n    ask: \"Which algorithm should join bins into segments?\"\n    default: \"circular binary segmentation\"\n\n  - id: D7\n    param: binSizes\n    kind: optional_conditional\n    source: user\n    depends_on: [D1]\n    ask: \"Do the default target and antitarget bin sizes suit this capture design?\"\n    default: \"200 bp targets, 150 kb antitargets\"\n\n  - id: D8\n    param: processes\n    kind: never_ask\n    source: data\n    reason: \"Affects runtime only, not the copy-number calls\"\n    default: \"min(8, available_cores)\"\n```\n\nD2 and D4 are the two that decide whether the calls mean anything. A flat\nreference instead of matched normals leaves capture bias in the log2 ratios,\nand a purity of 1.0 on a 40%-tumour sample compresses every real gain and loss\ntoward neutral. Both produce a complete, plausible-looking segment table.\n\n## Quick Start\n\n```bash\n# One-command paired tumor\u002Fnormal CNV analysis (WES)\ncnvkit.py batch tumor.bam \\\n    --normal normal.bam \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output-dir cnvkit_results\u002F \\\n    --diagram --scatter \\\n    --method hybrid\n\n# Output files in cnvkit_results\u002F:\n#   tumor.targetcoverage.cnn   — target bin coverage\n#   tumor.antitargetcoverage.cnn — antitarget coverage\n#   tumor.cnr                  — copy number ratios\n#   tumor.cns                  — segmented copy numbers\n#   tumor-scatter.png          — genome-wide scatter plot\n#   tumor-diagram.pdf          — chromosome diagram\necho \"CNV analysis complete\"\n```\n\n## Workflow\n\n### Step 1: Create Copy Number Reference\n\nBuild a reference from one or more normal BAM files. This corrects for systematic biases (GC content, mappability) and sets the neutral baseline.\n\n```bash\n# Option A: Paired normal reference (single matched normal)\ncnvkit.py reference normal.targetcoverage.cnn normal.antitargetcoverage.cnn \\\n    --fasta GRCh38.fa \\\n    -o reference_normal.cnn\n\n# Option B: Flat reference (no normal; uses GC\u002Fmappability correction only)\n# Use when no matched normal is available\ncnvkit.py reference \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output flat_reference.cnn\n\n# Option C: Pooled normal reference from multiple normals (most robust)\ncnvkit.py batch \\\n    normal1.bam normal2.bam normal3.bam \\\n    --normal \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output-reference pooled_reference.cnn \\\n    --output-dir normals_cov\u002F\n\necho \"Reference created: pooled_reference.cnn\"\n```\n\n### Step 2: Calculate Coverage in Target and Antitarget Bins\n\nBin the target BED file and compute per-bin read depth for tumor and normal samples.\n\n```bash\n# First, create accessible bins from the target BED\ncnvkit.py target targets.bed \\\n    --annotate refFlat.txt \\\n    --split \\\n    -o targets.split.bed\n\ncnvkit.py antitarget targets.bed \\\n    --access data\u002Faccess-5k-mappable.hg38.bed \\\n    -o antitargets.bed\n\n# Calculate coverage for tumor sample\ncnvkit.py coverage tumor.bam targets.split.bed \\\n    -o tumor.targetcoverage.cnn\n\ncnvkit.py coverage tumor.bam antitargets.bed \\\n    -o tumor.antitargetcoverage.cnn\n\necho \"Coverage files:\"\necho \"  tumor.targetcoverage.cnn\"\necho \"  tumor.antitargetcoverage.cnn\"\n```\n\n```python\n# Python API equivalent: compute coverage with cnvlib\nimport cnvlib\n\n# Load and inspect coverage files\ntarget_cov = cnvlib.read(\"tumor.targetcoverage.cnn\")\nantitarget_cov = cnvlib.read(\"tumor.antitargetcoverage.cnn\")\n\nprint(f\"Target bins: {len(target_cov)}\")\nprint(f\"Antitarget bins: {len(antitarget_cov)}\")\nprint(f\"Mean target depth: {target_cov['depth'].mean():.1f}×\")\nprint(f\"Median target depth: {target_cov['depth'].median():.1f}×\")\n\n# Export target-bin depths; render the coverage histogram with the omics-plotting SKILL (`skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md`)\n# \"Box \u002F Violin \u002F Bar\" recipe (or a histogram) -> figures\u002Fcoverage_distribution.png\ntarget_cov[\"depth\"].clip(upper=500).to_csv(\"target_depths.csv\", index=False)\nprint(\"Saved: target_depths.csv\")\n```\n\n### Step 3: Normalize and Correct Copy Ratios\n\nNormalize tumor coverage against the reference (correcting for GC bias, library depth, and target efficiency).\n\n```bash\n# Fix sample-level biases relative to the reference\ncnvkit.py fix \\\n    tumor.targetcoverage.cnn \\\n    tumor.antitargetcoverage.cnn \\\n    pooled_reference.cnn \\\n    -o tumor.cnr\n\necho \"Copy number ratios: tumor.cnr\"\n# tumor.cnr columns: chromosome, start, end, gene, log2, depth, weight\n```\n\n```python\n# Inspect copy ratio file with cnvlib Python API\nimport cnvlib\nimport pandas as pd\n\ncnr = cnvlib.read(\"tumor.cnr\")\nprint(f\"Total bins: {len(cnr)}\")\nprint(f\"Chromosomes: {sorted(cnr.chromosome.unique())}\")\n\n# Convert to DataFrame and inspect\ndf = cnr.data\nprint(f\"\\nLog2 copy ratio summary:\")\nprint(df[\"log2\"].describe().round(3))\n\n# Flag high-amplitude events\nhigh_amp = df[df[\"log2\"] >= 2.0]\nhom_del  = df[df[\"log2\"] \u003C= -3.0]\nprint(f\"\\nHigh amplitude bins (log2 >= 2.0): {len(high_amp)}\")\nprint(f\"Homozygous deletion bins (log2 \u003C= -3.0): {len(hom_del)}\")\nif not high_amp.empty:\n    print(high_amp[[\"chromosome\", \"start\", \"end\", \"gene\", \"log2\"]].head())\n```\n\n### Step 4: Segment Copy Number Ratios\n\nIdentify contiguous regions of similar copy ratio using CBS (Circular Binary Segmentation) or HMM segmentation.\n\n```bash\n# CBS segmentation (default; requires R DNAcopy)\ncnvkit.py segment tumor.cnr \\\n    -o tumor.cns \\\n    --method cbs\n\n# HMM segmentation (no R required; faster)\ncnvkit.py segment tumor.cnr \\\n    -o tumor.hmm.cns \\\n    --method hmm\n\necho \"Segments: tumor.cns\"\n# tumor.cns columns: chromosome, start, end, gene, log2, cn, depth, p_ttest, weight, probes\n```\n\n```python\n# Python API: segment and inspect\nimport cnvlib\nimport subprocess\n\n# Run segmentation via Python subprocess (mirrors CLI)\nsubprocess.run(\n    [\"cnvkit.py\", \"segment\", \"tumor.cnr\", \"-o\", \"tumor.cns\", \"--method\", \"cbs\"],\n    check=True\n)\n\n# Load and analyze segments\ncns = cnvlib.read(\"tumor.cns\")\ndf_seg = cns.data\nprint(f\"Total segments: {len(df_seg)}\")\nprint(f\"\\nSegment log2 summary:\")\nprint(df_seg[\"log2\"].describe().round(3))\n\n# Large segments (>5 Mb) with copy gain or loss\nlarge_events = df_seg[\n    ((df_seg[\"end\"] - df_seg[\"start\"]) > 5_000_000) &\n    (df_seg[\"log2\"].abs() > 0.3)\n].copy()\nlarge_events[\"size_mb\"] = (large_events[\"end\"] - large_events[\"start\"]) \u002F 1e6\nprint(f\"\\nLarge CNV segments (>5 Mb, |log2|>0.3): {len(large_events)}\")\nprint(large_events[[\"chromosome\", \"start\", \"end\", \"log2\", \"size_mb\"]].head(8).to_string(index=False))\n```\n\n### Step 5: Call CNV States\n\nAssign integer copy number states and classify amplifications and deletions.\n\n```bash\n# Call with default thresholds (diploid normal)\ncnvkit.py call tumor.cns \\\n    -o tumor.call.cns \\\n    --ploidy 2\n\n# Call with tumor purity estimate (if known)\ncnvkit.py call tumor.cns \\\n    --purity 0.7 \\\n    --ploidy 2 \\\n    -o tumor.call.purity.cns\n\necho \"Called CNVs: tumor.call.cns\"\n```\n\n```python\n# Parse called CNV file and classify events\nimport cnvlib\nimport pandas as pd\n\ncns_called = cnvlib.read(\"tumor.call.cns\")\ndf = cns_called.data\n\n# Classify by log2 thresholds (diploid assumed)\n# log2 >= 1.0 = high-level amplification (CN >= 4)\n# log2 0.2–1.0 = copy gain (CN = 3)\n# log2 -1.0–-0.2 = heterozygous deletion (CN = 1)\n# log2 \u003C= -3.5 = homozygous deletion (CN = 0)\n\ndef classify_cnv(log2):\n    if log2 >= 1.0:    return \"AMP\"\n    if log2 >= 0.2:    return \"GAIN\"\n    if log2 \u003C= -3.5:   return \"HOMDEL\"\n    if log2 \u003C= -1.0:   return \"LOSS\"\n    return \"NEUTRAL\"\n\ndf[\"cnv_class\"] = df[\"log2\"].apply(classify_cnv)\nprint(\"CNV class counts:\")\nprint(df[\"cnv_class\"].value_counts().to_string())\n\n# Focal amplifications in known oncogenes\noncogenes = [\"ERBB2\", \"MYC\", \"EGFR\", \"CCND1\", \"CDK6\", \"MDM2\", \"KRAS\"]\nfocal_amps = df[(df[\"cnv_class\"] == \"AMP\") &\n                (df[\"gene\"].str.split(\",\").apply(\n                    lambda genes: any(g in oncogenes for g in genes)))]\nif not focal_amps.empty:\n    print(f\"\\nFocal amplifications in oncogenes:\")\n    print(focal_amps[[\"chromosome\", \"start\", \"end\", \"gene\", \"log2\", \"cn\"]].to_string(index=False))\n```\n\n### Step 6: Visualize CNV Profile\n\nGenerate scatter plots and chromosome diagrams to review the copy number landscape.\n\n```bash\n# Genome-wide scatter plot (CNR bins + segments)\ncnvkit.py scatter tumor.cnr \\\n    -s tumor.cns \\\n    -o tumor-scatter.png\n\n# Chromosome diagram (color-coded by CN state)\ncnvkit.py diagram tumor.cnr \\\n    -s tumor.cns \\\n    -o tumor-diagram.pdf\n\n# Heatmap across multiple samples\ncnvkit.py heatmap sample1.cns sample2.cns sample3.cns \\\n    -o cohort_heatmap.pdf\n\necho \"Plots saved: tumor-scatter.png, tumor-diagram.pdf, cohort_heatmap.pdf\"\n```\n\n```python\n# Extract a single chromosome's bins + segments for a custom log2-ratio scatter\nimport cnvlib\n\ncnr = cnvlib.read(\"tumor.cnr\")\ncns = cnvlib.read(\"tumor.cns\")\n\nchrom = \"chr7\"   # EGFR locus\ncnr_chr = cnr.data[cnr.data[\"chromosome\"] == chrom][[\"start\", \"log2\"]]\ncns_chr = cns.data[cns.data[\"chromosome\"] == chrom][[\"start\", \"end\", \"log2\"]]\ncnr_chr.to_csv(f\"{chrom}_bins.csv\", index=False)\ncns_chr.to_csv(f\"{chrom}_segments.csv\", index=False)\nprint(f\"{chrom}: {len(cnr_chr)} bins, {len(cns_chr)} segments\")\n# Render a per-chromosome log2 scatter with the omics-plotting SKILL (`skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md`) scatter recipe\n# (overlay segment hlines and a gene-locus axvspan for EGFR) -> figures\u002Fchr7_cnv_scatter.png\n```\n\n### Step 7: Estimate Tumor Purity and Ploidy\n\nUse CNVkit's purity\u002Fploidy estimation to interpret absolute copy numbers.\n\n```bash\n# Estimate purity and ploidy from the segmented CNV profile\ncnvkit.py call tumor.cns \\\n    --purity auto \\\n    --ploidy 2 \\\n    --method clonal \\\n    -o tumor.call.auto.cns \\\n    --center median\n\n# Print purity\u002Fploidy estimate embedded in header\nhead -5 tumor.call.auto.cns\n```\n\n```python\n# Python API: purity\u002Fploidy estimation with cnvlib\nimport cnvlib\nfrom cnvlib import segmetrics\n\ncns = cnvlib.read(\"tumor.cns\")\ncnr = cnvlib.read(\"tumor.cnr\")\n\n# Compute segment-level statistics\ncns_with_stats = segmetrics.do_segmetrics(cnr, cns,\n    location_stats=[\"mean\", \"median\"],\n    spread_stats=[\"stdev\"])\n\n# Export stats to CSV for review\ndf = cns_with_stats.data\ndf.to_csv(\"tumor_segment_stats.csv\", index=False)\nprint(f\"Segment stats saved: tumor_segment_stats.csv\")\nprint(f\"Segments: {len(df)}\")\nprint(df[[\"chromosome\", \"start\", \"end\", \"log2\", \"cn\", \"mean\", \"stdev\"]].head(8).to_string(index=False))\n```\n\n### Step 8: Export to VCF, BED, and SEG Formats\n\nExport CNV calls for downstream tools (GISTIC2, cBioPortal, IGV, clinical reporting).\n\n```bash\n# Export to VCF (for clinical variant databases)\ncnvkit.py export vcf tumor.call.cns \\\n    -o tumor.cnv.vcf\n\n# Export to SEG format (for GISTIC2 and cBioPortal)\ncnvkit.py export seg tumor.call.cns \\\n    -o tumor.seg\n\n# Export to BED format (for bedtools\u002FIGV)\ncnvkit.py export bed tumor.call.cns \\\n    -o tumor.cnv.bed\n\necho \"Exported:\"\necho \"  tumor.cnv.vcf   — VCF format\"\necho \"  tumor.seg       — SEG format (GISTIC2 \u002F cBioPortal)\"\necho \"  tumor.cnv.bed   — BED format (IGV \u002F bedtools)\"\n```\n\n```python\n# Parse and summarize SEG file\nimport pandas as pd\n\nseg = pd.read_csv(\"tumor.seg\", sep=\"\\t\",\n                  names=[\"sample\", \"chrom\", \"start\", \"end\", \"n_probes\", \"log2\"],\n                  comment=\"#\")\nprint(f\"SEG file: {len(seg)} segments\")\nprint(seg.head())\n\n# Count amplifications and deletions by chromosome arm\namp_count = (seg[\"log2\"] >= 0.585).sum()\ndel_count  = (seg[\"log2\"] \u003C= -1.0).sum()\nprint(f\"\\nAmplifications (log2 >= 0.585): {amp_count}\")\nprint(f\"Deletions (log2 \u003C= -1.0):       {del_count}\")\nseg.to_csv(\"tumor_seg_annotated.csv\", index=False)\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `--method` (batch\u002Fcoverage) | `\"hybrid\"` | `\"hybrid\"`, `\"wgs\"`, `\"amplicon\"` | Sequencing method; selects target binning strategy |\n| `--segment-method` (segment) | `\"cbs\"` | `\"cbs\"`, `\"hmm\"`, `\"haar\"`, `\"none\"` | Segmentation algorithm; CBS requires R DNAcopy |\n| `--ploidy` (call) | `2` | `1`–`6` | Assumed baseline ploidy for absolute CN calling |\n| `--purity` (call) | `1.0` | `0.1`–`1.0` or `\"auto\"` | Tumor cell fraction; corrects log2 ratios for admixed normal |\n| `--target-avg-size` (target) | `200` (WES) | `50`–`500` bp | Desired mean target bin size after splitting |\n| `--antitarget-avg-size` | `150000` | `10000`–`500000` bp | Antitarget bin size (larger = fewer bins, less noise) |\n| `--drop-low-coverage` (segment) | off | flag | Drop bins with depth \u003C 5× before segmentation |\n| `-p` \u002F `--processes` (coverage) | `1` | `1`–CPU count | Parallel processes for coverage calculation |\n| `--scatter` (batch) | off | flag | Automatically generate scatter plot |\n| `--diagram` (batch) | off | flag | Automatically generate chromosome diagram |\n\n## Common Recipes\n\n### Recipe: Tumor-Only Analysis with Flat Reference\n\nWhen to use: No matched normal is available; use a flat GC\u002Fmappability-corrected reference.\n\n```bash\n# Step 1: Create flat reference\ncnvkit.py reference \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output flat_reference.cnn\n\n# Step 2: Run batch on tumor-only\ncnvkit.py batch tumor.bam \\\n    --reference flat_reference.cnn \\\n    --output-dir tumor_only_results\u002F\n\necho \"Tumor-only results: tumor_only_results\u002F\"\n```\n\n### Recipe: WGS Mode for Whole-Genome Data\n\nWhen to use: Input is whole-genome sequencing (no capture BED needed).\n\n```bash\n# WGS mode uses a uniform genome-wide bin grid\ncnvkit.py batch tumor_wgs.bam \\\n    --normal normal_wgs.bam \\\n    --method wgs \\\n    --fasta GRCh38.fa \\\n    --output-dir wgs_results\u002F \\\n    --scatter\n\necho \"WGS CNV analysis complete: wgs_results\u002F\"\n```\n\n### Recipe: Snakemake Integration for Multi-Sample Cohort\n\nWhen to use: Automate CNVkit for a cohort of paired tumor\u002Fnormal samples.\n\n```python\n# Snakefile — CNVkit batch pipeline\nconfigfile: \"config.yaml\"\nSAMPLES = config[\"tumor_samples\"]   # list of sample names\nGENOME  = config[\"genome_fasta\"]\nTARGETS = config[\"targets_bed\"]\nPOOLED  = config[\"pooled_reference\"]  # pre-built pooled normal reference\n\nrule all:\n    input:\n        expand(\"cnvkit\u002F{sample}.call.cns\", sample=SAMPLES),\n        expand(\"cnvkit\u002F{sample}-scatter.png\", sample=SAMPLES),\n\nrule cnvkit_batch:\n    input:\n        tumor  = \"bam\u002F{sample}.tumor.bam\",\n        ref    = POOLED,\n    output:\n        cnr    = \"cnvkit\u002F{sample}.cnr\",\n        cns    = \"cnvkit\u002F{sample}.cns\",\n        call   = \"cnvkit\u002F{sample}.call.cns\",\n        scatter = \"cnvkit\u002F{sample}-scatter.png\",\n    threads: 4\n    shell:\n        \"\"\"\n        cnvkit.py batch {input.tumor} \\\n            --reference {input.ref} \\\n            --targets {TARGETS} \\\n            --fasta {GENOME} \\\n            --output-dir cnvkit\u002F \\\n            --scatter --processes {threads}\n        cnvkit.py call cnvkit\u002F{wildcards.sample}.cns \\\n            --ploidy 2 -o {output.call}\n        \"\"\"\n```\n\n### Recipe: Export Gene-Level CNV Table\n\nWhen to use: Summarize copy number status for a panel of cancer genes from a called CNS file.\n\n```python\nimport cnvlib\nimport pandas as pd\n\ncns = cnvlib.read(\"tumor.call.cns\")\ndf = cns.data\n\n# Cancer genes of interest\ncancer_genes = [\"ERBB2\", \"MYC\", \"EGFR\", \"CDKN2A\", \"RB1\", \"TP53\",\n                \"KRAS\", \"PTEN\", \"BRCA1\", \"BRCA2\", \"MDM2\", \"CDK4\"]\n\nrows = []\nfor gene in cancer_genes:\n    hits = df[df[\"gene\"].str.contains(gene, na=False)]\n    if hits.empty:\n        rows.append({\"gene\": gene, \"log2_mean\": float(\"nan\"), \"cn\": \"n\u002Fa\", \"status\": \"not_detected\"})\n    else:\n        best = hits.loc[hits[\"log2\"].abs().idxmax()]\n        status = (\"AMP\" if best[\"log2\"] >= 1.0 else\n                  \"GAIN\" if best[\"log2\"] >= 0.2 else\n                  \"HOMDEL\" if best[\"log2\"] \u003C= -3.5 else\n                  \"LOSS\" if best[\"log2\"] \u003C= -1.0 else \"NEUTRAL\")\n        rows.append({\"gene\": gene, \"log2_mean\": round(best[\"log2\"], 3),\n                     \"cn\": best.get(\"cn\", \"?\"), \"status\": status})\n\nresult_df = pd.DataFrame(rows)\nprint(result_df.to_string(index=False))\nresult_df.to_csv(\"cancer_gene_cnv_summary.csv\", index=False)\nprint(\"\\nSaved: cancer_gene_cnv_summary.csv\")\n```\n\n## Expected Outputs\n\n| Output File | Format | Description |\n|-------------|--------|-------------|\n| `tumor.targetcoverage.cnn` | CNN | Per-bin target region read depth and log2 coverage |\n| `tumor.antitargetcoverage.cnn` | CNN | Per-bin antitarget region coverage (off-target reads) |\n| `tumor.cnr` | CNR | Normalized log2 copy ratio per bin (GC\u002Fdepth corrected) |\n| `tumor.cns` | CNS | Segmented copy ratios (CBS\u002FHMM output); one row per segment |\n| `tumor.call.cns` | CNS | Called copy number states with integer CN and purity adjustment |\n| `tumor-scatter.png` | PNG | Genome-wide scatter plot of bins + segment overlays |\n| `tumor-diagram.pdf` | PDF | Chromosome arm diagram color-coded by CN state |\n| `tumor.seg` | SEG | GISTIC2\u002FcBioPortal-format segment file |\n| `tumor.cnv.vcf` | VCF | VCF-format CNV calls for clinical databases |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| High noise in antitarget bins | Low off-target coverage (\u003C0.1× mean) | Increase `--antitarget-avg-size` to 500kb; use `--drop-low-coverage` to exclude low bins before segmentation |\n| CBS segmentation fails with `Error in DNAcopy` | R DNAcopy not installed or incompatible | Install via `BiocManager::install(\"DNAcopy\")`; alternatively use `--method hmm` (no R required) |\n| All segments near 0 (no CNVs detected) | Low tumor purity (\u003C20%) or shallow coverage | Verify purity with `cnvkit.py call --purity auto`; check target coverage depth with `cnvkit.py coverage` |\n| Wavy GC bias across chromosomes | GC normalization failed or flat reference used with biased tumor | Rebuild reference with matched normal BAMs; check `cnvkit.py reference` includes `--fasta` for GC correction |\n| Many very short segments (over-segmentation) | CBS threshold too sensitive | Add `--threshold 0.2` or `--smooth-cbs` to reduce false segment boundaries; increase minimum segment size |\n| `ImportError: No module named cnvlib` | CNVkit not installed in active environment | Activate the correct conda env: `conda activate cnvkit_env`; verify `cnvkit.py version` |\n| Chromosome naming mismatch | BAM uses `1` but reference uses `chr1` or vice versa | Ensure BAM, BED, and FASTA all use the same chromosome naming convention |\n\n## References\n\n- [CNVkit documentation](https:\u002F\u002Fcnvkit.readthedocs.io) — full CLI and API reference, algorithm details, and tutorials\n- [Talevich E et al. (2016) PLoS Comput Biol 12(4): e1004873](https:\u002F\u002Fdoi.org\u002F10.1371\u002Fjournal.pcbi.1004873) — CNVkit original paper with algorithm description and benchmarks\n- [CNVkit GitHub: etal\u002Fcnvkit](https:\u002F\u002Fgithub.com\u002Fetal\u002Fcnvkit) — source code, issue tracker, and example datasets\n- [UCSC Genome Browser data files](https:\u002F\u002Fhgdownload.soe.ucsc.edu\u002FgoldenPath\u002Fhg38\u002Fdatabase\u002F) — refFlat and access BED files used in CNVkit preprocessing\n","# CNVkit Copy Number Analysis\n\n## Overview\n\nCNVkit detects somatic copy number variants (CNVs) from whole-exome sequencing (WES), whole-genome sequencing (WGS), or targeted panel BAM files. It calculates read depth in both on-target (capture) bins and off-target (antitarget) bins, corrects for GC bias and library depth, segments the log2 copy ratio profile with circular binary segmentation (CBS) or a hidden Markov model (HMM), and calls amplifications and deletions. CNVkit provides both a CLI (`cnvkit.py`) and a Python API (`cnvlib`) for integration into analysis pipelines, and produces scatter plots, chromosome diagrams, heatmaps, and export files in VCF, BED, and SEG formats.\n\n## When to Use\n\n- Calling somatic copy number variants from tumor-normal paired exome (WES) or targeted panel sequencing\n- Detecting copy number alterations in tumor-only samples using a pooled normal reference\n- Running CNV analysis on whole-genome sequencing (WGS) data with the `--method wgs` mode\n- Estimating tumor purity and ploidy for samples where purity is unknown, to interpret copy ratio calls\n- Generating SEG format copy number files for GISTIC2, cBioPortal, or IGV visualization\n- Identifying focal amplifications (e.g., ERBB2, MYC) or homozygous deletions (e.g., CDKN2A, RB1)\n- Use **omics-plotting** SKILL for generic coverage\u002Flog2-ratio figures from exported tables; genome-wide CNV views use `cnvkit.py scatter\u002Fdiagram`\n- Use **GATK CNV** (`gatk DenoiseReadCounts` \u002F `gatk ModelSegments`) instead for deep WGS cohorts with large matched panel-of-normals (PoN); CNVkit is better suited for targeted\u002Fexome data\n- Use **Control-FREEC** instead when you need allele-frequency-based B-allele fraction modeling alongside CNV calling\n\n## Prerequisites\n\n- **Software**: CNVkit v0.9.x, Python 3.8+, R (for CBS segmentation), samtools\n- **Python packages**: `cnvlib` (installed as part of CNVkit), `matplotlib`, `pandas`\n- **Input files**: sorted, indexed BAM files (tumor ± matched normal); BED file of capture targets; reference genome FASTA; access to R with DNAcopy package for CBS\n- **Data requirements**: minimum ~50× mean target coverage for WES; WGS works at 20-30×\n\n> **Check before installing**: The tool may already be available in the current environment (e.g., inside a `pixi` \u002F `conda` env). Run `command -v cnvkit.py` first and skip the install commands below if it returns a path. When running inside a pixi project, invoke the tool via `pixi run cnvkit.py` rather than bare `cnvkit.py`.\n\n```bash\n# Install CNVkit via conda (recommended — handles R\u002FDNAcopy dependency)\nconda install -c bioconda cnvkit\n\n# Or via pip (requires R + DNAcopy already installed)\npip install cnvkit\n\n# Verify\ncnvkit.py version\n# cnvkit 0.9.10\n\n# Install R DNAcopy (for CBS segmentation)\nRscript -e 'if (!requireNamespace(\"BiocManager\")) install.packages(\"BiocManager\"); BiocManager::install(\"DNAcopy\")'\n\n# Index BAM files if not already indexed\nsamtools index tumor.bam\nsamtools index normal.bam\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: sequencingMethod\n    kind: required\n    source: data\n    ask: \"Was this whole-genome, hybrid-capture exome, or amplicon sequencing?\"\n    default: null\n\n  - id: D2\n    param: referenceNormals\n    kind: required\n    source: user\n    ask: \"Which normal samples should define the expected coverage baseline?\"\n    default: null\n\n  - id: D3\n    param: targetRegions\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"Which BED file describes the captured regions?\"\n    default: null\n    skip_if: \"whole-genome sequencing - there are no capture targets\"\n\n  - id: D4\n    param: tumorPurity\n    kind: required\n    source: user\n    ask: \"What fraction of the sample is tumour rather than contaminating normal tissue?\"\n    default: \"1.0 - assumes a pure sample, which understates every copy-number change\"\n\n  - id: D5\n    param: ploidy\n    kind: required\n    source: user\n    ask: \"What baseline ploidy should absolute copy number be called against?\"\n    default: 2\n\n  - id: D6\n    param: segmentMethod\n    kind: optional\n    source: user\n    ask: \"Which algorithm should join bins into segments?\"\n    default: \"circular binary segmentation\"\n\n  - id: D7\n    param: binSizes\n    kind: optional_conditional\n    source: user\n    depends_on: [D1]\n    ask: \"Do the default target and antitarget bin sizes suit this capture design?\"\n    default: \"200 bp targets, 150 kb antitargets\"\n\n  - id: D8\n    param: processes\n    kind: never_ask\n    source: data\n    reason: \"Affects runtime only, not the copy-number calls\"\n    default: \"min(8, available_cores)\"\n```\n\nD2 and D4 are the two that decide whether the calls mean anything. A flat\nreference instead of matched normals leaves capture bias in the log2 ratios,\nand a purity of 1.0 on a 40%-tumour sample compresses every real gain and loss\ntoward neutral. Both produce a complete, plausible-looking segment table.\n\n## Quick Start\n\n```bash\n# One-command paired tumor\u002Fnormal CNV analysis (WES)\ncnvkit.py batch tumor.bam \\\n    --normal normal.bam \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output-dir cnvkit_results\u002F \\\n    --diagram --scatter \\\n    --method hybrid\n\n# Output files in cnvkit_results\u002F:\n#   tumor.targetcoverage.cnn   — target bin coverage\n#   tumor.antitargetcoverage.cnn — antitarget coverage\n#   tumor.cnr                  — copy number ratios\n#   tumor.cns                  — segmented copy numbers\n#   tumor-scatter.png          — genome-wide scatter plot\n#   tumor-diagram.pdf          — chromosome diagram\necho \"CNV analysis complete\"\n```\n\n## Workflow\n\n### Step 1: Create Copy Number Reference\n\nBuild a reference from one or more normal BAM files. This corrects for systematic biases (GC content, mappability) and sets the neutral baseline.\n\n```bash\n# Option A: Paired normal reference (single matched normal)\ncnvkit.py reference normal.targetcoverage.cnn normal.antitargetcoverage.cnn \\\n    --fasta GRCh38.fa \\\n    -o reference_normal.cnn\n\n# Option B: Flat reference (no normal; uses GC\u002Fmappability correction only)\n# Use when no matched normal is available\ncnvkit.py reference \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output flat_reference.cnn\n\n# Option C: Pooled normal reference from multiple normals (most robust)\ncnvkit.py batch \\\n    normal1.bam normal2.bam normal3.bam \\\n    --normal \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output-reference pooled_reference.cnn \\\n    --output-dir normals_cov\u002F\n\necho \"Reference created: pooled_reference.cnn\"\n```\n\n### Step 2: Calculate Coverage in Target and Antitarget Bins\n\nBin the target BED file and compute per-bin read depth for tumor and normal samples.\n\n```bash\n# First, create accessible bins from the target BED\ncnvkit.py target targets.bed \\\n    --annotate refFlat.txt \\\n    --split \\\n    -o targets.split.bed\n\ncnvkit.py antitarget targets.bed \\\n    --access data\u002Faccess-5k-mappable.hg38.bed \\\n    -o antitargets.bed\n\n# Calculate coverage for tumor sample\ncnvkit.py coverage tumor.bam targets.split.bed \\\n    -o tumor.targetcoverage.cnn\n\ncnvkit.py coverage tumor.bam antitargets.bed \\\n    -o tumor.antitargetcoverage.cnn\n\necho \"Coverage files:\"\necho \"  tumor.targetcoverage.cnn\"\necho \"  tumor.antitargetcoverage.cnn\"\n```\n\n```python\n# Python API equivalent: compute coverage with cnvlib\nimport cnvlib\n\n# Load and inspect coverage files\ntarget_cov = cnvlib.read(\"tumor.targetcoverage.cnn\")\nantitarget_cov = cnvlib.read(\"tumor.antitargetcoverage.cnn\")\n\nprint(f\"Target bins: {len(target_cov)}\")\nprint(f\"Antitarget bins: {len(antitarget_cov)}\")\nprint(f\"Mean target depth: {target_cov['depth'].mean():.1f}×\")\nprint(f\"Median target depth: {target_cov['depth'].median():.1f}×\")\n\n# Export target-bin depths; render the coverage histogram with the omics-plotting SKILL (`skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md`)\n# \"Box \u002F Violin \u002F Bar\" recipe (or a histogram) -> figures\u002Fcoverage_distribution.png\ntarget_cov[\"depth\"].clip(upper=500).to_csv(\"target_depths.csv\", index=False)\nprint(\"Saved: target_depths.csv\")\n```\n\n### Step 3: Normalize and Correct Copy Ratios\n\nNormalize tumor coverage against the reference (correcting for GC bias, library depth, and target efficiency).\n\n```bash\n# Fix sample-level biases relative to the reference\ncnvkit.py fix \\\n    tumor.targetcoverage.cnn \\\n    tumor.antitargetcoverage.cnn \\\n    pooled_reference.cnn \\\n    -o tumor.cnr\n\necho \"Copy number ratios: tumor.cnr\"\n# tumor.cnr columns: chromosome, start, end, gene, log2, depth, weight\n```\n\n```python\n# Inspect copy ratio file with cnvlib Python API\nimport cnvlib\nimport pandas as pd\n\ncnr = cnvlib.read(\"tumor.cnr\")\nprint(f\"Total bins: {len(cnr)}\")\nprint(f\"Chromosomes: {sorted(cnr.chromosome.unique())}\")\n\n# Convert to DataFrame and inspect\ndf = cnr.data\nprint(f\"\\nLog2 copy ratio summary:\")\nprint(df[\"log2\"].describe().round(3))\n\n# Flag high-amplitude events\nhigh_amp = df[df[\"log2\"] >= 2.0]\nhom_del  = df[df[\"log2\"] \u003C= -3.0]\nprint(f\"\\nHigh amplitude bins (log2 >= 2.0): {len(high_amp)}\")\nprint(f\"Homozygous deletion bins (log2 \u003C= -3.0): {len(hom_del)}\")\nif not high_amp.empty:\n    print(high_amp[[\"chromosome\", \"start\", \"end\", \"gene\", \"log2\"]].head())\n```\n\n### Step 4: Segment Copy Number Ratios\n\nIdentify contiguous regions of similar copy ratio using CBS (Circular Binary Segmentation) or HMM segmentation.\n\n```bash\n# CBS segmentation (default; requires R DNAcopy)\ncnvkit.py segment tumor.cnr \\\n    -o tumor.cns \\\n    --method cbs\n\n# HMM segmentation (no R required; faster)\ncnvkit.py segment tumor.cnr \\\n    -o tumor.hmm.cns \\\n    --method hmm\n\necho \"Segments: tumor.cns\"\n# tumor.cns columns: chromosome, start, end, gene, log2, cn, depth, p_ttest, weight, probes\n```\n\n```python\n# Python API: segment and inspect\nimport cnvlib\nimport subprocess\n\n# Run segmentation via Python subprocess (mirrors CLI)\nsubprocess.run(\n    [\"cnvkit.py\", \"segment\", \"tumor.cnr\", \"-o\", \"tumor.cns\", \"--method\", \"cbs\"],\n    check=True\n)\n\n# Load and analyze segments\ncns = cnvlib.read(\"tumor.cns\")\ndf_seg = cns.data\nprint(f\"Total segments: {len(df_seg)}\")\nprint(f\"\\nSegment log2 summary:\")\nprint(df_seg[\"log2\"].describe().round(3))\n\n# Large segments (>5 Mb) with copy gain or loss\nlarge_events = df_seg[\n    ((df_seg[\"end\"] - df_seg[\"start\"]) > 5_000_000) &\n    (df_seg[\"log2\"].abs() > 0.3)\n].copy()\nlarge_events[\"size_mb\"] = (large_events[\"end\"] - large_events[\"start\"]) \u002F 1e6\nprint(f\"\\nLarge CNV segments (>5 Mb, |log2|>0.3): {len(large_events)}\")\nprint(large_events[[\"chromosome\", \"start\", \"end\", \"log2\", \"size_mb\"]].head(8).to_string(index=False))\n```\n\n### Step 5: Call CNV States\n\nAssign integer copy number states and classify amplifications and deletions.\n\n```bash\n# Call with default thresholds (diploid normal)\ncnvkit.py call tumor.cns \\\n    -o tumor.call.cns \\\n    --ploidy 2\n\n# Call with tumor purity estimate (if known)\ncnvkit.py call tumor.cns \\\n    --purity 0.7 \\\n    --ploidy 2 \\\n    -o tumor.call.purity.cns\n\necho \"Called CNVs: tumor.call.cns\"\n```\n\n```python\n# Parse called CNV file and classify events\nimport cnvlib\nimport pandas as pd\n\ncns_called = cnvlib.read(\"tumor.call.cns\")\ndf = cns_called.data\n\n# Classify by log2 thresholds (diploid assumed)\n# log2 >= 1.0 = high-level amplification (CN >= 4)\n# log2 0.2–1.0 = copy gain (CN = 3)\n# log2 -1.0–-0.2 = heterozygous deletion (CN = 1)\n# log2 \u003C= -3.5 = homozygous deletion (CN = 0)\n\ndef classify_cnv(log2):\n    if log2 >= 1.0:    return \"AMP\"\n    if log2 >= 0.2:    return \"GAIN\"\n    if log2 \u003C= -3.5:   return \"HOMDEL\"\n    if log2 \u003C= -1.0:   return \"LOSS\"\n    return \"NEUTRAL\"\n\ndf[\"cnv_class\"] = df[\"log2\"].apply(classify_cnv)\nprint(\"CNV class counts:\")\nprint(df[\"cnv_class\"].value_counts().to_string())\n\n# Focal amplifications in known oncogenes\noncogenes = [\"ERBB2\", \"MYC\", \"EGFR\", \"CCND1\", \"CDK6\", \"MDM2\", \"KRAS\"]\nfocal_amps = df[(df[\"cnv_class\"] == \"AMP\") &\n                (df[\"gene\"].str.split(\",\").apply(\n                    lambda genes: any(g in oncogenes for g in genes)))]\nif not focal_amps.empty:\n    print(f\"\\nFocal amplifications in oncogenes:\")\n    print(focal_amps[[\"chromosome\", \"start\", \"end\", \"gene\", \"log2\", \"cn\"]].to_string(index=False))\n```\n\n### Step 6: Visualize CNV Profile\n\nGenerate scatter plots and chromosome diagrams to review the copy number landscape.\n\n```bash\n# Genome-wide scatter plot (CNR bins + segments)\ncnvkit.py scatter tumor.cnr \\\n    -s tumor.cns \\\n    -o tumor-scatter.png\n\n# Chromosome diagram (color-coded by CN state)\ncnvkit.py diagram tumor.cnr \\\n    -s tumor.cns \\\n    -o tumor-diagram.pdf\n\n# Heatmap across multiple samples\ncnvkit.py heatmap sample1.cns sample2.cns sample3.cns \\\n    -o cohort_heatmap.pdf\n\necho \"Plots saved: tumor-scatter.png, tumor-diagram.pdf, cohort_heatmap.pdf\"\n```\n\n```python\n# Extract a single chromosome's bins + segments for a custom log2-ratio scatter\nimport cnvlib\n\ncnr = cnvlib.read(\"tumor.cnr\")\ncns = cnvlib.read(\"tumor.cns\")\n\nchrom = \"chr7\"   # EGFR locus\ncnr_chr = cnr.data[cnr.data[\"chromosome\"] == chrom][[\"start\", \"log2\"]]\ncns_chr = cns.data[cns.data[\"chromosome\"] == chrom][[\"start\", \"end\", \"log2\"]]\ncnr_chr.to_csv(f\"{chrom}_bins.csv\", index=False)\ncns_chr.to_csv(f\"{chrom}_segments.csv\", index=False)\nprint(f\"{chrom}: {len(cnr_chr)} bins, {len(cns_chr)} segments\")\n# Render a per-chromosome log2 scatter with the omics-plotting SKILL (`skills\u002Fdata-visualization\u002Fomics-plotting\u002FSKILL.md`) scatter recipe\n# (overlay segment hlines and a gene-locus axvspan for EGFR) -> figures\u002Fchr7_cnv_scatter.png\n```\n\n### Step 7: Estimate Tumor Purity and Ploidy\n\nUse CNVkit's purity\u002Fploidy estimation to interpret absolute copy numbers.\n\n```bash\n# Estimate purity and ploidy from the segmented CNV profile\ncnvkit.py call tumor.cns \\\n    --purity auto \\\n    --ploidy 2 \\\n    --method clonal \\\n    -o tumor.call.auto.cns \\\n    --center median\n\n# Print purity\u002Fploidy estimate embedded in header\nhead -5 tumor.call.auto.cns\n```\n\n```python\n# Python API: purity\u002Fploidy estimation with cnvlib\nimport cnvlib\nfrom cnvlib import segmetrics\n\ncns = cnvlib.read(\"tumor.cns\")\ncnr = cnvlib.read(\"tumor.cnr\")\n\n# Compute segment-level statistics\ncns_with_stats = segmetrics.do_segmetrics(cnr, cns,\n    location_stats=[\"mean\", \"median\"],\n    spread_stats=[\"stdev\"])\n\n# Export stats to CSV for review\ndf = cns_with_stats.data\ndf.to_csv(\"tumor_segment_stats.csv\", index=False)\nprint(f\"Segment stats saved: tumor_segment_stats.csv\")\nprint(f\"Segments: {len(df)}\")\nprint(df[[\"chromosome\", \"start\", \"end\", \"log2\", \"cn\", \"mean\", \"stdev\"]].head(8).to_string(index=False))\n```\n\n### Step 8: Export to VCF, BED, and SEG Formats\n\nExport CNV calls for downstream tools (GISTIC2, cBioPortal, IGV, clinical reporting).\n\n```bash\n# Export to VCF (for clinical variant databases)\ncnvkit.py export vcf tumor.call.cns \\\n    -o tumor.cnv.vcf\n\n# Export to SEG format (for GISTIC2 and cBioPortal)\ncnvkit.py export seg tumor.call.cns \\\n    -o tumor.seg\n\n# Export to BED format (for bedtools\u002FIGV)\ncnvkit.py export bed tumor.call.cns \\\n    -o tumor.cnv.bed\n\necho \"Exported:\"\necho \"  tumor.cnv.vcf   — VCF format\"\necho \"  tumor.seg       — SEG format (GISTIC2 \u002F cBioPortal)\"\necho \"  tumor.cnv.bed   — BED format (IGV \u002F bedtools)\"\n```\n\n```python\n# Parse and summarize SEG file\nimport pandas as pd\n\nseg = pd.read_csv(\"tumor.seg\", sep=\"\\t\",\n                  names=[\"sample\", \"chrom\", \"start\", \"end\", \"n_probes\", \"log2\"],\n                  comment=\"#\")\nprint(f\"SEG file: {len(seg)} segments\")\nprint(seg.head())\n\n# Count amplifications and deletions by chromosome arm\namp_count = (seg[\"log2\"] >= 0.585).sum()\ndel_count  = (seg[\"log2\"] \u003C= -1.0).sum()\nprint(f\"\\nAmplifications (log2 >= 0.585): {amp_count}\")\nprint(f\"Deletions (log2 \u003C= -1.0):       {del_count}\")\nseg.to_csv(\"tumor_seg_annotated.csv\", index=False)\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `--method` (batch\u002Fcoverage) | `\"hybrid\"` | `\"hybrid\"`, `\"wgs\"`, `\"amplicon\"` | Sequencing method; selects target binning strategy |\n| `--segment-method` (segment) | `\"cbs\"` | `\"cbs\"`, `\"hmm\"`, `\"haar\"`, `\"none\"` | Segmentation algorithm; CBS requires R DNAcopy |\n| `--ploidy` (call) | `2` | `1`–`6` | Assumed baseline ploidy for absolute CN calling |\n| `--purity` (call) | `1.0` | `0.1`–`1.0` or `\"auto\"` | Tumor cell fraction; corrects log2 ratios for admixed normal |\n| `--target-avg-size` (target) | `200` (WES) | `50`–`500` bp | Desired mean target bin size after splitting |\n| `--antitarget-avg-size` | `150000` | `10000`–`500000` bp | Antitarget bin size (larger = fewer bins, less noise) |\n| `--drop-low-coverage` (segment) | off | flag | Drop bins with depth \u003C 5× before segmentation |\n| `-p` \u002F `--processes` (coverage) | `1` | `1`–CPU count | Parallel processes for coverage calculation |\n| `--scatter` (batch) | off | flag | Automatically generate scatter plot |\n| `--diagram` (batch) | off | flag | Automatically generate chromosome diagram |\n\n## Common Recipes\n\n### Recipe: Tumor-Only Analysis with Flat Reference\n\nWhen to use: No matched normal is available; use a flat GC\u002Fmappability-corrected reference.\n\n```bash\n# Step 1: Create flat reference\ncnvkit.py reference \\\n    --targets targets.bed \\\n    --fasta GRCh38.fa \\\n    --output flat_reference.cnn\n\n# Step 2: Run batch on tumor-only\ncnvkit.py batch tumor.bam \\\n    --reference flat_reference.cnn \\\n    --output-dir tumor_only_results\u002F\n\necho \"Tumor-only results: tumor_only_results\u002F\"\n```\n\n### Recipe: WGS Mode for Whole-Genome Data\n\nWhen to use: Input is whole-genome sequencing (no capture BED needed).\n\n```bash\n# WGS mode uses a uniform genome-wide bin grid\ncnvkit.py batch tumor_wgs.bam \\\n    --normal normal_wgs.bam \\\n    --method wgs \\\n    --fasta GRCh38.fa \\\n    --output-dir wgs_results\u002F \\\n    --scatter\n\necho \"WGS CNV analysis complete: wgs_results\u002F\"\n```\n\n### Recipe: Snakemake Integration for Multi-Sample Cohort\n\nWhen to use: Automate CNVkit for a cohort of paired tumor\u002Fnormal samples.\n\n```python\n# Snakefile — CNVkit batch pipeline\nconfigfile: \"config.yaml\"\nSAMPLES = config[\"tumor_samples\"]   # list of sample names\nGENOME  = config[\"genome_fasta\"]\nTARGETS = config[\"targets_bed\"]\nPOOLED  = config[\"pooled_reference\"]  # pre-built pooled normal reference\n\nrule all:\n    input:\n        expand(\"cnvkit\u002F{sample}.call.cns\", sample=SAMPLES),\n        expand(\"cnvkit\u002F{sample}-scatter.png\", sample=SAMPLES),\n\nrule cnvkit_batch:\n    input:\n        tumor  = \"bam\u002F{sample}.tumor.bam\",\n        ref    = POOLED,\n    output:\n        cnr    = \"cnvkit\u002F{sample}.cnr\",\n        cns    = \"cnvkit\u002F{sample}.cns\",\n        call   = \"cnvkit\u002F{sample}.call.cns\",\n        scatter = \"cnvkit\u002F{sample}-scatter.png\",\n    threads: 4\n    shell:\n        \"\"\"\n        cnvkit.py batch {input.tumor} \\\n            --reference {input.ref} \\\n            --targets {TARGETS} \\\n            --fasta {GENOME} \\\n            --output-dir cnvkit\u002F \\\n            --scatter --processes {threads}\n        cnvkit.py call cnvkit\u002F{wildcards.sample}.cns \\\n            --ploidy 2 -o {output.call}\n        \"\"\"\n```\n\n### Recipe: Export Gene-Level CNV Table\n\nWhen to use: Summarize copy number status for a panel of cancer genes from a called CNS file.\n\n```python\nimport cnvlib\nimport pandas as pd\n\ncns = cnvlib.read(\"tumor.call.cns\")\ndf = cns.data\n\n# Cancer genes of interest\ncancer_genes = [\"ERBB2\", \"MYC\", \"EGFR\", \"CDKN2A\", \"RB1\", \"TP53\",\n                \"KRAS\", \"PTEN\", \"BRCA1\", \"BRCA2\", \"MDM2\", \"CDK4\"]\n\nrows = []\nfor gene in cancer_genes:\n    hits = df[df[\"gene\"].str.contains(gene, na=False)]\n    if hits.empty:\n        rows.append({\"gene\": gene, \"log2_mean\": float(\"nan\"), \"cn\": \"n\u002Fa\", \"status\": \"not_detected\"})\n    else:\n        best = hits.loc[hits[\"log2\"].abs().idxmax()]\n        status = (\"AMP\" if best[\"log2\"] >= 1.0 else\n                  \"GAIN\" if best[\"log2\"] >= 0.2 else\n                  \"HOMDEL\" if best[\"log2\"] \u003C= -3.5 else\n                  \"LOSS\" if best[\"log2\"] \u003C= -1.0 else \"NEUTRAL\")\n        rows.append({\"gene\": gene, \"log2_mean\": round(best[\"log2\"], 3),\n                     \"cn\": best.get(\"cn\", \"?\"), \"status\": status})\n\nresult_df = pd.DataFrame(rows)\nprint(result_df.to_string(index=False))\nresult_df.to_csv(\"cancer_gene_cnv_summary.csv\", index=False)\nprint(\"\\nSaved: cancer_gene_cnv_summary.csv\")\n```\n\n## Expected Outputs\n\n| Output File | Format | Description |\n|-------------|--------|-------------|\n| `tumor.targetcoverage.cnn` | CNN | Per-bin target region read depth and log2 coverage |\n| `tumor.antitargetcoverage.cnn` | CNN | Per-bin antitarget region coverage (off-target reads) |\n| `tumor.cnr` | CNR | Normalized log2 copy ratio per bin (GC\u002Fdepth corrected) |\n| `tumor.cns` | CNS | Segmented copy ratios (CBS\u002FHMM output); one row per segment |\n| `tumor.call.cns` | CNS | Called copy number states with integer CN and purity adjustment |\n| `tumor-scatter.png` | PNG | Genome-wide scatter plot of bins + segment overlays |\n| `tumor-diagram.pdf` | PDF | Chromosome arm diagram color-coded by CN state |\n| `tumor.seg` | SEG | GISTIC2\u002FcBioPortal-format segment file |\n| `tumor.cnv.vcf` | VCF | VCF-format CNV calls for clinical databases |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| High noise in antitarget bins | Low off-target coverage (\u003C0.1× mean) | Increase `--antitarget-avg-size` to 500kb; use `--drop-low-coverage` to exclude low bins before segmentation |\n| CBS segmentation fails with `Error in DNAcopy` | R DNAcopy not installed or incompatible | Install via `BiocManager::install(\"DNAcopy\")`; alternatively use `--method hmm` (no R required) |\n| All segments near 0 (no CNVs detected) | Low tumor purity (\u003C20%) or shallow coverage | Verify purity with `cnvkit.py call --purity auto`; check target coverage depth with `cnvkit.py coverage` |\n| Wavy GC bias across chromosomes | GC normalization failed or flat reference used with biased tumor | Rebuild reference with matched normal BAMs; check `cnvkit.py reference` includes `--fasta` for GC correction |\n| Many very short segments (over-segmentation) | CBS threshold too sensitive | Add `--threshold 0.2` or `--smooth-cbs` to reduce false segment boundaries; increase minimum segment size |\n| `ImportError: No module named cnvlib` | CNVkit not installed in active environment | Activate the correct conda env: `conda activate cnvkit_env`; verify `cnvkit.py version` |\n| Chromosome naming mismatch | BAM uses `1` but reference uses `chr1` or vice versa | Ensure BAM, BED, and FASTA all use the same chromosome naming convention |\n\n## References\n\n- [CNVkit documentation](https:\u002F\u002Fcnvkit.readthedocs.io) — full CLI and API reference, algorithm details, and tutorials\n- [Talevich E et al. (2016) PLoS Comput Biol 12(4): e1004873](https:\u002F\u002Fdoi.org\u002F10.1371\u002Fjournal.pcbi.1004873) — CNVkit original paper with algorithm description and benchmarks\n- [CNVkit GitHub: etal\u002Fcnvkit](https:\u002F\u002Fgithub.com\u002Fetal\u002Fcnvkit) — source code, issue tracker, and example datasets\n- [UCSC Genome Browser data files](https:\u002F\u002Fhgdownload.soe.ucsc.edu\u002FgoldenPath\u002Fhg38\u002Fdatabase\u002F) — refFlat and access BED files used in CNVkit preprocessing\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fcnvkit-copy-number",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill cnvkit-copy-number",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill cnvkit-copy-number",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill cnvkit-copy-number","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fcnvkit-copy-number\u002FSKILL.md",true,[],[49,58,65,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":54,"categories":55,"keywords":56,"publishedAt":57},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":57},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":57},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":57},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":57},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":53,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":57},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]