| 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 |
obsdist |
Character string naming the observation distribution used
to fit |
h |
Numeric. Step size for finite-difference approximation of the Hessian, a positive number.
Default is |
method |
Character string. Method for numerical Hessian computation.
Options are |
verbose |
Logical, if |
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 |
M |
Integer. Maximum dwell time to consider for semi-Markov states, or |
obsdist |
Character string naming the observation distribution used
to fit |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
h |
Numeric. Step size for finite-difference approximation of the Hessian, a positive number.
Default is |
method |
Character string. Method for numerical Hessian computation.
Options are |
verbose |
Logical, if |
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 |
An object of class |
type |
Character string: |
obsdist |
Optional character string naming the observation
distribution |
dwelldist |
Optional character string naming the dwell-time
distribution |
shift |
Optional logical, only used together with |
Details
Automatically detects HMM vs HSMM models based on dwellparameters presence.
Information criteria formulas:
-
AIC3:
-2 \log L + 3k -
AICu: Unbiased AIC with finite sample correction
-
HQC:
-2 \log L + 2k \log(\log n) -
BICadj:
-2 \log L + k \log n - k \log(2\pi)
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 |
return_periods |
Numeric vector of positive values. Return periods (in years) for which conditional return levels are computed. Default is |
varcov |
Optional variance–covariance matrix of parameter estimates.
If |
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 |
plot_title |
Character string. Title for the plot. Default is "Return Levels Over Time". |
ylab |
Character string. Label for the y-axis. Default is |
save_plot |
Logical. If |
filename |
Character string or |
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 |
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 |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
M |
Integer, or |
return_periods |
Numeric vector of positive values. Return periods (in years) for which conditional return levels are computed. Default is |
varcov |
Optional variance–covariance matrix of parameter estimates.
If |
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 |
shift |
Logical. If |
plot_title |
Character string. Title for the plot. Default is "Return Levels Over Time". |
ylab |
Character string. Label for the y-axis. Default is |
save_plot |
Logical. If |
filename |
Character string or |
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 |
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 |
obsdist |
Character string naming the observation distribution used
to fit |
level |
Numeric. Confidence level for the intervals, strictly between 0 and 1. Default is |
B |
Integer. Number of bootstrap replicates to perform, a positive integer. Default is |
EM |
Logical. Whether to use the EM algorithm during refitting. Default is |
verbose |
Logical. If |
seed |
Integer or |
num.workers |
Integer. Number of parallel worker processes to use,
passed to |
... |
Any other parameters that may need to be passed to |
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:
|
Pi_CI |
A list containing:
|
bootstrap_samples |
A list containing:
|
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 |
obsdist |
Character string naming the observation distribution used
to fit |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
level |
Numeric. Confidence level for the intervals, strictly between 0 and 1. Default is |
B |
Integer. Number of bootstrap replicates to attempt, a positive integer. Default is |
M |
Integer. Maximum dwell time to consider for semi-Markov states.
If |
shift |
Logical. Indicates whether the dwell-time distribution includes a user-specified shift parameter.
If |
maxiter |
Integer. Maximum number of EM iterations for each bootstrap refit. Default is |
tol |
Numeric. Convergence tolerance for the EM algorithm during bootstrap refits. Default is |
verbose |
Logical. If |
seed |
Integer or |
num.workers |
Integer. Number of parallel worker processes to use,
passed to |
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:
|
dwellpar_CI |
A data frame with columns:
|
Pi_CI |
A list containing:
|
bootstrap_samples |
A list containing:
|
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 |
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 |
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 |
plot_title |
Character string. Title for the plot. Default is "Exceedance Probabilities Over Time". |
save_plot |
Logical. If |
filename |
Character string or |
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 |
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 |
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 |
M |
Integer, or |
varcov |
Optional variance–covariance matrix of parameter estimates.
If |
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 |
shift |
Logical. If |
plot_title |
Character string. Title for the plot. Default is "Exceedance Probabilities Over Time". |
save_plot |
Logical. If |
filename |
Character string or |
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 |
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 |
obspar |
List. Initial parameters for the observation distribution.
Each parameter should be a vector of length
|
Pi |
Matrix. The |
EM |
Logical. If |
verbose |
Logical. If |
seed |
Integer or |
... |
Further arguments to be passed in the case of |
Details
This function fits a Hidden Markov Model to a sequence of observations using either:
An EM-based approximation via a semi-Markov model when
EM = TRUEDirect numerical maximization of the likelihood using
nlmwhenEM = FALSE
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 ( |
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 |
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 |
no.initials |
Integer. The number of random initializations to attempt, a positive integer. Defaults to 50. |
EM |
Logical. If |
verbose |
Logical. If |
seed |
Integer or |
num.workers |
Integer. Number of parallel worker processes to use,
passed to |
... |
Further arguments to be passed to |
Details
This function automates multiple trials of findmleHMM with randomized starting values, returning the fit that achieves the highest log-likelihood.
For most observation distributions, starting values are generated via
clusterHMM.For distributions registered with a
restart_sampler(currently only"gev"), starting values are drawn instead from repeated fits ofevd::fgevon random data segments. Up to 20,000 attempts are made, and a warning is issued if fewer than 1000 valid estimates are obtained.
During each iteration:
Observation parameters are perturbed slightly to encourage exploration.
A transition matrix
Piis drawn from a random uniform distribution with added self-transition bias.The HMM is estimated via
findmleHMM.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 |
EM |
The fitting method used, as supplied. |
call |
The matched call used to produce the winning |
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 |
obsdist |
Character string naming the observation distribution to use.
Any distribution registered via |
dwelldist |
Character string naming the dwell-time distribution to
use. Any distribution registered via |
obspar |
List. Parameters for the observation distribution. Each
parameter must be a vector of length
|
dwellpar |
List. Parameters for the dwell-time distribution. Each
parameter must be a vector of length
A |
Pi |
Matrix. The |
delta |
Numeric vector of length |
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 |
verbose |
Logical. If |
seed |
Integer or |
Details
This function fits a Hidden Semi-Markov Model to a sequence of observations using an EM algorithm. At each iteration, the algorithm:
Computes observation probabilities for each state
Calculates dwell-time probabilities and survival functions
Performs a forward-backward-like procedure to estimate expected sufficient statistics
Re-estimates observation and dwell-time parameters
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 |
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 |
shift |
The |
M |
The maximum dwell time used. |
converged |
Logical. Whether the EM algorithm converged before |
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 |
dwelldist |
Character string naming the dwell-time distribution to
use. Any distribution registered via |
M |
Integer, truncation parameter for dwell-time distribution (default |
no.initials |
Integer, number of random starting values to try (default 50). |
verbose |
Logical, if |
seed |
Integer or |
num.workers |
Integer. Number of parallel worker processes to use,
passed to |
shift |
Logical. If |
... |
Further arguments to pass to |
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 |
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 |
shift |
The |
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 |
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 |
obspar |
List. Parameters for the observation distribution. Required
parameters depend on
Each parameter should be a vector of length |
Pi |
Matrix. The |
delta |
Numeric vector of length |
seed |
Integer or |
Details
This function simulates data from a Hidden Markov Model where:
Hidden states follow a discrete-time Markov chain with transition matrix
PiAt each time step, observations are generated from state-dependent distributions
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 |
J |
Integer. The number of hidden states in the model. |
obsdist |
Character string naming the observation distribution to use.
Any distribution registered via |
dwelldist |
Character string naming the dwell-time distribution to
use. Any distribution registered via |
obspar |
List. Parameters for the observation distribution. Required
parameters depend on
Each parameter should be a vector of length |
dwellpar |
List. Parameters for the dwell time distribution, plus a
Each parameter (including |
Pi |
Matrix. The |
delta |
Numeric vector of length |
simtype |
Character string. Either "nobs" (generate |
shift |
Logical. If |
seed |
Integer or |
Details
This function simulates data from a Hidden Semi-Markov Model where:
Hidden states follow a Markov chain with transition matrix
PiEach state has an associated dwell time distribution that determines how long the process remains in that state
Observations are generated from state-dependent distributions
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 |
obsdist |
Character string naming the observation distribution used
to fit |
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 |
HSMM |
An object of class |
obsdist |
Character string naming the observation distribution used
to fit |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
shift |
Logical. Retained for backward compatibility but not
currently used: the fitted |
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 |
obsdist |
Character string naming the observation distribution used
to fit |
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 |
HSMM |
An object of class |
obsdist |
Character string naming the observation distribution used
to fit |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
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 |
obsdist |
Character string naming the observation distribution used
to fit |
confint_result |
Optional result from |
level |
Numeric between 0 and 1 (exclusive). Confidence level for parameter intervals, used only if |
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 |
plot_title |
Character string. Title for the full parameter plot layout. Default is "HMM Parameters Over Time". |
overlay_data |
Optional numeric vector of length |
overlay_label |
Character string. Label for overlayed data axis. Default is "Data". |
colors |
Character vector of plotting colors. Default is |
save_plot |
Logical. If |
filename |
Character string or |
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 |
seed |
Integer or |
num.workers |
Integer or |
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 |
obsdist |
Character string naming the observation distribution used
to fit |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
confint_result |
Optional result from |
level |
Numeric between 0 and 1 (exclusive). Confidence level for parameter intervals, used only if |
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 |
include_dwell |
Logical. If |
shift |
Logical. Passed to |
time_structure |
Optional list specifying the time scale.
Must include |
plot_title |
Character string. Title for the full plot layout. Default is "HSMM Parameters Over Time". |
overlay_data |
Optional numeric vector of length |
overlay_label |
Character string. Label for overlay axis. Default is "Data". |
colors |
Character vector of plot colors. Default is |
save_plot |
Logical. If |
filename |
Character string. File path for saving the plot. Required if |
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 |
seed |
Integer or |
num.workers |
Integer or |
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 |
dwell_ci_series |
List of confidence interval time series for each dwell parameter (if |
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 |
params |
A named list giving each parameter of the distribution and how
it should be transformed onto an unconstrained scale for optimisation, as
for |
dfun |
Probability mass function with signature
|
rfun |
Random-generation function with signature |
init_fun |
Function with signature |
reest_fun |
Optional. The EM M-step update for this dwell distribution,
with signature |
survivor_fun |
Optional, currently reserved. Accepted and validated but
not read anywhere else in the package: survival probabilities are always
computed generically from |
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 |
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 |
dfun |
Density function with signature |
rfun |
Random-generation function with signature |
init_fun |
Function with signature |
restart_sampler |
Optional. For distributions where clustering-based
starting values are unreliable (currently used only by |
reest_fun |
Optional. The EM M-step update for this distribution, with
signature |
pfun |
Optional. The cumulative distribution function, with signature
|
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 |
obsdist |
Character string naming the observation distribution used
to fit |
lag.max |
Integer. Maximum lag for autocorrelation function (ACF) computation, a positive integer. Default is 50. |
verbose |
Logical. If |
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:
QQ plots comparing observed residuals to the expected standard normal distribution.
Autocorrelation function plots to detect remaining temporal dependence.
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:
Generates a QQ plot of ordinary residuals against expected standard normal quantiles, with 95% confidence intervals.
Generates an ACF plot of the ordinary residuals with approximate 95% confidence bands.
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 |
obsdist |
Character string naming the observation distribution used
to fit |
dwelldist |
Character string naming the dwell-time distribution used
to fit |
M |
Integer. Maximum dwell time to consider for semi-Markov states, or |
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 |
verbose |
Logical. If |
seed |
Integer or |
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:
QQ plots comparing observed residuals to the expected standard normal distribution with a 95% simulation-based envelope.
Autocorrelation function plots to detect remaining temporal dependence with simulation-based or theoretical 95% bands.
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 |
proportion_outside |
Numeric value indicating the proportion of residuals outside the simulation-based 95% QQ envelope. |
n_successful_sims |
Integer. The number of the |
The function also produces diagnostic plots:
A QQ plot of ordinary residuals against a simulation-based envelope, rather than a fixed theoretical distribution.
An ACF plot of the ordinary residuals with a simulation-based or theoretical envelope.
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)