Package {HMMHSMM}


Type: Package
Title: Inference and Estimation of Hidden Markov Models and Hidden Semi-Markov Models
Version: 0.2.0
Maintainer: Ting Wang <ting.wang@otago.ac.nz>
Description: Provides flexible maximum likelihood estimation and inference for Hidden Markov Models (HMMs) and Hidden Semi-Markov Models (HSMMs), as well as the underlying systems in which they operate. The package supports a wide range of observation and dwell-time distributions, offering a flexible modelling framework suitable for diverse practical data. Efficient implementations of the forward-backward and Viterbi algorithms are provided via 'Rcpp' for enhanced computational performance. Additional functionality includes model simulation, residual analysis, non-initialised estimation, local and global decoding, calculation of diverse information criteria, computation of confidence intervals using parametric bootstrap methods, numerical covariance matrix estimation, and comprehensive visualisation functions for interpreting the data-generating processes inferred from the models. Methods follow standard approaches described by Guédon (2003) <doi:10.1198/1061860032030>, Zucchini and MacDonald (2009, ISBN:9781584885733), and O'Connell and Højsgaard (2011) <doi:10.18637/jss.v039.i04>.
License: GPL-3
Encoding: UTF-8
LazyData: true
Imports: Rcpp (≥ 1.0.0), evd, extRemes, stats, MASS, mnormt, grDevices, graphics, utils, future.apply, future, parallelly
LinkingTo: Rcpp
Depends: R (≥ 3.5.0)
Suggests: testthat (≥ 3.0.0), rcmdcheck, profvis
NeedsCompilation: yes
Config/roxygen2/version: 8.1.0
Packaged: 2026-11-30 05:24:11 UTC; aimee
Author: Aimee Cody [aut], Ting Wang [cre, ctb] (Research Supervisor)
Repository: CRAN
Date/Publication: 2026-11-30 22:40:02 UTC

Variance-Covariance Matrix for Hidden Markov Models

Description

Computes an approximate variance-covariance matrix of the parameter estimates from a fitted Hidden Markov Model (HMM) using a numerical Hessian of the log-likelihood. This function reformulates the HMM as a special case of a Hidden Semi-Markov Model (HSMM) with geometric dwell-time distributions, and calls HSMMVarianceMatrix.

Usage

HMMVarianceMatrix(x, HMM, obsdist, h = 1e-5, method = "central",
                  verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting.

obsdist

Character string naming the observation distribution used to fit HMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

h

Numeric. Step size for finite-difference approximation of the Hessian, a positive number. Default is 1e-5.

method

Character string. Method for numerical Hessian computation. Options are "central" (default, central differences) or "forward" (forward differences).

verbose

Logical, if TRUE (default), progress messages are printed to the console. Set to FALSE to suppress informational output.

Details

This function is a wrapper around HSMMVarianceMatrix, treating an HMM as a special case of an HSMM with geometric dwell-time distributions. The Hessian is computed numerically, inverted, and adjusted for positive-definiteness to provide a variance-covariance matrix for the estimated parameters.

Value

A square numeric matrix giving the approximate variance-covariance matrix of the state-dependent observation parameters only; the transition probabilities are not included. It has J p rows and columns, where J is the number of states and p is the number of parameters of obsdist, ordered parameter by parameter (all J values of the first registered parameter, then the second, and so on). Parameters are on the unconstrained (working) scale used for optimisation: a parameter registered as "log" (for example a scale or standard deviation) appears as its logarithm, and one registered as "logit" as its logit; "identity" parameters are unchanged. For obsdist = "gev" the observation parameters are therefore loc, log(scale), shape. The matrix is the inverse of the observed information (the negative Hessian of the log-likelihood), adjusted to be positive-definite.

Author(s)

Aimee Cody

See Also

generateHMM, for simulating HMM data. HSMMVarianceMatrix, for the general hidden semi-Markov case. confintHMM, for bootstrap confidence intervals of HMM parameters.
findmleHMM, for fitting Hidden Markov Models. register_obsdist, for adding custom observation distributions.

Examples

# Example with 2-state Normal HMM
J <- 2
Pi <- matrix(c(0.9, 0.1,
               0.2, 0.8), nrow = 2, byrow = TRUE)
delta <- c(0.5, 0.5)
obspar <- list(mean = c(0, 3), sd = c(1, 1))
# Simulate data
sim_data <- generateHMM(n = 100, J = J, obsdist = "norm",
                        obspar = obspar, Pi = Pi, delta = delta)
# Fit HMM
HMM_fit <- findmleHMM(x = sim_data$x, J = J,
                      obsdist = "norm", obspar = obspar,
                      Pi = Pi, delta = delta)
# Compute variance-covariance matrix
vcov_matrix <- HMMVarianceMatrix(x = sim_data$x, HMM = HMM_fit,
                                 obsdist = "norm")
vcov_matrix

Variance-Covariance Matrix for Hidden Semi-Markov Models

Description

Computes an approximate variance-covariance matrix of the parameter estimates from a fitted Hidden Semi-Markov Model (HSMM) using a numerical Hessian of the log-likelihood. The Hessian is inverted and adjusted to ensure positive-definiteness, providing an estimate of parameter uncertainty.

Usage

HSMMVarianceMatrix(x, HSMM, M = NA, obsdist, dwelldist,
                   h = 1e-5, method = "central", verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting.

M

Integer. Maximum dwell time to consider for semi-Markov states, or NA. If NA, defaults to min(length(x), 1000).

obsdist

Character string naming the observation distribution used to fit HSMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

h

Numeric. Step size for finite-difference approximation of the Hessian, a positive number. Default is 1e-5.

method

Character string. Method for numerical Hessian computation. Options are "central" (default, central differences) or "forward" (forward differences).

verbose

Logical, if TRUE (default), progress messages are printed to the console. Set to FALSE to suppress informational output.

Details

This function approximates the observed Fisher information for an HSMM by numerically differentiating the log-likelihood with respect to the model parameters. The resulting Hessian is inverted to obtain a variance-covariance matrix. Since numerical Hessians can yield non-positive-definite matrices due to rounding error or flat likelihood surfaces, the eigenvalues are adjusted to enforce positive-definiteness.

Value

A square numeric matrix giving the approximate variance-covariance matrix of the observation parameters followed by the dwell-time parameters; the transition probabilities, the initial distribution and the dwell shift are not included. It has J (p_o + p_d) rows and columns, where J is the number of states and p_o, p_d are the numbers of parameters of obsdist and dwelldist. Parameters are ordered parameter by parameter (all J values of the first registered parameter, then the second, and so on), observation parameters first. Parameters are on the unconstrained (working) scale used for optimisation: a parameter registered as "log" (for example a scale or standard deviation) appears as its logarithm, and one registered as "logit" as its logit; "identity" parameters are unchanged. For obsdist = "gev" the observation parameters are therefore loc, log(scale), shape. The matrix is the inverse of the observed information (the negative Hessian of the log-likelihood), adjusted to be positive-definite. Row and column names identify each parameter.

Author(s)

Aimee Cody

See Also

generateHSMM, for simulating HSMM data. findmleHSMM, for fitting Hidden Semi-Markov Models. HMMVarianceMatrix, for numerically computing the variance-covariance matrix of a fitted hidden Markov model. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

# Example with 2-state Normal HSMM
J <- 2
Pi <- matrix(c(0, 1,
               1, 0), nrow = 2, byrow = TRUE)
obspar <- list(mean = c(0, 3), sd = c(1, 1))
dwellpar <- list(lambda = c(5, 7))
# Simulate data
sim_data <- generateHSMM(n = 100, J = J, obsdist = "norm",
                         dwelldist = "pois", obspar = obspar,
                         dwellpar = dwellpar, Pi = Pi)
# Fit HSMM
HSMM_fit <- findmleHSMM(x = sim_data$x, J = J, M = 50,
                        obsdist = "norm", dwelldist = "pois",
                        obspar = obspar, dwellpar = dwellpar, Pi = Pi)
# Compute variance-covariance matrix
vcov_matrix <- HSMMVarianceMatrix(x = sim_data$x, HSMM = HSMM_fit,
                                  obsdist = "norm", dwelldist = "pois",
                                  M = 50)
vcov_matrix

Calculate Information Criteria for HMM/HSMM Models

Description

Computes information criteria (AIC3, AICu, HQC, BICadj) for Hidden Markov Models (HMM) or Hidden Semi-Markov Models (HSMM).

Usage

IC(data, model, type, obsdist = NULL, dwelldist = NULL, shift = NULL)

Arguments

data

Numeric vector of the observed data used to fit model (i.e. x, not the full list returned by generateHMM or generateHSMM). Its length is used as the sample size n in the AICu, HQC, and BICadj formulas.

model

An object of class "HMMHSMM_HMM" or "HMMHSMM_HSMM", as returned by findmleHMM, findmleHMMnostarting, findmleHSMM, or findmleHSMMnostarting. Which kind is present is detected automatically from the presence of dwellparameters.

type

Character string: "AIC3", "AICu", "HQC", or "BICadj". Any other value raises an error.

obsdist

Optional character string naming the observation distribution model was fit with. If supplied, the number of observation parameters per state is taken from get_obsdist(obsdist)$params rather than inferred from the structure of model itself; this is the more robust option and is recommended, particularly for custom distributions registered via register_obsdist.

dwelldist

Optional character string naming the dwell-time distribution model was fit with (only relevant when model is an HSMM). If supplied, the number of dwell parameters per state is taken from get_dwelldist(dwelldist)$params rather than inferred from model$dwellparameters.

shift

Optional logical, only used together with dwelldist. If TRUE, one extra parameter per state is counted for the dwell-time shift.

Details

Automatically detects HMM vs HSMM models based on dwellparameters presence.

Information criteria formulas:

where L is likelihood, k is number of parameters, n is sample size.

When obsdist/dwelldist are not supplied, the parameter count k is inferred from the structure of model itself; supplying them explicitly is more reliable and is recommended, especially for models fit with custom registered distributions.

Value

Numeric value of the specified information criterion.

Author(s)

Aimee Cody

Examples


J <- 3
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = J, byrow = TRUE)

obspar <- list(
  mean = c(-2, 0, 3),
  sd   = c(1, 1.5, 2)
)

dwellpar <- list(
  lambda = c(3, 5, 4)
)

sim <- generateHSMM(n = 1000, J = J, obsdist = "norm",
                    dwelldist = "pois", obspar = obspar,
                    dwellpar = dwellpar, Pi = Pi)

fit <- findmleHSMM(x = sim$x, J = J, M = 100,
                   obsdist = "norm", dwelldist = "pois",
                   obspar = obspar, dwellpar = dwellpar,
                   Pi = Pi)

AIC3 <- IC(sim$x, fit, "AIC3", obsdist = "norm", dwelldist = "pois")
AICu <- IC(sim$x, fit, "AICu", obsdist = "norm", dwelldist = "pois")
HQC <- IC(sim$x, fit, "HQC", obsdist = "norm", dwelldist = "pois")
BICadj <- IC(sim$x, fit, "BICadj", obsdist = "norm", dwelldist = "pois")



Plot Conditional Return Levels from GEV-HMM

Description

Computes and plots conditional return levels from a fitted Hidden Markov Model (HMM) with generalized extreme value (GEV) state-dependent distributions. Bootstrap confidence intervals are included. Return levels are aggregated over user-defined time periods.

Usage

conditionalreturnsHMMgev(x, HMM, return_periods = c(50, 100, 200, 500),
                         varcov = NULL, B = 10000, level = 0.95,
                         time_structure = NULL,
                         plot_title = "Return Levels Over Time", ylab = NULL,
                         save_plot = FALSE, filename = NULL,
                         width = 12, height = 8, dpi = 300,
                         verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting, fitted with obsdist = "gev". This function is specific to the GEV distribution; it checks for the presence of loc, scale, and shape in HMM$estimate and raises an error if they are missing.

return_periods

Numeric vector of positive values. Return periods (in years) for which conditional return levels are computed. Default is c(50, 100, 200, 500). Each return period is converted to a per-observation exceedance probability using the number of observations per year (see time_structure).

varcov

Optional variance–covariance matrix of parameter estimates. If NULL, computed internally via HMMVarianceMatrix with obsdist = "gev".

B

Integer. Number of bootstrap replicates used for confidence intervals, a positive integer. Default is 10000.

level

Numeric between 0 and 1 (exclusive). Confidence level for intervals. Default is 0.95.

time_structure

Optional list describing the time scale. Includes unit, observations_per_unit, and optionally start_point, end_point. Supported units: "year", "day", "hour", "week", "month", or "custom" with conversion_factor and unit_name. If unit = "year", observations_per_unit is taken as the number of observations per year (for example 365.25 for daily data or 52.18 for weekly data) and is used to convert return periods into exceedance probabilities. For any other unit, or if time_structure is NULL, the data are assumed to be weekly maxima (365.25/7 observations per year). The time axis runs from start_point to end_point. If only one of them is given the other is derived from the number of observations and observations_per_unit; if neither is given the axis starts at 0.

plot_title

Character string. Title for the plot. Default is "Return Levels Over Time".

ylab

Character string. Label for the y-axis. Default is NULL, which gives "Return level"; supply the units of your data, for example "Return level (nT/min)".

save_plot

Logical. If TRUE, the plot is saved to file. Default is FALSE.

filename

Character string or NULL. Filename for saved plot (if save_plot = TRUE). Must be specified when save_plot = TRUE. Default is NULL.

width

Numeric. Width of saved plot in inches. Default is 12.

height

Numeric. Height of saved plot in inches. Default is 8.

dpi

Integer. Resolution of saved plot in dots per inch. Default is 300.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

Details

For each state, the conditional return level for a given return period is computed from the fitted GEV parameters. Uncertainty is estimated by parametric bootstrap using draws from a multivariate normal approximation of parameter estimates. Observation-level return levels are aggregated over time periods defined by time_structure (e.g., years, weeks, months). The number of observations per year used to convert return periods into per-observation exceedance probabilities is taken from time_structure when unit = "year"; otherwise weekly data are assumed.

Value

Invisibly returns a list containing:

return_levels_states

List of matrices, one per return period, containing estimated return levels and confidence intervals for each state (3 rows: estimate, lower CI, upper CI).

return_levels_time

List of matrices, one per return period, mapping state-specific return levels to the time series.

return_periods

Numeric vector of return periods used.

time_info

List containing time axis information and labels.

A time-series plot is also produced, showing aggregated conditional return levels with bootstrap confidence intervals.

Author(s)

Aimee Cody

See Also

findmleHMM, for fitting HMMs. generateHMM, for simulating HMM data. globaldecodeHMM, for decoding the most likely state sequence. HMMVarianceMatrix, for variance–covariance estimation.

Examples

set.seed(123)
J <- 2
Pi <- matrix(c(0.9, 0.1,
               0.2, 0.8), nrow = J, byrow = TRUE)
delta <- c(0.5, 0.5)
obspar <- list(loc = c(0, 5), scale = c(1, 2), shape = c(0.1, -0.1))

sim <- generateHMM(n = 200, J = J, obsdist = "gev",
                   obspar = obspar, Pi = Pi, delta = delta)

HMM_fit <- findmleHMM(x = sim$x, J = J, obsdist = "gev",
                      obspar = obspar, Pi = Pi, delta = delta)

time_struct <- list(unit = "week", observations_per_unit = 10, start_point = 1)


result <- conditionalreturnsHMMgev(x = sim$x, HMM = HMM_fit,
                                   return_periods = c(50, 100, 200, 500),
                                   B = 1000,
                                   time_structure = time_struct,
                                   plot_title = "GEV-HMM Conditional Return Levels")

result <- conditionalreturnsHMMgev(x = sim$x, HMM = HMM_fit,
                                   return_periods = c(50, 100),
                                   B = 1000,
                                   time_structure = time_struct,
                                   save_plot = TRUE,
                                   filename = tempfile(fileext = ".png"))


Plot Conditional Return Levels from GEV-HSMM

Description

Computes and plots conditional return levels from a fitted Hidden Semi-Markov Model (HSMM) with generalized extreme value (GEV) state-dependent distributions. Bootstrap confidence intervals are included. Return levels are aggregated over user-defined time periods.

Usage

conditionalreturnsHSMMgev(x, HSMM, dwelldist, M = NA,
                          return_periods = c(50, 100, 200, 500),
                          varcov = NULL, B = 10000, level = 0.95,
                          time_structure = NULL, shift = FALSE,
                          plot_title = "Return Levels Over Time", ylab = NULL,
                          save_plot = FALSE, filename = NULL,
                          width = 12, height = 8, dpi = 300,
                          verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting, fitted with obsdist = "gev". This function is specific to the GEV distribution; it checks for the presence of loc, scale, and shape in HSMM$observationparameters and raises an error if they are missing.

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

M

Integer, or NA. Truncation parameter for the dwell-time distribution. If NA (the default), it is set automatically to min(1000, length(x)).

return_periods

Numeric vector of positive values. Return periods (in years) for which conditional return levels are computed. Default is c(50, 100, 200, 500). Each return period is converted to a per-observation exceedance probability using the number of observations per year (see time_structure).

varcov

Optional variance–covariance matrix of parameter estimates. If NULL, computed internally via HSMMVarianceMatrix with obsdist = "gev".

B

Integer. Number of bootstrap replicates used for confidence intervals, a positive integer. Default is 10000.

level

Numeric between 0 and 1 (exclusive). Confidence level for intervals. Default is 0.95.

time_structure

Optional list describing the time scale. Includes unit, observations_per_unit, and optionally start_point, end_point. Supported units: "year", "day", "hour", "week", "month", or "custom" with conversion_factor and unit_name. If unit = "year", observations_per_unit is taken as the number of observations per year (for example 365.25 for daily data or 52.18 for weekly data) and is used to convert return periods into exceedance probabilities. For any other unit, or if time_structure is NULL, the data are assumed to be weekly maxima (365.25/7 observations per year). The time axis runs from start_point to end_point. If only one of them is given the other is derived from the number of observations and observations_per_unit; if neither is given the axis starts at 0.

shift

Logical. If TRUE, uses shifted dwell-time distributions. Default is FALSE.

plot_title

Character string. Title for the plot. Default is "Return Levels Over Time".

ylab

Character string. Label for the y-axis. Default is NULL, which gives "Return level"; supply the units of your data, for example "Return level (nT/min)".

save_plot

Logical. If TRUE, the plot is saved to file. Default is FALSE.

filename

Character string or NULL. Filename for saved plot (if save_plot = TRUE). Must be specified when save_plot = TRUE. Default is NULL.

width

Numeric. Width of saved plot in inches. Default is 12.

height

Numeric. Height of saved plot in inches. Default is 8.

dpi

Integer. Resolution of saved plot in dots per inch. Default is 300.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

Details

For each state, the conditional return level for a given return period is computed from the fitted GEV parameters. Uncertainty is estimated by parametric bootstrap using draws from a multivariate normal approximation of parameter estimates. Observation-level return levels are aggregated over time periods defined by time_structure (e.g., years, weeks, months). The number of observations per year used to convert return periods into per-observation exceedance probabilities is taken from time_structure when unit = "year"; otherwise weekly data are assumed.

Value

Invisibly returns a list containing:

return_levels_states

List of matrices, one per return period, containing estimated return levels and confidence intervals for each state (3 rows: estimate, lower CI, upper CI).

return_levels_time

List of matrices, one per return period, mapping state-specific return levels to the time series.

return_periods

Numeric vector of return periods used.

time_info

List containing time axis information and labels.

A time-series plot is also produced, showing aggregated conditional return levels with bootstrap confidence intervals.

Author(s)

Aimee Cody

See Also

findmleHSMM, for fitting HSMMs. generateHSMM, for simulating HSMM data. globaldecodeHSMM, for decoding the most likely state sequence. HSMMVarianceMatrix, for variance–covariance estimation. register_dwelldist, for adding custom dwell-time distributions.

Examples

set.seed(123)

J <- 2
Pi <- matrix(c(0, 1,
               1, 0), nrow = J, byrow = TRUE)
delta <- c(0.5, 0.5)

obspar <- list(
  loc   = c(0, 5),
  scale = c(1, 2),
  shape = c(0.1, -0.1)
)

dwellpar <- list(lambda = c(5, 10))

sim <- generateHSMM(
  n = 200, J = J, obsdist = "gev", dwelldist = 'pois',
  obspar = obspar, dwellpar = dwellpar, Pi = Pi, delta = delta
)

HSMM_fit <- findmleHSMM(
  x = sim$x, J = J, obsdist = "gev", dwelldist = 'pois',
  obspar = obspar, dwellpar = dwellpar, Pi = Pi, delta = delta
)

time_struct <- list(
  unit = "week", observations_per_unit = 10, start_point = 1
)


result <- conditionalreturnsHSMMgev(
  x = sim$x, HSMM = HSMM_fit,
  return_periods = c(50, 100, 200, 500),
  dwelldist = "pois", B = 1000,
  time_structure = time_struct,
  plot_title = "GEV-HSMM Conditional Return Levels"
)

result <- conditionalreturnsHSMMgev(
  x = sim$x, HSMM = HSMM_fit,
  return_periods = c(50, 100),
  dwelldist = "pois", B = 1000,
  time_structure = time_struct,
  save_plot = TRUE,
  filename = tempfile(fileext = ".png")
)


Bootstrap Confidence Intervals for Hidden Markov Models

Description

Computes bootstrap confidence intervals for the parameters of a fitted Hidden Markov Model (HMM). The function resamples data by simulating from the fitted model, refits the HMM repeatedly to the simulated data, and constructs confidence intervals for the state-dependent parameters and the transition probability matrix.

Usage

confintHMM(x, HMM, obsdist, level = 0.95, B = 100, EM = FALSE,
           verbose = TRUE, seed = NULL, num.workers = NULL, ...)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting.

obsdist

Character string naming the observation distribution used to fit HMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

level

Numeric. Confidence level for the intervals, strictly between 0 and 1. Default is 0.95.

B

Integer. Number of bootstrap replicates to perform, a positive integer. Default is 100.

EM

Logical. Whether to use the EM algorithm during refitting. Default is FALSE.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

num.workers

Integer. Number of parallel worker processes to use, passed to future::plan(multisession, workers = num.workers). If not specified, inferred as one less than the number of available cores, but never less than 1 (so a single-core machine still uses one worker rather than failing).

...

Any other parameters that may need to be passed to findmleHMM, for example tol or maxiter.

Details

The function uses a parametric bootstrap procedure. Data are simulated from the fitted HMM using generateHMM, and parameters are re-estimated with findmleHMM. Confidence intervals are then obtained from the empirical quantiles of the bootstrap replicates. When verbose = TRUE, the function reports progress. If every bootstrap replicate fails to converge, the function raises an error rather than returning an unusable result.

Value

A list with three elements:

obspar_CI

A data frame with columns: Parameter, Estimate, Lower, and Upper, giving bootstrap confidence intervals for the observation distribution parameters.

Pi_CI

A list containing: Estimate, the estimated transition matrix from the fitted model; Lower, the lower bounds of the bootstrap confidence intervals for each transition probability; Upper, the corresponding upper bounds.

bootstrap_samples

A list containing: obspar, matrix of bootstrap samples for observation parameters; Pi, array of bootstrap samples for transition matrix; n_successful, number of successful bootstrap iterations; n_attempts, total number of attempts made.

Author(s)

Aimee Cody

See Also

findmleHMM, for estimating HMM parameters from data. generateHMM, for simulating HMM data. confintHSMM, computing bootstrapped confidence intervals for a hidden semi-Markov model. register_obsdist, for adding custom observation distributions.

Examples

J <- 2
Pi <- matrix(c(0.9, 0.1,
               0.2, 0.8), nrow = 2, byrow = TRUE)
obspar <- list(lambda = c(2, 7))
sim_data <- generateHMM(n = 1000, J = J, obsdist = "pois", obspar = obspar, Pi = Pi)
HMM_fit <- findmleHMM(J = J, x = sim_data$x, obsdist = "pois",
                      obspar = obspar, Pi = Pi, EM = FALSE)

ci <- confintHMM(x = sim_data$x, HMM = HMM_fit, obsdist = "pois",
                 B = 50, level = 0.9)
ci$obspar_CI
ci$Pi_CI
ci_silent <- confintHMM(x = sim_data$x, HMM = HMM_fit, obsdist = "pois",
                        B = 50, level = 0.9, verbose = FALSE)


Bootstrap Confidence Intervals for Hidden Semi-Markov Models

Description

Computes bootstrap confidence intervals for the parameters of a fitted Hidden Semi-Markov Model (HSMM). The function resamples data by simulation from the fitted model, refits the HSMM repeatedly, and constructs confidence intervals for the state-dependent observation parameters, dwell-time distribution parameters, and the transition probability matrix.

Usage

confintHSMM(x, HSMM, obsdist, dwelldist, level = 0.95, B = 100, M = NA,
            shift = FALSE, maxiter = 100, tol = 1e-5, verbose = TRUE, seed = NULL, 
            num.workers = NULL)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting.

obsdist

Character string naming the observation distribution used to fit HSMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

level

Numeric. Confidence level for the intervals, strictly between 0 and 1. Default is 0.95.

B

Integer. Number of bootstrap replicates to attempt, a positive integer. Default is 100.

M

Integer. Maximum dwell time to consider for semi-Markov states. If NA, defaults to min(length(x), 1000).

shift

Logical. Indicates whether the dwell-time distribution includes a user-specified shift parameter. If FALSE, a shift of 1 is applied automatically. Defaults to FALSE.

maxiter

Integer. Maximum number of EM iterations for each bootstrap refit. Default is 100.

tol

Numeric. Convergence tolerance for the EM algorithm during bootstrap refits. Default is 1e-5.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

num.workers

Integer. Number of parallel worker processes to use, passed to future::plan(multisession, workers = num.workers). If not specified, inferred as one less than the number of available cores, but never less than 1 (so a single-core machine still uses one worker rather than failing).

Details

The function uses a parametric bootstrap procedure. Data are simulated from the fitted HSMM using generateHSMM, and parameters are re-estimated with findmleHSMM. Confidence intervals are then obtained from the empirical quantiles of the bootstrap replicates. When verbose = TRUE, progress is reported. Exactly B bootstrap replicates are attempted; if an individual replicate fails to converge, it is retried internally (up to 100 attempts) before being counted as failed – additional replicates beyond B are not attempted to make up the shortfall, so the final confidence intervals may be based on fewer than B successful replicates (see bootstrap_samples$n_successful). If every replicate fails, the function raises an error rather than returning an unusable result.

Value

A list with four elements:

obspar_CI

A data frame with columns: Parameter, Estimate, Lower, and Upper, giving bootstrap confidence intervals for the observation distribution parameters.

dwellpar_CI

A data frame with columns: Parameter, Estimate, Lower, and Upper, giving bootstrap confidence intervals for the dwell-time distribution parameters.

Pi_CI

A list containing: Estimate, the estimated transition matrix from the fitted model; Lower, the lower bounds of the bootstrap confidence intervals for each transition probability; Upper, the corresponding upper bounds.

bootstrap_samples

A list containing: obspar, matrix of bootstrap samples for observation parameters; dwellpar, matrix of bootstrap samples for dwell-time parameters; Pi, array of bootstrap samples for transition matrix; n_successful, number of the B replicates that converged successfully; n_attempts, the requested number of replicates, B.

Author(s)

Aimee Cody

See Also

findmleHSMM, for estimating HSMM parameters from data. generateHSMM, for simulating HSMM data. confintHMM, computing bootstrapped confidence intervals for a hidden Markov model. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

J <- 2
Pi <- matrix(c(0, 1,
               1, 0), nrow = 2, byrow = TRUE)

obspar <- list(mean = c(4, 3), sd = c(1, 1))

dwellpar <- list(lambda = c(5, 7))

sim_data <- generateHSMM(n = 1000, J = J, obsdist = "norm",
                         dwelldist = "pois", obspar = obspar,
                         dwellpar = dwellpar, Pi = Pi)

HSMM_fit <- findmleHSMM(x = sim_data$x, J = J, M = 100,
                        obsdist = "norm", dwelldist = "pois",
                        obspar = obspar, dwellpar = dwellpar, Pi = Pi)


ci <- confintHSMM(x = sim_data$x, HSMM = HSMM_fit,
                  obsdist = "norm", dwelldist = "pois",
                  B = 50, M = 50, level = 0.9)

ci$obspar_CI
ci$dwellpar_CI
ci$Pi_CI

ci_silent <- confintHSMM(x = sim_data$x, HSMM = HSMM_fit,
                         obsdist = "norm", dwelldist = "pois",
                         B = 50, M = 50, level = 0.9, verbose = FALSE)


Daily Maxima of Geomagnetic Variation at Eskdalemuir, 2002-2005

Description

Daily maxima of the one-minute rate of change of the horizontal magnetic field recorded at the Eskdalemuir Magnetic Observatory. This is the series analysed in the HMMHSMM paper.

Usage

data(daily_maxima)

Format

A numeric vector with one value per day over 2002-2005, in nT/min.

Details

Each value is the largest one-minute change \sqrt{(\Delta x)^2 + (\Delta y)^2} within the day, computed from the minute-resolution x and y components of the field. Missing readings (coded 99999) were replaced by the mean of up to five neighbouring readings on either side.

Source

Eskdalemuir Magnetic Observatory.

Examples

data(daily_maxima)
plot(daily_maxima, xlab = "Day", ylab = "Daily maximum (nT/min)")

Plot Exceedance Probabilities from GEV-HMM

Description

Computes and plots exceedance probabilities of a given threshold from a fitted Hidden Markov Model (HMM) with generalized extreme value (GEV) state-dependent distributions. Bootstrap confidence intervals are included. Probabilities are aggregated over user-defined time periods.

Usage

exceedanceplotHMMgev(x, HMM, threshold, varcov = NULL, B = 10000, level = 0.95,
                     time_structure = NULL,
                     plot_title = "Exceedance Probabilities Over Time",
                     save_plot = FALSE, filename = NULL,
                     width = 12, height = 8, dpi = 300,
                     verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting, fitted with obsdist = "gev". This function is specific to the GEV distribution; it checks for the presence of loc, scale, and shape in HMM$estimate and raises an error if they are missing.

threshold

Numeric. A single finite value giving the exceedance threshold. Probabilities of exceeding this value are computed.

varcov

Optional variance–covariance matrix of parameter estimates. If NULL, computed internally via HMMVarianceMatrix with obsdist = "gev".

B

Integer. Number of bootstrap replicates used for confidence intervals, a positive integer. Default is 10000.

level

Numeric between 0 and 1 (exclusive). Confidence level for intervals. Default is 0.95.

time_structure

Optional list describing the time scale. Includes unit, observations_per_unit, and optionally start_point, end_point. Supported units: "year", "day", "hour", "week", "month", or "custom" with conversion_factor and unit_name. observations_per_unit is the number of observations in one aggregation period (for example 365 for daily data aggregated to years, or 52.18 for weekly data). If NULL, weekly data aggregated to years of 52 observations are assumed. Each aggregated period is labelled on the time axis: labels count up from start_point (default 1) in steps of one, or count back from end_point; if both are given the labels are spaced evenly between them.

plot_title

Character string. Title for the plot. Default is "Exceedance Probabilities Over Time".

save_plot

Logical. If TRUE, the plot is saved to file. Default is FALSE.

filename

Character string or NULL. Filename for saved plot (if save_plot = TRUE). Must be specified when save_plot = TRUE. Default is NULL.

width

Numeric. Width of saved plot in inches. Default is 12.

height

Numeric. Height of saved plot in inches. Default is 8.

dpi

Integer. Resolution of saved plot in dots per inch. Default is 300.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

Details

For each state, the exceedance probability of threshold is computed from the fitted GEV parameters. Uncertainty is estimated by parametric bootstrap using draws from a multivariate normal approximation of parameter estimates. Observation-level probabilities are aggregated over time periods defined by time_structure (e.g., years, months, weeks). When verbose = TRUE, progress messages are displayed during computation. The number of aggregation periods is floor(length(x) / observations_per_unit), so a trailing partial period is dropped; choose observations_per_unit so that it divides the series length if every observation should be used.

Value

Invisibly returns a list containing:

exceedance_probs

Matrix of exceedance probabilities over time (3 rows: estimate, lower CI, upper CI).

time_info

List containing time axis information and labels.

threshold

The threshold value used.

A time-series plot is also produced, showing aggregated exceedance probabilities with confidence intervals.

Author(s)

Aimee Cody

See Also

findmleHMM, for fitting HMMs. generateHMM, for simulating HMM data. globaldecodeHMM, for decoding the most likely state sequence. HMMVarianceMatrix, for variance–covariance estimation.

Examples

set.seed(99)
J <- 2
Pi <- matrix(c(0.9, 0.1,
               0.2, 0.8), nrow = J, byrow = TRUE)
delta <- c(0.5, 0.5)
obspar <- list(loc = c(0, 5), scale = c(1, 2), shape = c(0.1, -0.1))

sim <- generateHMM(n = 200, J = J, obsdist = "gev",
                   obspar = obspar, Pi = Pi, delta = delta)

HMM_fit <- findmleHMM(x = sim$x, J = J, obsdist = "gev",
                      obspar = obspar, Pi = Pi, delta = delta)

time_struct <- list(unit = "week", observations_per_unit = 10, start_point = 1)


result <- exceedanceplotHMMgev(x = sim$x, HMM = HMM_fit,
                               threshold = 20, B = 10000,
                               time_structure = time_struct,
                               plot_title = "GEV-HMM Exceedance Probabilities")

result <- exceedanceplotHMMgev(x = sim$x, HMM = HMM_fit,
                               threshold = 20, B = 10000,
                               time_structure = time_struct,
                               save_plot = TRUE,
                               filename = tempfile(fileext = ".png"),
                               verbose = FALSE)


Plot Exceedance Probabilities from GEV-HSMM

Description

Computes and plots exceedance probabilities of a given threshold from a fitted Hidden Semi-Markov Model (HSMM) with generalized extreme value (GEV) state-dependent distributions. Bootstrap confidence intervals are included. Probabilities are aggregated over user-defined time periods.

Usage

exceedanceplotHSMMgev(x, HSMM, threshold, dwelldist, M = NA,
                      varcov = NULL, B = 10000, level = 0.95,
                      time_structure = NULL, shift = FALSE,
                      plot_title = "Exceedance Probabilities Over Time",
                      save_plot = FALSE, filename = NULL,
                      width = 12, height = 8, dpi = 300,
                      verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting, fitted with obsdist = "gev". This function is specific to the GEV distribution; it checks for the presence of loc, scale, and shape in HSMM$observationparameters and raises an error if they are missing.

threshold

Numeric. A single finite value giving the exceedance threshold. Probabilities of exceeding this value are computed.

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

M

Integer, or NA. Truncation parameter for the dwell-time distribution. If NA (the default), it is set automatically to min(1000, length(x)).

varcov

Optional variance–covariance matrix of parameter estimates. If NULL, computed internally via HSMMVarianceMatrix with obsdist = "gev".

B

Integer. Number of bootstrap replicates used for confidence intervals, a positive integer. Default is 10000.

level

Numeric between 0 and 1 (exclusive). Confidence level for intervals. Default is 0.95.

time_structure

Optional list describing the time scale. Includes unit, observations_per_unit, and optionally start_point, end_point. Supported units: "year", "day", "hour", "week", "month", or "custom" with conversion_factor and unit_name. observations_per_unit is the number of observations in one aggregation period (for example 365 for daily data aggregated to years, or 52.18 for weekly data). If NULL, weekly data aggregated to years of 52 observations are assumed. Each aggregated period is labelled on the time axis: labels count up from start_point (default 1) in steps of one, or count back from end_point; if both are given the labels are spaced evenly between them.

shift

Logical. If TRUE, uses shifted dwell-time distributions. Default is FALSE.

plot_title

Character string. Title for the plot. Default is "Exceedance Probabilities Over Time".

save_plot

Logical. If TRUE, the plot is saved to file. Default is FALSE.

filename

Character string or NULL. Filename for saved plot (if save_plot = TRUE). Must be specified when save_plot = TRUE. Default is NULL.

width

Numeric. Width of saved plot in inches. Default is 12.

height

Numeric. Height of saved plot in inches. Default is 8.

dpi

Integer. Resolution of saved plot in dots per inch. Default is 300.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

Details

For each state, the exceedance probability of threshold is computed from the fitted GEV parameters. Uncertainty is estimated by parametric bootstrap using draws from a multivariate normal approximation of parameter estimates. Observation-level probabilities are aggregated over time periods defined by time_structure (e.g., years, months, weeks). When verbose = TRUE, progress messages are displayed during computation. The number of aggregation periods is floor(length(x) / observations_per_unit), so a trailing partial period is dropped; choose observations_per_unit so that it divides the series length if every observation should be used.

Value

Invisibly returns a list containing:

exceedance_probs

Matrix of exceedance probabilities over time (3 rows: estimate, lower CI, upper CI).

time_info

List containing time axis information and labels.

decoded_states

Vector of decoded hidden states for each time point.

time_unit

Number of observations per aggregation period.

threshold

The threshold value used.

A time-series plot is also produced, showing aggregated exceedance probabilities with confidence intervals.

Author(s)

Aimee Cody

See Also

findmleHSMM, for fitting HSMMs. generateHSMM, for simulating HSMM data. globaldecodeHSMM, for decoding the most likely state sequence. HSMMVarianceMatrix, for variance–covariance estimation. register_dwelldist, for adding custom dwell-time distributions.

Examples

set.seed(123)

J <- 2
Pi <- matrix(c(0, 1,
               1, 0), nrow = J, byrow = TRUE)
delta <- c(0.5, 0.5)

obspar <- list(
  loc   = c(0, 5),
  scale = c(1, 2),
  shape = c(0.1, -0.1)
)

dwellpar <- list(lambda = c(5, 10))

sim <- generateHSMM(
  n = 200, J = J, obsdist = "gev", dwelldist = "pois",
  obspar = obspar, dwellpar = dwellpar, Pi = Pi, delta = delta
)

HSMM_fit <- findmleHSMM(
  x = sim$x, J = J, obsdist = "gev", dwelldist = "pois",
  obspar = obspar, dwellpar = dwellpar, Pi = Pi, delta = delta
)

time_struct <- list(
  unit = "week", observations_per_unit = 10, start_point = 1
)


result <- exceedanceplotHSMMgev(
  x = sim$x, HSMM = HSMM_fit,
  threshold = 20, dwelldist = "pois",
  B = 10000, time_structure = time_struct,
  plot_title = "GEV-HSMM Exceedance Probabilities"
)

result <- exceedanceplotHSMMgev(
  x = sim$x, HSMM = HSMM_fit,
  threshold = 20, dwelldist = "pois",
  B = 10000, time_structure = time_struct,
  save_plot = TRUE,
  filename = tempfile(fileext = ".png"),
  verbose = FALSE
)


Maximum Likelihood Estimation for Hidden Markov Models

Description

Estimates the parameters of a Hidden Markov Model (HMM) using either the EM-based semi-Markov parameterisation or direct numerical maximization of the likelihood.

Usage

findmleHMM(J, x, obsdist, obspar, Pi, EM = FALSE, verbose = TRUE, seed = NULL, ...)

Arguments

J

Integer. The number of hidden states in the HMM. Must be greater than 1.

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

obsdist

Character string naming the observation distribution to use. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

obspar

List. Initial parameters for the observation distribution. Each parameter should be a vector of length J with values for each state. Required parameters depend on obsdist; for any registered distribution these can be found via names(get_obsdist(obsdist)$params). For the fifteen built-in distributions:

  • norm: mean, sd

  • pois: lambda

  • weibull: scale, shape

  • zip: lambda, pi

  • nbinom: size, mu

  • zinb: size, pi, mu

  • exp: rate

  • gamma: shape, rate

  • lnorm: meanlog, sdlog

  • gev: loc, scale, shape

  • ZInormal: mean, pi, sd

  • ZIgamma: shape, pi, rate

  • t: mu, sigma, df

  • logis: location, scale

  • bern: prob

Pi

Matrix. The J x J transition probability matrix between states. Rows must sum to 1.

EM

Logical. If TRUE, uses an EM-based semi-Markov approximation to estimate the HMM parameters. If FALSE, maximizes the likelihood directly using nlm. Defaults to FALSE.

verbose

Logical. If TRUE, progress messages are printed to the console when EM = TRUE. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

...

Further arguments to be passed in the case of EM=TRUE, such as maxiter and tol.

Details

This function fits a Hidden Markov Model to a sequence of observations using either:

The EM-based approach initializes dwell-time probabilities from the diagonal of Pi and estimates the HMM via the corresponding semi-Markov model. After fitting, transition probabilities are adjusted to incorporate self-transition probabilities. Observation distributions are looked up in an internal registry rather than hard-coded; the fifteen distributions listed under obsdist above are registered when the package loads, and register_obsdist can add further distributions (built-in or user-defined) without modifying package code. Parameter requirements vary by distribution. When verbose = TRUE and EM = TRUE, progress messages from the EM algorithm are displayed.

Value

An object of class "HMMHSMM_HMM", which has print, summary, logLik, coef, and nobs methods; AIC() and BIC() also work directly on it. Underneath, it is a list containing:

estimate

List of estimated HMM parameters, including state-dependent observation parameters and transition probabilities (Pi, delta).

loglik

The maximized log-likelihood value.

AIC

The Akaike Information Criterion for the fitted model.

BIC

Bayesian Information Criteria for the fitted model.

obsdist

The observation distribution used, as supplied.

J

The number of states, as supplied.

n

The number of observations in x.

EM

The fitting method used, as supplied.

call

The matched call used to produce this fit.

Author(s)

Aimee Cody

See Also

generateHMM for simulating HMM data. findmleHSMM for EM-based semi-Markov estimation. register_obsdist for adding custom observation distributions.

Examples

J <- 3
Pi <- matrix(c(0.8, 0.15, 0.05,
               0.1, 0.7, 0.2,
               0.2, 0.3, 0.5), nrow = 3, byrow = TRUE)

obspar <- list(
  mean = c(-2, 0, 3),
  sd = c(0.5, 1, 1.5)
)

x <- generateHMM(n = 200, J = J, obsdist = "norm",
                       obspar = obspar, Pi = Pi)$x

fit <- findmleHMM(J = J, x = x, obsdist = "norm",
                   obspar = obspar, Pi = Pi, EM = FALSE)

fit
fit$loglik
AIC(fit)

fit_em <- findmleHMM(J = J, x = x, obsdist = "norm",
                      obspar = obspar, Pi = Pi, EM = TRUE, verbose = FALSE)

Multiple Initialization Maximum Likelihood Estimation for Hidden Markov Models

Description

Fits a Hidden Markov Model (HMM) by repeatedly initializing observation and transition parameters and selecting the fit with the highest log-likelihood. This approach helps avoid convergence to poor local optima. For distributions registered with a restart_sampler (see register_obsdist; currently only the generalized extreme value distribution, "gev"), starting values are generated from repeated maximum likelihood fits on random data subsets instead.

Usage

findmleHMMnostarting(J, x, obsdist, no.initials = 50, EM = FALSE,
                     verbose = TRUE, seed = NULL, num.workers = NULL, ...)

Arguments

J

Integer. The number of hidden states in the HMM. Must be strictly greater than 1.

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

obsdist

Character string naming the observation distribution to use. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

no.initials

Integer. The number of random initializations to attempt, a positive integer. Defaults to 50.

EM

Logical. If TRUE, uses an EM-based semi-Markov approximation for estimation. If FALSE, maximizes the likelihood directly using nlm. Defaults to FALSE. For obsdist = "gev" a warning recommends EM = TRUE, since direct maximisation is slow for this distribution.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

num.workers

Integer. Number of parallel worker processes to use, passed to future::plan(multisession, workers = num.workers). If not specified, inferred as one less than the number of available cores, but never less than 1 (so a single-core machine still uses one worker rather than failing).

...

Further arguments to be passed to findmleHMM in the case of EM=TRUE.

Details

This function automates multiple trials of findmleHMM with randomized starting values, returning the fit that achieves the highest log-likelihood.

During each iteration:

  1. Observation parameters are perturbed slightly to encourage exploration.

  2. A transition matrix Pi is drawn from a random uniform distribution with added self-transition bias.

  3. The HMM is estimated via findmleHMM.

  4. If the resulting log-likelihood exceeds the current best, the model is updated.

At the end of all iterations, the best-fitting model is returned. If every attempt across every initialization fails to converge, the function raises an error rather than returning an unusable result. When fitting is parallelised, a custom observation distribution registered only in the calling session is automatically re-registered inside each worker process the first time it is needed (see register_obsdist). When verbose = TRUE, iteration numbers and error messages are displayed during the fitting process.

Value

An object of class "HMMHSMM_HMM" (see findmleHMM), corresponding to the best fit across all initializations. Underneath, it is a list containing:

estimate

List of estimated HMM parameters, including state-dependent observation parameters and transition probabilities.

loglik

The maximized log-likelihood value.

AIC

The Akaike Information Criterion for the fitted model.

BIC

Bayesian Information Criteria for the fitted model.

obsdist

The observation distribution used, as supplied.

J

The number of states, as supplied.

n

The number of observations in x.

EM

The fitting method used, as supplied.

call

The matched call used to produce the winning findmleHMM fit.

Author(s)

Aimee Cody

See Also

findmleHMM for fitting an HMM with user-supplied starting values. generateHMM for simulating HMM data. findmleHSMMnostarting for the non-initialised estimation of hidden semi-Markov models. register_obsdist for adding custom observation distributions.

Examples

set.seed(123)
J <- 3
Pi <- matrix(c(0.7, 0.2, 0.1,
               0.1, 0.8, 0.1,
               0.2, 0.3, 0.5), nrow = 3, byrow = TRUE)
obspar <- list(mean = c(-2, 0, 3),
               sd   = c(0.5, 1, 1.5))
x <- generateHMM(n = 200, J = J, Pi = Pi, obsdist = "norm", obspar = obspar)$x


fit <- findmleHMMnostarting(J = J, x = x, obsdist = "norm",
                            no.initials = 30)

fit
fit$loglik
fit$estimate

fit_silent <- findmleHMMnostarting(J = J, x = x, obsdist = "norm",
                                   no.initials = 30, verbose = FALSE)


Maximum Likelihood Estimation for Hidden Semi-Markov Models

Description

Estimates the parameters of a Hidden Semi-Markov Model (HSMM) using the EM algorithm with specified observation and dwell-time distributions.

Usage

findmleHSMM(x, J, M = NA, obsdist, dwelldist, obspar, dwellpar,
            Pi, delta = NULL, maxiter = 100, tol = 1e-05, shift = FALSE,
            verbose = TRUE, seed = NULL)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

J

Integer. The number of hidden states in the model. Must be greater than 1.

M

Integer. Maximum dwell time to consider for semi-Markov states. Defaults to min(length(x), 1000) if NA.

obsdist

Character string naming the observation distribution to use. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution to use. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

obspar

List. Parameters for the observation distribution. Each parameter must be a vector of length J, with values for each state. Required parameters depend on obsdist; for any registered distribution these can be found via names(get_obsdist(obsdist)$params). For the fifteen built-in distributions:

  • norm: mean, sd

  • pois: lambda

  • weibull: scale, shape

  • zip: lambda, pi

  • nbinom: size, mu

  • zinb: size, pi, mu

  • exp: rate

  • gamma: shape, rate

  • lnorm: meanlog, sdlog

  • gev: loc, scale, shape

  • ZInormal: mean, pi, sd

  • ZIgamma: shape, pi, rate

  • t: mu, sigma, df

  • logis: location, scale

  • bern: prob

dwellpar

List. Parameters for the dwell-time distribution. Each parameter must be a vector of length J, with values for each state. Required parameters depend on dwelldist; for any registered distribution these can be found via names(get_dwelldist(dwelldist)$params). For the five built-in dwell distributions:

  • pois: lambda

  • nbinom: size, mu

  • geom: prob

  • gamma: shape, rate

  • logarithmic: prob

A shift component is also used internally (see shift below); it does not need to be supplied unless shift = TRUE.

Pi

Matrix. The J x J transition probability matrix between states. Rows must sum to 1, and the diagonal must be zero because staying in a state is modelled by the dwell-time distribution.

delta

Numeric vector of length J. Initial state distribution. If NULL, the stationary distribution of Pi is used.

maxiter

Integer. Maximum number of EM iterations. Defaults to 100.

tol

Numeric. Convergence tolerance for the change in log-likelihood. Defaults to 1e-05.

shift

Logical. Indicates whether the dwell-time distribution includes a user-specified shift parameter. If TRUE, the distribution uses the provided shift parameter. If FALSE, the dwell-time distribution is automatically shifted by 1. Defaults to FALSE.

verbose

Logical. If TRUE, progress messages including iteration numbers and log-likelihood values are printed to the console. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

Details

This function fits a Hidden Semi-Markov Model to a sequence of observations using an EM algorithm. At each iteration, the algorithm:

Observation and dwell-time distributions are looked up in internal registries rather than hard-coded; the distributions listed under obsdist and dwelldist above are registered when the package loads, and register_obsdist/register_dwelldist can add further distributions (built-in or user-defined) without modifying package code. Fitting a custom dwell distribution requires it to be registered with a reest_fun (see register_dwelldist); custom observation distributions without a reest_fun fall back to a generic numerical M-step automatically.

When verbose = TRUE, the function displays log-likelihood values at each iteration and reports whether convergence was achieved.

Value

An object of class "HMMHSMM_HSMM", which has print, summary, logLik, coef, and nobs methods; AIC() and BIC() also work directly on it. Underneath, it is a list containing:

loglikelihoods

Numeric vector of log-likelihood values across iterations.

AIC

Akaike Information Criteria for the fitted model.

BIC

Bayesian Information Criteria for the fitted model.

delta

Numeric vector. Estimated initial state probabilities.

Pi

Matrix. Estimated J x J transition probability matrix.

dwellparameters

List. Estimated dwell-time distribution parameters.

observationparameters

List. Estimated observation distribution parameters.

obsdist

The observation distribution used, as supplied.

dwelldist

The dwell-time distribution used, as supplied.

J

The number of states, as supplied.

n

The number of observations in x.

shift

The shift setting used, as supplied.

M

The maximum dwell time used.

converged

Logical. Whether the EM algorithm converged before maxiter was reached.

call

The matched call used to produce this fit.

Author(s)

Aimee Cody

See Also

findmleHMM for Hidden Markov Model estimation. generateHSMM for simulating HSMM data. register_obsdist and register_dwelldist for adding custom distributions.

Examples


J <- 3
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = J, byrow = TRUE)

obspar <- list(
  mean = c(-2, 0, 3),
  sd   = c(1, 1.5, 2)
)

dwellpar <- list(
  lambda = c(3, 5, 4)
)

sim <- generateHSMM(n = 1000, J = J, obsdist = "norm",
                    dwelldist = "pois", obspar = obspar,
                    dwellpar = dwellpar, Pi = Pi)

fit <- findmleHSMM(x = sim$x, J = J, M = 100,
                   obsdist = "norm", dwelldist = "pois",
                   obspar = obspar, dwellpar = dwellpar,
                   Pi = Pi)

fit
fit$observationparameters
fit$dwellparameters
fit$Pi
fit$delta
fit$loglikelihoods

fit_silent <- findmleHSMM(x = sim$x, J = J, M = 100,
                          obsdist = "norm", dwelldist = "pois",
                          obspar = obspar, dwellpar = dwellpar,
                          Pi = Pi, verbose = FALSE)

Fit Hidden Semi-Markov Model (HSMM) Without User-Provided Starting Values

Description

Fits a hidden semi-Markov model (HSMM) to a univariate time series by maximum likelihood, using multiple randomly generated initializations instead of user-provided starting parameters. The best-fitting model is selected by log-likelihood.

Usage

findmleHSMMnostarting(J, x, obsdist, dwelldist, M = NA, no.initials = 50,
                      verbose = TRUE, seed = NULL, num.workers = NULL, shift = FALSE, ...)

Arguments

J

Integer, number of hidden states (must be at least 2).

x

Numeric vector, observed time series, with at least two observations and no missing or infinite values.

obsdist

Character string naming the observation distribution to use. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution to use. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

M

Integer, truncation parameter for dwell-time distribution (default NA, computed automatically).

no.initials

Integer, number of random starting values to try (default 50).

verbose

Logical, if TRUE (default), progress messages are printed to the console. Set to FALSE to suppress informational output.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

num.workers

Integer. Number of parallel worker processes to use, passed to future::plan(multisession, workers = num.workers). If not specified, inferred as one less than the number of available cores, but never less than 1 (so a single-core machine still uses one worker rather than failing).

shift

Logical. If TRUE, a shift (minimum dwell time) is also estimated for each state, and is used when initialising the starting values and in every fit. Default is FALSE, which fixes all shifts at 1.

...

Further arguments to pass to findmleHSMM, such as maxiter and tol.

Details

This function automates parameter initialization by sampling plausible random values for state-dependent observation parameters, dwell-time parameters, initial distribution \delta, and transition matrix \Pi. It repeatedly calls findmleHSMM with these initializations, and retains the model with the highest log-likelihood. If every attempt across every initialization fails to converge, the function raises an error rather than returning an unusable result. For observation distributions registered with a restart_sampler (see register_obsdist; currently only obsdist = "gev"), initial values are obtained instead via repeated calls to evd::fgev on random data segments until a sufficient number of estimates are collected; since clustering is skipped in this case, dwell-time starting values are instead derived from synthetic durations via the dwell distribution's own initializer. When fitting is parallelised, a custom observation or dwell distribution registered only in the calling session is automatically re-registered inside each worker process the first time it is needed (see register_obsdist and register_dwelldist).

Value

An object of class "HMMHSMM_HSMM" (see findmleHSMM), corresponding to the best fit across all initializations. Underneath, it is a list containing:

loglikelihoods

Numeric vector of log-likelihood values across iterations.

AIC

Akaike Information Criteria for the fitted model.

BIC

Bayesian Information Criteria for the fitted model.

delta

Numeric vector. Estimated initial state probabilities.

Pi

Matrix. Estimated J x J transition probability matrix.

dwellparameters

List. Estimated dwell-time distribution parameters.

observationparameters

List. Estimated observation distribution parameters.

obsdist

The observation distribution used, as supplied.

dwelldist

The dwell-time distribution used, as supplied.

J

The number of states, as supplied.

n

The number of observations in x.

shift

The shift setting used by the winning fit.

M

The maximum dwell time used.

converged

Logical. Whether the winning fit's EM algorithm converged.

call

The matched call used to produce the winning findmleHSMM fit.

Author(s)

Aimee Cody

See Also

findmleHSMM, for fitting an HSMM with user-supplied initial values. generateHSMM, for simulating HSMM data. findmleHMMnostarting, for the non-initialised estimation of hidden Markov models. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

set.seed(321)
J <- 3
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = J, byrow = TRUE)
obspar <- list(
  mean = c(-2, 0, 3),
  sd   = c(1, 1.5, 2)
)
dwellpar <- list(
  lambda = c(3, 5, 4)
)
sim <- generateHSMM(n = 200, J = J, obsdist = "norm",
                    dwelldist = "pois", obspar = obspar,
                    dwellpar = dwellpar, Pi = Pi)
fit <- findmleHSMMnostarting(J = J, x = sim$x,
                                       obsdist = "norm", dwelldist = "pois",
                                       M = 100, no.initials = 30)
fit
fit$observationparameters
fit$dwellparameters
fit$Pi
fit$delta
fit$loglikelihoods


Generate Data from a Hidden Markov Model

Description

Simulates observations and hidden states from a Hidden Markov Model (HMM) with specified observation distributions.

Usage

generateHMM(n, J, obsdist, obspar, Pi, delta = NULL, seed = NULL)

Arguments

n

Integer. The number of observations to generate.

J

Integer. The number of hidden states in the model.

obsdist

Character string naming the observation distribution to use. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

obspar

List. Parameters for the observation distribution. Required parameters depend on obsdist; for any registered distribution these can be found via names(get_obsdist(obsdist)$params). For the fifteen built-in distributions:

  • norm: mean, sd

  • pois: lambda

  • weibull: scale, shape

  • zip: lambda, pi

  • nbinom: size, mu

  • zinb: size, pi, mu

  • exp: rate

  • gamma: shape, rate

  • lnorm: meanlog, sdlog

  • gev: loc, scale, shape

  • ZInormal: mean, pi, sd

  • ZIgamma: shape, pi, rate

  • t: mu, sigma, df

  • logis: location, scale

  • bern: prob

Each parameter should be a vector of length J with values for each state.

Pi

Matrix. The J x J transition probability matrix between states. Rows must sum to 1.

delta

Numeric vector of length J. The initial state distribution. If NULL, the stationary distribution is computed from Pi.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

Details

This function simulates data from a Hidden Markov Model where:

Observation distributions are looked up in an internal registry rather than hard-coded; the fifteen distributions listed under obsdist above are registered when the package loads, and register_obsdist can add further distributions (built-in or user-defined) without modifying package code. The initial state is sampled according to the initial distribution delta. If delta is not provided, it is computed as the stationary distribution of the Markov chain defined by Pi.

Value

A list containing:

x

Numeric vector of the simulated observations.

state

Numeric vector of the simulated hidden state sequence.

Author(s)

Aimee Cody

See Also

generateHSMM for Hidden Semi-Markov Models. register_obsdist for adding custom observation distributions.

Examples

# Example with 3 states, normal observations
J <- 3
# HMM transition matrix
Pi <- matrix(c(0.8, 0.15, 0.05,
               0.1, 0.7,  0.2,
               0.2, 0.3,  0.5), nrow = 3, byrow = TRUE)
# Observation parameters (normal distribution)
obspar <- list(
  mean = c(-2, 0, 3),
  sd = c(0.5, 1, 1.5)
)
# Generate 200 observations
sim_data <- generateHMM(n = 200, J = J, obsdist = "norm",
                       obspar = obspar, Pi = Pi)
# View the results
head(sim_data$x)      # observations
head(sim_data$state)  # hidden states
length(sim_data$x)    # number of observations

Generate Data from a Hidden Semi-Markov Model

Description

Simulates observations and hidden states from a Hidden Semi-Markov Model (HSMM) with specified observation and dwell time distributions.

Usage

generateHSMM(n, J, obsdist, dwelldist, obspar, dwellpar, Pi,
             delta = NULL, simtype = "nobs", shift = FALSE, seed = NULL)

Arguments

n

Integer. The number of observations to generate (if simtype = "nobs") or the number of state visits (sojourns) to generate (if simtype = "nseq"), in which case the number of observations depends on the realised dwell times.

J

Integer. The number of hidden states in the model.

obsdist

Character string naming the observation distribution to use. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution to use. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

obspar

List. Parameters for the observation distribution. Required parameters depend on obsdist; for any registered distribution these can be found via names(get_obsdist(obsdist)$params). For the fifteen built-in distributions:

  • norm: mean, sd

  • pois: lambda

  • weibull: scale, shape

  • zip: lambda, pi

  • nbinom: size, mu

  • zinb: size, pi, mu

  • exp: rate

  • gamma: shape, rate

  • lnorm: meanlog, sdlog

  • gev: loc, scale, shape

  • ZInormal: mean, pi, sd

  • ZIgamma: shape, pi, rate

  • t: mu, sigma, df

  • logis: location, scale

  • bern: prob

Each parameter should be a vector of length J with values for each state.

dwellpar

List. Parameters for the dwell time distribution, plus a shift component (see shift below). Required parameters depend on dwelldist; for any registered distribution these can be found via names(get_dwelldist(dwelldist)$params). For the five built-in dwell distributions:

  • pois: lambda

  • nbinom: size, mu

  • geom: prob

  • gamma: shape, rate

  • logarithmic: prob

Each parameter (including shift) should be a vector of length J with values for each state.

Pi

Matrix. The J x J transition probability matrix between states. Rows must sum to 1, and the diagonal must be zero because staying in a state is modelled by the dwell-time distribution.

delta

Numeric vector of length J. The initial state distribution. If NULL, the stationary distribution is computed from Pi.

simtype

Character string. Either "nobs" (generate n observations) or "nseq" (generate n state sequences). Default is "nobs".

shift

Logical. If TRUE, uses the shift parameter from dwellpar. If FALSE and no shift is provided in dwellpar, sets shift to 1 for all states. Default is FALSE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

Details

This function simulates data from a Hidden Semi-Markov Model where:

Observation and dwell-time distributions are looked up in internal registries rather than hard-coded; the distributions listed under obsdist and dwelldist above are registered when the package loads, and register_obsdist/register_dwelldist can add further distributions (built-in or user-defined) without modifying package code.

When simtype = "nobs", the function generates exactly n observations. When simtype = "nseq", it generates n state sequences and the total number of observations depends on the realized dwell times.

Value

A list containing:

states

Numeric vector of the simulated hidden state sequence.

x

Numeric vector of the simulated observations.

N

Integer. The number of observations generated.

Author(s)

Aimee Cody

See Also

generateHMM for Hidden Markov Models. register_obsdist and register_dwelldist for adding custom distributions.

Examples

# Example with 3 states, normal observations, Poisson dwell times
J <- 3
# HSMM transition matrix
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = 3, byrow = TRUE)

# Observation parameters (normal distribution)
obspar <- list(
  mean = c(-2, 0, 3),
  sd = c(1, 1.5, 2)
)

# Dwell time parameters (Poisson distribution)
dwellpar <- list(
  lambda = c(3, 5, 4)
)

# Generate 100 observations
sim_data <- generateHSMM(n = 100, J = J, obsdist = "norm", dwelldist = "pois",
                        obspar = obspar, dwellpar = dwellpar, Pi = Pi)

# View the results
head(sim_data$x)        # observations
head(sim_data$states)   # hidden states
sim_data$N              # total number of observations

Global Decoding for Hidden Markov Models

Description

Computes the most likely hidden state sequence for a univariate time series using a fitted Hidden Markov Model (HMM) via global decoding (Viterbi algorithm).

Usage

globaldecodeHMM(x, HMM, obsdist)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting.

obsdist

Character string naming the observation distribution used to fit HMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

Details

This function implements global decoding for an HMM using the estimated parameters from a fitted model. It calculates the forward probabilities and recursively determines the most probable sequence of hidden states. Global decoding provides the single most likely state sequence, unlike local decoding which gives the most probable state at each time point independently. The initial state distribution is taken to be the stationary distribution of the fitted transition matrix Pi.

Value

A numeric vector of the same length as x, giving the single most likely hidden state (an integer from 1 to the number of states) at each time point.

Author(s)

Aimee Cody

See Also

findmleHMM, for estimating HMM parameters from data. generateHMM, for simulating HMM data. localdecodeHMM, for local decoding of an HMM. globaldecodeHSMM, for global decoding of a hidden semi-Markov model. register_obsdist, for adding custom observation distributions.

Examples

# Example with 3 states, normal observations
J <- 3

# HMM transition matrix
Pi <- matrix(c(0.8, 0.15, 0.05,
               0.1, 0.7, 0.2,
               0.2, 0.3, 0.5), nrow = 3, byrow = TRUE)

# Observation parameters (normal distribution)
obspar <- list(
  mean = c(-2, 0, 3),
  sd = c(0.5, 1, 1.5)
)

# Simulate HMM data
sim_data <- generateHMM(n = 200, J = J, obsdist = "norm", obspar = obspar, Pi = Pi)

# Fit HMM to simulated data
HMM_fit <- findmleHMM(J = J, x = sim_data$x, obsdist = "norm",
                       obspar = obspar, Pi = Pi, EM = FALSE)

# Compute global decoding
decoded_states <- globaldecodeHMM(x = sim_data$x, HMM = HMM_fit, obsdist = "norm")

decoded_states

Global Decoding of Hidden Semi-Markov Models

Description

Computes the most likely hidden state sequence for a univariate time series using a fitted Hidden Semi-Markov Model (HSMM) via the Viterbi algorithm.

Usage

globaldecodeHSMM(x, M = NA, HSMM, obsdist, dwelldist, shift = FALSE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

M

Integer. Maximum dwell time to consider for semi-Markov states. Defaults to min(length(x), 1000) if NA.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting.

obsdist

Character string naming the observation distribution used to fit HSMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

shift

Logical. Retained for backward compatibility but not currently used: the fitted HSMM's own dwell-time shift values (HSMM$dwellparameters$shift) are always used as-is, regardless of this argument, since they already correctly reflect how the model was fit. Defaults to FALSE.

Details

This function computes the global most probable state sequence (Viterbi path) for a sequence of observations under a Hidden Semi-Markov Model using the parameters contained in a fitted HSMM object. The function calculates observation log-probabilities, dwell-time log-probabilities, and forward log-probabilities to determine the Viterbi path.

Value

A numeric vector of length length(x), giving the most likely hidden state at each observation.

Author(s)

Aimee Cody

See Also

findmleHSMM, for estimating HSMM parameters from data. generateHSMM, for simulating HSMM data. localdecodeHSMM, for local decoding of HSMM states. globaldecodeHMM, for global decoding hidden Markov models. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

J <- 3
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = J, byrow = TRUE)

obspar <- list(
  mean = c(4, 2, 6),
  sd   = c(1, 1, 2)
)

dwellpar <- list(
  lambda = c(3, 5, 4)
)

# Simulate HSMM data
sim <- generateHSMM(n = 1000, J = J, obsdist = "norm",
                    dwelldist = "pois", obspar = obspar,
                    dwellpar = dwellpar, Pi = Pi)

# Fit HSMM using the true parameters
HSMM_true <- findmleHSMM(x = sim$x, J = J, M = 100,
                          obsdist = "norm", dwelldist = "pois",
                          obspar = obspar, dwellpar = dwellpar,
                          Pi = Pi)

# Decode states using globaldecodeHSMM
states <- globaldecodeHSMM(x = sim$x, M = 100, HSMM = HSMM_true,
                           obsdist = "norm", dwelldist = "pois")

head(states)

Local Decoding for Hidden Markov Models

Description

Computes the most likely hidden state sequence for a univariate time series using a fitted Hidden Markov Model (HMM) object via the forward-backward algorithm.

Usage

localdecodeHMM(x, HMM, obsdist)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting.

obsdist

Character string naming the observation distribution used to fit HMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

Details

This function uses the forward-backward algorithm to compute local state probabilities from a fitted Hidden Markov Model (HMM). The most probable state at each observation is returned. The initial state distribution is taken to be the stationary distribution of the fitted transition matrix Pi.

Observation distributions are looked up in an internal registry rather than hard-coded; the fifteen distributions listed under obsdist above are registered when the package loads, and register_obsdist can add further distributions (built-in or user-defined) without modifying package code.

Value

Numeric vector of length length(x), containing the most likely hidden state at each observation, computed via local decoding using the forward-backward algorithm.

Author(s)

Aimee Cody

See Also

findmleHMM, for estimating HMM parameters from data. generateHMM, for simulating HMM data. localdecodeHSMM, for local decoding of Hidden Semi-Markov Models. globaldecodeHMM, for global decoding in HMMs. register_obsdist, for adding custom observation distributions.

Examples

# Example with 3 states, normal observations
J <- 3

# HMM transition matrix
Pi <- matrix(c(0.8, 0.15, 0.05,
               0.1, 0.7, 0.2,
               0.2, 0.3, 0.5), nrow = 3, byrow = TRUE)

# Observation parameters (normal distribution)
obspar <- list(
  mean = c(-2, 0, 3),
  sd = c(0.5, 1, 1.5)
)

# Simulate HMM data
sim_data <- generateHMM(n = 200, J = J, obsdist = "norm", obspar = obspar, Pi = Pi)

# Fit HMM to simulated data
HMM_fit <- findmleHMM(J = J, x = sim_data$x, obsdist = "norm",
                       obspar = obspar, Pi = Pi, EM = FALSE)

# Compute local decoding
decoded_states <- localdecodeHMM(x = sim_data$x, HMM = HMM_fit, obsdist = "norm")

decoded_states

Local Decoding for Hidden Semi-Markov Models

Description

Computes the most likely hidden state sequence for a univariate time series using a fitted Hidden Semi-Markov Model (HSMM).

Usage

localdecodeHSMM(x, M = NA, HSMM, obsdist, dwelldist)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

M

Integer. Maximum dwell time to consider for semi-Markov states. Defaults to min(length(x), 1000) if NA.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting.

obsdist

Character string naming the observation distribution used to fit HSMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

Details

This function uses the forward-backward algorithm for HSMMs to compute local state probabilities and returns the most probable state at each time point. It supports any observation and dwell-time distribution registered via register_obsdist/register_dwelldist. The user can supply a maximum dwell-time truncation parameter M; dwell-time shift values are taken directly from HSMM$dwellparameters$shift (however HSMM was originally fit) and are not separately configurable through this function.

Value

A numeric vector of length length(x), giving the most likely hidden state at each observation, computed via local decoding.

Author(s)

Aimee Cody

See Also

findmleHSMM, for estimating HSMM parameters from data. generateHSMM, for simulating HSMM data. localdecodeHMM, for local decoding of a hidden Markov model. globaldecodeHSMM, for finding the most likely sequence of states using global decoding. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

J <- 3
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = J, byrow = TRUE)

obspar <- list(
  mean = c(-4, 0, 4),
  sd   = c(1, 0.5, 1.5)
)

dwellpar <- list(
  lambda = c(3, 5, 4)
)

# Simulate HSMM data
sim <- generateHSMM(n = 1000, J = J, obsdist = "norm",
                    dwelldist = "pois", obspar = obspar,
                    dwellpar = dwellpar, Pi = Pi)

# Fit HSMM using the true parameters
HSMM_true <- findmleHSMM(x = sim$x, J = J, M = 100,
                          obsdist = "norm", dwelldist = "pois",
                          obspar = obspar, dwellpar = dwellpar,
                          Pi = Pi)

# Decode states using localdecodeHSMM
decoded <- localdecodeHSMM(x = sim$x, HSMM = HSMM_true,
                            obsdist = "norm", dwelldist = "pois",
                            M = 100)
decoded


Plot Hidden Markov Model Parameters Over Time

Description

Plots the estimated state-dependent parameters of a fitted Hidden Markov Model (HMM) over time. Confidence intervals can be included, along with optional overlay of observed data for visual comparison.

Usage

plotHMMParameters(x, HMM, obsdist, confint_result = NULL,
                  level = 0.95, B = 100,
                  time_structure = NULL,
                  plot_title = "HMM Parameters Over Time",
                  overlay_data = NULL, overlay_label = "Data",
                  colors = c("black", "red", "blue", "green"),
                  save_plot = FALSE, filename = NULL,
                  width = 12, height = 8, dpi = 300,
                  verbose = TRUE, seed = NULL, num.workers = NULL)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting.

obsdist

Character string naming the observation distribution used to fit HMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

confint_result

Optional result from confintHMM. If not provided, confidence intervals are computed internally.

level

Numeric between 0 and 1 (exclusive). Confidence level for parameter intervals, used only if confint_result is not supplied. Default is 0.95.

B

Integer. Number of bootstrap replicates used when computing confidence intervals (if not supplied), a positive integer. Default is 100.

time_structure

Optional list specifying the time scale for plotting. May include unit, observations_per_unit, and optional start_point, end_point. Supports calendar units (e.g., "day", "year") or custom scaling. The time axis runs from start_point to end_point. If only one of them is given the other is derived from the number of observations and observations_per_unit; if neither is given the axis starts at 0.

plot_title

Character string. Title for the full parameter plot layout. Default is "HMM Parameters Over Time".

overlay_data

Optional numeric vector of length length(x). External series to overlay on parameter plots (e.g., covariates or raw data).

overlay_label

Character string. Label for overlayed data axis. Default is "Data".

colors

Character vector of plotting colors. Default is c("black", "red", "blue", "green").

save_plot

Logical. If TRUE, saves the plot to filename as a PNG file. Default is FALSE.

filename

Character string or NULL. Filename for saved plot (if save_plot = TRUE). Must be specified when save_plot = TRUE. Default is NULL.

width

Numeric. Width of saved plot in inches. Default is 12.

height

Numeric. Height of saved plot in inches. Default is 8.

dpi

Integer. Resolution of saved plot in dots per inch. Default is 300.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

num.workers

Integer or NULL. Passed through to confintHMM when confint_result is not supplied, controlling the number of parallel worker processes used for the bootstrap; see confintHMM for details. Default is NULL.

Details

For each observation, the most likely hidden state is decoded using globaldecodeHMM. The corresponding state-dependent parameters are extracted and plotted over time. If confint_result is not supplied, bootstrap confidence intervals are computed via confintHMM using its default settings, in particular direct numerical maximisation (EM = FALSE) for each refit. For a model fitted with EM = TRUE, especially with the "gev" distribution, compute the intervals yourself with confintHMM(..., EM = TRUE) and pass them in through confint_result. Custom time scaling can be applied using the time_structure argument. Overlay data (such as covariates or raw series) can be plotted on a secondary axis for comparison. When verbose = TRUE, progress messages are displayed during confidence interval computation.

Value

Invisibly returns a list containing:

param_series

List of parameter time series for each parameter.

ci_series

List of confidence interval time series (lower and upper bounds) for each parameter.

time_info

List containing time axis information and labels.

decoded_states

Vector of decoded hidden states for each time point.

The function also produces parameter trajectory plots with confidence intervals and optional overlays.

Author(s)

Aimee Cody

See Also

findmleHMM, for fitting HMMs. generateHMM, for simulating HMM data. globaldecodeHMM, for decoding the most likely state sequence. confintHMM, for bootstrap confidence intervals of HMM parameters. register_obsdist, for adding custom observation distributions.

Examples

set.seed(123)
J <- 2
Pi <- matrix(c(0.9, 0.1,
               0.2, 0.8), nrow = 2, byrow = TRUE)
delta <- c(0.5, 0.5)
obspar <- list(lambda = c(2, 7))

sim_data <- generateHMM(n = 120, J = J, obsdist = "pois",
                        obspar = obspar, Pi = Pi, delta = delta)

HMM_fit <- findmleHMM(x = sim_data$x, J = J, obsdist = "pois",
                      obspar = obspar, Pi = Pi, delta = delta)

overlay_series <- sim_data$x

time_struct <- list(unit = "day", observations_per_unit = 12, start_point = 1)


result <- plotHMMParameters(x = sim_data$x, HMM = HMM_fit, obsdist = "pois",
                            overlay_data = overlay_series,
                            overlay_label = "Observed counts",
                            time_structure = time_struct,
                            plot_title = "Poisson HMM Parameters with Overlay")

result <- plotHMMParameters(x = sim_data$x, HMM = HMM_fit, obsdist = "pois",
                            overlay_data = overlay_series,
                            overlay_label = "Observed counts",
                            time_structure = time_struct,
                            save_plot = TRUE,
                            filename = tempfile(fileext = ".png"),
                            verbose = FALSE)


Plot Hidden Semi-Markov Model Parameters Over Time

Description

Plots state-dependent observation parameters and dwell-time parameters of a fitted Hidden Semi-Markov Model (HSMM) over time. Confidence intervals can be included, with optional overlay of observed data for comparison.

Usage

plotHSMMParameters(x, HSMM, obsdist, dwelldist, confint_result = NULL,
                   level = 0.95, B = 100, M = NA, include_dwell = FALSE,
                   shift = FALSE, time_structure = NULL,
                   plot_title = "HSMM Parameters Over Time",
                   overlay_data = NULL, overlay_label = "Data",
                   colors = c("black", "red", "blue", "darkgreen"),
                   save_plot = FALSE, filename = NULL,
                   width = 12, height = 8, dpi = 300,
                   verbose = TRUE, seed = NULL, num.workers = NULL)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting.

obsdist

Character string naming the observation distribution used to fit HSMM. Any distribution registered via register_obsdist is accepted; call list_obsdists to see everything currently available. Fifteen distributions are registered by default: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

confint_result

Optional result from confintHSMM. If not provided, confidence intervals are computed internally.

level

Numeric between 0 and 1 (exclusive). Confidence level for parameter intervals, used only if confint_result is not supplied. Default is 0.95.

B

Integer. Number of bootstrap replicates for confidence intervals if not supplied, a positive integer. Default is 100.

M

Integer. Maximum dwell time used in decoding and in the bootstrap refits, or NA. Defaults to min(1000, length(x)) if NA.

include_dwell

Logical. If TRUE, the dwell parameters will also be plotted through time. Default is FALSE.

shift

Logical. Passed to confintHSMM when the confidence intervals are computed internally: if TRUE, the dwell-time shift is treated as a user-specified parameter when simulating and refitting. It has no effect on decoding, which always uses the shift values stored in HSMM, nor when confint_result is supplied. Default is FALSE.

time_structure

Optional list specifying the time scale. Must include unit, observations_per_unit, and optionally start_point, end_point. Supports calendar units ("day", "year", "hour") or custom scaling. The time axis runs from start_point to end_point. If only one of them is given the other is derived from the number of observations and observations_per_unit; if neither is given the axis starts at 0.

plot_title

Character string. Title for the full plot layout. Default is "HSMM Parameters Over Time".

overlay_data

Optional numeric vector of length length(x). External data to overlay on parameter plots.

overlay_label

Character string. Label for overlay axis. Default is "Data".

colors

Character vector of plot colors. Default is c("black", "red", "blue", "darkgreen").

save_plot

Logical. If TRUE, the plot is saved to a file. Default is FALSE.

filename

Character string. File path for saving the plot. Required if save_plot = TRUE.

width

Numeric. Width of saved plot in inches. Default is 12.

height

Numeric. Height of saved plot in inches. Default is 8.

dpi

Numeric. Resolution (dots per inch) for saved plot. Default is 300.

verbose

Logical. If TRUE, progress messages are printed to the console. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

num.workers

Integer or NULL. Passed through to confintHSMM when confint_result is not supplied, controlling the number of parallel worker processes used for the bootstrap; see confintHSMM for details. Default is NULL.

Details

The most likely hidden state sequence is decoded using globaldecodeHSMM. For each decoded state, observation and dwell-time parameters are extracted and plotted over time. If confint_result is not provided, bootstrap intervals are computed via confintHSMM. Plots include observation parameter trajectories, dwell-time parameter trajectories (if include_dwell = TRUE), and optional overlay data on secondary axes. Time scaling is configurable using time_structure. When verbose = TRUE, progress messages are displayed during confidence interval computation. If save_plot = TRUE, the plot is saved as a PNG file to the specified filename with the given dimensions and resolution.

Value

Invisibly returns a list containing:

obs_param_series

List of observation parameter time series for each parameter.

obs_ci_series

List of confidence interval time series (lower and upper bounds) for each observation parameter.

dwell_param_series

List of dwell parameter time series for each parameter (if include_dwell = TRUE).

dwell_ci_series

List of confidence interval time series for each dwell parameter (if include_dwell = TRUE).

time_info

List containing time axis information and labels.

decoded_states

Vector of decoded hidden states for each time point.

The function also generates multi-panel plots of parameter trajectories with confidence intervals and optional overlays.

Author(s)

Aimee Cody

See Also

findmleHSMM, for fitting HSMMs. generateHSMM, for simulating HSMM data. globaldecodeHSMM, for decoding the most likely state sequence. confintHSMM, for bootstrap confidence intervals of HSMM parameters. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

set.seed(42)
J <- 2
Pi <- matrix(c(0.0, 1.0,
               1.0, 0.0), nrow = J, byrow = TRUE)

obspar <- list(mean = c(0, 3), sd = c(1, 1.2))
dwellpar <- list(lambda = c(5, 8))

sim <- generateHSMM(n = 200, J = J,
                    obsdist = "norm", dwelldist = "pois",
                    obspar = obspar, dwellpar = dwellpar,
                    Pi = Pi)

HSMM_fit <- findmleHSMM(x = sim$x, J = J, M = 100,
                        obsdist = "norm", dwelldist = "pois",
                        obspar = obspar, dwellpar = dwellpar,
                        Pi = Pi)

overlay_series <- sim$x
time_struct <- list(unit = "day", observations_per_unit = 10, start_point = 1)


result <- plotHSMMParameters(x = sim$x, HSMM = HSMM_fit,
                             obsdist = "norm", dwelldist = "pois",
                             overlay_data = overlay_series,
                             overlay_label = "Observed values",
                             time_structure = time_struct,
                             plot_title = "HSMM Parameters with Overlay")

result_silent <- plotHSMMParameters(x = sim$x, HSMM = HSMM_fit,
                                    obsdist = "norm", dwelldist = "pois",
                                    include_dwell = TRUE,
                                    overlay_data = overlay_series,
                                    time_structure = time_struct,
                                    verbose = FALSE)


Register and Query Custom Dwell-Time Distributions

Description

The HSMM (Hidden Semi-Markov Model) side of the package looks up every dwell-time distribution (dwelldist argument, e.g. "pois", "geom") in an internal registry, mirroring register_obsdist for observation distributions. register_dwelldist adds a new dwell-time distribution, making it available to findmleHSMM, generateHSMM, and every other function that takes a dwelldist argument. get_dwelldist and list_dwelldists inspect the registry's current contents.

Usage

register_dwelldist(name, params, dfun, rfun, init_fun,
                    reest_fun = NULL, survivor_fun = NULL)

get_dwelldist(name)

list_dwelldists()

Arguments

name

Character string. The name used to refer to this distribution elsewhere in the package (e.g. as the dwelldist argument to findmleHSMM).

params

A named list giving each parameter of the distribution and how it should be transformed onto an unconstrained scale for optimisation, as for register_obsdist ("identity", "log", or "logit"). Do not include shift in params: it is handled separately by init_fun/reest_fun, since it is integer-valued and estimated via discrete search rather than continuous optimisation.

dfun

Probability mass function with signature function(u, par, log = TRUE), where par is a named list holding one value for each entry in params plus par$shift. Dwell times are supported on integers shift, shift+1, ..., so dfun should typically evaluate the unshifted distribution at u - par$shift. Must be vectorised over u.

rfun

Random-generation function with signature function(n, par), returning n dwell-time draws (already including the shift). Used by generateHSMM.

init_fun

Function with signature function(durations, shift) that produces starting values from a vector of observed dwell durations. shift is the logical flag passed to findmleHSMM: when FALSE, init_fun should fix shift at 1; when TRUE, it should estimate a starting shift from durations as well. Must return a named list with one value per entry in params, plus shift.

reest_fun

Optional. The EM M-step update for this dwell distribution, with signature function(eta_matrix, J, shift), where eta_matrix holds expected dwell-duration counts per state. Should return a named list with one updated value per entry in params, plus shift. Unlike register_obsdist's reest_fun, there is no generic fallback for dwell distributions – the M-step is distribution-specific enough that findmleHSMM raises a clear error if reest_fun is missing and model fitting (rather than only simulation) is attempted.

survivor_fun

Optional, currently reserved. Accepted and validated but not read anywhere else in the package: survival probabilities are always computed generically from dfun by cumulative summation. Included for forward compatibility only.

Details

As with register_obsdist, registering a distribution under a name that is already registered overwrites the existing entry and issues a warning; this includes the five dwell distributions that ship with the package ("pois", "nbinom", "geom", "gamma", "logarithmic"), registered when the package is loaded.

A dwell distribution registered without reest_fun can still be used for simulation (generateHSMM) and decoding (globaldecodeHSMM, localdecodeHSMM), which don't require an M-step; only model fitting via findmleHSMM requires it.

The same multisession self-registration described in register_obsdist applies here: a custom dwell distribution registered only in the calling session is automatically re-registered inside each parallel worker process when needed.

Functions supplied here are copied to the worker processes, so they should be self-contained: avoid relying on helper objects that exist only in your global environment (define such helpers inside the function, or in an installed package).

Value

register_dwelldist is called for its side effect and returns NULL invisibly.

get_dwelldist returns the named list stored for name (with elements params, dfun, rfun, init_fun, reest_fun, survivor_fun), or raises an informative error if name is not registered.

list_dwelldists returns a sorted character vector of every currently registered dwell distribution name.

See Also

register_obsdist for the equivalent registry used for observation distributions.

Examples

# A simple discrete-uniform dwell distribution, not built into the package
dunif_disc <- function(u, par, log = FALSE) {
  k <- max(1, round(par$k))
  p <- ifelse(u >= par$shift & u < par$shift + k, 1 / k, 0)
  if (log) log(p) else p
}
runif_disc <- function(n, par) {
  k <- max(1, round(par$k))
  par$shift + sample(0:(k - 1), n, replace = TRUE)
}

register_dwelldist(
  "unif_disc",
  params   = list(k = "log"),
  dfun     = dunif_disc,
  rfun     = runif_disc,
  init_fun = function(durations, shift) {
    s <- if (!shift) 1 else max(1, min(durations) - 1)
    list(k = max(2, diff(range(durations)) + 1), shift = s)
  }
  # no reest_fun supplied: usable for simulation/decoding, but findmleHSMM()
  # would raise a clear error if asked to fit it
)

"unif_disc" %in% list_dwelldists()

Register and Query Custom Observation Distributions

Description

HMMHSMM looks up every observation distribution (obsdist argument throughout the package, e.g. "norm", "gev") in an internal registry rather than hard-coding a fixed list. register_obsdist adds a new distribution to that registry, so it becomes available to findmleHMM, findmleHSMM, generateHMM, generateHSMM, and every other function that takes an obsdist argument, without editing any package code. get_obsdist and list_obsdists inspect the registry's current contents.

Usage

register_obsdist(name, params, dfun, rfun, init_fun,
                  restart_sampler = NULL, reest_fun = NULL, pfun = NULL)

get_obsdist(name)

list_obsdists()

Arguments

name

Character string. The name used to refer to this distribution elsewhere in the package (e.g. as the obsdist argument to findmleHMM).

params

A named list giving each parameter of the distribution and how it should be transformed onto an unconstrained scale for optimisation. Each entry must be one of "identity" (unconstrained already, e.g. a normal mean), "log" (must stay positive, e.g. a standard deviation), or "logit" (must stay in (0,1), e.g. a zero-inflation probability). The order of params determines the order states are sorted in by clusterHMM (by the first parameter listed) and the order parameters are packed in internally (e.g. by HMMVarianceMatrix).

dfun

Density function with signature function(x, par, log = TRUE), where par is a named list holding one value for each entry in params. Should return the log-density when log = TRUE (the default used throughout the package) and the density otherwise. Must be vectorised over x.

rfun

Random-generation function with signature function(n, par), returning n draws from the distribution given parameters par. Used by generateHMM and generateHSMM.

init_fun

Function with signature function(cluster_x) that produces a reasonable starting parameter list (one value per entry in params) from a vector of data believed to belong to a single state. Used by clusterHMM/clusterHSMM (internal) for cluster-based starting values.

restart_sampler

Optional. For distributions where clustering-based starting values are unreliable (currently used only by "gev"), a function with signature function(x, J, ...) that returns a closure function(J) which, when called, draws a fresh set of J plausible starting parameter values (e.g. by fitting the distribution to random segments of x and resampling the fits). Used by findmleHMMnostarting and findmleHSMMnostarting in place of clustering when supplied.

reest_fun

Optional. The EM M-step update for this distribution, with signature function(x, wt, J), where wt is a matrix of per-observation, per-state posterior weights. Should return a named list with one updated value per entry in params. If omitted, model fitting falls back to a generic numerical weighted-MLE update (generic_weighted_mle, internal) built from dfun and init_fun, which is slower but requires no extra code from the user.

pfun

Optional. The cumulative distribution function, with signature function(x, par). Required only by residualsHMM and residualsHSMM for computing ordinary (probability-integral- transform) residuals; omit it if you don't need residual diagnostics for this distribution.

Details

Registering a distribution under a name that is already registered overwrites the existing entry and issues a warning; this includes the 15 distributions that ship with the package ("norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern"), which are registered when the package is loaded.

When fitting is parallelised across multiple worker processes (as in findmleHMMnostarting, findmleHSMMnostarting, confintHMM, and confintHSMM), a distribution registered only in the calling session is automatically re-registered inside each worker process the first time it's needed, so custom distributions work correctly under parallel fitting without any extra steps.

Functions supplied here are copied to the worker processes, so they should be self-contained: avoid relying on helper objects that exist only in your global environment (define such helpers inside the function, or in an installed package).

Value

register_obsdist is called for its side effect and returns NULL invisibly.

get_obsdist returns the named list stored for name (with elements params, dfun, rfun, init_fun, restart_sampler, reest_fun, pfun), or raises an informative error if name is not registered.

list_obsdists returns a sorted character vector of every currently registered distribution name.

See Also

register_dwelldist for the equivalent registry used for HSMM dwell-time distributions.

Examples

# A Laplace (double-exponential) distribution, not built into the package
dlaplace <- function(x, mu, b, log = FALSE) {
  d <- -abs(x - mu) / b - log(2 * b)
  if (log) d else exp(d)
}
rlaplace <- function(n, mu, b) {
  u <- runif(n) - 0.5
  mu - b * sign(u) * log(1 - 2 * abs(u))
}

register_obsdist(
  "laplace",
  params   = list(mu = "identity", b = "log"),
  dfun     = function(x, par, log = TRUE) dlaplace(x, par$mu, par$b, log = log),
  rfun     = function(n, par) rlaplace(n, par$mu, par$b),
  init_fun = function(cluster_x) list(mu = median(cluster_x),
                                       b = mean(abs(cluster_x - median(cluster_x))))
)

"laplace" %in% list_obsdists()

# now usable anywhere obsdist is accepted, e.g.:
Pi <- matrix(c(0.9, 0.1, 0.15, 0.85), 2, 2, byrow = TRUE)
obspar <- list(mu = c(0, 10), b = c(1, 2))
sim <- generateHMM(200, J = 2, obsdist = "laplace", obspar = obspar, Pi = Pi, seed = 1)

Ordinary Residuals for Hidden Markov Models

Description

Computes ordinary (probability integral transform) residuals for a fitted Hidden Markov Model (HMM). Generates quantile-quantile and autocorrelation plots for assessing model fit.

Usage

residualsHMM(x, HMM, obsdist, lag.max = 50, verbose = TRUE)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HMM

An object of class "HMMHSMM_HMM", as returned by findmleHMM or findmleHMMnostarting.

obsdist

Character string naming the observation distribution used to fit HMM. Any distribution registered via register_obsdist is accepted, provided it was registered with a pfun (cumulative distribution function) – required for computing these residuals. All fifteen default distributions have one registered: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

lag.max

Integer. Maximum lag for autocorrelation function (ACF) computation, a positive integer. Default is 50.

verbose

Logical. If TRUE, prints proportion of residuals outside 95% interval. Default is TRUE.

Details

The function computes probability integral transform (PIT) residuals for HMM observations by combining forward and backward probabilities with the cumulative distribution functions of the state-dependent observations. The residuals are assessed via:

This provides a visual check of model adequacy, where ideally residuals should behave as independent standard normal variables. When verbose = TRUE, the proportion of residuals outside the 95% interval is printed.

Value

Invisibly returns a list containing:

residuals

Vector of ordinary residuals.

probabilities

Vector of probability integral transform values.

qq_bands

List containing median, lower, and upper quantiles for QQ plot confidence bands.

acf_values

ACF object containing autocorrelation values.

acf_bands

List containing lower and upper confidence bands for ACF plot.

proportion_outside

Numeric value indicating the proportion of residuals outside the 95% interval.

The function also produces diagnostic plots:

Author(s)

Aimee Cody

See Also

findmleHMM, for fitting HMMs. generateHMM, for simulating HMM data. residualsHSMM, for residual analysis of hidden semi-Markov models. register_obsdist, for adding custom observation distributions (including a pfun, needed for this function).

Examples

J <- 2
Pi <- matrix(c(0.9, 0.1,
               0.2, 0.8), nrow = 2, byrow = TRUE)
delta <- c(0.5, 0.5)
obspar <- list(lambda = c(2, 7))

sim_data <- generateHMM(n = 200, J = J, obsdist = "pois", obspar = obspar, Pi = Pi, delta = delta)

HMM_fit <- findmleHMM(x = sim_data$x, J = J, obsdist = "pois",
                      obspar = obspar, Pi = Pi, delta = delta)

result <- residualsHMM(x = sim_data$x, HMM = HMM_fit, obsdist = "pois", lag.max = 30)

result_silent <- residualsHMM(x = sim_data$x, HMM = HMM_fit, obsdist = "pois",
                              lag.max = 30, verbose = FALSE)


Ordinary Residuals for Hidden Semi-Markov Models

Description

Computes ordinary (probability integral transform) residuals for a fitted Hidden Semi-Markov Model (HSMM). Generates quantile-quantile and autocorrelation plots for assessing model fit via simulation-based envelopes.

Usage

residualsHSMM(x, HSMM, obsdist, dwelldist, M = NA, lag.max = 50, nsim = 100,
              use.theoretical.acf = FALSE, verbose = TRUE, seed = NULL)

Arguments

x

Numeric vector. The observed data sequence, with at least two observations and no missing or infinite values.

HSMM

An object of class "HMMHSMM_HSMM", as returned by findmleHSMM or findmleHSMMnostarting.

obsdist

Character string naming the observation distribution used to fit HSMM. Any distribution registered via register_obsdist is accepted, provided it was registered with a pfun (cumulative distribution function) – required for computing these residuals. All fifteen default distributions have one registered: "norm", "pois", "weibull", "zip", "nbinom", "zinb", "exp", "gamma", "lnorm", "gev", "ZInormal", "ZIgamma", "t", "logis", "bern".

dwelldist

Character string naming the dwell-time distribution used to fit HSMM. Any distribution registered via register_dwelldist is accepted; call list_dwelldists to see everything currently available. Five distributions are registered by default: "pois", "nbinom", "geom", "gamma", "logarithmic".

M

Integer. Maximum dwell time to consider for semi-Markov states, or NA. Defaults to min(1000, length(x)) if NA.

lag.max

Integer. Maximum lag for autocorrelation function (ACF) computation, a positive integer. Default is 50.

nsim

Integer. Number of simulated datasets to generate for constructing the residual envelope, a positive integer. Default is 100.

use.theoretical.acf

Logical. If TRUE, uses theoretical 95% ACF bands for white noise instead of simulation-based envelope. Default is FALSE.

verbose

Logical. If TRUE, prints progress messages during simulation and diagnostic summaries. Default is TRUE.

seed

Integer or NULL. Random seed for reproducibility. Default is NULL.

Details

The function computes probability integral transform (PIT) residuals for HSMM observations by combining forward-backward probabilities with cumulative distribution functions of the state-dependent observations and dwell-time distributions. Residuals are assessed via:

This provides a visual check of model adequacy, where ideally residuals behave as independent standard normal variables.

Value

Invisibly returns a list containing:

residuals

Vector of ordinary residuals for the observed data.

qq_envelope

List containing median, lower, and upper simulation-based quantiles for the QQ plot envelope.

acf_values

ACF object containing autocorrelation values for the observed residuals.

acf_envelope

List containing lower and upper bounds for the ACF plot envelope (simulation-based, or theoretical if use.theoretical.acf = TRUE).

proportion_outside

Numeric value indicating the proportion of residuals outside the simulation-based 95% QQ envelope.

n_successful_sims

Integer. The number of the nsim requested simulations that successfully produced residuals.

The function also produces diagnostic plots:

Author(s)

Aimee Cody

See Also

findmleHSMM, for estimating HSMM parameters from data. generateHSMM, for simulating HSMM data. residualsHMM, for residual analysis of hidden Markov models. register_obsdist and register_dwelldist, for adding custom distributions.

Examples

J <- 3
Pi <- matrix(c(0.0, 0.6, 0.4,
               0.5, 0.0, 0.5,
               0.3, 0.7, 0.0), nrow = J, byrow = TRUE)
obspar <- list(
  mean = c(-2, 0, 3),
  sd   = c(1, 1.5, 2)
)
dwellpar <- list(
  lambda = c(3, 5, 4)
)
# Simulate HSMM data
sim <- generateHSMM(n = 200, J = J, obsdist = "norm",
                    dwelldist = "pois", obspar = obspar,
                    dwellpar = dwellpar, Pi = Pi)
# Fit HSMM using the true parameters
HSMM_true <- findmleHSMM(x = sim$x, J = J, M = 100,
                          obsdist = "norm", dwelldist = "pois",
                          obspar = obspar, dwellpar = dwellpar,
                          Pi = Pi)
# Compute residuals and diagnostic plots
residualsHSMM(x = sim$x, HSMM = HSMM_true,
              obsdist = "norm", dwelldist = "pois",
              M = 100, nsim = 50, lag.max = 30)