% 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 "weibull").
Use \code{"multiphase"} for N-phase additive hazard models (requires \code{phases}).}

\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{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.
}
}
\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.
}
