% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/sg-fit.R
\name{sg_fit}
\alias{sg_fit}
\title{Run fit with monolix/simurg/nonmem fitter}
\usage{
sg_fit(
  model,
  data,
  headers,
  theta,
  ruv,
  re,
  occ,
  covs,
  project_name,
  task_opt = NULL,
  opt_name = "Monolix",
  fit = FALSE,
  path_to_save_output = NULL,
  path_to_fitter = NULL,
  max_wait_time = 3600
)
}
\arguments{
\item{model}{string. Path to a txt file file with model structure in Monolix syntax. This should be a valid file path pointing to a model file that defines the pharmacokinetic/pharmacodynamic model structure}

\item{data}{String. Path to the dataset used to fit a model. Should be a CSV file containing the pharmacokinetic/pharmacodynamic data with appropriate column structure matching the headers specification}

\item{headers}{List. A list specifying the data frame column headers.
Each element should be a list containing column information with the following structure:
\itemize{
\item \code{name} - string, column name in the dataset
\item \code{use} - string, column usage type. Valid values include:
\itemize{
\item "identifier" for subject ID columns
\item "time" for time columns
\item "observation" for dependent variable columns
\item "observationtype" for observation type identifier
\item "administration" for administration route
\item "amount" for dose amount
\item "eventidentifier" for event ID
\item "missingdependentvariable" for missing DV flag
\item "covariate" for covariate columns
}
\item \code{type} - string or NULL, data type specification. For observations use
"continuous", "count/categorical" or "event", depending on the nature of
observations. For covariates use "continuous" or "categorical". Can be NULL for non-covariate columns.
}}

\item{theta}{tibble or data.frame. Should contain the following columns:
\itemize{
\item \code{NAME} - string, parameter name. Should match names specified in the model file
\item \code{TRANS} - string, parameter transformation type. Can be: \code{"normal"}, \code{"logNormal"}, \code{"logitNormal"}
\item \code{INIT} - numeric, initial value for the parameter
\item \code{LB} - numeric, lower bound for logit transformation, \code{NA} for other transformations
\item \code{UB} - numeric, upper bound for logit transformation,  \code{NA} for other transformation
\item \code{EST} - logical, whether to estimate this parameter.
}}

\item{ruv}{A list specifying options for residual error used in model fit, containing:
\itemize{
\item \code{YNAME} - string, output name. Typically \code{"y1"}, \code{"y2"},...
\item \code{DVID} - numeric, observation type identifier corresponding to DVID column values
\item \code{TRANS} - string, residual error distribution. Can be: \code{"normal"}, \code{"logNormal"}, \code{"logitNormal"}
\item \code{PRED} - string, prediction variable name from the model
\item \code{ERR} - string, error model type. Options include:
\itemize{
\item "constant" for additive error
\item "proportional" for proportional error
\item "combined1" for combined additive and proportional error
}
\item \code{INIT} - numeric vector, initial values for error parameters (length depends on error model)
\item \code{EST} - logical vector, whether to estimate each error parameter (same length as INIT)
\item \code{BLQM} - below limit of quantification method (can be NULL)
For several observation types list of lists should be provided:
one residual error (ruv) object for each observations.
}}

\item{re}{List. A list specifying options for random effects used in model fit, containing:
\itemize{
\item \code{init} - matrix, initial values for the variance-covariance matrix of random
effects. Rows and columns should correspond to parameters defined in theta.
Diagonal elements represent variances, off-diagonal elements represent covariances. Use 0 for no variability
\item \code{est} - matrix, logical matrix of same dimensions as \code{init} specifying
which variance-covariance elements to estimate. Use \code{TRUE} to estimate,
\code{FALSE} to fix, \code{NA} to not use this random effect.
}}

\item{occ}{A list specifying interoccasion variability properties, containing:
\itemize{
\item \code{init} - matrix, initial values for the interoccasion variance-covariance matrix.
Same structure as \code{re$init} but for occasion-to-occasion variability. Use 0 for no interoccasion variability
\item \code{est} - matrix, logical matrix specifying which interoccasion variance-covariance
elements to estimate. Use \code{TRUE} to estimate, \code{FALSE} to fix, \code{NA} for
elements not applicable. Typically all elements are NA when no interoccasion variability is modeled.
}}

\item{covs}{A list of covariate structures. Each element should be a list containing covariate relationship definitions with the following structure:
\itemize{
\item \code{PAR} - string, name of the parameter to which covariate effect is applied
\item \code{COVNAME} - string, name of the covariate column in the dataset
\item \code{FUNC} - string, functional form of the covariate effect
\item \code{TRANS} - string, transformation applied to covariate
\item \code{REF} - numeric, reference value for categorical covariates
\item \code{INIT} - numeric, initial value for the covariate effect parameter
\item \code{EST} - logical, whether to estimate the covariate effect
Can be \code{NULL}, if no covariates are used. Default is \code{NULL}
}}

\item{project_name}{String. The name of the Monolix project without file extension.
This will be used as the base name for output files and directories.}

\item{task_opt}{String. Additional task options to be passed to the fitting software.
For Monolix, this can include specific task configurations or optimization settings.
When \code{NULL}, default tasks (populationParameters, individualParameters, fim, logLikelihood)
will be used.  Default is \code{NULL}.}

\item{opt_name}{String. Specify the optimizer/fitter to use for model fitting.
Currently supported options:
\itemize{
\item \code{"Monolix"} - uses Monolix Suite for population pharmacokinetic modeling (generates .mlxtran files)
\item \code{"Simurg"} - uses SimuRg internal fitter (generates .R files with JSON control structure)
Default is \code{"Monolix"}.
}}

\item{fit}{Logical. If \code{TRUE}, the model fitting will be executed immediately
using the specified fitter. If \code{FALSE}, only the fit configuration file will
be generated without running the fit. Set to \code{FALSE} for file preparation only,
or \code{TRUE} to run the complete fitting process. Default is \code{FALSE}.}

\item{path_to_save_output}{String. Path to save fit output files.
Should be a valid directory path where the fit results and project files
will be saved. If \code{NULL}, current working directory will be used. Default is \code{NULL}.}

\item{path_to_fitter}{String. The path to the program fitter executable.
For Monolix, this should point to the monolix.bat file.
If \code{NULL}, "C:/ProgramData/Lixoft/MonolixSuite2023R1/bin/monolix.bat" will be used as default. Default is \code{NULL}.}

\item{max_wait_time}{numeric. Maximum time in seconds to wait for fit results to complete. Default is 3600 seconds (1 hour). Set to \code{Inf} for no timeout.}
}
\value{
if option \code{fit = TRUE}, generalized simurg output object is returned. Otherwise, the file for fit is written and no output is returned
}
\description{
Run fit with monolix/simurg/nonmem fitter
}
\examples{
\donttest{
library(tibble)
library(dplyr)
library(stringr)
# Specify structural model path. For fit, should be in Monolix syntax
model <- system.file("extdata", "models", "model_PK_1c.txt", package = "SimuRg")
# Specify data path. Should be ADPPK-like format
data  <- system.file("extdata", "datasets", "dspk-warf.csv", package = "SimuRg")

# Specify headers. Should be a list of lists with the following elements:
# name - string, name of the column
# use - string, use of the column from Monolix documentation
# type - string, type of the column. for use = "covariate", should be
# "continuous" or "categorical", for other uses should be NULL
 headers <- list(list(name = "ID", use = "identifier", type = NULL),
                 list(name = "TIME", use = "time", type = NULL),
                 list(name = "DV", use = "observation", type = "continuous"),
                 list(name = "DVID", use = "observationtype", type = NULL),
                 list(name = "ADM", use = "administration", type = NULL),
                 list(name = "AMT", use = "amount", type = NULL),
                 list(name = "EVID", use = "eventidentifier", type = NULL),
                 list(name = "MDV", use = "missingdependentvariable", type = NULL),
                 list(name = "AGE", use = "covariate", type = "continuous"),
                 list(name = "AGE_centered", use = "covariate", type = "continuous"),
                 list(name = "SEX", use = "covariate", type = "categorical"),
                 list(name = "WEIGHT", use = "covariate", type = "continuous"),
                 list(name = "BMI", use = "covariate", type = "continuous"))

# Dataset with the parameters properties. Should be a tibble with the following columns:
# NAME - string, name of the parameter
# TRANS - string, distribution of the parameter. Should be one of the following:
# "normal", "logNormal", "logitNormal"
# INIT - numeric, initial value of the parameter or its fixed value
# LB - numeric, lower bound of the parameter for logit transformation
# UB - numeric, upper bound of the parameter for logit transformation
# EST - logical, estimation status of the parameter. For estimation, should
# be TRUE, for fixed, should be FALSE
 theta <- tribble(~NAME, ~TRANS, ~INIT, ~LB, ~UB, ~EST,
                  "Cl", "logNormal", 0.2, NA, NA, TRUE,
                  "V", "logNormal", 20, NA, NA, TRUE,
                  "ka", "logNormal", 0.2, NA, NA, TRUE
 )
 # Examples of random effect model specification
 # Examples of random effect model specification for fit
 # Single observation (legacy format):
 # YNAME - string, name of the observation, ususally y1, y2, ...
 # DVID - numeric, observation type identifier corresponding to DVID column values
 # TRANS - string, residual error distribution. Can be: "normal", "logNormal",
 # "logitNormal"
 # PRED - string, prediction variable name from the model
 # ERR - string, error model type. Options include: "constant" for additive
 # error, "proportional" for proportional error, "combined1" for combined
 # additive and proportional error
 # INIT - numeric vector, initial values for error parameters
 # (length depends on error model)
 # EST - logical vector, whether to estimate each error parameter
 # (same length as INIT)
 # BLQM - below limit of quantification method (can be NULL)
 # Single observation (legacy format):
 ruv <- list(YNAME = "y1", DVID = 1, TRANS = "normal", PRED = "Cc",
             ERR = "combined1", INIT = c(1, 1), EST = c(TRUE, TRUE), BLQM = NULL)

 # Multiple observations (recommended format):
ruv <- list(
  list(YNAME = "y1", DVID = 1, TRANS = "normal", PRED = "Cc",
       ERR = "combined1", INIT = c(1, 1), EST = c(TRUE, TRUE), BLQM = NULL),
  list(YNAME = "y2", DVID = 2, TRANS = "normal", PRED = "EFF",
      ERR = "proportional", INIT = c(0.1), EST = c(TRUE), BLQM = NULL)
)

 # Example of random effects (RE) specification.
 #
 # init matrix: provides the initial values for the random effects.
 # est matrix: controls how each random effect is handled:
 #   TRUE  - the random effect will be estimated,
 #   FALSE - the random effect will be fixed at its initial value,
 #   NA    - no random effect will be applied.
 #
 # To fit a model without random effects, set all entries in the
 # est matrix to NA.
 #
 # The same logic applies to the between-occasion variability
 # matrix (occ).

 re <- list(init = tribble(~Cl, ~V, ~ka,
                           1, 0, 0,
                           0, 0, 0,
                           0, 0, 1) \%>\% as.matrix(),
            est = tribble(~Cl, ~V, ~ka,
                          TRUE, NA, NA,
                          NA, NA, NA,
                          NA, NA, TRUE) \%>\% as.matrix())
# Example of between-occasion variability (BOV) specification. The structure
# is the same as for RE, but for BOV

 occ <- list(init = tribble(~Cl, ~V, ~ka,
                            0, 0, 0,
                            0, 0, 0,
                            0, 0, 0) \%>\% as.matrix(),
             est = tribble(~Cl, ~V, ~ka,
                           NA, NA, NA,
                           NA, NA, NA,
                           NA, NA, NA) \%>\% as.matrix())
# Example of covariate specification. Should be a list of lists with the following elements:
# PAR - string, name of the parameter to which the covariate is applied
# COVNAME - string, name of the covariate
# FUNC - string, function to apply to the covariate. Should be "linear" for
# continuous covariates, "categorical" for categorical covariates
# TRANS - string, transformation of the covariate. Should be "median" for
# continuous covariates, "reference" for categorical covariates
# INIT - numeric, initial value of the covariate
# EST - logical, estimation status of the covariate. For estimation, should
#be TRUE, for fixed, should be FALSE
 covs <- list(list(PAR = "V", COVNAME = "AGE", FUNC = "linear",
                   TRANS = "median", INIT = 1, EST = TRUE),
              list(PAR = "ka", COVNAME = "SEX", REF = 0, INIT = 1, EST = TRUE))
 output_path <- str_c(tempdir(), "/")
 fitter_path <- "C:/ProgramData/Lixoft/MonolixSuite2023R1/bin/monolix.bat"
 # Examples of task_opt parameter

 task_opt <-  paste("populationParameters()", "individualParameters()",
                    "logLikelihood()", sep = "\n")
 task_opt_lin <-  paste("populationParameters()", "individualParameters()",
                        "fim(method = Linearization)",
                        "logLikelihood(method = Linearization)", sep = "\n")
# Generalized control object
# gco <-list(headers = headers,
#            data = data,
#            model = model,
#            task_opt = task_opt
#            covs = covs,
#            project_name = "test-proj",
#            theta = theta,
#            ruv = ruv,
#            re = re,
#            occ = occ,
#            modelText = "")
 result <- sg_fit(model, data, headers, theta, ruv, re, occ, covs,
                  project_name = "my_project", fit = FALSE, # set fit = TRUE for fit
                  path_to_save_output =  output_path,
                  path_to_fitter = fitter_path)
}
}
