ccnv is an independent Python 3.12+ bioinformatics toolkit for copy-number variation (CNV) detection in whole-genome sequencing (WGS) data at any coverage, building on published within-sample reference normalization methodology (Straver et al., Nucleic Acids Research, 2014; Raman et al., Nucleic Acids Research, 2019).
Complete documentation, architecture diagrams, and methodology are available at https://matthdsm.github.io/ccnv/.
Whole-genome sequencing read depth fluctuates across chromosomes for reasons unrelated to true copy-number changes: GC-rich and AT-rich regions amplify unevenly, repetitive sequences lose uniquely mapped reads, and individual libraries differ in fragment length, DNA extraction, and flowcell batch effects. Comparing a test sample only against a static external cohort average leaves sample-specific "genomic waves" behind whenever a new library behaves slightly differently from the controls.
ccnv addresses this with two complementary layers of normalization. First, between-sample modeling removes systematic GC, mappability, fragment-size, and cohort-wide batch trends learned from normal controls. Second, within-sample reference normalization groups genomic windows that co-vary similarly across the control cohort into reference prototypes located on other chromosomes. When scoring a new sample, each window is compared against its matched off-chromosome prototypes inside that same sample—canceling out sample-specific technical quirks while ensuring a gain or loss on one chromosome never distorts 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: Streams aBAMorCRAMalignment once (in parallel genomic tiles when indexed, or sequentially on a single thread without an index), filtering out unmapped, secondary, supplementary, duplicate, and low-MAPQ reads. Paired-end proper pairs are assigned by their fragment midpoint so reads spanning window boundaries are never double-counted, while single-end reads are binned by 5' start coordinate (5 kbwindows by default). Alongside read counts, paired-end runs capture per-window fragment length bands, short-fragment counts, fragment GC, and sample-wide insert-size and end-motif summaries in a compact.ccnvParquet file. Contig names and lengths come directly from the alignment header, soccnvworks with any reference assembly or organism and can coarsen finer.ccnvfiles automatically in memory if window sizes differ.ccnv reference— Cohort Modeling & Baseline Construction: Builds a reusable reference.ccnvmodel from normal control.ccnvfiles listed in a YAML or JSON samplesheet. It scales library depths using genome-wide median ratios (preventing an unexpected trisomy in a control sample from skewing total depth), masks gap-heavy (N-rich) and low-mappability windows from optionalFASTAand BigWig tracks, and regresses out sample-specific GC, mappability, and fragment-length biases. It then infers biological sex from X/Y dosage (quarantining sex-chromosome outliers) to fit separateautosomal,female_sex, andmale_sexbranches, captures recurring cohort batch patterns via PCA, links each window to matching off-chromosome prototypes, and separates random low-coverage counting noise from repeatable biological variability so the model generalizes across sequencing depths. When no control cohort is available,--fastabuilds a simpler sequence-based germline baseline directly from a referenceFASTA.ccnv ref-qc— Reference Usability Audit: Evaluates an existing reference.ccnvfile before routine use by checking unmasked window counts, prototype match quality across branches, and male Y-chromosome representation. Writes structured diagnostics to<prefix>_qc.jsonand emits aPASS,WARN, orFAILverdict (--fastareferences reportWARNbecause empirical cohort noise estimates are absent).ccnv predict— Projection, Segmentation & Event Calling: Projects a test sample (.ccnv,BAM, orCRAM) onto the reference model using outlier-resistant regression so large CNVs or whole-chromosome aneuploidies cannot pull the baseline toward the aberration, then computes per-windowlog2copy-number ratios and 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 segments do not bridge across chromosome arms, partitioned into contiguous segments via change-point detection, and scored using both multi-scale Z-scores and discrete integer copy-number likelihoods (CN = 0, 1, 2, 3, 4+)—resolving focal homozygous deletions (CN = 0) down to0.1xcoverage as well as calls in standard30x+WGS. Deliverables include bgzipped/indexed bin, segment, and callBEDandVCFfiles,<prefix>_qc.json, and an interactive WebGL genome viewer (<prefix>_plot.html).
- Germline Mode (
--mode germline, default): Profiles constitutional, clinical, or research WGS samples where copy-number changes affect the full sample. Automatically selects the matching female (XX) or male (XY) sex-chromosome branch (unless overridden with--sex) so both autosomes and sex chromosomes are normalized and 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 only ~4–20% of sequenced fragments in a maternal background—proportionally dampening thelog2ratio shift of fetal gains and losses.ccnvcombines four independent fetal fraction signals (male Y-chromosome coverage, genome-wide autosomal coverage patterns, X-chromosome dosage, and shorter fetal vs. longer maternal fragment-size distributions), up-weights fetal-enriched fragment sizes, screens for singleton sex-chromosome aneuploidies (XX,XY,XO,XXX,XXY,XYY) alongside 2-fetus twin pregnancy stoichiometry (FF,FM,MM, explicitly via--twinsor de novo auto-detection, reportingscacall andconfidencealongsidetwincall,twin_probability, and sex-pairposteriorsin<prefix>_qc.json), normalizeschrXagainst the diploidXXbaseline and male-fetus (fetal_sex == "M")5 kbchrYwindows against an FF-calibrated 1-copy MSY baseline onprenatal_ffy(omittingchrYwhenfetal_sex == "F"), checks whether each segment's depth shift matches the sample's fetal fraction, and couples coverage depth with fragment lengths to distinguish fetal constitutional CNVs, confined placental mosaicism, inherited CNVs, and maternal CNVs.
conda 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, interactive Plotly HTML reports (_plot.html), 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: Interactive HTML genome viewer tracks, controls, icons, and color legends.
- API Reference: Module-by-module function reference and call-graph DAGs.
- Mathematical Methodology: Statistical formulations, models, 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.