R/helpers_predictions.R

Defines functions plot_gee_predictions make_pred_grid

make_pred_grid <- function(di_tbl, gee_fit, level = 0.95, factors = 'trat') {

  di_tbl <- normalize_factors(di_tbl, factors = factors)

  # Grade de predicao: combinacoes dos fatores x tempos observados
  grid_values <- lapply(
    factors,
    function(nm) levels(di_tbl[[nm]])
  )
  names(grid_values) <- factors

  grid_values$time <- sort(unique(di_tbl$time))

  pred_grid <- do.call(
    expand.grid,
    c(
      grid_values,
      list(
        KEEP.OUT.ATTRS = FALSE,
        stringsAsFactors = FALSE
      )
    )
  )

  # Mantem, em cada fator, os niveis usados no ajuste
  for (nm in factors) {
    pred_grid[[nm]] <- factor(
      pred_grid[[nm]],
      levels = levels(di_tbl[[nm]])
    )
  }

  # Matriz do modelo
  tt <- stats::delete.response(stats::terms(gee_fit))

  X <- stats::model.matrix(
    tt,
    data = pred_grid,
    contrasts.arg = gee_fit$contrasts
  )

  beta <- stats::coef(gee_fit)

  # Garante mesma ordem das colunas e coeficientes
  X <- X[, names(beta), drop = FALSE]

  # Predicao na escala angular
  theta_hat <- as.numeric(X %*% beta)

  # Variancia robusta dos coeficientes do GEE
  V <- stats::vcov(gee_fit)

  se <- sqrt(
    pmax(
      0,
      diag(X %*% V %*% t(X))
    )
  )

  z <- stats::qnorm(1 - (1 - level) / 2)

  theta_lwr <- theta_hat - z * se
  theta_upr <- theta_hat + z * se

  # Limites naturais da transformacao angular
  theta_hat_clip <- pmin(pmax(theta_hat, 0), pi / 2)
  theta_lwr_clip <- pmin(pmax(theta_lwr, 0), pi / 2)
  theta_upr_clip <- pmin(pmax(theta_upr, 0), pi / 2)

  # Back-transform: DI = sin(theta)^2
  pred_grid$theta_hat <- theta_hat

  pred_grid$DI_hat <- sin(theta_hat_clip)^2
  pred_grid$DI_lwr <- sin(theta_lwr_clip)^2
  pred_grid$DI_upr <- sin(theta_upr_clip)^2

  pred_grid
}


plot_gee_predictions <- function(
  pred_grid,
  factors = 'trat',
  title = 'GEE (angular transformation) - predictions with 95% CI'
) {

  required <- c(
    factors,
    'time',
    'DI_hat',
    'DI_lwr',
    'DI_upr'
  )

  missing_cols <- setdiff(required, names(pred_grid))

  if (length(missing_cols) > 0L) {
    stop(
      'Missing required column(s): ',
      paste(missing_cols, collapse = ', '),
      call. = FALSE
    )
  }

  pred_grid <- normalize_factors(
    pred_grid,
    factors = factors
  )

  curve_factor <- factors[1L]

  g <- ggplot2::ggplot(
    pred_grid,
    ggplot2::aes(
      x = time,
      y = DI_hat,
      colour = .data[[curve_factor]],
      group = .data[[curve_factor]]
    )
  ) +
    ggplot2::geom_ribbon(
      ggplot2::aes(
        ymin = DI_lwr,
        ymax = DI_upr,
        fill = .data[[curve_factor]]
      ),
      alpha = 0.20,
      colour = NA
    ) +
    ggplot2::geom_line(linewidth = 1) +
    ggplot2::theme_minimal() +
    ggplot2::labs(
      title = title,
      x = 'Time',
      y = 'DI (0\u20131)',
      colour = if (identical(factors, 'trat')) {
        'Treatment'
      } else {
        curve_factor
      },
      fill = if (identical(factors, 'trat')) {
        'Treatment'
      } else {
        curve_factor
      }
    )

  if (length(factors) > 1L) {
    facet_factors <- factors[-1L]

    facet_formula <- stats::as.formula(
      paste('~', paste(facet_factors, collapse = ' + '))
    )

    g <- g + ggplot2::facet_wrap(facet_formula)
  }

  g
} 

Try the infectionIndex package in your browser

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

infectionIndex documentation built on Dec. 4, 2026, 5:10 p.m.