% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/multimsm.R
\name{multimsm}
\alias{multimsm}
\title{Fit a Multi-regime Marginal Structural Cox Model for Three-way Treatment Switching}
\usage{
multimsm(dat_long, id = "id", tstart = "t.start", tstop = "t.stop",
  event = "event", cens = NULL, rand = "rand", cross = "cross",
  subseq = "subseq", base_cov = NULL, iptw_num = NULL, iptw_den,
  ipcw_mod = NULL, wt_trunc = NULL, prob_bounds = c(1e-06, 1 - 1e-06),
  normalize_weights = TRUE, robust = TRUE, check_inputs = TRUE,
  trace_multinom = FALSE, maxit = 200)
}
\arguments{
\item{dat_long}{A \code{data.frame} in long-format start-stop format with one row
per subject follow-up interval.}

\item{id}{Character. Subject identifier variable name.}

\item{tstart}{Character. Interval start-time variable name.}

\item{tstop}{Character. Interval stop-time variable name.}

\item{event}{Character. Event indicator variable name (\code{1}: event, \code{0}: censor).}

\item{cens}{Optional character Ordinary right-censoring indicator used
only if \code{ipcw_mod} is supplied. This is not the treatment-switching process.}

\item{rand}{Character. Baseline randomization variable name (\code{1}: randomized
experimental treatment, \code{0}: randomized control). The value must be constant
within subject over time.}

\item{cross}{Character. \emph{Time-varying} control-to-experimental crossover
indicator. It may be one-time pulse at crossover time (...,0,1,0,0,...) or
absorbing (...,0,1,1,1,...). It must be structurally 0 always for subjects
randomized to experimental treatment (assumed no EC switch).}

\item{subseq}{Character. \emph{Time-varying} subsequent therapy initiation indicator.
It may be pulse or absorbing.}

\item{base_cov}{Optional character vector of baseline covariates to include in
the default numerator model when \code{iptw_num} is \code{NULL}.}

\item{iptw_num}{Optional \emph{right-hand-side} formula or character string for
the stabilized numerator multinomial regime model. If \code{NULL}, the default is
\verb{~ regime_lag + factor(visit) + < base_cov >}.}

\item{iptw_den}{Required \emph{right-hand-side formula} or character string for
the denominator multinomial regime model. This should typically include
\code{regime_lag}, visit or time terms, baseline covariates, and time-varying
confounders affected by prior treatment and predictive of subsequent
switching.}

\item{ipcw_mod}{Optional right-hand-side formula or character string for an
ordinary censoring model. If supplied, \code{cens} must also be supplied.}

\item{wt_trunc}{Optional numeric in \verb{(0.5, 1)}. If supplied, the
final combined inverse probability weight is truncated at the
\code{(1 - wt_trunc)} and \code{wt_trunc} empirical quantiles before the Cox model is
fit. For example, \code{wt_trunc = 0.95} caps the lower and upper tails at the
5th and 95th percentiles. The default \code{NULL} performs no quantile
truncation.}

\item{prob_bounds}{Numeric length-2 vector of lower and upper probability
bounds used to stabilize extreme predicted probabilities away from 0 and 1.}

\item{normalize_weights}{Logical. If \code{TRUE}, normalize the final truncated
weights to have mean 1.}

\item{robust}{Logical. If \code{TRUE}, fit the Cox model with \code{cluster(id)} to use
the standard robust sandwich variance estimator.}

\item{check_inputs}{Logical. If \code{TRUE}, enforce structural checks for the
five-regime treatment-switching system.}

\item{trace_multinom}{Logical. Passed to \code{\link[nnet:multinom]{nnet::multinom()}}.}

\item{maxit}{Integer maximum number of iterations for the multinomial models.}
}
\value{
An object of class \code{"multimsm"}; a list with components:

\itemize{
\item \code{coef_table} A \code{data.frame} of full estimated coefficient table.
\item \code{coef} Log-hazard ratio estimates for treatment regimes against control.
\item \code{hr} Hazard ratio estimates for treatment regimes against control.
\item \code{hr_ci} Wald 95\% confidence intervals for the hazard ratios.
\item \code{fit} The fitted weighted Cox model from \code{\link[survival:coxph]{survival::coxph()}}.
\item \code{p.val} P values of regime effect estimates.
\item \code{dat_long} Augmented long-format data containing the derived variables,
including switch indicators, and final estimated weights
(\code{.w_use}/\code{.w_use_trunc}).
\item \code{regime_models} A list containing the fitted numerator and denominator
mulinomial regime models.
\item \code{censor_model} The fitted censoring model when \code{ipcw_mod} is supplied;
othrwise \code{NULL}.
\item \code{diagnostics} A list containing untruncated final-weight quantiles,
final switch-regime counts/proportions, cohort size, and truncation bounds.
\item \code{call} The matched function call.
}
}
\description{
\code{multimsm()} fits a marginal structural Cox model with categorical treatment
for randomized clinical trials or trial-like longitudinal data with multi-way
treatment switching, assuming participants underwent regular longitudinal
follow-up visits. This method assumes a three-way treatment switch scenario:
control participants may crossover to experimental group and both control
and experimental participants may switch to a subsequent therapy.
\code{multimsm()} takes a longitudinal survival dataset with 3 treatment process
variables as primary inputs:
\itemize{
\item \code{rand}: \strong{baseline} randomized treatment arm. \code{1} denotes randomized
experimental treatment and \code{0} denotes randomized control/SOC.
\item \code{cross}: \strong{time-varying} control-to-experimental crossover indicator (1/0).
\item \code{subseq}: \strong{time-varying} subsequent therapy initiation indicator (1/0).
}

Internally, \code{multimsm()} converts this triplet of treatment trajectory into
the five-level \emph{time-varying treatment regime}:

\deqn{G(t) \in \{C, E, CE, CS, ES\}}

where \code{C} and \code{E} denote \strong{sustained control} and \strong{sustained experimental}
treatment regime at t, \code{CE} denotes \strong{control-to-experimental crossover}, \code{CS}
denotes on \strong{control-to-subsequent switch} regime status at t, and \code{ES} denotes
on \strong{experimental-to-subsequent switch} regime status at t.

The downstream estimator is a multinomial-regime stabilized-weight marginal
structural Cox model with the time-varying regime as predictor:

\deqn{\lambda_{T^{\overline g}}(t)=\lambda_0(t)\exp\{\beta_e\mathbb{I}({G(t)=E}) +
\beta_{ce} \mathbb{I}({G(t)=CE}) + \beta_{cs} \mathbb{I}({G(t)=CS}) +
\beta_{es} \mathbb{I}({G(t)=ES})\}}

The stabilized treatment-regime weight (S-IPTW) at each
post-baseline interval is the probability of the observed current regime under
a stabilizer model divided by the corresponding probability under a denominator
model. The cumulative product of these row-specific ratios is used as the
inverse probability weight. Optional ordinary censoring weights may also be
multiplied in, if informative censoring is present.
}
\details{
The treatment-switching process is assumed to follow the package's
five-regime structure G(t):

\deqn{
G_i(t)=
\begin{cases}
C,  & R_i=0,\ Crs_i(t)=0,\ Subs_i(t)=0,\\
E,  & R_i=1,\ Crs_i(t)=0,\ Subs_i(t)=0,\\
CE, & R_i=0,\ Crs_i(t)=1,\ Subs_i(t)=0,\\
CS, & R_i=0,\ Crs_i(t)=0,\ Subs_i(t)=1,\\
ES, & R_i=1,\ Crs_i(t)=0,\ Subs_i(t)=1.
\end{cases}
}

\code{R(t)} is \code{rand} randomized arm, \code{Crs(t)} is \code{cross} the absorbing crossover
status, and \code{Subs(t)} is \code{subseq} the absorbing subsequent initiation status.
Users may supply \code{cross} and \code{subseq} with either sustained absorbing
status indicator such as (\verb{0, 0, 1, 1, 1}), or as switch-initiation action
indicators such as (\verb{0, 0, 1, 0, 0}) - both acceptable.

The current method allows \emph{only one switch type} per subject's follow up. Thus,
control-arm subjects may remain in \code{C}, transition to \code{CE}, or transition to \code{CS};
experimental-arm subjects may remain in \code{E} or transition to \code{ES}.

The outcome model uses generated \code{regime} as the exposure. By default
\strong{\code{C} is the reference regime}, so the coefficient for \code{regimeE} estimates the
marginal sustained experimental-versus-control contrast aimed by the package's
primary no-switch estimand. The remaining coefficients describe the distinct
switched-regime contrasts averaging switch times relative to sustained control.
}
\examples{
set.seed(123)

sim_obj <- simswc(
  n = 300,
  n_visit = 8,
  base_cov = c("L1", "L3"),
  trt_prob = 0.5,
  param_tdcov = c(-1.5, 0.3, 0.3, -0.2, 0.5),
  param_tdcov2 = c(0.05, 0.2, 0.2, -0.2, 0.7),
  param_sw = c(-3, 0.4, 0.4, -0.3, 0.3, 0.8),
  param_haz = c(0.1, log(0.8), log(1.1), log(1.1),
                log(1.4), log(1.4), log(1.3), log(1), log(0.9)),
  param_cens = NULL,
  param_select = c(0, 0.5, 0.25),
  lagk = TRUE,
  true_hr = FALSE
)

# Convert to the required treatment switch indicator triplet
dat <- sim_obj$dat_long
dat$rand <- stats::ave(dat$A, dat$id, FUN = function(x) rep(x[1], length(x)))
dat$cross <- dat$S_CE
dat$subseq <- pmax(dat$S_ES, dat$S_CS)

fit <- multimsm(
  dat_long = dat, id = "id", tstart = "t.start", tstop = "t.stop",
  event = "event", rand = "rand", cross = "cross", subseq = "subseq",
  base_cov = c("L1", "L3"),
  iptw_num = ~ regime_lag + factor(visit) + L1 + L3,
  iptw_den = ~ regime_lag + factor(visit) + L1 + L3 + X + U + Alag1,
  wt_trunc = 0.95
)

fit

}
\references{
Robins JM, Hernan MA, Brumback B. Marginal structural models and causal
inference in epidemiology. \emph{Epidemiology}. 2000;11(5):550-560.

Suarez D, Haro JM, Novick D, et al. Marginal structural models for multiple
treatment comparisons: an application to antipsychotic treatment for
schizophrenia. \emph{Journal of Clinical Epidemiology}. 2008;61(6):525-530.
}
