tests/testthat/test-truncated-normal.R

################################################################################
# tnorm_mean() -----------------------------------------------------------

test_that("tnorm_mean matches known closed-form results", {
  # untruncated normal just returns mu
  expect_equal(tnorm_mean(), 0)
  expect_equal(tnorm_mean(mu = 3, sigma = 2, lower = -Inf, upper = Inf), 3)

  # standard normal truncated to (-Inf, 0] has known mean -sqrt(2/pi)
  expect_equal(tnorm_mean(mu = 0, sigma = 1, lower = -Inf, upper = 0), -sqrt(2 / pi))
  # and truncated to [0, Inf) has known mean sqrt(2/pi)
  expect_equal(tnorm_mean(mu = 0, sigma = 1, lower = 0, upper = Inf), sqrt(2 / pi))

  # scaling: truncating N(mu, sigma^2) at mu +/- k*sigma should scale linearly
  expect_equal(
    tnorm_mean(mu = 5, sigma = 2, lower = -Inf, upper = 5),
    5 - 2 * sqrt(2 / pi)
  )
})

test_that("tnorm_mean matches brute-force numeric integration for finite two-sided truncation", {
  mu <- 0.3; sigma <- 1.4; lower <- -0.5; upper <- 2.1
  denom <- stats::integrate(function(x) dnorm(x, mu, sigma), lower, upper)$value
  expected <- stats::integrate(function(x) x * dnorm(x, mu, sigma), lower, upper)$value / denom
  expect_equal(tnorm_mean(mu = mu, sigma = sigma, lower = lower, upper = upper), expected,
               tolerance = 1e-6)
})

test_that("tnorm_mean treats lower == upper as a dirac point mass", {
  expect_equal(tnorm_mean(mu = 0, sigma = 1, lower = 2, upper = 2), 2)
  expect_equal(tnorm_mean(mu = 10, sigma = 5, lower = -3, upper = -3), -3)
})

test_that("tnorm_mean errors on swapped/impossible bounds at +/-Inf", {
  expect_error(tnorm_mean(lower = Inf, upper = Inf), "switched")
  expect_error(tnorm_mean(lower = 0, upper = -Inf), "switched")
})

################################################################################
# tnorm_var() --------------------------------------------------------------

test_that("tnorm_var matches known closed-form results", {
  expect_equal(tnorm_var(), 1)
  expect_equal(tnorm_var(mu = 0, sigma = 2, lower = -Inf, upper = Inf), 4)

  # standard normal truncated to (-Inf, 0] or [0, Inf) has known variance 1 - 2/pi
  expect_equal(tnorm_var(mu = 0, sigma = 1, lower = -Inf, upper = 0), 1 - 2 / pi)
  expect_equal(tnorm_var(mu = 0, sigma = 1, lower = 0, upper = Inf), 1 - 2 / pi)
})

test_that("tnorm_var matches brute-force numeric integration for finite two-sided truncation", {
  mu <- 0.3; sigma <- 1.4; lower <- -0.5; upper <- 2.1
  denom <- stats::integrate(function(x) dnorm(x, mu, sigma), lower, upper)$value
  m <- stats::integrate(function(x) x * dnorm(x, mu, sigma), lower, upper)$value / denom
  expected <- stats::integrate(function(x) (x - m)^2 * dnorm(x, mu, sigma), lower, upper)$value / denom
  expect_equal(tnorm_var(mu = mu, sigma = sigma, lower = lower, upper = upper), expected,
               tolerance = 1e-6)
})

test_that("tnorm_var treats lower == upper as having zero variance", {
  expect_equal(tnorm_var(mu = 0, sigma = 1, lower = 2, upper = 2), 0)
  expect_equal(tnorm_var(mu = 10, sigma = 5, lower = -3, upper = -3), 0)
})

test_that("tnorm_var errors on swapped/impossible bounds at +/-Inf", {
  expect_error(tnorm_var(lower = Inf, upper = Inf), "switched")
  expect_error(tnorm_var(lower = 0, upper = -Inf), "switched")
})

test_that("tnorm_var is finite and non-negative near the one-sided special cases", {
  # exercises the beta == Inf branch (lower-only truncation)
  v_lower_only <- tnorm_var(mu = 0, sigma = 1, lower = 5, upper = Inf)
  expect_true(is.finite(v_lower_only) && v_lower_only >= 0)

  # exercises the alpha == -Inf branch (upper-only truncation)
  v_upper_only <- tnorm_var(mu = 0, sigma = 1, lower = -Inf, upper = -5)
  expect_true(is.finite(v_upper_only) && v_upper_only >= 0)
})

################################################################################
# tnorm_mixture_conditional() -----------------------------------------------

test_that("tnorm_mixture_conditional gives an exact dirac for a known case (lower == upper)", {
  # Regression test: prepare_thresholds(..., lower_equal_upper = TRUE) gives
  # cases lower == upper == thr (a finite dirac point mass), while
  # K_i/K_pop are still populated for every individual, case or control.
  # This used to still trigger the K_i/K_pop mixture calculation (a
  # `upper != Inf | lower == upper` condition that fired *because* of
  # lower == upper, rather than being skipped for it), which shrank the
  # case's mean away from the point mass and inflated its variance away
  # from 0. A known case has no "might still become a case later"
  # component to mix in - the outcome is already certain.
  res <- tnorm_mixture_conditional(mu = 0, var = 1, lower = 1.5, upper = 1.5,
                                    K_i = 0.05, K_pop = 0.10)
  expect_equal(res$mean, 1.5)
  expect_equal(res$var, 0)

  # holds regardless of where the dirac sits, and regardless of how close
  # K_i is to K_pop
  res2 <- tnorm_mixture_conditional(mu = -1, var = 2, lower = -4, upper = -4,
                                     K_i = 0.29, K_pop = 0.30)
  expect_equal(res2$mean, -4)
  expect_equal(res2$var, 0)
})

test_that("tnorm_mixture_conditional errors when only one of K_i/K_pop is missing", {
  # Both NA is a legitimate "no mixture requested" opt-out (tested below);
  # exactly one NA is ambiguous input (e.g. one merge succeeded upstream and
  # the other didn't) and should fail loudly rather than silently
  # propagating NA through the whole PA_algorithm() computation.
  expect_error(
    tnorm_mixture_conditional(mu = 0, var = 1, lower = -Inf, upper = 1.2, K_i = NA, K_pop = 0.10),
    "must either both be provided or both be NA"
  )
  expect_error(
    tnorm_mixture_conditional(mu = 0, var = 1, lower = -Inf, upper = 1.2, K_i = 0.05, K_pop = NA),
    "must either both be provided or both be NA"
  )
})

test_that("tnorm_mixture_conditional matches plain truncated-normal moments when K_i/K_pop are NA", {
  # The non-PA-FGRS path (plain Gibbs sampling): no mixture is possible
  # without K_i/K_pop, so this should reduce to tnorm_mean()/tnorm_var().
  res <- tnorm_mixture_conditional(mu = 0.4, var = 1.6, lower = -Inf, upper = 1.1,
                                    K_i = NA, K_pop = NA)
  expect_equal(res$mean, tnorm_mean(mu = 0.4, sigma = sqrt(1.6), lower = -Inf, upper = 1.1))
  expect_equal(res$var,  tnorm_var(mu = 0.4, sigma = sqrt(1.6), lower = -Inf, upper = 1.1))
})

test_that("tnorm_mixture_conditional matches plain truncated-normal moments when upper == Inf", {
  # No future tail exists beyond `upper` when upper is already Inf, so the
  # mixture should be skipped (mixture_prob == 1) even when K_i/K_pop are
  # supplied - this is the default `prepare_thresholds()` representation
  # for cases (lower = thr, upper = Inf).
  res <- tnorm_mixture_conditional(mu = 0, var = 1, lower = 1.5, upper = Inf,
                                    K_i = 0.05, K_pop = 0.10)
  expect_equal(res$mean, tnorm_mean(mu = 0, sigma = 1, lower = 1.5, upper = Inf))
  expect_equal(res$var,  tnorm_var(mu = 0, sigma = 1, lower = 1.5, upper = Inf))
})

test_that("tnorm_mixture_conditional's mixture weighting matches its documented formula for controls", {
  mu <- 0; var <- 1; lower <- -Inf; upper <- 1.2; K_i <- 0.05; K_pop <- 0.10
  cur_sigma <- sqrt(var)

  # independently recompute mixture_prob, m0/m1 and sd0/sd1 from the
  # already-verified tnorm_mean()/tnorm_var(), rather than duplicating the
  # function's own arithmetic, and check they combine to the same result.
  thr_pop <- qnorm(K_pop, lower.tail = FALSE)
  cdf_pop <- pnorm((thr_pop - mu) / cur_sigma)
  mixture_prob <- cdf_pop / (cdf_pop + (1 - cdf_pop) * (K_pop - K_i) / K_pop)

  m0 <- tnorm_mean(mu = mu, sigma = cur_sigma, lower = lower, upper = upper)
  m1 <- tnorm_mean(mu = mu, sigma = cur_sigma, lower = upper, upper = Inf)
  sd0 <- tnorm_var(mu = mu, sigma = cur_sigma, lower = lower, upper = upper)
  sd1 <- tnorm_var(mu = mu, sigma = cur_sigma, lower = upper, upper = Inf)

  expected_mean <- mixture_prob * m0 + (1 - mixture_prob) * m1
  expected_var <- mixture_prob * (m0^2 + sd0) + (1 - mixture_prob) * (m1^2 + sd1) - expected_mean^2

  res <- tnorm_mixture_conditional(mu = mu, var = var, lower = lower, upper = upper,
                                    K_i = K_i, K_pop = K_pop)
  expect_equal(res$mean, expected_mean)
  expect_equal(res$var, expected_var)

  # sanity: for an "average" individual (mu = 0, sigma = 1), mixture_prob
  # reduces to the elementary conditional probability P(never a case | not
  # a case yet) = (1 - K_pop) / (1 - K_i)
  expect_equal(mixture_prob, (1 - K_pop) / (1 - K_i))
})

test_that("tnorm_mixture_conditional's mixture weight moves toward 1 as K_i approaches K_pop", {
  # As an individual's current stratified incidence K_i approaches the
  # population lifetime prevalence K_pop, there is decreasing room left for
  # them to still convert to a case later, so weight should shift toward
  # the observed component (m0) and away from the future-tail component (m1).
  mu <- 0; var <- 1; lower <- -Inf; upper <- 1.2; K_pop <- 0.10

  probs <- sapply(c(0.01, 0.05, 0.09), function(K_i) {
    thr_pop <- qnorm(K_pop, lower.tail = FALSE)
    cdf_pop <- pnorm(thr_pop / sqrt(var))
    cdf_pop / (cdf_pop + (1 - cdf_pop) * (K_pop - K_i) / K_pop)
  })
  expect_true(all(diff(probs) > 0))
})

Try the LTFGRS package in your browser

Any scripts or data that you put into this service are public.

LTFGRS documentation built on Nov. 20, 2026, 5:10 p.m.