| Title: | Regularized Point Processes and Stochastic Marginalization for Extremes |
|---|---|
| Description: | Implements a non-stationary extreme value analysis framework by coupling a covariate-driven non-homogeneous Poisson process (NHPP) with (adaptive) elastic-net regularization and analytical gradients. Provides methods for estimating conditional return levels and unconditional (marginalized) return levels via parametric stochastic integration over stable vector autoregressive VAR(p) covariate trajectories, or non-parametric annual-block resampling. Supports block-specific penalty controls, BIC selection along a regularization path, Karush-Kuhn-Tucker convergence checks, time-rescaling residual diagnostics, conditional parametric bootstrap inference, and walk-forward assessment. |
| Authors: | Rodrigo Fonseca Villa [aut, cre] (ORCID: <https://orcid.org/0009-0005-2938-2270>) |
| Maintainer: | Rodrigo Fonseca Villa <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 0.4.0 |
| Built: | 2026-10-13 19:37:18 UTC |
| Source: | https://github.com/rodrigosqrt3/margevt |
Returns the covariate names that appear in the model with a non-negligible
coefficient - i.e. those that actually affect the parameters and need to
be supplied during marginalization. Seasonal harmonic columns
(cos<k>, sin<k>, sen<k>) are always excluded.
active_covariates(fit, free_cols = NULL, tol = NULL)active_covariates(fit, free_cols = NULL, tol = NULL)
fit |
An |
free_cols |
Character vector of column names to always exclude from
the result (intercept and seasonality terms are always excluded).
Default |
tol |
Numeric. Coefficients smaller than this in absolute value are
treated as zero. If |
Character vector of active covariate names, or NULL if
the model has no active non-seasonal covariates.
set.seed(1) df <- data.frame(x = rnorm(2000), z = rnorm(2000)) df$y <- 10 + 2 * df$x + rexp(2000, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = c("x", "z"), penalty = "lasso", lambda = 5, verbose = FALSE) active_covariates(fit)set.seed(1) df <- data.frame(x = rnorm(2000), z = rnorm(2000)) df$y <- 10 + 2 * df$x + rexp(2000, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = c("x", "z"), penalty = "lasso", lambda = 5, verbose = FALSE) active_covariates(fit)
Evaluates predictive performance of a fitted nhpp_fit model via
walk-forward cross-validation. For each window, the model is refit on
training data at the original penalty and lambda, return levels are
computed, and exceedance rates are compared to nominal rates via
binomial tests. A Kolmogorov-Smirnov comparison on tail-conditional PIT
values is returned as an exploratory diagnostic; it is not a formal test
of global predictive calibration. Validation years with fewer than
min_obs_year observed values are excluded from binomial denominators.
backtest( fit, data, varname, TRs = c(2, 5, 10), n_obs = NULL, period = NULL, window_years = 5L, min_train_years = 10L, n_boot = 200L, interactions = list(), year_col = "year", min_obs_year = NULL, seed = 2024L, trend_col = NULL, fixed = list(), reselect_lambda = FALSE, cores = 1L, verbose = TRUE )backtest( fit, data, varname, TRs = c(2, 5, 10), n_obs = NULL, period = NULL, window_years = 5L, min_train_years = 10L, n_boot = 200L, interactions = list(), year_col = "year", min_obs_year = NULL, seed = 2024L, trend_col = NULL, fixed = list(), reselect_lambda = FALSE, cores = 1L, verbose = TRUE )
fit |
An |
data |
The data frame used to fit |
varname |
Character. Name of the column in |
TRs |
Numeric vector of return periods to evaluate. Default
|
n_obs |
Integer observations per year. If |
period |
Numeric seasonal period in observations. If |
window_years |
Integer. Width of each validation window in years.
Default |
min_train_years |
Integer. Minimum number of training years before
the first validation window. Default |
n_boot |
Integer. Bootstrap years for covariate marginalization
within each window. Default |
interactions |
Named list of interactions passed to
|
year_col |
Character. Name of the year column. Default |
min_obs_year |
Integer. Minimum observations in a validation year
for it to be included. Default |
seed |
Integer. Seed used for empirical annual-block sampling.
Default |
trend_col |
Optional name of a linear time-trend covariate. Within
each window it is recomputed as |
fixed |
Named list of scalar covariate values imposed on every
covariate block (see |
reselect_lambda |
Logical. If |
cores |
Positive integer number of worker processes over which the
windows are distributed. Results do not depend on |
verbose |
Logical. Print progress. Default |
A list with three elements:
results |
Data frame with one row per validation year, containing the observed annual maximum, PIT value, and exceedance indicators for each return period. |
binom_tests |
Data frame with nominal binomial comparisons for each
TR. The |
ks_test |
Data frame with the exploratory tail-conditional PIT
KS comparison, including |
set.seed(1) n_years <- 30; n_obs <- 50 df <- data.frame(x = rnorm(n_years * n_obs), year = rep(1991:2020, each = n_obs)) df$y <- 5 + df$x + rexp(nrow(df), 1 / 2) fit <- fit_nhpp(df, threshold = 10, loc_vars = "x", penalty = "none", obs_per_year = n_obs, verbose = FALSE) bt <- backtest(fit, df, varname = "y", TRs = c(2, 5), n_obs = n_obs, window_years = 5, min_train_years = 15, n_boot = 50, verbose = FALSE) bt$binom_testsset.seed(1) n_years <- 30; n_obs <- 50 df <- data.frame(x = rnorm(n_years * n_obs), year = rep(1991:2020, each = n_obs)) df$y <- 5 + df$x + rexp(nrow(df), 1 / 2) fit <- fit_nhpp(df, threshold = 10, loc_vars = "x", penalty = "none", obs_per_year = n_obs, verbose = FALSE) bt <- backtest(fit, df, varname = "y", TRs = c(2, 5), n_obs = n_obs, window_years = 5, min_train_years = 15, n_boot = 50, verbose = FALSE) bt$binom_tests
Computes , where is the unpenalized
log-likelihood at the operational estimator, the number of active
parameters, and the number of exceedances. Equivalent to
BIC(fit) for fits produced by margEVT 0.4.0 or later.
bic_nhpp(fit, tol = NULL)bic_nhpp(fit, tol = NULL)
fit |
An |
tol |
Numeric. Coefficients smaller than this are counted as zero
for the active parameter count. If |
Numeric scalar. BIC value.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) bic_nhpp(fit)set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) bic_nhpp(fit)
Simulates R bootstrap samples, refits at the original penalty,
lambda, and penalty weights, and returns empirical percentile intervals
for each operational coefficient. See bootstrap_rl for the
resampling scheme and the random-number streams.
bootstrap_coef( fit, data, R = 200L, level = 0.95, seed = 42L, cores = 1L, verbose = TRUE )bootstrap_coef( fit, data, R = 200L, level = 0.95, seed = 42L, cores = 1L, verbose = TRUE )
fit |
An |
data |
The data frame used to fit |
R |
Integer. Number of bootstrap replicates. Default |
level |
Numeric. Confidence level. Default |
seed |
Seed of the replicate streams, or |
cores |
Positive integer number of worker processes. Default |
verbose |
Logical. Print progress. Default |
A data frame with columns parameter, estimate,
CI_low, CI_high, n_ok, with one row for every
coefficient in the fitted model. Intervals require at least five
successful replicates. The replicate matrix is attached as attribute
"replicates".
set.seed(1) df <- data.frame(x = rnorm(1500)) df$y <- 10 + df$x + rexp(1500, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", verbose = FALSE) bootstrap_coef(fit, df, R = 50, verbose = FALSE)set.seed(1) df <- data.frame(x = rnorm(1500)) df$y <- 10 + df$x + rexp(1500, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", verbose = FALSE) bootstrap_coef(fit, df, R = 50, verbose = FALSE)
Simulates R bootstrap samples from the fitted model, refits at the
original model design, penalty, lambda, penalty weights, and activity
tolerance (starting from the original estimate), recomputes return levels
via marginalize, and returns empirical percentile intervals.
Exceedance count and times are held fixed, so the result is a nominal
conditional summary rather than unconditional or post-selection
inference.
bootstrap_rl( fit, data, TRs = c(2, 5, 10, 20, 50, 100), R = 200L, approach = "C", marginalize_args = list(), level = 0.95, seed = 42L, cores = 1L, verbose = TRUE )bootstrap_rl( fit, data, TRs = c(2, 5, 10, 20, 50, 100), R = 200L, approach = "C", marginalize_args = list(), level = 0.95, seed = 42L, cores = 1L, verbose = TRUE )
fit |
An |
data |
The data frame used to fit |
TRs |
Numeric vector of return periods. Default |
R |
Integer. Number of bootstrap replicates. Default |
approach |
Character. Which marginalization approach to use for each
replicate: |
marginalize_args |
Named list of additional arguments passed to
|
level |
Numeric. Confidence level. Default |
seed |
Seed of the replicate streams, or |
cores |
Positive integer number of worker processes. Default |
verbose |
Logical. Print progress. Default |
Each replicate uses its own L'Ecuyer-CMRG random-number stream derived
from seed, so the output does not depend on cores. The
caller's random-number state is left untouched when seed is
supplied.
A data frame with columns TR, RL_est (the return
level from the original fitted model under the requested approach),
CI_low, CI_high, n_ok (number of successful
replicates). The R x length(TRs) matrix of replicate return
levels is attached as attribute "replicates".
set.seed(1) df <- data.frame(x = rnorm(1500)) df$y <- 10 + df$x + rexp(1500, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", verbose = FALSE) bootstrap_rl(fit, df, TRs = c(10, 50), R = 50, approach = "A", verbose = FALSE)set.seed(1) df <- data.frame(x = rnorm(1500)) df$y <- 10 + df$x + rexp(1500, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", verbose = FALSE) bootstrap_rl(fit, df, TRs = c(10, 50), R = 50, approach = "A", verbose = FALSE)
Constructs a data frame with n_obs rows containing all columns
required by a fitted nhpp_fit model. The default seasonal columns
(cos1, sen1, cos2, sen2) and any other
harmonic column required by the model (cos<k>, sin<k>,
sen<k>) are computed automatically with period (see
seasonal_harmonics). Any other required column is filled from
cov_vals, or set to zero with a warning if absent.
build_cov_annual( fit, cov_vals = list(), n_obs = NULL, period = NULL, interactions = list() )build_cov_annual( fit, cov_vals = list(), n_obs = NULL, period = NULL, interactions = list() )
fit |
An |
cov_vals |
Named list of covariate values. Each element is either
a scalar (replicated to |
n_obs |
Integer number of rows (time points) to generate. If
|
period |
Numeric seasonal period in observations. If |
interactions |
Named list of length-2 character vectors declaring
interaction columns to compute. Each element is
|
A data frame with n_obs rows and all columns required
by fit.
set.seed(1) n <- 3650 df <- cbind(data.frame(x = rnorm(n)), seasonal_harmonics(rep(1:365, 10))) df$y <- 10 + df$x + 3 * df$cos1 + rexp(n, 1 / 3) fit <- fit_nhpp(df, threshold = 20, loc_vars = c("x", "cos1", "sen1"), free_vars = c("cos1", "sen1"), penalty = "none", verbose = FALSE) head(build_cov_annual(fit, list(x = 0.5), n_obs = 365))set.seed(1) n <- 3650 df <- cbind(data.frame(x = rnorm(n)), seasonal_harmonics(rep(1:365, 10))) df$y <- 10 + df$x + 3 * df$cos1 + rexp(n, 1 / 3) fit <- fit_nhpp(df, threshold = 20, loc_vars = c("x", "cos1", "sen1"), free_vars = c("cos1", "sen1"), penalty = "none", verbose = FALSE) head(build_cov_annual(fit, list(x = 0.5), n_obs = 365))
Build design matrices for the NHPP point process model
build_design_matrices( df, loc_vars = NULL, scale_vars = NULL, shape_vars = NULL, free_vars = NULL )build_design_matrices( df, loc_vars = NULL, scale_vars = NULL, shape_vars = NULL, free_vars = NULL )
df |
A data frame containing all required columns. |
loc_vars |
Character vector of covariate names for the location (mu) parameter. |
scale_vars |
Character vector of covariate names for the scale (sigma) parameter. |
shape_vars |
Character vector of covariate names for the shape (xi) parameter. |
free_vars |
Character vector of column names that should never be penalized
(e.g. seasonality terms like |
A list with elements:
X_mu |
Design matrix for location. |
X_sigma |
Design matrix for scale. |
X_xi |
Design matrix for shape. |
idx_pen_mu |
Integer indices of penalized columns in X_mu. |
idx_pen_sigma |
Integer indices of penalized columns in X_sigma. |
idx_pen_xi |
Integer indices of penalized columns in X_xi. |
df <- cbind(data.frame(y = rexp(10), x = rnorm(10)), seasonal_harmonics(1:10)) dm <- build_design_matrices(df, loc_vars = c("x", "cos1", "sen1"), scale_vars = "x", free_vars = c("cos1", "sen1")) colnames(dm$X_mu) dm$idx_pen_mudf <- cbind(data.frame(y = rexp(10), x = rnorm(10)), seasonal_harmonics(1:10)) dm <- build_design_matrices(df, loc_vars = c("x", "cos1", "sen1"), scale_vars = "x", free_vars = c("cos1", "sen1")) colnames(dm$X_mu) dm$idx_pen_mu
Extract coefficients of a fitted nhpp_fit model
## S3 method for class 'nhpp_fit' coef(object, operational = FALSE, ...)## S3 method for class 'nhpp_fit' coef(object, operational = FALSE, ...)
object |
An |
operational |
Logical. If |
... |
Ignored. |
Named numeric vector of coefficients.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) coef(fit)set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) coef(fit)
Fits a peaks-over-threshold point process model via penalized maximum
likelihood with quasi-Newton optimization and exact analytical gradients.
The location, log-scale, and shape parameters are linear in the supplied
covariates; seasonal harmonics and other free_vars are never
penalized.
fit_nhpp( df, threshold, loc_vars = NULL, scale_vars = NULL, shape_vars = NULL, free_vars = NULL, penalty = c("none", "lasso", "ridge", "elnet"), alpha = 0.5, lambda = "bic", penalize_shape = TRUE, obs_per_year = 365.25, active_tol = 0.01, lambda_scaling = c("common", "gradient"), penalty_weights = "none", adaptive_gamma = 1, lambda_grid = NULL, init = NULL, grad_tol = 5e-04, maxit = 10000L, calc_hessian = FALSE, verbose = TRUE )fit_nhpp( df, threshold, loc_vars = NULL, scale_vars = NULL, shape_vars = NULL, free_vars = NULL, penalty = c("none", "lasso", "ridge", "elnet"), alpha = 0.5, lambda = "bic", penalize_shape = TRUE, obs_per_year = 365.25, active_tol = 0.01, lambda_scaling = c("common", "gradient"), penalty_weights = "none", adaptive_gamma = 1, lambda_grid = NULL, init = NULL, grad_tol = 5e-04, maxit = 10000L, calc_hessian = FALSE, verbose = TRUE )
df |
A data frame containing the response and all covariates.
Must have a column named |
threshold |
Numeric scalar. The extreme value threshold u. |
loc_vars |
Character vector of covariate names for the location
parameter. |
scale_vars |
Character vector of covariate names for the log-scale
parameter. |
shape_vars |
Character vector of covariate names for the shape
parameter. |
free_vars |
Character vector of covariate names that are never
penalized (e.g. seasonality terms). |
penalty |
Character. Penalty type: |
alpha |
Numeric in [0, 1]. Elastic-net mixing parameter.
Only used when |
lambda |
Numeric scalar or named vector |
penalize_shape |
Logical. Penalize shape parameter covariates?
Default |
obs_per_year |
Numeric. Observations per year. E.g. |
active_tol |
Positive numeric tolerance used for BIC complexity
counting, active-covariate extraction, and default coefficient reporting.
Default |
lambda_scaling |
Character. Scaling used when |
penalty_weights |
Coordinate weights multiplying |
adaptive_gamma |
Positive exponent |
lambda_grid |
Optional decreasing numeric vector of base penalties used for BIC selection instead of the default two-phase grid. |
init |
Optional numeric starting vector, one entry per parameter. |
grad_tol |
Positive tolerance for the KKT violation divided by the
number of exceedances. Default |
maxit |
Integer. Maximum optimizer iterations. Default |
calc_hessian |
Logical. Compute the Hessian of the penalized
objective at the solution? Default |
verbose |
Logical. Print progress during BIC grid search and
convergence warnings. Default |
Convergence is assessed with the Karush-Kuhn-Tucker (KKT) conditions of
the smoothed elastic-net objective: unpenalized and active coordinates
must have a near-zero gradient, while penalized coordinates numerically at
zero must satisfy the subgradient condition. The violation is scaled by
the number of exceedances and compared with grad_tol.
When lambda = "bic", the regularization path is evaluated on a
coarse grid followed by a refined grid around the provisional optimum (or
on a user-supplied lambda_grid). The returned model is the path
solution at the selected penalty, so the reported fit is exactly the one
scored by the BIC.
An object of class nhpp_fit. Besides the smooth optimizer
solution (par) and the operational activity-thresholded solution
(par_oper), it stores the penalty weights, the scaled KKT
violation (kkt), and, for lambda = "bic", the evaluated
regularization path (path).
marginalize, bootstrap_coef,
plot.nhpp_fit
set.seed(42) n <- 2000 df <- data.frame(x1 = rnorm(n), x2 = rnorm(n)) df$y <- 10 + 2 * df$x1 + rexp(n, 1 / 3) # Unpenalized stationary-shape model fit0 <- fit_nhpp(df, threshold = 18, loc_vars = c("x1", "x2"), penalty = "none", verbose = FALSE) coef(fit0) # Adaptive LASSO with BIC-selected penalty fit <- fit_nhpp(df, threshold = 18, loc_vars = c("x1", "x2"), penalty = "lasso", lambda = "bic", penalty_weights = "adaptive", verbose = FALSE) summary(fit)set.seed(42) n <- 2000 df <- data.frame(x1 = rnorm(n), x2 = rnorm(n)) df$y <- 10 + 2 * df$x1 + rexp(n, 1 / 3) # Unpenalized stationary-shape model fit0 <- fit_nhpp(df, threshold = 18, loc_vars = c("x1", "x2"), penalty = "none", verbose = FALSE) coef(fit0) # Adaptive LASSO with BIC-selected penalty fit <- fit_nhpp(df, threshold = 18, loc_vars = c("x1", "x2"), penalty = "lasso", lambda = "bic", penalty_weights = "adaptive", verbose = FALSE) summary(fit)
Deseasonalizes each base variable by OLS on n_harmonics Fourier
harmonic pairs, standardizes the residuals, and fits a stable
vector autoregression VAR(p) without intercept by least squares, with the
order selected by the Schwarz criterion on a common estimation sample
(the convention of vars::VARselect). A univariate base variable
gives a stable AR(p) model.
fit_var_generator( fit, data, vars = NULL, period = NULL, lag_max = NULL, n_harmonics = 2L, derive = NULL, derive_lead = 0L )fit_var_generator( fit, data, vars = NULL, period = NULL, lag_max = NULL, n_harmonics = 2L, derive = NULL, derive_lead = 0L )
fit |
An |
data |
Data frame containing the base variables (and, optionally, seasonal harmonic columns). |
vars |
Character vector of base variables. Default |
period |
Numeric seasonal period in observations. If |
lag_max |
Integer. Maximum VAR order considered. Default |
n_harmonics |
Positive integer number of harmonic pairs used for
deseasonalization. Default |
derive |
Optional function taking a data frame of simulated base variables (plus the harmonic columns) for one trajectory and returning a data frame with the same number of rows containing the model covariates. |
derive_lead |
Non-negative integer number of leading observations
simulated before each year so that |
By default the base variables are the active covariates of fit.
When model covariates are deterministic transformations of a smaller set
of base variables (lags, rolling means, differences, interactions,
standardizations), supply the base variables in vars and a
derive function: simulate_covariates then simulates
the base variables and recomputes the model covariates on each
trajectory, preserving their deterministic relations.
Seasonal harmonics present in data (cos<k>, sen<k> or
sin<k>) are reused; otherwise they are computed from the row index,
which assumes contiguous rows starting at the first position of a year.
An object of class nhpp_var_generator, including the
coefficient matrix, innovation covariance, root moduli and spectral
radius, or NULL (with a warning) if there are no variables to
model. An unstable selected VAR causes an error.
set.seed(1) n <- 3650 t <- rep(1:365, 10) x <- as.numeric(stats::arima.sim(list(ar = 0.7), n)) + 2 * cos(2 * pi * t / 365.25) df <- cbind(data.frame(x = x), seasonal_harmonics(t)) df$y <- 10 + df$x + rexp(n, 1 / 3) fit <- fit_nhpp(df, threshold = 20, loc_vars = "x", penalty = "none", verbose = FALSE) gen <- fit_var_generator(fit, df) gen$p_opt gen$spectral_radius # Model covariates derived from a base variable: the lagged value of x df$x_lag1 <- c(NA, head(df$x, -1)) gen_d <- fit_var_generator( fit, df[-1, ], vars = "x", derive_lead = 1, derive = function(b) data.frame(x = b$x, x_lag1 = c(NA, head(b$x, -1)))) head(simulate_covariates(gen_d, n_mc = 2, seed = 1)[[1]])set.seed(1) n <- 3650 t <- rep(1:365, 10) x <- as.numeric(stats::arima.sim(list(ar = 0.7), n)) + 2 * cos(2 * pi * t / 365.25) df <- cbind(data.frame(x = x), seasonal_harmonics(t)) df$y <- 10 + df$x + rexp(n, 1 / 3) fit <- fit_nhpp(df, threshold = 20, loc_vars = "x", penalty = "none", verbose = FALSE) gen <- fit_var_generator(fit, df) gen$p_opt gen$spectral_radius # Model covariates derived from a base variable: the lagged value of x df$x_lag1 <- c(NA, head(df$x, -1)) gen_d <- fit_var_generator( fit, df[-1, ], vars = "x", derive_lead = 1, derive = function(b) data.frame(x = b$x, x_lag1 = c(NA, head(b$x, -1)))) head(simulate_covariates(gen_d, n_mc = 2, seed = 1)[[1]])
Check if an object is an nhpp_fit
is_nhpp_fit(x)is_nhpp_fit(x)
x |
Any R object. |
Logical.
is_nhpp_fit(list())is_nhpp_fit(list())
Given a fitted nhpp_fit model, computes return levels by
integrating out covariate uncertainty under one or more approaches:
marginalize( fit, data, TRs = c(2, 5, 10, 20, 50, 100), n_obs = NULL, period = NULL, approaches = c("A", "C"), scenarios = NULL, mc_sample = NULL, interactions = list(), fixed = list(), year_col = "year", n_boot = 500L, seed = 2024L, tol_root = 1e-04, z_hi = NULL )marginalize( fit, data, TRs = c(2, 5, 10, 20, 50, 100), n_obs = NULL, period = NULL, approaches = c("A", "C"), scenarios = NULL, mc_sample = NULL, interactions = list(), fixed = list(), year_col = "year", n_boot = 500L, seed = 2024L, tol_root = 1e-04, z_hi = NULL )
fit |
An |
data |
The data frame used to fit |
TRs |
Numeric vector of return periods in years. Default
|
n_obs |
Integer observations per year. If |
period |
Numeric seasonal period in observations. If |
approaches |
Character vector. Which approaches to run. Any subset of
|
scenarios |
Named list of covariate scenarios for approach A. Each
element is itself a named list of scalar covariate values, passed to
|
mc_sample |
List of data frames for approach B. Each element is one
simulated year of covariates ( |
interactions |
Named list of interactions passed to
|
fixed |
Named list of scalar covariate values imposed on every
scenario and trajectory, overriding values from |
year_col |
Name of the year column in |
n_boot |
Integer. Number of resampled years for approach C.
Default |
seed |
Integer seed for approach C (the caller's random-number stream
is preserved). Default |
tol_root |
Numeric. Root-finding tolerance. Default |
z_hi |
Numeric. Upper search bound for return levels. If |
Covariates fixed at user-specified scenarios (e.g. quantiles of observed distributions). Fast; useful for sensitivity analysis.
Covariates drawn from a user-supplied Monte Carlo
sample of complete annual trajectories (e.g. from
simulate_covariates).
Annual-block resampling of observed covariate
years from data, preserving within-year temporal structure.
For each approach and return period , the return level solves
, where is the annual non-exceedance
probability averaged over trajectories. For approaches B and C the
conditional Monte Carlo standard error of the root,
, is reported in se_mc, with
the standard deviation of the pathwise probabilities at the
root and the mean pathwise derivative with respect to the
level. It measures only finite-ensemble integration error, conditional on
the fitted model and trajectory law.
A data frame of class nhpp_rl with columns
approach, scenario, TR, RL, and
se_mc (NA for approach A). See plot.nhpp_rl
and rl_table.
set.seed(1) n_years <- 30; n_obs <- 50 df <- data.frame(x = rnorm(n_years * n_obs), year = rep(seq_len(n_years), each = n_obs)) df$y <- 10 + 2 * df$x + rexp(nrow(df), 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", obs_per_year = n_obs, verbose = FALSE) rl <- marginalize(fit, df, TRs = c(5, 10, 50), scenarios = list(low = list(x = -1), high = list(x = 1)), n_boot = 200) rl rl_table(rl)set.seed(1) n_years <- 30; n_obs <- 50 df <- data.frame(x = rnorm(n_years * n_obs), year = rep(seq_len(n_years), each = n_obs)) df$y <- 10 + 2 * df$x + rexp(nrow(df), 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", obs_per_year = n_obs, verbose = FALSE) rl <- marginalize(fit, df, TRs = c(5, 10, 50), scenarios = list(low = list(x = -1), high = list(x = 1)), n_boot = 200) rl rl_table(rl)
Extract the number of exceedances from a fitted model
n_exceedances(fit, y)n_exceedances(fit, y)
fit |
An |
y |
Numeric vector of observations. If missing, the series stored in the fitted object is used. |
Integer. Number of observations exceeding the threshold.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10))) fit <- fit_nhpp(df, threshold = 4, penalty = "none", verbose = FALSE) n_exceedances(fit)set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10))) fit <- fit_nhpp(df, threshold = 4, penalty = "none", verbose = FALSE) n_exceedances(fit)
logLik() returns the unpenalized log-likelihood at the operational
estimator, with degrees of freedom equal to the number of active
parameters and nobs equal to the number of exceedances, so that
AIC() and BIC() work; BIC(fit) equals
bic_nhpp(fit). predict() is a thin wrapper around
predict_params.
## S3 method for class 'nhpp_fit' logLik(object, ...) ## S3 method for class 'nhpp_fit' nobs(object, ...) ## S3 method for class 'nhpp_fit' predict(object, newdata = NULL, operational = TRUE, ...)## S3 method for class 'nhpp_fit' logLik(object, ...) ## S3 method for class 'nhpp_fit' nobs(object, ...) ## S3 method for class 'nhpp_fit' predict(object, newdata = NULL, operational = TRUE, ...)
object |
An |
... |
Ignored. |
newdata |
Optional data frame of covariates (see
|
operational |
Logical; see |
logLik(): an object of class logLik.
nobs(): the number of exceedances. predict(): a list with
components mu, sigma, xi.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) logLik(fit) c(AIC = AIC(fit), BIC = BIC(fit), nobs = nobs(fit)) str(predict(fit, newdata = data.frame(x = c(-1, 0, 1))))set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) logLik(fit) c(AIC = AIC(fit), BIC = BIC(fit), nobs = nobs(fit)) str(predict(fit, newdata = data.frame(x = c(-1, 0, 1))))
Plot diagnostics for a fitted nhpp_fit object
## S3 method for class 'nhpp_fit' plot( x, type = c("intensity", "fitted", "path", "qq"), residuals = c("interarrival", "magnitude"), ... )## S3 method for class 'nhpp_fit' plot( x, type = c("intensity", "fitted", "path", "qq"), residuals = c("interarrival", "magnitude"), ... )
x |
An |
type |
Character. |
residuals |
Residual type for |
... |
Additional graphical parameters passed to
|
Invisibly returns NULL, called for side effects.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) plot(fit, type = "intensity") plot(fit, type = "qq")set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) plot(fit, type = "intensity") plot(fit, type = "qq")
Draws return level against return period (logarithmic axis), one curve
per approach and scenario. For approaches with a Monte Carlo standard
error, dashed lines show standard errors.
## S3 method for class 'nhpp_rl' plot(x, ...)## S3 method for class 'nhpp_rl' plot(x, ...)
x |
An |
... |
Additional graphical parameters passed to
|
Invisibly returns NULL, called for side effects.
set.seed(1) df <- data.frame(x = rnorm(1500), year = rep(1:30, each = 50)) df$y <- 10 + 2 * df$x + rexp(1500, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", obs_per_year = 50, verbose = FALSE) plot(marginalize(fit, df, TRs = c(2, 5, 10, 50, 100), n_boot = 200))set.seed(1) df <- data.frame(x = rnorm(1500), year = rep(1:30, each = 50)) df$y <- 10 + 2 * df$x + rexp(1500, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", obs_per_year = 50, verbose = FALSE) plot(marginalize(fit, df, TRs = c(2, 5, 10, 50, 100), n_boot = 200))
Analytical gradient of the penalized negative log-likelihood
pp_grad( par, dm, y, threshold, lambda = 0.1, alpha = 0.5, pen_xi = TRUE, eps_l1 = 1e-10, obs_per_year = 365.25, penalty_weights = NULL )pp_grad( par, dm, y, threshold, lambda = 0.1, alpha = 0.5, pen_xi = TRUE, eps_l1 = 1e-10, obs_per_year = 365.25, penalty_weights = NULL )
par |
Numeric vector of parameters: c(beta_mu, beta_sigma, beta_xi). |
dm |
Design matrix list from |
y |
Numeric vector of observations. |
threshold |
Numeric scalar. The extreme value threshold u. |
lambda |
Penalty strength. Either a scalar or a vector
|
alpha |
Elastic-net mixing parameter in [0,1]. 1 = LASSO, 0 = ridge.
Either a scalar or a vector |
pen_xi |
Logical. Should the shape parameter covariates be penalized? |
eps_l1 |
Small positive constant for smooth L1 approximation. |
obs_per_year |
Number of observations per year (e.g. 365.25 for daily). |
penalty_weights |
Optional non-negative numeric vector of length
|
Numeric vector of length length(par).
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) dm <- build_design_matrices(df, loc_vars = "x") pp_grad(c(6, 0.1, log(1.5), 0.1), dm, df$y, threshold = 4, lambda = 0)set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) dm <- build_design_matrices(df, loc_vars = "x") pp_grad(c(6, 0.1, log(1.5), 0.1), dm, df$y, threshold = 4, lambda = 0)
Evaluates the negative log-likelihood of the non-homogeneous Poisson process (point-process) representation of threshold exceedances, plus a smoothed elastic-net penalty on the penalized coefficients.
pp_nllh( par, dm, y, threshold, lambda = 0.1, alpha = 0.5, pen_xi = TRUE, eps_l1 = 1e-10, obs_per_year = 365.25, penalty_weights = NULL )pp_nllh( par, dm, y, threshold, lambda = 0.1, alpha = 0.5, pen_xi = TRUE, eps_l1 = 1e-10, obs_per_year = 365.25, penalty_weights = NULL )
par |
Numeric vector of parameters: c(beta_mu, beta_sigma, beta_xi). |
dm |
Design matrix list from |
y |
Numeric vector of observations. |
threshold |
Numeric scalar. The extreme value threshold u. |
lambda |
Penalty strength. Either a scalar or a vector
|
alpha |
Elastic-net mixing parameter in [0,1]. 1 = LASSO, 0 = ridge.
Either a scalar or a vector |
pen_xi |
Logical. Should the shape parameter covariates be penalized? |
eps_l1 |
Small positive constant for smooth L1 approximation. |
obs_per_year |
Number of observations per year (e.g. 365.25 for daily). |
penalty_weights |
Optional non-negative numeric vector of length
|
Scalar. The penalized negative log-likelihood value. Parameter
vectors outside the point-process support return 1e9.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) dm <- build_design_matrices(df, loc_vars = "x") par <- c(6, 0.1, log(1.5), 0.1) pp_nllh(par, dm, df$y, threshold = 4, lambda = 0) pp_nllh(par, dm, df$y, threshold = 4, lambda = 1)set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) dm <- build_design_matrices(df, loc_vars = "x") par <- c(6, 0.1, log(1.5), 0.1) pp_nllh(par, dm, df$y, threshold = 4, lambda = 0) pp_nllh(par, dm, df$y, threshold = 4, lambda = 1)
Given an nhpp_fit object and a data frame of covariate values,
returns the implied location, scale, and shape parameters at each row.
predict_params(fit, newdata = NULL, operational = TRUE)predict_params(fit, newdata = NULL, operational = TRUE)
fit |
An object of class |
newdata |
A data frame with one row per time point. Must contain all
columns that appear in the model's design matrices (except the intercept).
If |
operational |
Logical. If |
A list with three numeric vectors of length nrow(newdata):
mu |
Location parameter. |
sigma |
Scale parameter (always positive). |
xi |
Shape parameter. |
set.seed(1) df <- data.frame(x = rnorm(2000)) df$y <- 10 + 2 * df$x + rexp(2000, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", verbose = FALSE) predict_params(fit, data.frame(x = c(-1, 0, 1)))set.seed(1) df <- data.frame(x = rnorm(2000)) df$y <- 10 + 2 * df$x + rexp(2000, 1 / 3) fit <- fit_nhpp(df, threshold = 18, loc_vars = "x", penalty = "none", verbose = FALSE) predict_params(fit, data.frame(x = c(-1, 0, 1)))
Print a fitted nhpp_fit model
## S3 method for class 'nhpp_fit' print(x, ...)## S3 method for class 'nhpp_fit' print(x, ...)
x |
An |
... |
Ignored. |
Invisibly returns x.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) print(fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE))set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) print(fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE))
Print a summary of a fitted nhpp_fit model
## S3 method for class 'summary.nhpp_fit' print(x, digits = 5L, ...)## S3 method for class 'summary.nhpp_fit' print(x, digits = 5L, ...)
x |
A |
digits |
Number of significant digits for coefficients. |
... |
Ignored. |
Invisibly returns x.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10))) print(summary(fit_nhpp(df, threshold = 4, penalty = "none", verbose = FALSE)))set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10))) print(summary(fit_nhpp(df, threshold = 4, penalty = "none", verbose = FALSE)))
Two residual types are available, both standard exponential under a correctly specified model:
"interarrival"Time-rescaled inter-exceedance increments
,
, where is the fitted
exceedance rate at the threshold (Ogata, 1988; Smith and Shively, 1995).
"magnitude"Exponential transforms of the threshold
excesses under the implied generalized Pareto law,
with
.
## S3 method for class 'nhpp_fit' residuals( object, type = c("interarrival", "magnitude"), operational = TRUE, ... )## S3 method for class 'nhpp_fit' residuals( object, type = c("interarrival", "magnitude"), operational = TRUE, ... )
object |
An |
type |
Character, |
operational |
Logical. Use the operational estimator (default). |
... |
Ignored. |
Numeric vector of residuals.
Ogata, Y. (1988). Statistical models for earthquake occurrences and residual analysis for point processes. Journal of the American Statistical Association, 83(401), 9–27.
Smith, R. L. and Shively, T. S. (1995). Point process approach to modeling trends in tropospheric ozone based on exceedances of a high threshold. Atmospheric Environment, 29(23), 3489–3499.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) z <- residuals(fit) c(mean = mean(z), var = var(z))set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) z <- residuals(fit) c(mean = mean(z), var = var(z))
Converts the long-format output of marginalize into a
wide table with one row per scenario and one column per return period.
rl_table(marg_result)rl_table(marg_result)
marg_result |
Data frame returned by |
A wide data frame.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), year = rep(1991:2020, each = 11)) fit <- fit_nhpp(df, threshold = 4, penalty = "none", obs_per_year = 11, verbose = FALSE) rl_table(marginalize(fit, df, TRs = c(10, 50), approaches = "A"))set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), year = rep(1991:2020, each = 11)) fit <- fit_nhpp(df, threshold = 4, penalty = "none", obs_per_year = 11, verbose = FALSE) rl_table(marginalize(fit, df, TRs = c(10, 50), approaches = "A"))
Builds the seasonal harmonic columns used by margEVT. The
-th pair is and ,
where is the position of the observation within the year and
is the seasonal period. Using this function to build the fitting
data guarantees that build_cov_annual reconstructs the same
seasonal cycle during marginalization, where positions run from 1 to
n_obs within each simulated or resampled year.
seasonal_harmonics( t, period = 365.25, n_harmonics = 2L, sine = c("sen", "sin") )seasonal_harmonics( t, period = 365.25, n_harmonics = 2L, sine = c("sen", "sin") )
t |
Numeric vector of within-year positions (e.g. day of year). |
period |
Positive seasonal period. Default |
n_harmonics |
Positive integer number of harmonic pairs. Default 2. |
sine |
Prefix of the sine columns: |
A data frame with columns cos1, sen1 (or
sin1), ..., one row per element of t.
h <- seasonal_harmonics(1:365, period = 365.25) head(h) names(seasonal_harmonics(1:52, period = 52, n_harmonics = 3, sine = "sin"))h <- seasonal_harmonics(1:365, period = 365.25) head(h) names(seasonal_harmonics(1:52, period = 52, n_harmonics = 3, sine = "sin"))
Simulates n_mc independent annual trajectories. All trajectories
are propagated simultaneously, so the cost grows with the trajectory
length rather than with n_mc times the length. Each trajectory is
initialized from the stationary Gaussian law of the companion state
(default) or from zero followed by burn_in transitions. Seasonality
is re-added at positions 1, ..., n_obs; if the generator has a
derive function, model covariates are recomputed from the
simulated base variables, using derive_lead additional leading
observations that are discarded afterwards.
simulate_covariates( generator, n_mc, n_obs = NULL, burn_in = 300L, initialization = c("stationary", "burnin"), seed = NULL )simulate_covariates( generator, n_mc, n_obs = NULL, burn_in = 300L, initialization = c("stationary", "burnin"), seed = NULL )
generator |
Object from |
n_mc |
Integer. Number of independently simulated annual trajectories. |
n_obs |
Integer observations per simulated year. If |
burn_in |
Integer. Burn-in applied when
|
initialization |
Character. |
seed |
Integer seed or |
A list of length n_mc, each element an n_obs-row
data frame of covariates, directly usable as mc_sample in
marginalize (approach B).
set.seed(1) n <- 3650 t <- rep(1:365, 10) df <- cbind(data.frame(x = as.numeric(stats::arima.sim(list(ar = 0.6), n))), seasonal_harmonics(t)) df$y <- 10 + df$x + rexp(n, 1 / 3) fit <- fit_nhpp(df, threshold = 20, loc_vars = "x", penalty = "none", verbose = FALSE) mc <- simulate_covariates(fit_var_generator(fit, df), n_mc = 3, seed = 1) length(mc); dim(mc[[1]])set.seed(1) n <- 3650 t <- rep(1:365, 10) df <- cbind(data.frame(x = as.numeric(stats::arima.sim(list(ar = 0.6), n))), seasonal_harmonics(t)) df$y <- 10 + df$x + rexp(n, 1 / 3) fit <- fit_nhpp(df, threshold = 20, loc_vars = "x", penalty = "none", verbose = FALSE) mc <- simulate_covariates(fit_var_generator(fit, df), n_mc = 3, seed = 1) length(mc); dim(mc[[1]])
Builds a structured summary of a fitted nhpp_fit object, including
the penalty used, the active and shrunk coefficients, information
criteria, convergence diagnostics, and (when available) Hessian
conditioning. Coefficient standard errors are deliberately not reported:
after penalization and data-driven selection they lack a valid
interpretation (see bootstrap_coef for conditional intervals).
## S3 method for class 'nhpp_fit' summary(object, tol = NULL, ...)## S3 method for class 'nhpp_fit' summary(object, tol = NULL, ...)
object |
An |
tol |
Numeric. Coefficients smaller than this in absolute value are
treated as zero. If |
... |
Ignored. |
An object of class summary.nhpp_fit, printed by
print.summary.nhpp_fit.
set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) summary(fit)set.seed(1) df <- data.frame(y = c(rexp(300), runif(30, 5, 10)), x = rnorm(330)) fit <- fit_nhpp(df, threshold = 4, loc_vars = "x", penalty = "none", verbose = FALSE) summary(fit)