ccnv is a Python 3.12+ toolkit (backed by a compiled Rust core) for copy-number variation (CNV) detection in whole-genome sequencing (WGS) data at any coverage, building on within-sample reference normalization (Straver et al., Nucleic Acids Research, 2014; Raman et al., Nucleic Acids Research, 2019).
Full documentation, architecture diagrams, and method details live at https://matthdsm.github.io/ccnv/.
WGS read depth fluctuates across chromosomes even in diploid samples: GC-rich and AT-rich regions amplify unevenly, repetitive regions lose uniquely mapped reads, and each library carries its own fragment-length, DNA extraction, and sequencing batch effects. Comparing a test sample only against a static control average leaves sample-specific "genomic waves" behind whenever a new library differs slightly from the training panel.
ccnv solves this with two complementary normalization steps. First, between-sample modeling removes library-level GC, mappability, fragment-size, and cohort batch trends learned from normal controls. Second, within-sample normalization groups genomic windows that co-vary across controls into prototype sets on other chromosomes. Each window in a test sample is then scored against its matched off-chromosome prototypes in that same sample, canceling sample-specific technical waves while preventing a gain or loss on one chromosome from biasing its own baseline.
flowchart LR
A["BAM / CRAM Reads"] -->|"1. ccnv extract"| B["Binned Sample (.ccnv)"]
C["Control Samples or FASTA"] -->|"2. ccnv reference"| D["Reference Model (.ccnv)"]
D -->|"3. ccnv ref-qc"| E["Usability Verdict (PASS / WARN / FAIL)"]
B -->|"4. ccnv predict"| F["CNV Calls (BED.gz, VCF.gz, QC.json, HTML Plot)"]
D -->|"4. ccnv predict"| F
ccnv extract— Alignment Streaming & Fragment Profiling: Reads aBAMorCRAMfile once (in parallel genomic tiles when indexed, or sequentially on one thread without an index) and drops unmapped, secondary, supplementary, duplicate, andMAPQ = 0reads. Proper read pairs are binned by fragment midpoint (5 kbwindows by default) so reads spanning a bin edge are never counted twice; single-end reads are binned by 5' start coordinate. For paired-end data, it also stores per-bin fragment-length bands, short-fragment counts, fragment GC, and sample-wide insert-size and 5' motif counts in a compact.ccnvParquet file. Contig names and lengths come directly from the alignment header, soccnvworks on any genome build or species and can coarsen finer.ccnvfiles automatically in memory when window sizes differ.ccnv reference— Cohort Modeling & Baseline Construction: Builds a reusable.ccnvreference from control.ccnvfiles listed in a YAML or JSON samplesheet. It scales library depths across1 Mbblocks using median ratios (so an unexpected trisomy in a control cannot skew total depth), masks gap-heavy (N-rich) and low-mappability bins from optionalFASTAand BigWig tracks, and regresses out GC, mappability, and fragment-length biases without dropping zero-count bins. It then separatesautosomal,female_sex, andmale_sexbranches from X/Y dosage (setting sex-chromosome outliers aside), captures cohort batch waves via PCA, links each bin to off-chromosome prototype sets, and splits random low-coverage Poisson noise from repeatable biological variability so the model works across sequencing depths. Without a control cohort,--fastabuilds a sequence-only flat germline reference.ccnv ref-qc— Reference Usability Audit: Audits a reference.ccnvmodel before use by checking unmasked bin counts, prototype distance distributions across branches, and malechrYcoverage. It writes structured diagnostics to<prefix>_qc.jsonand logs aPASS,WARN, orFAILverdict (--fastareferences reportWARNbecause empirical cohort noise estimates are missing).ccnv predict— Projection, Segmentation & Event Calling: Normalizes a test sample (.ccnv,BAM, orCRAM) using outlier-resistant regression onto the reference PCA waves so large CNVs or trisomies cannot pull the baseline, then computeslog2ratios and per-bin precision weights against off-chromosome prototypes while iteratively masking extreme regions. Chromosomes are split across large unmappable gaps such as centromeres (> 2 Mbby default) so calls never bridge chromosome arms, segmented via linear-time PELT change-point detection, and scored with both autocorrelation-adjusted Z-scores and integer copy-number likelihoods (CN = 0, 1, 2, 3, 4+), resolving homozygous deletions (CN = 0) down to0.1xcoverage as well as high-depth30x+WGS. Outputs include bgzipped/indexedBEDandVCFfiles,<prefix>_qc.json, and a self-contained offline HTML genome plot (<prefix>_plot.html) with a collapsible aberrations table and TSV export.
Warning
Human GRCh38 *_alt Contigs & Reference Consistency: Prefer GRCh38_no_alt_analysis_set (or a consistent ALT-aware mapper across all control and test samples) for human WGS and cfDNA CNV calling. Never mix no_alt and *_alt-containing alignments between ccnv reference and ccnv predict (or pair an ALT-aligned sample with a --fasta flat reference), as MAPQ = 0 dropouts across polymorphic *_alt loci (chr6 MHC, chr19 KIR, chr17q21.31) cause false-positive deletion calls. Do not pass --all-contigs on full GRCh38: it bins *_alt and decoy scaffolds as independent chromosomes rather than projecting them onto canonical coordinates.
- Germline Mode (
--mode germline, default): Profiles constitutional, clinical, or research WGS where copy-number changes affect the entire sample. Automatically selects the female (XX) or male (XY) sex-chromosome branch (unless overridden with--sex) so autosomes and sex chromosomes are called against their expected ploidy. - Prenatal cfDNA Mode (
--mode prenatal): Built for non-invasive prenatal testing (NIPT) from maternal plasma cell-free DNA, where placental/fetal DNA typically makes up ~4–20% of fragments and scales down fetallog2shifts accordingly.ccnvcombines four independent fetal fraction signals (malechrYcoverage, genome-wide autosomal depth patterns,chrXdosage, and shorter fetal vs. longer maternal fragment lengths) into one outlier-resistant estimate, up-weights fetal-enriched fragment sizes, and normalizeschrXagainst the diploidXXbranch plus male-fetus (fetal_sex == "M")5 kbchrYbins against a calibrated 1-copy MSY baseline onprenatal_ffy(omittingchrYwhenfetal_sex == "F"). It also screens singleton sex-chromosome aneuploidies (XX,XY,XO,XXX,XXY,XYY) alongside twin sex pairs (FF,FM,MM, via--twinsor automatic detection, reportingscaandtwinmetrics in<prefix>_qc.json), flags segments whose shift disagrees with the sample's fetal fraction, and couples read depth with fragment lengths to distinguish fetal constitutional CNVs, confined placental mosaicism, inherited CNVs, and maternal CNVs.
Pre-compiled manylinux_2_28 (x86_64, aarch64) and macOS (arm64) wheels are published to PyPI:
pip install ccnv
# or isolated CLI installation via uv:
uv tool install ccnv
ccnv --helpconda install -c conda-forge -c bioconda ccnv
# or using mamba / pixi global:
mamba install -c conda-forge -c bioconda ccnv
pixi global install -c conda-forge -c bioconda ccnv
ccnv --helppython -m pip install .
ccnv --helppixi install
pixi run ccnv --helpMulti-platform container images (linux/amd64 and linux/arm64) are published to GHCR:
docker pull ghcr.io/matthdsm/ccnv:latest
docker run --rm ghcr.io/matthdsm/ccnv:latest ccnv --helpIUC-compatible Galaxy wrappers (ccnv_extract, ccnv_reference, ccnv_ref_qc, ccnv_predict) and ToolShed suite metadata live under galaxy/. See the CLI Reference for dataset staging and workflow output details.
# 1. Extract BAM or CRAM alignments into binned sample Parquet (.ccnv)
ccnv extract sample.bam --prefix sample --bin-size 5000
# 2a. Build a germline reference model from a cohort samplesheet
ccnv reference -s cohort.yaml --prefix reference --bin-size 5000 --gc genome.fa --mappability mappability.bw
# 2b. Or build a flat uniform-depth germline reference from a FASTA
ccnv reference --fasta genome.fa --prefix reference --bin-size 5000 --mappability mappability.bw
# 2c. Or build a unified prenatal reference from a maternal cfDNA cohort samplesheet
ccnv reference -s cohort.yaml --mode prenatal --prefix prenatal_ref --bin-size 5000
# 3. Audit reference quality control metrics
ccnv ref-qc reference.ccnv
# 4a. Predict copy-number gains and losses from .ccnv, .bam, or .cram (with --fasta)
ccnv predict sample.ccnv reference.ccnv --prefix results/sample
# 4b. Or run prenatal prediction with fetal fraction estimation and sex chromosome analysis
ccnv predict sample.ccnv prenatal_ref.ccnv --mode prenatal --prefix results/sample_prenatalOutputs include bgzipped/indexed BED tables, VCFv4.2 files, self-contained offline Plotly HTML reports (_plot.html, including an interactive aberrations table and TSV export), and structured JSON metrics (<prefix>_qc.json).
Visit the documentation site for detailed guides:
- Pipeline Architecture: 4-stage execution model and storage contracts.
- CLI Reference: Flag specification, inputs, outputs, and exit codes.
- Visualization Overview: Self-contained offline HTML genome viewer tracks, clinical gene annotations and bundled catalog provenance, aberrations table, TSV export, controls, and color legends.
- API Reference: Module-by-module function reference and call-graph DAGs.
- Mathematical Methodology: Statistical models, assumptions, and citations.
pixi run format # Format code with Ruff
pixi run lint # Lint code with Ruff
pixi run test # Run unit & contract test suite
pixi run hooks # Run pre-commit hooks with Prek
pixi run docs-build # Build documentation site with Zensical
pixi run docs-serve # Serve documentation site locallyAll changes must be submitted via pull request and recorded in CHANGELOG.md.
Licensed under the GNU Affero General Public License v3 or later (AGPL-3.0-or-later). See LICENSE.md.