R/hhh4_tidy.R

Defines functions glance.hhh4

Documented in glance.hhh4

################################################################################
### Create a 'tidy' table of fitted "hhh4" parameters
###
### Copyright (C) 2025-2026 Sebastian Meyer
###
### This file is part of the R package "surveillance",
### free software under the terms of the GNU General Public License, version 2,
### a copy of which is available at https://www.R-project.org/Licenses/.
################################################################################

tidy.hhh4 <- function (x, effects = c("fixed", "random"),
                       idx2Exp = NULL, # or TRUE or an index vector
                       amplitudeShift = FALSE, # omits freq, so needs opt-in
                       conf.int = FALSE, conf.level = 0.95, ...)
{
    chkDots(...)

    allEffects <- c("fixed", "random", "ri")
    effects <- match.arg(effects, c(allEffects,
                                    "ran_pars", "ran_vals"), # = 'broom.mixed'
                         several.ok = TRUE)
    effects[effects == "ran_pars"] <- "random"
    effects[effects == "ran_vals"] <- "ri"

    ## "conditional" fixef() and ranef() parameters are processed jointly
    if (any(c("fixed", "ri") %in% effects)) {
        result <- coef(x, se = TRUE, idx2Exp = idx2Exp, # via delta method
                       amplitudeShift = amplitudeShift)
        colnames(result) <- c("estimate", "std.error") # 'broom' convention
        exp. <- startsWith(rownames(result), "exp(")
        if (conf.int) {
            ## Could transform raw CIs for idx2Exp to avoid negative limits,
            ## but we use what confint() provides, also for amplitudeShift.
            cis <- confint(x, level = conf.level,
                           idx2Exp = idx2Exp, # or NULL and exp-transform below
                           amplitudeShift = amplitudeShift)
            colnames(cis) <- c("conf.low", "conf.high") # 'broom' convention
            ## if (any(exp.)) cis[exp.,] <- exp(cis[exp.,])
            result <- cbind(result, cis)
        }
        keys <- rbind(
            .hhh4tab_fixef(x, amplitudeShift = amplitudeShift),
            .hhh4tab_ranef(x)
        )
        result <- cbind(keys, "exp" = exp., result)
        if ("fixed" %in% effects && (x$dim[["random"]] > 0)) {
            ## intercepts should come first in each component: move ri() up
            result <- result[order(cumsum(!duplicated(result$component)),
                                   result$term != "(Intercept)"), ]
        }
        result <- result[result$effect %in% effects, ]
    } else
        result <- NULL

    ## add "sd.corr" parameters of random intercepts
    if ("random" %in% effects && (x$dim[["random"]] > 0)) {
        risd <- sqrt(diag(x$Sigma))
        if (length(x$Sigma.orig) > length(risd)) # FIXME
            warning("\"random\" currently omits correlation parameters")
        rilogsdSE <- if (is.matrix(x$Sigma.cov)) # not a "try-error"
            sqrt(diag(x$Sigma.cov)[seq_along(risd)]) # exclude corr pars
        else NA_real_
        rikeys <- do.call(rbind, strsplit(names(risd), ".", fixed = TRUE))
        ri <- data.frame("component" = rikeys[,1L], "effect" = "random",
                         "term" = "SD (Intercept)",
                         "unit" = NA_character_, "exp" = NA,
                         "estimate" = risd, "std.error" = risd * rilogsdSE,
                         row.names = NULL, check.names = FALSE)
        if (conf.int) { # TODO?
            ri <- cbind(ri, "conf.low" = NA_real_, "conf.high" = NA_real_)
        }
        result <- rbind(result, ri)
    }

    ## drop superfluous metadata
    rownames(result) <- NULL
    if (all(is.na(result$unit))) # no unit-specific effects/dispersion
        result$unit <- NULL
    if (all(result$effect == "fixed"))
        result$effect <- NULL
    if (!any(result$exp, na.rm = TRUE))
        result$exp <- NULL
    result
}

## create index columns for the fixed effects (fe, neweights, overdisp)
.hhh4tab_fixef <- function (object, amplitudeShift = FALSE)
{
    model <- terms(object)
    names_terms <- unlist(model$terms["name",])
    ## move ".UNIT" suffix of 'unitSpecific' terms into 'unit' column
    units_terms <- colnames(model$response)[
        unlist(lapply(model$terms["which",], function (x)
            if (is.null(x)) NA_integer_ else which(x)))
    ]
    if (any(withUnit <- !is.na(units_terms))) {
        .stop <- nchar(names_terms) - ifelse(withUnit, nchar(units_terms)+1L, 0L)
        names_terms <- substr(names_terms, 1L, .stop)
    }
    names_terms[names_terms %in% c("1", "ri(iid)", "ri(car)")] <- "(Intercept)"
    if (amplitudeShift) {
        names_theta <- names(model$initialTheta)
        idxAS <- getCoefIdxRenamed(names_theta, amplitudeShift = TRUE)$AS
        names_terms[idxAS] <- paste0(
            rep_len(c("amplitude", "shift"), length(idxAS)), ".",
            as.integer(sub(".*\\(([0-9]+).*", "\\1", names_terms[idxAS])) / 2
        )
    }
    comp_terms <- rep(unlist(model$terms["offsetComp",]),
                      unlist(model$terms["dim.fe",]))
    ## names_weights <- sub("^neweights\\.", "",
    ##                      names_theta[model$nFE + seq_len(model$nd)])
    names_weights <- names(coefW(object))
    result <- data.frame(
        "component" = c(names(model$offset)[comp_terms],
                        rep("weights", model$nd),
                        rep("dispersion", model$nOverdisp)),
        "effect" = "fixed",
        "term" = c(names_terms, names_weights,
                   rep("overdisp", model$nOverdisp)),
        "unit" = c(units_terms, rep(NA_character_, model$nd),
                   if (model$nOverdisp > 1L) levels(model$indexPsi)
                   else rep(NA_character_, model$nOverdisp)),
        row.names = NULL, check.names = FALSE
    )
    result
}

## create index columns for the random intercepts
.hhh4tab_ranef <- function (object)
{
    names_ri <- tail(names(object$coefficients), object$dim[2L])
    if (length(names_ri) == 0) return(NULL)
    m <- regexec("^([^.]+)\\.([^.]+)\\.(.+)$", names_ri)
    tab <- do.call(rbind, regmatches(names_ri, m))[,-1L]
    result <- data.frame(
        "component" = tab[,1L], # =~ model$terms["offsetComp",model$indexRE]
        "effect" = "ri",
        "term" = tab[,2L],
        "unit" = tab[,3L],
        row.names = NULL, check.names = FALSE
    )
    result
}


## mainly for 'modelsummary'
glance.hhh4 <- function(x, ...)
{
    ## using names from modelsummary::gof_map
    criteria <- list(
        converged = x$convergence,  # FIXME: warn from here if not?
        logLik = x$loglikelihood,   # if with ri(): actually 'penLogLik'
        AIC = AIC(x), BIC = BIC(x), #               and these will be NA
        MAE = mean(abs(residuals(x, type = "response"))),
        ## RMSE = sqrt(mean(residuals(x, "response")^2)), # skewed ...
        nobs = x$nObs, #x[c("nTime", "nUnit")],
        npar = sum(x$dim)
        ## FIXME: Include "empirical" proportions of mean components?
        ## epiprop = sum(predict(x, type="epidemic")) / sum(fitted(x))
    )
    as.data.frame(criteria, row.names = NULL, check.names = FALSE)  # list2DF()
}

Try the surveillance package in your browser

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

surveillance documentation built on Dec. 3, 2026, 5:09 p.m.