% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/hazard_api.R
\name{hazard}
\alias{hazard}
\title{Build and optionally fit a hazard model}
\usage{
hazard(
  formula = NULL,
  data = NULL,
  time = NULL,
  status = NULL,
  time_lower = NULL,
  time_upper = NULL,
  x = NULL,
  time_windows = NULL,
  theta = NULL,
  dist = "weibull",
  phases = NULL,
  fit = FALSE,
  weights = NULL,
  control = list(),
  ...
)
}
\arguments{
\item{formula}{Optional formula of the form \code{Surv(time, status) ~ predictors}.
When provided, overrides direct time/status/x arguments and extracts from data.
Example: \code{hazard(Surv(time, status) ~ x1 + x2, data = df, dist = "weibull", fit = TRUE)}.}

\item{data}{Optional data frame containing variables referenced in formula.}

\item{time}{Numeric follow-up time vector.}

\item{status}{Numeric or logical event indicator vector.}

\item{time_lower}{Optional numeric lower bound vector for censoring intervals.
Used when \code{status == 2} (interval-censored); defaults to \code{time} if NULL.}

\item{time_upper}{Optional numeric upper bound vector for censoring intervals.
Used when \code{status \%in\% c(-1, 2)}; defaults to \code{time} if NULL.}

\item{x}{Optional design matrix (or data frame coercible to matrix).}

\item{time_windows}{Optional numeric vector of strictly positive cut points for
piecewise time-varying coefficients. When provided, each predictor column in
\code{x} is expanded into one column per time window so each window gets its own
coefficient.}

\item{theta}{Optional numeric coefficient vector (starting values for optimization).}

\item{dist}{Character baseline distribution label (default \code{"weibull"}).
One of \code{"weibull"}, \code{"exponential"}, \code{"loglogistic"}, \code{"lognormal"}, or
\code{"multiphase"}.  The single-distribution families differ in the \emph{shape} the
hazard traces over time; \code{"multiphase"} builds an additive N-phase hazard
and requires \code{phases}.  See the \strong{Baseline distributions} section for what
each means and when to use it.}

\item{phases}{Optional named list of \code{\link[=hzr_phase]{hzr_phase()}} objects specifying the
phases for a multiphase model (\code{dist = "multiphase"}).  See Examples.}

\item{fit}{Logical; if TRUE, fit the model via maximum likelihood (default FALSE).}

\item{weights}{Optional numeric vector of observation weights (non-negative).
Each observation's log-likelihood contribution is multiplied by its weight.
Use for severity-weighted repeated events. Default \code{NULL} (unit weights).
Implements the SAS \code{WEIGHT} statement.}

\item{control}{Named list of control options (see Details).}

\item{...}{Additional named arguments retained for parity with legacy calling
conventions.}
}
\value{
An object of class \code{hazard}, a named list with components:
\code{call} (the matched call),
\code{spec} (model specification: \code{dist}, \code{control},
\code{time_windows}, \code{phases}),
\code{data} (input data: \code{time}, \code{status}, \code{x},
\code{weights}, etc.),
\code{fit} (optimisation results: \code{theta}, \code{objective},
\code{converged}, \code{se}, \code{vcov}, \code{counts}, \code{message};
all \code{NULL} when \code{fit = FALSE}),
and \code{engine} (implementation tag, \code{"native-r-m2"}).
}
\description{
Creates a \code{hazard} object and optionally fits it via maximum likelihood.
This mirrors the argument-oriented workflow of the legacy HAZARD C/SAS
implementation: supply starting values in \code{theta} and the function will
optimize to produce fitted estimates.
}
\details{
Control parameters:
\itemize{
\item \code{maxit}: Maximum iterations (default 1000)
\item \code{n_starts}: Number of optimization starts for multiphase fits (default 5).
Each start after the first adds random noise to the initial values, drawn
from the ambient RNG stream; call \code{set.seed()} before fitting for
reproducible results.
\item \code{reltol}: Relative parameter change tolerance (default 1e-5)
\item \code{abstol}: Absolute gradient norm tolerance (default 1e-6)
\item \code{method}: Optimization method: "bfgs" or "nm" (default "bfgs")
\item \code{condition}: Condition number control (default 14)
\item \code{nocov}, \code{nocor}: Suppress covariance/correlation output (legacy; no-op in M2)
}

Censoring status coding:
\itemize{
\item 1: Exact event at time
\item 0: Right-censored at time
\item -1: Left-censored with upper bound at time_upper \(or time\)
\item 2: Interval-censored in the interval \(time_lower, time_upper\)
}

Time-varying coefficients:
\itemize{
\item If \code{time_windows} is supplied, predictors are expanded to piecewise window
interactions so each window has its own coefficient vector.
\item This is implemented as design-matrix expansion, so the existing likelihood
engines remain unchanged.
}
}
\section{The fitted model}{


For \code{dist = "multiphase"} the cumulative hazard, instantaneous hazard, and
survival are

\deqn{H(t \mid \mathbf{x}) = \sum_{j=1}^{J} \mu_j(\mathbf{x}) \, \Phi_j(t),
      \qquad
      h(t \mid \mathbf{x}) = \sum_{j=1}^{J} \mu_j(\mathbf{x}) \, \varphi_j(t),
      \qquad
      S(t \mid \mathbf{x}) = \exp\!\bigl(-H(t \mid \mathbf{x})\bigr)}

where \eqn{\mu_j(\mathbf{x}) = \exp(\alpha_j + \mathbf{x}_j^\top
\boldsymbol{\beta}_j)} and the temporal shapes \eqn{\Phi_j}, \eqn{\varphi_j}
are set by each phase's \code{type} (see \code{\link[=hzr_phase]{hzr_phase()}}).  The
proportional-hazards single-phase families (\code{"weibull"}, \code{"exponential"})
are the special case \eqn{J = 1}, with covariates acting multiplicatively on
one temporal shape.  The \code{"loglogistic"} (proportional-odds) and
\code{"lognormal"} (accelerated-failure-time) families place covariates
differently --- on the odds of failure and the log-time location,
respectively --- so they are separate parameterizations, not special cases
of this additive form.  Parameters are estimated
on an unconstrained internal scale (e.g. \eqn{\log\mu}, \eqn{\log t_{1/2}})
and transformed back for reporting; see
\code{vignette("mf-mathematical-foundations")}.
}

\section{Baseline distributions}{


The \code{dist} argument selects the parametric form of the baseline hazard.  The
four single-distribution families differ in the \emph{shape} the
hazard traces over follow-up; choose by what the risk is expected to do over
time.  \code{"multiphase"} is the general additive model that lets several such
shapes coexist.

\describe{
\item{\code{"weibull"} --- monotone rising or falling hazard (default)}{The
workhorse parametric model: \eqn{H(t \mid \mathbf{x}) = (\mu t)^\nu
    \exp(\eta)}, with hazard \eqn{h \propto t^{\nu - 1}}.  The single shape
\eqn{\nu} makes risk increase over time (\eqn{\nu > 1}), decrease
(\eqn{\nu < 1}), or stay flat (\eqn{\nu = 1}).  Use it as the default when
a single monotone trend describes the hazard.}
\item{\code{"exponential"} --- constant hazard}{The memoryless special case
\eqn{\nu = 1}: a time-invariant baseline rate, \eqn{H(t \mid \mathbf{x}) =
    \mu t \exp(\eta)}.  Use it when the event rate does not change with
follow-up time (the constant background risk also appears as the
\code{"constant"} phase in a multiphase model).}
\item{\code{"loglogistic"} --- unimodal (rise-then-fall) hazard}{A log-logistic
proportional-odds form (covariates act multiplicatively on the odds of
failure, \eqn{\exp(\eta)}, not as an AFT time shift) whose hazard rises to
a single peak and then declines when the shape exceeds 1 (and is monotone
decreasing otherwise), with heavier tails than the log-normal.  Use it
when risk climbs to an early peak and then eases off.}
\item{\code{"lognormal"} --- early-peaking, resolving hazard}{An
accelerated-failure-time form in which \eqn{\log} time is Gaussian; the
hazard rises to an early peak and then decays toward zero.  Use it for
risk that is concentrated early and resolves over time.}
\item{\code{"multiphase"} --- additive N-phase hazard}{Sums several phase shapes
into one model, \eqn{H = \sum_j \mu_j(\mathbf{x}) \Phi_j(t)}, so the
overall hazard can fall, level off, and rise again within one fit.
Requires \code{phases}; see \code{\link[=hzr_phase]{hzr_phase()}} for the available phase shapes.  This
is the form that reproduces the classic C/SAS HAZARD models.}
}
}

\examples{
# -- Univariable Weibull ----------------------------------------------
set.seed(1)
time   <- rexp(50, rate = 0.3)
status <- sample(0:1, 50, replace = TRUE, prob = c(0.3, 0.7))
fit <- hazard(time = time, status = status,
              theta = c(0.3, 1.0), dist = "weibull", fit = TRUE)
summary(fit)

# -- Formula interface with covariates --------------------------------
set.seed(1001)
n   <- 180
dat <- data.frame(
  time   = rexp(n, rate = 0.35) + 0.05,
  status = rbinom(n, size = 1, prob = 0.6),
  age    = rnorm(n, mean = 62, sd = 11),
  nyha   = sample(1:4, n, replace = TRUE),
  shock  = rbinom(n, size = 1, prob = 0.18)
)

fit2 <- hazard(
  survival::Surv(time, status) ~ age + nyha + shock,
  data    = dat,
  theta   = c(mu = 0.25, nu = 1.10, beta1 = 0, beta2 = 0, beta3 = 0),
  dist    = "weibull",
  fit     = TRUE,
  control = list(maxit = 300)
)
summary(fit2)

\donttest{
# -- Parametric survival with Kaplan-Meier overlay -----------------
if (requireNamespace("ggplot2", quietly = TRUE)) {
  library(ggplot2)

  # Parametric curve on a fine grid at median covariate profile
  t_grid   <- seq(0.05, max(dat$time), length.out = 80)
  curve_df <- data.frame(
    time = t_grid, age = median(dat$age), nyha = 2, shock = 0
  )
  curve_df$survival <- predict(fit2, newdata = curve_df,
                               type = "survival") * 100

  # Kaplan-Meier empirical overlay
  km    <- survival::survfit(survival::Surv(time, status) ~ 1, data = dat)
  km_df <- data.frame(time = km$time, survival = km$surv * 100)

  ggplot() +
    geom_step(data = km_df, aes(time, survival, colour = "Kaplan-Meier")) +
    geom_line(data = curve_df, aes(time, survival,
                                   colour = "Parametric (Weibull)")) +
    scale_colour_manual(
      values = c("Parametric (Weibull)" = "#0072B2",
                 "Kaplan-Meier"         = "#D55E00")
    ) +
    scale_y_continuous(limits = c(0, 100)) +
    labs(x = "Months after surgery", y = "Freedom from death (\%)",
         colour = NULL) +
    theme_minimal() +
    theme(legend.position = "bottom")
}
}

\donttest{
# -- Multiphase model (two phases) ---------------------------------
fit_mp <- hazard(
  survival::Surv(time, status) ~ 1,
  data   = dat,
  dist   = "multiphase",
  phases = list(
    early = hzr_phase("cdf", t_half = 0.5, nu = 2, m = 0,
                       fixed = "shapes"),
    late  = hzr_phase("cdf", t_half = 5,   nu = 1, m = 0,
                       fixed = "shapes")
  ),
  fit     = TRUE,
  control = list(n_starts = 5, maxit = 1000)
)
summary(fit_mp)

# -- Per-phase decomposed cumulative hazard ------------------------
if (requireNamespace("ggplot2", quietly = TRUE)) {
  t_grid <- seq(0.01, max(dat$time), length.out = 100)
  decomp <- predict(fit_mp, newdata = data.frame(time = t_grid),
                    type = "cumulative_hazard", decompose = TRUE)

  df_long <- data.frame(
    time = rep(decomp$time, 3),
    cumhaz = c(decomp$total, decomp$early, decomp$late),
    component = rep(c("Total", "Early (cdf)", "Late (cdf)"),
                    each = nrow(decomp))
  )
  df_long$component <- factor(df_long$component,
    levels = c("Total", "Early (cdf)", "Late (cdf)"))

  ggplot2::ggplot(df_long,
    ggplot2::aes(x = time, y = cumhaz, colour = component,
                 linewidth = component)) +
    ggplot2::geom_line() +
    ggplot2::scale_colour_manual(values = c(
      "Total" = "black", "Early (cdf)" = "#0072B2",
      "Late (cdf)" = "#D55E00"
    )) +
    ggplot2::scale_linewidth_manual(values = c(
      "Total" = 1.2, "Early (cdf)" = 0.6, "Late (cdf)" = 0.6
    )) +
    ggplot2::labs(
      x = "Time", y = "Cumulative hazard H(t)",
      colour = NULL, linewidth = NULL,
      title = "Multiphase decomposition: early + late"
    ) +
    ggplot2::theme_minimal() +
    ggplot2::theme(legend.position = "bottom")
}
}

}
\references{
Blackstone EH, Naftel DC, Turner ME Jr. The decomposition of time-varying
hazard into phases, each incorporating a separate stream of concomitant
information. \emph{J Am Stat Assoc.} 1986;81(395):615--624.
\doi{10.1080/01621459.1986.10478314}

Rajeswaran J, Blackstone EH, Ehrlinger J, Li L, Ishwaran H, Parides MK.
Probability of atrial fibrillation after ablation: Using a parametric
nonlinear temporal decomposition mixed effects model. \emph{Stat Methods Med Res.}
2018;27(1):126--141. \doi{10.1177/0962280215623583}
}
\seealso{
\code{\link[=predict.hazard]{predict.hazard()}} for survival/cumulative-hazard predictions,
\code{\link[=summary.hazard]{summary.hazard()}} for model summaries,
\code{\link[=hzr_phase]{hzr_phase()}} for specifying multiphase temporal shapes.

Vignettes with worked examples:
\code{vignette("fitting-hazard-models")} --- single-phase through multiphase fitting,
\code{vignette("prediction-visualization")} --- prediction types and decomposed hazard plots,
\code{vignette("inference-diagnostics")} --- bootstrap CIs and model diagnostics.
}
