Skip to content

Copy number from coverage and an independent array

A region with twice as many reads does not necessarily contain twice as many DNA copies. Capture efficiency, GC content, sequencing depth, and the reference sample all affect coverage. Copy number analysis first removes those effects as far as the experiment permits, then asks which neighboring measurements support a shared change.

This lesson uses the published C0902 cell line example distributed by the CNVkit authors. It starts with archived on-target and off-target coverage, uses the matching pooled reference, and compares the resulting copy ratios with an independently measured array. It does not repeat alignment or coverage extraction from sequencing reads.

The Python example uses CNVkit 0.9.14 and its HaarSeg implementation. It keeps autosomes for the comparison so that sex chromosome reference assumptions do not enter the displayed results. The coordinates use the hg19 assembly of the source example.

Download the four source files below into an inputs folder. They come from one fixed revision of the authors’ example repository. Rename the reference file to reference_cell.cnn when you save it.

File Role
CL_seq.targetcoverage.cnn The file contains coverage in targeted intervals.
CL_seq.antitargetcoverage.cnn The file contains coverage outside targeted intervals.
reference-cell.cnn The pooled reference includes the matched bins and bias annotations.
CL_acgh.cnr The file contains the independent array log2 ratios.

The reference must describe the same target design, assembly, and interval boundaries as the sample. A reference from another capture panel is not a replacement for these files, even if its chromosome names match.

from pathlib import Path
import json
import cnvlib
from cnvlib.call import do_call
from cnvlib.fix import do_fix
from cnvlib.segmentation.haar import segment_haar
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
output = Path("outputs")
output.mkdir(exist_ok=True)
targets = cnvlib.read("inputs/CL_seq.targetcoverage.cnn")
off_targets = cnvlib.read("inputs/CL_seq.antitargetcoverage.cnn")
reference = cnvlib.read("inputs/reference_cell.cnn")
array = pd.read_csv("inputs/CL_acgh.cnr", sep="\t")
key = ["chromosome", "start", "end"]
sample_bins = pd.concat([targets.data, off_targets.data], ignore_index=True)
assert not sample_bins.duplicated(key).any()
assert not reference.data.duplicated(key).any()
matched = sample_bins.merge(reference.data[key], on=key, how="left",
indicator=True, validate="one_to_one")
assert matched["_merge"].eq("both").all()
assert np.isfinite(sample_bins.log2).all()
assert np.isfinite(array.log2).all()
print("Target intervals:", len(targets))
print("Off-target intervals:", len(off_targets))
print("Array probes:", len(array))
print("Coverage intervals with a reference:", len(matched))
Target intervals: 8662
Off-target intervals: 19402
Array probes: 174182
Coverage intervals with a reference: 28064

The two coverage files describe different interval sizes. They are not two sets of biological replicates. CNVkit uses the reference annotations and reference spread to correct and weight their measurements.

do_fix() applies the reference and the GC, target-edge, and repeat corrections available in these files. The example removes near-zero coverage and bins with zero reference weight before it calls HaarSeg directly. HaarSeg combines neighboring bins into segments with similar log2 ratios. Its threshold is a segmentation parameter, not a test of a treatment effect across donors.

corrected = do_fix(targets, off_targets, reference)
autosomes = [f"chr{number}" for number in range(1, 23)]
corrected = corrected[corrected.chromosome.isin(autosomes)]
corrected.sort()
segment_input = corrected.drop_low_coverage()
segment_input = segment_input[segment_input["weight"] > 0]
segments = segment_haar(segment_input, fdr_q=0.0001)
segments.sort()
for _, chromosome in segments.by_chromosome():
starts = chromosome.start.to_numpy()
ends = chromosome.end.to_numpy()
assert np.all(starts < ends)
assert np.all(starts[1:] >= ends[:-1])
called = do_call(segments, method="clonal", ploidy=2, purity=1.0)
cnvlib.write(corrected, output / "c0902_corrected.cnr")
segment_input.data.to_csv(output / "segmentation_input.tsv", sep="\t",
index=False)
cnvlib.write(segments, output / "c0902_segments.cns")
cnvlib.write(called, output / "c0902_conditional_calls.cns")
assert np.isfinite(corrected.log2).all()
assert np.isfinite(segments.log2).all()
expected_copies = np.maximum(0, np.rint(2 * np.exp2(segments.log2)))
assert np.array_equal(called["cn"], expected_copies)
print("Retained autosomal bins:", len(corrected))
print("Estimated autosomal segments:", len(segments))
print("Segments below log2 ratio -0.25:", int((segments.log2 < -0.25).sum()))
print("Segments above log2 ratio 0.20:", int((segments.log2 > 0.20).sum()))
Retained autosomal bins: 25865
Estimated autosomal segments: 797
Segments below log2 ratio -0.25: 147
Segments above log2 ratio 0.20: 409

The exported integer calls are conditional on a diploid baseline and a pure clonal sample. They do not establish the cell line’s absolute ploidy. The segmented log2 ratios remain the primary measurement here; changing the baseline changes their interpretation as copy numbers.

The two descriptive cutoffs count segments with clear departures from zero. They are not confidence bounds, and a long segment does not provide more independent samples than a short segment.

The array and sequencing assay do not measure identical intervals. We assign an array probe to a sequencing bin when its midpoint lies inside that bin. For bins with at least three array probes, the comparison uses their mean log2 ratio. This rule fixes the comparison before looking at concordance.

rows = []
for chromosome in autosomes:
probes = array.loc[array.chromosome.eq(chromosome)].copy()
probes["midpoint"] = (probes.start + probes.end) / 2
probes = probes.sort_values("midpoint")
positions = probes.midpoint.to_numpy()
values = probes.log2.to_numpy()
cumulative = np.concatenate([[0.0], np.cumsum(values)])
bins = corrected.data.loc[corrected.chromosome.eq(chromosome)]
for row in bins.itertuples(index=False):
left = np.searchsorted(positions, row.start, side="left")
right = np.searchsorted(positions, row.end, side="left")
count = int(right - left)
if count >= 3:
mean_array = (cumulative[right] - cumulative[left]) / count
rows.append([chromosome, row.start, row.end, row.log2,
mean_array, count])
comparison = pd.DataFrame(rows, columns=[
"chromosome", "start", "end", "sequencing_log2", "array_log2", "probes"
])
assert not comparison.empty
correlation = comparison.sequencing_log2.corr(comparison.array_log2)
absolute_difference = np.abs(comparison.sequencing_log2 - comparison.array_log2)
comparison.to_csv(output / "assay_comparison.csv", index=False)
print("Bins with at least three array probes:", len(comparison))
print(f"Pearson correlation: {correlation:.3f}")
print(f"Median absolute log2 difference: {np.median(absolute_difference):.3f}")
Bins with at least three array probes: 17025
Pearson correlation: 0.747
Median absolute log2 difference: 0.117

This is agreement between two measurements of the same cell line. It is not sensitivity against a complete truth set, and neighboring bins are correlated. A large correlation can coexist with a biased baseline or missed focal events. The comparison therefore retains the paired measurements rather than reducing validation to one coefficient.

The left panel shows the matched bins. The right panel displays chromosome 7 with the fresh sequencing segments. Probe density differs between assays, so their point clouds should not receive equal weight just because one has more points.

figure, axes = plt.subplots(1, 2, figsize=(12, 4.8))
density = axes[0].hexbin(comparison.array_log2, comparison.sequencing_log2,
gridsize=45, mincnt=1, cmap="Blues", bins="log")
figure.colorbar(density, ax=axes[0], label="Matched bins per hexagon")
limits = [-2.0, 2.5]
axes[0].plot(limits, limits, color="#777777", linestyle="--", linewidth=1)
axes[0].set(xlabel="Mean array log2 ratio", ylabel="Sequencing bin log2 ratio",
title="C0902 across two assays")
sequence_chr = corrected.data.loc[corrected.chromosome.eq("chr7")]
array_chr = array.loc[array.chromosome.eq("chr7")]
axes[1].scatter((array_chr.start + array_chr.end) / 2e6, array_chr.log2,
s=3, alpha=0.15, color="#a0a0a0", label="Array probes")
axes[1].scatter((sequence_chr.start + sequence_chr.end) / 2e6,
sequence_chr.log2, s=5, alpha=0.4, color="#32658b",
label="Sequencing bins")
for row in segments.data.loc[segments.chromosome.eq("chr7")].itertuples():
axes[1].plot([row.start / 1e6, row.end / 1e6], [row.log2, row.log2],
color="#b76525", linewidth=2)
axes[1].axhline(0, color="#555555", linewidth=0.8)
axes[1].set(xlabel="Chromosome 7 position, Mb", ylabel="Log2 ratio",
title="HaarSeg estimates from sequencing bins")
axes[1].legend(frameon=False, markerscale=2)
for axis in axes:
axis.spines[["top", "right"]].set_visible(False)
figure.tight_layout()
figure.savefig(output / "copy_number_concordance.png", dpi=160)
plt.close(figure)
metrics = {"matched_bins": len(comparison), "correlation": correlation,
"median_absolute_difference": float(np.median(absolute_difference)),
"segments": len(segments), "conditional_ploidy": 2}
(output / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")

Matched C0902 bins compare sequencing and array log2 ratios, beside their chromosome 7 profiles and the sequencing segments.

For a tumor specimen, normal-cell contamination attenuates the observed copy ratio. Whole-genome duplication also changes the baseline. A real absolute-copy analysis must account for those quantities, often with allelic information; rounding these ratios under the example’s assumptions is not sufficient.

Talevich and colleagues, 2016 describe CNVkit’s reference correction, copy ratio estimates, and comparisons with independent assays.

Ben-Yaacov and Eldar, 2008 describe HaarSeg, the segmentation method used in this example.

Botton and colleagues, 2013 describe the melanocytic tumor study that supplies the C0902 cell line measurements distributed in the CNVkit examples.

The CNVkit 0.9.14 pipeline description explains the reference, bias corrections, and segmentation options. Use it to connect these archived coverage inputs to the preceding BAM processing steps.

The copy number interpretation guide explains how purity, ploidy, and allelic information affect integer calls. Read it before applying the example’s diploid assumption to a tumor specimen.

The source dataset description identifies the studies behind the example files. Its cell line dataset is separate from the melanoma exome and targeted cohorts in that repository.