% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/MortalityLaw_main.R
\name{MortalityLaw}
\alias{MortalityLaw}
\title{Fit Mortality Laws}
\usage{
MortalityLaw(x, Dx = NULL, Ex = NULL, mx = NULL, qx = NULL,
                law = NULL,
                opt.method = "LF2",
                parS = NULL,
                fit.this.x = x,
                custom.law = NULL,
                show = FALSE, ...)
}
\arguments{
\item{x}{Numeric vector of ages at the beginning of each age interval. 
For a full life table, use single-year ages (e.g., \code{0:110}). 
For an abridged life table, use the lower bound of each interval 
(e.g., \code{c(0, 1, 5, 10, ..., 110)}).}

\item{Dx}{Death counts. Each element represents the total number of 
deaths during the calendar year to persons aged \code{x} to 
\code{x + n} (where \code{n} is the length of the age interval). 
Must be provided together with \code{Ex}.}

\item{Ex}{Exposure-to-risk in the period. This is usually approximated 
by the mid-year population aged \code{x} to \code{x + n}. Must be 
provided together with \code{Dx}.}

\item{mx}{Age-specific death rate in the age interval \code{[x, x+n)}. 
Defined as \code{Dx / Ex}.}

\item{qx}{Probability of dying within the age interval \code{[x, x+n)}.}

\item{law}{The name of the mortality law to be used (e.g., \code{"gompertz"},
\code{"makeham"}). Run \code{\link{availableLaws}} to see all options.}

\item{opt.method}{The function to optimise. Available options:
\itemize{
  \item{\code{"poissonL"}: Poisson log-likelihood.}
  \item{\code{"binomialL"}: Binomial log-likelihood.}
  \item{\code{"LF1"}: Squared relative error \code{(1 - mu/nu)^2}.}
  \item{\code{"LF2"}: Squared log-ratio \code{log(mu/nu)^2}.}
  \item{\code{"LF3"}: Chi-squared-type \code{((nu - mu)^2)/nu}.}
  \item{\code{"LF4"}: Squared error \code{(nu - mu)^2}.}
  \item{\code{"LF5"}: Deviance-type \code{(nu - mu) * log(nu/mu)}.}
  \item{\code{"LF6"}: Absolute error \code{abs(nu - mu)}.}
}
See \code{\link{availableLF}} for details.}

\item{parS}{Optional starting parameter values for the optimisation. If
\code{NULL}, sensible defaults are automatically chosen via
\code{\link{bring_parameters}}.}

\item{fit.this.x}{A subset of \code{x} over which to fit the model. The
default is the entire \code{x} vector. Use this to exclude, for example,
advanced ages where data are sparse.}

\item{custom.law}{A user-defined function for fitting a model not included
in the package. The function must accept arguments \code{x} (age vector)
and \code{par} (named parameter vector) and return a list containing at
least an element named \code{hx} (the hazard or force of mortality). See
the examples below.}

\item{show}{Logical. If \code{TRUE}, a progress bar is displayed during
fitting. Default: \code{FALSE}.}

\item{...}{Additional arguments passed to or from other methods.}
}
\value{
An object of class \code{"MortalityLaw"}, which is a list with the following
components:
\item{input}{List of input arguments, stored for reproducibility.}
\item{info}{Model information (name, formula, date of fitting).}
\item{coefficients}{Estimated parameters of the mortality law. A named
vector for a single fit, or a matrix for multiple fits.}
\item{fitted.values}{Fitted hazard rates (or death probabilities) evaluated
at the input ages \code{x}.}
\item{residuals}{Deviance residuals, computed as observed minus fitted
values.}
\item{goodness.of.fit}{List or matrix of goodness-of-fit measures: AIC,
BIC and log-likelihood (available only for likelihood-based methods).}
\item{opt.diagnosis}{Object returned by the optimisation routine, useful
for checking convergence.}
\item{df}{Number of parameters and residual degrees of freedom.}
\item{deviance}{Sum of squared log-residuals, used as a deviance measure.}
}
\description{
Fit parametric mortality models given a set of input data. The data can be
supplied as death counts and mid-interval population estimates
\code{(Dx, Ex)}, age-specific death rates \code{(mx)}, or death
probabilities \code{(qx)}. Use the \code{law} argument to specify the
model to be fitted. Over 30 parametric models are currently implemented;
run \code{\link{availableLaws}} to see the full list. Models can be fitted
using maximum likelihood or by optimising a loss function. See the
\code{\link{availableLF}} function for the implemented options.
}
\details{
\strong{Optimisation:} The PORT routines (via \code{\link{nlminb}}) are used
for unconstrained and box-constrained optimisation. Parameters are estimated
on the log scale to ensure positivity, and the routine is set to allow up to
5000 iterations. When the optimisation method is \code{"poissonL"} or
\code{"binomialL"}, the AIC, BIC and log-likelihood are computed from the
likelihood. Otherwise these are set to \code{NaN}.

\strong{Scaling of the age vector:} For models that cover only a portion
of the lifespan (e.g., adult or old-age mortality), the age vector \code{x}
is automatically re-scaled as \code{x = x - min(x) + 1} before fitting.
This transformation improves numerical stability and helps the optimisation
algorithm converge, especially when the starting age is far from zero.
Models that apply this scaling are flagged with \code{SCALE_X = TRUE} in
the table returned by \code{\link{availableLaws}}. When using
\code{\link{predict.MortalityLaw}} or \code{\link{LawTable}} with such
models, the same scaling is applied internally, so predictions remain
consistent with the fitted coefficients.

\strong{Handling matrix input:} If \code{Dx}, \code{Ex}, \code{mx} or
\code{qx} are provided as matrices (with one column per population or
time period), the function iterates over the columns and fits a separate
model to each, returning a collection of results.
}
\examples{
# Example 1: Fitting the Makeham model --------------------------
x  <- 45:75
Dx <- ahmd$Dx[paste(x), "1950"]
Ex <- ahmd$Ex[paste(x), "1950"]

M1 <- MortalityLaw(x = x, Dx = Dx, Ex = Ex, law = 'makeham')

M1
ls(M1)
coef(M1)
summary(M1)
fitted(M1)
predict(M1, x = 45:95)
plot(M1)


# Example 2: --------------------------
# We can fit the same model using a different data format
# and a different optimization method.
x  <- 45:75
mx <- ahmd$mx[paste(x), ]
M2 <- MortalityLaw(x = x, mx = mx, law = 'makeham', opt.method = 'LF1')
M2
fitted(M2)
predict(M2, x = 55:90)

# Example 3: --------------------------
# Now let's fit a mortality law that is not defined
# in the package, say a reparameterized Gompertz in
# terms of modal age at death
# hx = b*exp(b*(x-m)) (here b and m are the parameters to be estimated)

# A function with 'x' and 'par' as input has to be defined, which returns
# at least an object called 'hx' (hazard rate).
my_gompertz <- function(x, par = c(b = 0.13, M = 45)){
  hx  <- with(as.list(par), b*exp(b*(x - M)) )
  return(as.list(environment()))
}

M3 <- MortalityLaw(x = x, Dx = Dx, Ex = Ex, custom.law = my_gompertz)
summary(M3)
# predict M3 for different ages
predict(M3, x = 85:130)


# Example 4: --------------------------
# Fit Heligman-Pollard model for a single
# year in the dataset between age 0 and 100 and build a life table.

x  <- 0:100
mx <- ahmd$mx[paste(x), "1950"] # select data
M4 <- MortalityLaw(x = x, mx = mx, law = 'HP', opt.method = 'LF2')
M4
plot(M4)

LifeTable(x = x, qx = fitted(M4))
}
\seealso{
\code{\link{availableLaws}} for a list of all implemented models;
\code{\link{availableLF}} for loss function details;
\code{\link{LifeTable}} for life table construction;
\code{\link{ReadHMD}} for downloading data from the Human Mortality Database.
}
\author{
Marius D. Pascariu
}
