tests/testthat/test-id_post_pred.R

# Tests for id_post_pred function
options(cmdstanr_warn_inits = FALSE)
# Function existence and signature tests ----

test_that("id_post_pred generic exists", {
  expect_true(isGeneric("id_post_pred"))
})

test_that("id_post_pred method exists for idealstan class", {
  methods <- showMethods("id_post_pred", printTo = FALSE)
  expect_true(any(grepl("idealstan", methods)))
})

test_that("id_post_pred has expected parameters", {
  # Get the method for idealstan - note that S4 methods may show only
  # generic params in formals(), but additional params are in the method body
  method <- selectMethod("id_post_pred", "idealstan")
  args <- names(formals(method))

  expect_true("object" %in% args)
  # Additional parameters (draws, output, type) are defined in the method body
  # and passed via ..., so we just check that ... is available
  expect_true("..." %in% args)
})

# Parameter documentation tests ----

test_that("id_post_pred output parameter accepts expected values", {
  # Document expected output types
  valid_outputs <- c("observed", "missing", "all")
  expect_true(length(valid_outputs) > 0)
})

test_that("id_post_pred type parameter accepts expected values", {
  # Document expected type values
  valid_types <- c("predict", "log_lik")
  expect_true(length(valid_types) > 0)
})

# Error handling tests ----

test_that("id_post_pred requires idealstan object", {
  skip_on_cran()

  expect_error(
    id_post_pred("not_an_idealstan"),
    class = "error"
  )

  expect_error(
    id_post_pred(data.frame(x = 1)),
    class = "error"
  )
})

# Posterior predictions against the data ----

# fit a small simulated model; 30 persons answer each item, more than the 10
# draws used below, so that draws and observations can't be confused
fit_sim <- function(model_type, sim_type, ...) {
  set.seed(4)
  sim <- id_sim_gen(num_person = 30, num_items = 10, model_type = sim_type,
                    inflate = model_type %% 2 == 0, ...)
  suppressMessages(suppressWarnings(
    id_estimate(sim, model_type = model_type, use_method = "pathfinder", ncores = 1,
                fixtype = "prefix", restrict_ind_high = 1, restrict_ind_low = 2, seed = 1)
  ))
}

pred_sim <- function(fit, ...) {
  suppressMessages(suppressWarnings(capture.output(
    out <- id_post_pred(fit, draws = 10, ...)
  )))
  out
}

# the outcome, as passed to Stan, of each column of the predictions
pred_outcome <- function(pred) {
  unlist(lapply(unlist(pred, recursive = FALSE), function(p) attr(p, "data")$outcome))
}

pred_matrix <- function(pred) {
  do.call(cbind, unlist(pred, recursive = FALSE))
}

test_that("binary predictions are coded as the outcome is", {
  skip_on_cran()
  skip_if_not_installed("cmdstanr")

  fit <- fit_sim(1, "binary")
  pred <- pred_sim(fit)
  y <- pred_outcome(pred)

  expect_equal(dim(pred_matrix(pred)), c(10, length(y)))
  expect_setequal(unique(as.numeric(pred_matrix(pred))), c(0, 1))
  expect_setequal(unique(y), c(0, 1))

  # the plot has the categories of the data only
  g <- suppressMessages(id_plot_ppc(fit, ppc_pred = pred))
  expect_setequal(g$data$x, c(0, 1))
})

test_that("inflated binary and latent-space predictions code missing values as the data do", {
  skip_on_cran()
  skip_if_not_installed("cmdstanr")

  for(model in c(2, 14)) {
    fit <- fit_sim(model, "binary", latent_space = model == 14)
    y <- pred_outcome(pred_sim(fit, output = "all"))
    miss_val <- fit@this_data$y_int_miss

    # by default, the predictions include the missing category
    pred <- pred_sim(fit)
    expect_equal(unique(sapply(unlist(pred, recursive = FALSE), attr, "output")), "all")
    expect_setequal(unique(as.numeric(pred_matrix(pred))), c(0, 1, miss_val))
    g <- suppressMessages(id_plot_ppc(fit, ppc_pred = pred))
    expect_setequal(g$data$x, c(0, 1, miss_val))
    expect_error(suppressMessages(id_plot_ppc(fit, ppc_pred = pred, observed_only = TRUE)),
                 "output='observed'")

    # the observed outcomes only
    obs <- pred_sim(fit, output = "observed")
    expect_setequal(unique(as.numeric(pred_matrix(obs))), c(0, 1))
    g <- suppressMessages(id_plot_ppc(fit, ppc_pred = obs, observed_only = TRUE))
    expect_setequal(g$data$x, c(0, 1))
    expect_equal(sum(g$data$y_obs), sum(y != miss_val))

    # whether each outcome is missing
    miss <- pred_sim(fit, output = "missing")
    g <- suppressMessages(id_plot_ppc(fit, ppc_pred = miss))
    expect_equal(g$data$y_obs[g$data$x == 1], sum(y == miss_val))
  }
})

test_that("ordinal and Poisson predictions have one row per draw", {
  skip_on_cran()
  skip_if_not_installed("cmdstanr")

  fit <- fit_sim(4, "ordinal_ratingscale")
  pred <- pred_sim(fit)
  y <- pred_outcome(pred)
  expect_equal(dim(pred_matrix(pred)), c(10, length(y)))
  expect_setequal(unique(as.numeric(pred_matrix(pred))), unique(y))

  obs <- pred_sim(fit, output = "observed")
  expect_true(all(pred_matrix(obs) %in% 1:3))

  fit <- fit_sim(8, "poisson")
  miss <- pred_sim(fit, output = "missing")
  expect_equal(dim(pred_matrix(miss)), c(10, length(pred_outcome(miss))))
  expect_true(all(pred_matrix(miss) %in% c(0, 1)))

  expect_error(pred_sim(fit, output = "both"), "must be one of")
})

test_that("id_plot_ppc subsets by person and item", {
  skip_on_cran()
  skip_if_not_installed("cmdstanr")

  fit <- fit_sim(1, "binary")
  pred <- pred_sim(fit)

  g <- suppressMessages(id_plot_ppc(fit, ppc_pred = pred, group = c("1", "2")))
  expect_setequal(as.character(g$data$group), c("1", "2"))
  # each person answers all 10 items
  expect_equal(sum(g$data$y_obs), 20)

  g <- suppressMessages(id_plot_ppc(fit, ppc_pred = pred, item = "3"))
  expect_equal(sum(g$data$y_obs), 30)

  # the plots are printed as well as returned
  grDevices::pdf(NULL)
  on.exit(grDevices::dev.off(), add = TRUE)
  plots <- suppressMessages(id_plot_ppc(fit, ppc_pred = pred, item = c("3", "4"),
                                        combine_item = FALSE, prompt_plot = FALSE))
  expect_named(plots, c("3", "4"))
  expect_s3_class(plots[[1]], "ggplot")

  # predictions of some items only
  sub <- pred_sim(fit, item_subset = c("3", "4"))
  expect_length(unlist(sub, recursive = FALSE), 2)
})

Try the idealstan package in your browser

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

idealstan documentation built on Dec. 2, 2026, 5:07 p.m.