hmm_estimate_CN() returns a CN_reliability value for every window. It is meant to be read as the probability that the copy-number (CN) call of that window is correct. This tutorial explains how the score is built and uses simulated samples, where the true CN is known, to show what to expect when:

  1. the amount of BAF information changes along the genome,
  2. depth (z-score) and BAF point to different copy numbers,
  3. samples differ in ploidy and in how dispersed their BAF is.

All data here are simulated, so every number can be compared with the truth.

library(Qploidy2)
library(ggplot2)

1 Why not just use the HMM posterior?

post_max is the HMM posterior of the called state. It answers “given the fitted model, how much better is this state than the others?”. It does not ask whether the evidence itself can be trusted, so it is close to 1 in most windows, including wrong calls. CN_reliability starts from post_max and multiplies it by checks of the evidence behind the call.

2 How the score is built

\[ CN\_reliability = post\_max \times \big[\, s \cdot fit \;+\; (1 - s \cdot fit) \cdot z\_no\_baf\_scale \cdot depth \,\big] \times \big[\, 1 - s\,(1 - agree) \,\big] \times sample\_baf \times depth\_fit \]

Every term is returned as a column of by_window, so you can always see which one lowered a score.

Column Question it answers Values
rel_baf_support (\(s\)) How many heterozygous markers does the window have? min(1, n_het / 30): 0 with no heterozygous markers, 1 from 30 on
rel_baf_fit (\(fit\)) How well do the heterozygous BAFs resolve the peaks expected for the final called CN? 1 for tight peaks; 0 when the BAFs are as spread as noise
rel_baf_agree (\(agree\)) Do the heterozygous BAFs fit the peaks of the final called CN at least as well as those of any other CN? 1 if yes; falls to 0.3 when another CN clearly fits better
rel_depth (\(depth\)) From the window’s own z-score, how likely is the final called CN, knowing that most of the genome sits at the sample’s baseline CN? 0 to 1
rel_sample_baf (\(sample\_baf\)) Do the BAF peaks of the whole sample sit at the positions expected for its baseline (most common) CN (1/CN, 2/CN, ...), whatever their width? close to 1 for clear peaks, close to 0 for no peaks or peaks elsewhere; same value in every window of a sample
rel_depth_fit (\(depth\_fit\)) Is the window’s z-score where the final called CN expects it? 1 within 2.5 standard deviations; decays beyond

How to read the formula:

  • The first bracket chooses the evidence. \(s \cdot fit\) is the share of the score that rests on BAF; the rest rests on depth. With many heterozygous markers and tight peaks (\(s \cdot fit = 1\)), a call that BAF and depth both support reaches 1.
  • With no heterozygous markers (\(s = 0\)) the score rests on depth: post_max × z_no_baf_scale × depth × sample_baf × depth_fit. It can reach at most z_no_baf_scale (0.9 by default), and only when the depth evidence for the called CN is clear.
  • Peaks too wide to resolve (\(fit\) near 0, common at high ploidy) are not held against the call: the score moves to depth and behaves like a depth-only call. So the score does not drop with ploidy for the same BAF noise.
  • The second bracket is a veto. When the BAF fits another CN better (\(agree = 0.3\)), the score is multiplied by about 0.3, however confident the HMM is and whatever the fit.
  • \(sample\_baf\) checks the sample as a whole. When the sample’s BAF shows no peaks at the positions of its baseline CN (failed sample, or wrong baseline ploidy), every window of the sample scores close to 0.

3 Simulating samples

The helper below simulates one sample directly as standardized BAF and z-scores, which is the input hmm_estimate_CN() uses. Each chromosome (or part of one) gets a true copy number, the copy number the depth signal reflects (normally the same), and a heterozygosity rate. Depth also carries slow “waves” along the chromosome, as real arrays and sequencing do.

# chrs: one row per segment, built with chr_spec()
sim_cn_sample <- function(sample_id, chrs, ploidy = 4, n_markers = 1500,
                          baf_sd = 0.035, z_per_copy = 1 / ploidy, z_sd = 1,
                          wave_sd = 0.05, seed = 1) {
  set.seed(seed)
  out <- lapply(unique(chrs$Chr), function(ch) {
    s <- chrs[chrs$Chr == ch, ]
    frac <- seq_len(n_markers) / n_markers
    k <- vapply(frac, function(f) which(f > s$start & f <= s$end)[1], integer(1))
    cn <- s$cn[k]
    het <- runif(n_markers) < s$het_rate[k] & cn > 1
    dose <- ifelse(
      het,
      vapply(cn, function(x) if (x > 1) sample.int(x - 1, 1) else 0L, integer(1)),
      ifelse(runif(n_markers) < 0.5, 0L, cn)
    )
    wave <- stats::filter(rnorm(n_markers + 400, 0, wave_sd * sqrt(200)),
                          rep(1 / 200, 200), sides = 1)
    wave <- as.numeric(wave)[-seq_len(400)]
    baf <- pmin(1, pmax(0, dose / cn + rnorm(n_markers, 0, baf_sd)))
    data.frame(
      MarkerName = paste0(ch, "_", seq_len(n_markers)), SampleName = sample_id,
      Chr = ch, Position = sort(sample.int(5e7, n_markers)),
      X = 500, Y = 500, R = 1000, ratio = baf, baf = baf,
      z = (s$z_cn[k] - ploidy) * z_per_copy + wave + rnorm(n_markers, 0, z_sd),
      true_cn = cn, stringsAsFactors = FALSE
    )
  })
  structure(list(data = do.call(rbind, out)), class = "qploidy_standardization")
}

# cn: true copy number; z_cn: copy number the depth reflects;
# het_rate: fraction of heterozygous markers; start/end: fraction of the chromosome
chr_spec <- function(Chr, cn, het_rate = 0.3, z_cn = cn, start = 0, end = 1) {
  data.frame(Chr, cn, z_cn, het_rate, start, end, stringsAsFactors = FALSE)
}

run_hmm <- function(sim, ...) {
  suppressMessages(hmm_estimate_CN(sim, sample_id = sim$data$SampleName[1],
                                   cn_grid = 1:6, verbose = FALSE, ...))
}

# Add the true CN of each window (the most common true CN among its markers)
add_truth <- function(res, sim) {
  bm <- merge(res$by_marker[, c("MarkerName", "Chr", ".__w__")],
              sim$data[, c("MarkerName", "true_cn")], by = "MarkerName")
  tr <- aggregate(true_cn ~ Chr + .__w__, bm,
                  function(x) as.integer(names(which.max(table(x)))))
  bw <- res$by_window
  bw$true_cn <- tr$true_cn[match(paste(bw$Chr, bw$WindowID), paste(tr$Chr, tr$.__w__))]
  bw$correct <- bw$CN_call == bw$true_cn
  bw
}

# One row per chromosome and called CN, with the score and its components
rel_cols <- c("rel_baf_support", "rel_baf_agree", "rel_baf_fit", "rel_depth",
              "rel_sample_baf", "rel_depth_fit")
summarize_rel <- function(bw) {
  out <- lapply(split(bw, list(bw$Chr, bw$CN_call), drop = TRUE), function(x) {
    w <- x$n_snps
    data.frame(
      Chr = x$Chr[1], true_CN = paste(unique(x$true_cn), collapse = "/"),
      CN_call = x$CN_call[1], n_het = sum(x$n_het),
      post_max = round(weighted.mean(x$post_max, w), 2),
      CN_reliability = round(weighted.mean(x$CN_reliability, w), 2),
      round(as.data.frame(lapply(x[rel_cols], weighted.mean, w = w)), 2)
    )
  })
  out <- do.call(rbind, out)
  rownames(out) <- NULL
  out[order(out$Chr), ]
}

4 A reference sample

A clean tetraploid: six chromosomes with 30% heterozygous markers, one of them (Chr3) with a true extra copy.

ref_chrs <- rbind(
  chr_spec("Chr1", 4), chr_spec("Chr2", 4), chr_spec("Chr3", 5),
  chr_spec("Chr4", 4), chr_spec("Chr5", 4), chr_spec("Chr6", 4)
)
ref_sim <- sim_cn_sample("reference", ref_chrs, seed = 11)
ref_res <- run_hmm(ref_sim)
summarize_rel(add_truth(ref_res, ref_sim))

What to expect. Every call, including the gain on Chr3, is backed by BAF peaks at the right positions and by depth, so every window scores close to 1. On Chr3 rel_depth is lower than elsewhere because one window’s z-score alone cannot fully prove a gain, but with full BAF support (\(s \cdot fit = 1\)) that term does not enter the score.

In plot_cn_track() the CN segments (bottom track) are coloured by CN_reliability.

plot_cn_track(ref_res, ref_sim, sample_id = "reference")$arranged

5 Scenario 1: low and high BAF weight along the genome

Stretches with few or no heterozygous markers (runs of homozygosity, inbred regions, hemizygous segments) carry little or no BAF information. Here a tetraploid has chromosomes with 30%, 3% and 0% heterozygous markers, a true gain with BAF support (Chr4), a true gain without any heterozygous marker (Chr5), and a chromosome that loses heterozygosity half-way (Chr6).

mix_chrs <- rbind(
  chr_spec("Chr1", 4, het_rate = 0.3),
  chr_spec("Chr2", 4, het_rate = 0.03),
  chr_spec("Chr3", 4, het_rate = 0),
  chr_spec("Chr4", 5, het_rate = 0.3),
  chr_spec("Chr5", 5, het_rate = 0),
  chr_spec("Chr6", 4, het_rate = 0.3, end = 0.5),
  chr_spec("Chr6", 4, het_rate = 0, start = 0.5)
)
mix_sim <- sim_cn_sample("mixed_baf", mix_chrs, seed = 12)
mix_res <- run_hmm(mix_sim)
mix_bw <- add_truth(mix_res, mix_sim)
summarize_rel(mix_bw)

What to expect.

  • Chromosomes with BAF support score close to 1, as in the reference sample. A few dozen heterozygous markers in a window are enough: Chr2 has only 3% heterozygous markers and still scores high.
  • Windows with no heterozygous markers (rel_baf_support = 0) are capped at z_no_baf_scale = 0.9. Chr3 is at the sample’s baseline CN, so depth alone is convincing and it scores just below 0.9. With rel_baf_support = 0 the two BAF terms (rel_baf_agree, rel_baf_fit) do not enter the score, whatever their value.
  • Chr5 is a real gain supported by depth only. It also scores close to 0.9 because the depth shift is clear (rel_depth near 1). A weaker shift would score lower; see the next scenario.
  • A depth-only call is never scored as high as a call that BAF also supports. To keep only BAF-supported calls, filter with a threshold above 0.9 or with min_n_het.
ggplot(mix_bw, aes(x = n_het, y = CN_reliability, colour = factor(CN_call))) +
  geom_point(size = 3) +
  scale_x_continuous(trans = "log1p", breaks = c(0, 10, 30, 100, 300)) +
  geom_hline(yintercept = c(0.9, 1), linetype = "dashed", colour = "grey50") +
  labs(x = "Heterozygous markers in the window", y = "CN reliability",
       colour = "CN call") +
  ylim(0, 1) + theme_bw()

6 Scenario 2: depth and BAF disagree

Depth can shift without a change in copy number: probe or reference bias on a chromosome, GC content, or a sample-specific artefact. Here the true CN is 4 everywhere, but:

  • on Chr3 the depth is that of 5 copies while the BAF shows a tetraploid pattern,
  • on Chr5 the depth is that of 3 copies, again with tetraploid BAF,
  • on Chr4, which has no heterozygous markers, the depth is shifted only partly towards 5 copies,
  • on Chr6, which also has no heterozygous markers, the depth is fully that of 5 copies.
dis_chrs <- rbind(
  chr_spec("Chr1", 4), chr_spec("Chr2", 4),
  chr_spec("Chr3", 4, z_cn = 5),
  chr_spec("Chr4", 4, het_rate = 0, z_cn = 4.5),
  chr_spec("Chr5", 4, z_cn = 3),
  chr_spec("Chr6", 4, het_rate = 0, z_cn = 5)
)
dis_sim <- sim_cn_sample("disagreement", dis_chrs, seed = 13)
dis_res <- run_hmm(dis_sim)
summarize_rel(add_truth(dis_res, dis_sim))

What to expect.

  • Chr5. The HMM follows the depth and calls 3 copies with post_max near 1. The BAF fits the tetraploid peaks better than the triploid ones (rel_baf_agree = 0.3), so the score is capped at about 0.3, below the default filter. This is the kind of call post_max cannot flag.
  • Chr3. Here the HMM is torn between the depth (5 copies) and the BAF (4 copies). It keeps 4 copies, which is correct, but with a low post_max, so the score is low as well: the call is right, yet the evidence is contradictory and the window deserves a look.
  • Chr4. The depth shift is only partial and there is no BAF. The call stays at the baseline CN, where depth alone is convincing enough, and scores just below 0.9.
  • Chr6. A full depth shift with no heterozygous markers. The HMM returns the chromosome to the baseline CN (see hom_z_sigma_inflate) but with a low post_max, so the score is low.

Whether the HMM follows depth or BAF in a conflict depends on how strong each signal is, and can change from sample to sample. The score does not depend on that choice: a call that BAF contradicts, or that the HMM itself is unsure about, ends up low either way.

One limit remains. Had a gain been called on Chr6, it would look exactly like the real depth-only gain on Chr5 of the previous scenario and score up to 0.9. A depth shift on a region without heterozygous markers cannot be told apart from a real copy-number change. Depth-only gains and losses deserve a look at the raw signal, especially when the same chromosome is called in many samples, which suggests a chromosome-specific depth bias and not biology.

plot_cn_track(dis_res, dis_sim, sample_id = "disagreement")$arranged

7 Scenario 3: ploidy and BAF dispersion

BAF peaks get wider with noisy genotyping, low depth, or contamination. The same amount of noise blurs the peaks of higher ploidies first because they are closer together: 0.5 apart in a diploid, 0.33 in a triploid, 0.25 in a tetraploid.

Below, diploid, triploid and tetraploid samples (each with one chromosome carrying an extra copy) are simulated with increasing BAF spread, given as the standard deviation of the BAF around each peak.

grid <- expand.grid(ploidy = c(2, 3, 4), baf_sd = c(0.03, 0.045, 0.06, 0.12))
disp <- do.call(rbind, lapply(seq_len(nrow(grid)), function(i) {
  pl <- grid$ploidy[i]
  chrs <- rbind(
    chr_spec("Chr1", pl), chr_spec("Chr2", pl), chr_spec("Chr3", pl + 1),
    chr_spec("Chr4", pl), chr_spec("Chr5", pl), chr_spec("Chr6", pl)
  )
  sim <- sim_cn_sample(paste0("s", i), chrs, ploidy = pl,
                       baf_sd = grid$baf_sd[i], seed = 20 + i)
  bw <- add_truth(run_hmm(sim), sim)
  data.frame(
    ploidy = pl, baf_sd = grid$baf_sd[i],
    fraction_correct = round(weighted.mean(bw$correct, bw$n_snps), 2),
    mean_CN_reliability = round(weighted.mean(bw$CN_reliability, bw$n_snps), 2),
    mean_rel_baf_fit = round(weighted.mean(bw$rel_baf_fit, bw$n_snps), 2)
  )
}))
disp
hist_df <- do.call(rbind, lapply(c(0.03, 0.045, 0.06, 0.12), function(s) {
  sim <- sim_cn_sample("h", chr_spec("Chr1", 4), baf_sd = s, seed = 3)
  data.frame(baf = sim$data$baf, baf_sd = paste("BAF sd =", s))
}))
ggplot(hist_df[hist_df$baf > 0.05 & hist_df$baf < 0.95, ], aes(x = baf)) +
  geom_histogram(bins = 80, fill = "#2c7fb8") +
  facet_wrap(~baf_sd, nrow = 1) +
  labs(x = "BAF (heterozygous range, tetraploid)", y = "Markers") + theme_bw()

What to expect.

  • Tight peaks (sd 0.03): every ploidy scores close to 1.
  • Wider but distinct peaks (sd 0.045, and sd 0.06 in diploids and triploids): calls stay correct and still score close to 1. rel_baf_fit drops in triploids and tetraploids, but that only moves part of the score from BAF to depth, which supports the same calls.
  • Overlapping peaks in tetraploids (sd 0.06): BAF can no longer resolve the peaks (rel_baf_fit near 0.25), so the score rests mostly on depth. Some calls are now wrong, and the mean score falls to match the fraction of correct calls instead of dropping because of the ploidy.
  • No peaks (sd 0.12): the baseline ploidy itself is usually wrong, and rel_sample_baf brings every window close to 0. A sample whose mean CN_reliability is this low should be treated as failed, not filtered window by window.

A segment with dispersed BAF inside an otherwise clean sample is scored like a depth-only call: up to 0.9 when depth supports it.

8 How well does the score match the truth?

To check that the score behaves like a probability, 120 samples are simulated with random ploidy (2, 3 or 4), BAF spread, heterozygosity per chromosome, whole-chromosome and segmental copy-number changes, and depth shifts without a copy-number change. Windows are then grouped by CN_reliability, and the fraction of correct calls in each group is compared with the score.

one_sample <- function(i) {
  set.seed(5000 + i)
  pl <- sample(c(2, 3, 4), 1)
  chrs <- do.call(rbind, lapply(1:8, function(j) {
    ch <- sprintf("Chr%02d", j)
    hr <- sample(c(0.3, 0.1, 0.02, 0), 1, prob = c(0.5, 0.2, 0.15, 0.15))
    ty <- sample(c("normal", "aneuploid", "segmental", "depth shift only"), 1,
                 prob = c(0.6, 0.15, 0.1, 0.15))
    dl <- sample(c(-1, 1), 1)
    s <- switch(ty,
      "normal" = chr_spec(ch, pl, hr),
      "aneuploid" = chr_spec(ch, pl + dl, hr),
      "segmental" = {
        b <- runif(1, 0.3, 0.7)
        rbind(chr_spec(ch, pl, hr, end = b), chr_spec(ch, pl + dl, hr, start = b))
      },
      "depth shift only" = chr_spec(ch, pl, hr, z_cn = pl + dl * runif(1, 0.5, 1))
    )
    s$type <- ty
    s
  }))
  sim <- sim_cn_sample(
    paste0("S", i), chrs, ploidy = pl,
    baf_sd = sample(c(0.03, 0.05, 0.08, 0.15), 1, prob = c(0.4, 0.3, 0.2, 0.1)),
    z_per_copy = runif(1, 0.8, 1.2) / pl, wave_sd = sample(c(0.03, 0.08), 1),
    seed = i
  )
  res <- tryCatch(run_hmm(sim), error = function(e) NULL)
  if (is.null(res)) return(NULL)
  bw <- add_truth(res, sim)
  bw$type <- chrs$type[match(bw$Chr, chrs$Chr)]
  bw[, c("Sample", "Chr", "n_snps", "n_het", "CN_call", "post_max",
         "CN_reliability", "correct", "type")]
}
calib <- do.call(rbind, lapply(1:120, one_sample))
calib <- calib[!is.na(calib$CN_call), ]
bin_table <- function(score) {
  b <- cut(score, c(-0.01, 0.1, 0.3, 0.5, 0.7, 0.85, 0.95, 1))
  data.frame(
    score_range = levels(b),
    windows = as.vector(table(b)),
    mean_score = round(as.vector(tapply(score, b, mean)), 2),
    fraction_correct = round(as.vector(tapply(calib$correct, b, mean)), 2)
  )
}
rel_tab <- bin_table(calib$CN_reliability)
post_tab <- bin_table(calib$post_max)
rel_tab
both <- rbind(cbind(rel_tab, metric = "CN_reliability"),
              cbind(post_tab, metric = "post_max"))
ggplot(both[both$windows > 0, ],
       aes(x = mean_score, y = fraction_correct, colour = metric)) +
  geom_abline(linetype = "dashed", colour = "grey50") +
  geom_line() + geom_point(aes(size = windows)) +
  labs(x = "Mean score of the group", y = "Fraction of correct calls",
       colour = NULL, size = "Windows") +
  coord_equal(xlim = c(0, 1), ylim = c(0, 1)) + theme_bw()

What to expect. A score that is a perfect probability follows the dashed diagonal.

  • High scores can be trusted: from about 0.7 up, the score is close to the fraction of correct calls, and calls scoring above 0.95 are almost always correct.
  • Very low scores (below 0.1) are mostly wrong calls.
  • Between 0.1 and 0.7 the score is conservative: calls there are correct more often than their score suggests. This range mixes two kinds of windows. Calls at the baseline CN on chromosomes without any change are nearly always correct, but the HMM was less sure of them (lower post_max). Calls on chromosomes whose depth shifted without a copy-number change are mostly wrong. The score cannot tell them apart, so read it here as “check this window”, not as an exact probability.
  • post_max is far from the diagonal: its highest group contains many wrong calls, which is why it should not be used alone to filter.

The exact fractions depend on how often each problem occurs in the simulation, and real datasets have a different mix. Use them as a guide to the ordering of calls, not as exact error rates for your data.

9 Filtering

filter_hmm_CN() masks windows below min_CN_reliability (default 0.5).

dis_filtered <- filter_hmm_CN(dis_res, min_CN_reliability = 0.5)
dis_filtered$by_window[, c("Chr", "WindowID", "n_het", "CN_call", "CN_reliability")]

Choosing a threshold:

Goal Suggested filter
Remove calls contradicted by BAF and failed samples, keep everything else min_CN_reliability = 0.5 (default)
Keep only calls with BAF support min_CN_reliability = 0.95, or add min_n_het = 30
Flag samples to re-check instead of filtering windows mean CN_reliability per sample below about 0.5
keep <- c("Sample", "CN_reliability")
all_bw <- rbind(ref_res$by_window[, keep], mix_res$by_window[, keep],
                dis_res$by_window[, keep])
aggregate(CN_reliability ~ Sample, all_bw, function(x) round(mean(x), 2))

10 Summary

Situation Expected CN_reliability Term to look at
BAF and depth support the call close to 1 all terms near 1
No heterozygous markers, call at the sample’s baseline CN up to 0.9 rel_baf_support = 0
No heterozygous markers, gain or loss with a clear depth shift up to 0.9 rel_depth near 1
No heterozygous markers, gain or loss with a weak depth shift low rel_depth
BAF fits another CN better than the one called about 0.3 or less rel_baf_agree
BAF peaks too wide to resolve (common at high ploidy) like a depth-only call, up to 0.9 rel_baf_fit low, rel_depth
A segment with dispersed BAF in an otherwise clean sample like a depth-only call, up to 0.9 rel_baf_fit
Whole sample without BAF peaks at its baseline CN (failed sample or wrong baseline ploidy) close to 0 in every window rel_sample_baf
Window depth far from the called state low rel_depth_fit

Limits to keep in mind:

  • A depth shift on a region without heterozygous markers cannot be told apart from a real copy-number change. Such calls score up to 0.9.
  • The score checks each call against the evidence in its own window or run of windows. A copy-number change smaller than the window, or one the HMM merged into a neighbouring segment, can lower rel_baf_agree or rel_depth_fit but is not located by the score.
  • Results computed with earlier versions use other definitions of CN_reliability: with Qploidy2 1.25.1 or earlier values are much lower, and with 1.26.0 they drop with ploidy. Re-run hmm_estimate_CN() with 1.26.1 or later before applying the thresholds above.