Metadata-Version: 2.4
Name: ccnv
Version: 1.2.0
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Dist: jinja2
Requires-Dist: numpy>=2.5,<3
Requires-Dist: polars>=2,<3
Requires-Dist: polars-runtime-compat ; platform_machine == 'x86_64'
Requires-Dist: pyarrow>=26,<27
Requires-Dist: pyyaml>=6.0
Requires-Dist: scikit-learn>=1.9,<2
Requires-Dist: scipy>=1.18,<2
Requires-Dist: typer>=0.29,<0.30
Requires-Dist: pybigwig ; extra == 'dev'
Requires-Dist: pysam ; extra == 'dev'
Requires-Dist: ruptures>=1.1.10 ; extra == 'dev'
Provides-Extra: dev
License-File: LICENSE.md
Summary: Copy-number analysis for whole-genome sequencing
Home-Page: https://github.com/matthdsm/ccnv
Author: Matthias De Smet
License-Expression: AGPL-3.0-or-later
Requires-Python: >=3.12
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/matthdsm/ccnv/blob/master/CHANGELOG.md
Project-URL: Documentation, https://matthdsm.github.io/ccnv/
Project-URL: Homepage, https://github.com/matthdsm/ccnv
Project-URL: Issues, https://github.com/matthdsm/ccnv/issues
Project-URL: Repository, https://github.com/matthdsm/ccnv

# `ccnv`

[![PyPI Version](https://img.shields.io/pypi/v/ccnv.svg)](https://pypi.org/project/ccnv/) [![install with bioconda](https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg?style=flat)](https://bioconda.github.io/recipes/ccnv/README.html) [![Bioconda Version](https://img.shields.io/conda/vn/bioconda/ccnv.svg)](https://anaconda.org/bioconda/ccnv) [![DOI](https://zenodo.org/badge/github/1340649924.svg)](https://doi.org/10.5281/zenodo.24390872)

`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/](https://matthdsm.github.io/ccnv/).

---

## How It Works

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.

```mermaid
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
```

### Pipeline Stages

1. **`ccnv extract` — Alignment Streaming & Fragment Profiling**: Reads a `BAM` or `CRAM` file once (in parallel genomic tiles when indexed, or sequentially on one thread without an index) and drops unmapped, secondary, supplementary, duplicate, and `MAPQ = 0` reads. Proper read pairs are binned by fragment midpoint (`5 kb` windows 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 `.ccnv` Parquet file. Contig names and lengths come directly from the alignment header, so `ccnv` works on any genome build or species and can coarsen finer `.ccnv` files automatically in memory when window sizes differ.
2. **`ccnv reference` — Cohort Modeling & Baseline Construction**: Builds a reusable `.ccnv` reference from control `.ccnv` files listed in a YAML or JSON samplesheet. It scales library depths across `1 Mb` blocks using median ratios (so an unexpected trisomy in a control cannot skew total depth), masks gap-heavy (`N`-rich) and low-mappability bins from optional `FASTA` and BigWig tracks, and regresses out GC, mappability, and fragment-length biases without dropping zero-count bins. It then separates `autosomal`, `female_sex`, and `male_sex` branches 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, `--fasta` builds a sequence-only flat germline reference.
3. **`ccnv ref-qc` — Reference Usability Audit**: Audits a reference `.ccnv` model before use by checking unmasked bin counts, prototype distance distributions across branches, and male `chrY` coverage. It writes structured diagnostics to `<prefix>_qc.json` and logs a `PASS`, `WARN`, or `FAIL` verdict (`--fasta` references report `WARN` because empirical cohort noise estimates are missing).
4. **`ccnv predict` — Projection, Segmentation & Event Calling**: Normalizes a test sample (`.ccnv`, `BAM`, or `CRAM`) using outlier-resistant regression onto the reference PCA waves so large CNVs or trisomies cannot pull the baseline, then computes `log2` ratios 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 Mb` by 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 to `0.1x` coverage as well as high-depth `30x+` WGS. Outputs include bgzipped/indexed `BED` and `VCF` files, `<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.

### Analysis Modes

- **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 fetal `log2` shifts accordingly. `ccnv` combines four independent fetal fraction signals (male `chrY` coverage, genome-wide autosomal depth patterns, `chrX` dosage, and shorter fetal vs. longer maternal fragment lengths) into one outlier-resistant estimate, up-weights fetal-enriched fragment sizes, and normalizes `chrX` against the diploid `XX` branch plus male-fetus (`fetal_sex == "M"`) `5 kb` `chrY` bins against a calibrated 1-copy MSY baseline on `prenatal_ffy` (omitting `chrY` when `fetal_sex == "F"`). It also screens singleton sex-chromosome aneuploidies (`XX`, `XY`, `XO`, `XXX`, `XXY`, `XYY`) alongside twin sex pairs (`FF`, `FM`, `MM`, via `--twins` or automatic detection, reporting `sca` and `twin` metrics 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.

---

## Installation

### PyPI (pip / uv)

Pre-compiled `manylinux_2_28` (`x86_64`, `aarch64`) and `macOS` (`arm64`) wheels are published to PyPI:

```console
pip install ccnv
# or isolated CLI installation via uv:
uv tool install ccnv
ccnv --help
```

### Bioconda

```console
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 --help
```

### pip (from source)

```console
python -m pip install .
ccnv --help
```

### Pixi (from source)

```console
pixi install
pixi run ccnv --help
```

### Docker

Multi-platform container images (`linux/amd64` and `linux/arm64`) are published to GHCR:

```console
docker pull ghcr.io/matthdsm/ccnv:latest
docker run --rm ghcr.io/matthdsm/ccnv:latest ccnv --help
```

### Galaxy

IUC-compatible Galaxy wrappers (`ccnv_extract`, `ccnv_reference`, `ccnv_ref_qc`, `ccnv_predict`) and ToolShed suite metadata live under [galaxy/](galaxy/). See the [CLI Reference](https://matthdsm.github.io/ccnv/cli/#galaxy-tool-suite) for dataset staging and workflow output details.

---

## Quickstart

```console
# 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_prenatal
```

Outputs 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`).

---

## Documentation

Visit the [documentation site](https://matthdsm.github.io/ccnv/) for detailed guides:

- [Pipeline Architecture](https://matthdsm.github.io/ccnv/pipeline/): 4-stage execution model and storage contracts.
- [CLI Reference](https://matthdsm.github.io/ccnv/cli/): Flag specification, inputs, outputs, and exit codes.
- [Visualization Overview](https://matthdsm.github.io/ccnv/visualization/): Self-contained offline HTML genome viewer tracks, clinical gene annotations and bundled catalog provenance, aberrations table, TSV export, controls, and color legends.
- [API Reference](https://matthdsm.github.io/ccnv/api/): Module-by-module function reference and call-graph DAGs.
- [Mathematical Methodology](https://matthdsm.github.io/ccnv/methodology/): Statistical models, assumptions, and citations.

---

## Development & Verification

```console
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 locally
```

All changes must be submitted via pull request and recorded in [CHANGELOG.md](CHANGELOG.md).

---

## License

Licensed under the GNU Affero General Public License v3 or later (AGPL-3.0-or-later). See [LICENSE.md](LICENSE.md).
