Skip to contents

Fits a ctsem model specified via ctModel with type either 'ct' or 'dt'. ctStanFit is maintained as a backward-compatible alias.

Usage

ctFit(
  datalong,
  model,
  stanmodeltext = NA,
  iter = 1000,
  intoverstates = TRUE,
  binomial = FALSE,
  fit = TRUE,
  intoverpop = "auto",
  poprank = "auto",
  sameInitialTimes = FALSE,
  stationary = FALSE,
  plot = FALSE,
  derrind = NA,
  optimize = TRUE,
  optimcontrol = list(),
  backend = c("julia", "stan"),
  nlcontrol = list(),
  nopriors = NA,
  priors = FALSE,
  chains = 2,
  cores = getOption("mc.cores", 2L),
  inits = NULL,
  compileArgs = list(),
  forcerecompile = FALSE,
  saveCompile = TRUE,
  savescores = FALSE,
  savesubjectmatrices = FALSE,
  saveComplexPars = FALSE,
  gendata = FALSE,
  sampleControl = list(),
  control = list(),
  verbose = 0,
  ...,
  popunique = NULL,
  popblocks = NULL,
  weights = NULL,
  ctstanmodel
)

Arguments

datalong

long format data containing columns for subject id, time, manifest variables, any time dependent (i.e. varying within subject) predictors, and any time independent (not varying within subject) predictors.

model

model object as generated by ctModel with type='ct' or 'dt', for continuous or discrete time models respectively.

stanmodeltext

already specified Stan model character string, generally leave NA unless modifying Stan model directly. (Possible after modification of output from fitting with argument fit=FALSE.) backend='stan' only.

iter

Deprecated – use sampleControl$iter. Still honoured, with a warning.

intoverstates

Logical. TRUE (the default) integrates over the latent states with a Kalman filter. FALSE makes the states part of what is estimated – the target becomes the joint density of the data and the states, and the fit reports the trajectory in fit$estimate$states – and is for sampling: with backend='julia' that route makes no Gaussian assumption about the state anywhere, where the filter's update for a binary, ordinal or count indicator is an assumed-density projection. optimize=TRUE is refused, because the joint mode is degenerate rather than an estimate; optimcontrol$estonly=TRUE returns it anyway, with no standard errors.

binomial

Deprecated. Logical indicating the use of binary rather than Gaussian data, as with IRT analyses. This now sets the manifesttype of every indicator to 1, for binary.

fit

If FALSE, prepare the model and data without fitting: stan returns its fit object unfitted, julia the specification its engine reads.

intoverpop

How declared individual differences (random effects) are handled: integrated out of the likelihood, or sampled with everything else.

'auto', the default, integrates them out when optimizing, as TRUE does, and samples them ('none') when optimize=FALSE – except on julia where every subject's likelihood is Gaussian in its effects (Gaussian indicators, effects only on means through the affine transform), where they are integrated exactly and the population parameters sampled ('laplace').

TRUE integrates them out: by 'laplace' on backend='julia', and by 'augmented' on stan, which has only that route, or with intoverstates=FALSE, which composes with it only. fit$args$resolved$intoverpopreason records why. Before 4.0.0 TRUE always meant 'augmented'.

'laplace' (backend='julia') integrates an effect that shifts a mean in a linear Gaussian model – a manifest mean, an initial mean, a continuous intercept – exactly, inside each subject's filter, and every other effect by a Laplace approximation at its mode, which summary() reports. 'augmented' makes each random effect a state of the filter: exact for effects that shift a mean in a linear Gaussian model, and a linearisation elsewhere. That shrinks random effects on the dynamics; where the dynamics depend on the state, an effect that reaches them – a random initial mean too, the more so beside a random manifest mean that keeps the data from pinning it down – is linearised over its population spread, which can overstate the likelihood and move the maximum; and variation on a DIFFUSION or MANIFESTVAR parameter is only partly identified. ctFit warns of both.

'quadrature' (backend='julia', optimizing) fits by 'laplace' and then refines the fit with the units the random-effects check names (optimcontrol$checks) integrated numerically – each unit by adaptive Gauss-Hermite or lattice rules, whichever reaches the accuracy at the lower cost, at any number of effects – reporting that objective's estimate, standard errors and log likelihood (Laplace's kept in loglik_laplace). Seconds to minutes; longer where the units nest; ctFitUncertainty(fit, intoverpop = 'quadrature') does the same after a fit.

FALSE, or 'none', samples them, so it needs optimize=FALSE: maximising over every subject's effects would drive the population variance to zero. With optimize=FALSE on julia, 'none' (and so 'auto', but for the exception above) samples the joint posterior of parameters and random effects; 'laplace' and 'augmented' sample the population parameters with the effects integrated out, by the Laplace approximation or the filter, and TRUE by whichever of the two it resolves to.

poprank

Rank of the population covariance of the individually varying parameters. 'auto', the default, uses the number of varying parameters that reach the observation mean: under intoverpop='augmented' that is all the route can identify, so it costs no likelihood, it does nothing on a model whose varying parameters all reach the mean, and it says so when it reduces. NA leaves the covariance unrestricted. A smaller whole number is an approximation – fewer dimensions than the data support, which lowers the likelihood and distorts the parameters retained – useful for parsimony or speed.

Requires backend='julia', and the default applies to 'augmented' only: under 'laplace' and 'none' the dropped coordinates are identified, so a rank has to be asked for. There it may be given per grouping level by name, as poprank=c(study=2), with 'auto' resolved per level, and it may not fall below the number of individually varying T0MEANS with a free T0VAR, whose latents then take their initial variance from this covariance. Under 'augmented' a varying T0MEANS cannot be reduced at all, and an explicit rank is refused. A restricted covariance is L %*% t(L) for a loading matrix L, reported as poploading_<parameter>_dim<j>.<level>; a loading's sign is arbitrary, so read the standard deviations and correlations summary() reports. A stated RAWPOPVAR cell turns a defaulted reduction off, and is refused alongside a rank asked for. May also be set on the model, as model$poprank <- 2. A rank of 0 is allowed at a level whose every varying parameter has an own variance (popunique).

sameInitialTimes

if TRUE, include an empty observation for every subject that has no observation at the earliest observation time of the dataset. This ensures that the T0MEANS occurs for every subject at the same time, rather than just at the earliest observation for that subject. Important when modelling trends over time, age, etc.

stationary

Logical. If TRUE, each subject's latent processes start from the distribution DRIFT, CINT and DIFFUSION settle into – the mean -DRIFT^-1 CINT and the asymptotic covariance – rather than from T0MEANS and T0VAR, which are then not estimated. Suits processes observed long after they began, and saves estimating the initial state. Requires backend='julia', a continuous time model, and a DRIFT, CINT and DIFFUSION that are fixed within each subject: no cell may depend on the latent states or on time dependent predictors. Individual differences in those matrices are allowed with intoverpop='laplace', which intoverpop='auto' then chooses; each subject starts from its own stationary distribution. A latent process whose DRIFT is fixed so that it never settles – a row fixed at zero, or a fixed oscillation such as ctModelPeriodicComponent's clock – is refused.

To start only some initial conditions there, name those cells 'stationary' in the model (backend='julia'); every other initial condition stays as written. A T0MEANS cell takes its entry of the stationary mean, asymCINT. A T0VAR diagonal cell gives its latent the stationary variance, asymDIFFUSION's diagonal, keeping that latent's T0VAR correlations with the others. A T0VAR off-diagonal cell gives the pair the stationary covariance, and needs both their variances, and every covariance among the latents it joins, named too. The stationary moments are those of the marked latents and every latent that drives them, so a latent driven by others works, and DRIFT, CINT and DIFFUSION need to be fixed within each subject only for those.

plot

if TRUE, for sampling, a Shiny program is launched upon fitting to interactively plot samples. May struggle with many (e.g., > 5000) parameters. For optimizing, the optimisation trace is plotted – with backend='julia' once the fit returns, since the fit is one call into the engine; for live output use optimcontrol$callback.

derrind

deprecated, latents involved in dynamic error calculations are determined automatically now.

optimize

if TRUE, estimate by optimisation – maximum likelihood, or maximum a posteriori with priors=TRUE – with uncertainty from the curvature at the estimate. If FALSE, sample the posterior: with Stan's HMC sampler for backend='stan', and for backend='julia' with NUTS through a learnt map on the joint posterior of parameters and random effects, or NUTS or tempered SMC when there are none or intoverpop integrates them out – slower, but exact rather than a normal approximation at a mode. Other uncertainty methods for an optimised fit, importance sampling among them, are in ctFitUncertainty. A sampled fit's point estimate is the per-parameter median of the draws on stan (fit$stanfit$rawest) and their mean on julia (fit$estimate$raw).

optimcontrol

List of optimiser settings, read by both backends with the same meaning: stopping rules (tol, g_tol, maxiter), the start (initsd, carefulfit), the uncertainty computed at the end (uncertainty, estonly), and optional phases such as stochastic and, under intoverpop='laplace', saem and checks. ctOptimControl lists every name with its backend and default. A misspelled name, or one the chosen backend cannot honour, is an error.

backend

Either 'julia' (the default) or 'stan'. The two take the same model definitions and give the same summaries. The julia backend optimises and samples (optimize=FALSE), and adds intoverpop='laplace', grouping levels above the subject, and ordinal, count and censored indicators, and it integrates a binary one rather than linearising it. It needs a working Julia, which ctJuliaInstall sets up once; see also ctJuliaSetup. 'stan' was the default up to ctsem 3.11 and needs no external toolchain; it is to be deprecated.

nlcontrol

List of non-linear control parameters. maxtimestep must be a positive numeric, specifying the largest time span covered by the numerical integration. The large default ensures that for each observation time interval, only a single step of exponential integration is used. When maxtimestep is smaller than the observation time interval, the integration is nested within an Euler like loop. Smaller values may offer greater accuracy, but are slower and not always necessary. Given the exponential integration, linear model elements are fit exactly with only a single step. nsubsteps = 'auto' (julia backend only) instead measures, at the starting values and again at the optimum, how nonlinear each observation interval is and refines only the intervals that need it (under intoverpop = 'laplace', with each subject at its random-effect modes); substeptol (default 0.01) is the largest acceptable linearisation error as a fraction of the predicted state standard deviation, and maxsubsteps (default 64) caps an interval. maxtimestep remains a ceiling on the step. The choice is reported in fit$substeps. With optimize = FALSE that optimum is the one that places the sampler, and the chains keep the mesh chosen there. transition = 'euler' (julia backend, intoverstates = FALSE only) replaces the exponential step between substeps of the state-explicit path with plain Euler-Maruyama, for a reference that shares no approximation with the filter; it needs a fine maxtimestep. See also ctParticleLik.

nopriors

deprecated, use priors argument. logical. If TRUE, any priors are disabled – sometimes desirable for optimization.

priors

FALSE (the default), TRUE or 'randomCorr'. FALSE uses no prior: maximum likelihood. TRUE adds ctsem's normal(0,1) raw-scale prior to every parameter, making an optimised fit maximum a posteriori. 'randomCorr' applies it to the random-effect correlations only, at every level: a bounded correlation on an unbounded coordinate can walk along a direction the data do not determine, and the prior holds it. Sampling (optimize=FALSE) without a prior on every parameter warns, because a parameter the data leave flat has an improper posterior; use priors=TRUE there. 'randomCorr' needs backend='julia'.

chains

Deprecated – use sampleControl$chains. Still honoured, with a warning.

cores

number of cpu cores to use: a positive whole number, or 'maxneeded' for all but one (capped at the number of chains on stan). Defaults to getOption("mc.cores", 2). It is the most CPU cores the call uses at once, counting every process it starts: on julia the threads a fit uses, BLAS included, and a sampling run's worker processes, which share it between them. A julia fit at cores > 1 is not reproducible to the last decimal, because its sums are divided among workers in an order that varies from run to run; use cores = 1 for a before-and-after comparison. The Julia session starts as wide as the call that starts it, and a later call asking for more runs at what it has and says so: ctJuliaSetup(threads = n, force = TRUE) restarts it wider, and options(ctsem.julia.restart = TRUE) has a fit do so itself.

inits

NULL (the default) for ctsem's own starting values, or a vector of starting values on the raw (unconstrained) scale, one per free parameter, as a fit holds its estimate: fit$estimate$raw on julia, fit$stanfit$rawest on stan. On julia, a fit itself: its estimates are matched to this model's parameters by name, so a model extended by a predictor or a smooth starts where the fit stopped, with the new coefficients at zero. With backend='stan' and optimize=FALSE, the string 'optimize' optimises first and starts the chains there.

compileArgs

List of arguments to pass to stan_model for compilation of the Stan model.

forcerecompile

logical. For backend='stan', recompiles the stan model regardless of apparent need (for development). For backend='julia', compiles the model's state-dependent expressions – matrix cells that read a latent state, and their derivatives – and any parameter transforms of your own into code for this model, rather than evaluating them as data. The model's first fit in a session then compiles for a minute or more, and its gradients run faster: by up to a third for a heavily nonlinear model (many state-dependent cells, or long formulas in them), and by little otherwise. Worth it only when such a model's fit takes many minutes.

saveCompile

if TRUE and compilation is needed / requested, writes the stan model to the parent frame as ctsem.compiled (unless that object already exists and is not from ctsem), to avoid unnecessary recompilation.

savescores

Logical. If TRUE, output from the Kalman filter is saved in output. For datasets with many variables or time points, will increase file size substantially. backend='stan' only; on julia, ctKalman computes it from the fit.

savesubjectmatrices

Logical. If TRUE, subject specific matrices are saved – only relevant when either time dependent predictors or individual differences are used. Can increase memory usage dramatically in large models, and can be computed after fitting using ctExtract or ctSubjectPars. backend='stan' only.

saveComplexPars

Logical. If TRUE, also save rowwise output of any complex parameters specified, i.e. combinations of parameters, functions and states.

gendata

Logical – If TRUE, uses provided data for only covariates and a time and missingness structure, and generates random data according to the specified model / priors. Generated data is in the $Ygen subobject after running extract on the fit object. For datasets with many manifest variables or time points, file size may be large. To generate data based on the posterior of a fitted model, see ctGenerateFromFit. backend='stan' only; julia generates with ctGenerate.

sampleControl

Used when optimize=FALSE: a list of sampler settings. chains (4 on julia, 2 on stan); iter (1000, warmup and sampling together); warmup (200, or half of iter if that is less); draws, the post-warmup count, which wins over iter when given; seed; saveEffects, whether every random-effect draw is kept; and processes (FALSE), whether the chains run in worker processes – at most cores at once, so four chains on two cores run two at a time – rather than together in this session.

For backend='julia' also sampler ('map', NUTS through a learnt map, on the joint posterior; 'saem', SAEM's kernel, or 'nuts' by choice), placement (the map starts from an optimised fit; for 'saem' and 'nuts' on the joint posterior 'saem': SAEM's state places the chains, so no Laplace optimum is needed; 'fit' places them around an optimised fit), the stopping target minESS (200, of the worst parameter) and rhatTarget (1.01), with meanESS, maxDraws and settleTol, and NUTS's maxdepth, target_accept, maxdelta, init_scale, adapt_metric and adapt_effects – all described under uncertainty = 'sample' in ctFitUncertainty, with how lower targets give a quicker approximate posterior. A run stops once the target is met, and may run to four times the post-warmup count to reach it. A name the sampler does not read is an error. For backend='stan' the settings are rstan's, passed to stan's control.

control

Deprecated – use sampleControl, which is the same list under a name that says what it controls. Still honoured, with a warning; where both name the same setting, sampleControl wins.

verbose

Integer from 0 to 2. 1 reports progress while the model fits; 2 additionally keeps every progress line rather than overwriting one in place, and prints more for debugging. Whether overwriting is possible is detected from where the output is going; set options(ctsem.progress.overwrite = FALSE) if that detection is wrong for your front end – a Shiny app capturing stdout, for instance – or TRUE to force it on.

...

additional arguments to pass to stan function (backend='stan' only; refused on julia).

popunique

Own variances on a reduced-rank level: the parameters selected get a variance of their own beside the poprank shared dimensions, so that level's covariance is L %*% t(L) plus a diagonal – the factor-analytic form. TRUE selects every parameter varying at a level, FALSE none, and names select matrices or parameters, e.g. popunique = c(subject = 'MANIFESTMEANS'). One unnamed value applies to every level; named entries, or a named list, apply per level. Each selected level needs a poprank below its number of varying parameters; poprank = 0 with every parameter selected gives independent random effects. Reported as popunique_<parameter>.<level>, on the same raw scale as a full-rank sd. Requires backend = 'julia' and intoverpop = 'laplace' or sampling ('none'); must be passed by name.

popblocks

Shared dimensions in blocks, on a reduced-rank level: a list of blocks, each a list with rank, how many shared dimensions, and effects, which parameters load on them – TRUE for every parameter varying at the level, or names of matrices or parameters, as for popunique. A parameter loads only on the dimensions of the blocks that name it, so parameters with no block in common are uncorrelated, and one named in no block needs an own variance (popunique). A level's rank is the sum of its blocks' ranks, so poprank need not be given for it; 'auto' there defers to the blocks, and a number must equal the sum. One unnamed list of blocks applies to every level; a list named by level gives each level its own. For example, person-level item intercepts that do not covary with a latent level but may covary with each other and with the dynamics: popblocks = list(level = list(rank = 1, effects = c('lev', 'DRIFT')), items = list(rank = 2, effects = c('MANIFESTMEANS', 'DRIFT'))). Within a block, its first rank parameters, in the order the model lists them, form its basis. Loadings are reported as poploading_<parameter>_dim<j>, the dimensions numbered across the blocks in order. Requires backend = 'julia' and intoverpop = 'laplace' or sampling ('none'); must be passed by name.

weights

Sampling weights, one per subject: the name of a column of datalong that is constant within subject, or a numeric vector named by subject id (or unnamed, in the order subjects first appear in the data). Each subject's contribution to the likelihood – its marginal likelihood, random effects integrated out – is multiplied by its weight (the weighted pseudo-likelihood), and the prior is not; a weight of zero leaves the subject out. Weights are normalised to a mean of one over the weighted subjects, and standard errors come from the sandwich estimator unless optimcontrol$uncertainty says otherwise. fit$estimate$loglik stays the data's log likelihood at the estimate; fit$estimate$loglik_weighted is the weighted one. Requires backend = 'julia' and optimisation; with nested ids, weights must be constant within each group of the outermost level. Must be passed by name.

ctstanmodel

Deprecated. Use model.

Value

A fitted object of class ctStanFit (backend='stan') or ctJuliaFit (backend='julia'), both also classed ctFit. Besides backend-specific components, every fit carries $args, a list with two sublists that mean the same thing on both backends:

input

Exactly what was passed to ctFit(), or the formal default when an argument was not supplied – intoverpop may still read 'auto', and cores 'maxneeded' if that is what was passed.

resolved

What the fit actually ran with, after 'auto' routing, deprecated-argument merges (e.g. nopriors into priors) and backend-specific defaults were settled – cores is a concrete integer, intoverpop is one of 'augmented', 'laplace' or 'none', and priors is TRUE, FALSE or 'randomCorr'. A call that gives the same input on both backends gives the same resolved on both.

Before this, $args itself held the raw call on a stan fit and only the resolved settings on a julia fit, so the same field name meant opposite things across backends; code reading fit$args$intoverpop or fit$args$cores directly should now read fit$args$resolved (or $input, if the literal call is what is wanted, as ctFitUpdate does).

Details

A julia fit with random effects reports, at its estimate, how much of each random effect each subject's own data determine, and how many subjects' worth of information each population standard deviation rests on (fit$identifiability$effects). An effect resting on fewer than two is named in a message, in summary() and in ctReport, with a lower poprank suggested where its level can take one and indvarying = FALSE after it.

See also

ctOptimControl for every optimiser setting; ctFitUncertainty for uncertainty after a fit; ctIdentify reports which parameters the data can inform, before a fit is spent finding out; ctTracePlot draws the optimisation trace a julia fit records.

Examples

# \donttest{

#generate a modern ctsem model relying heavily on defaults
model<-ctModel(type='ct',
  latentNames=c('eta1','eta2'),
  manifestNames=c('Y1','Y2'),
  MANIFESTVAR=diag(.1,2),
  TDpredNames='TD1',
  TIpredNames=c('TI1','TI2','TI3'),
  LAMBDA=diag(2))

# The default backend is julia; ctJuliaInstall() sets it up.
if (isTRUE(ctJuliaStatus()$available)) {
  fit<-ctFit(ctstantestdat, model,priors=TRUE)

  summary(fit)

  plot(fit,wait=FALSE)
}

#### extended examples

library(ctsem)
set.seed(3)

#  Data generation (run this, but no need to understand!) -----------------

Tpoints <- 20
nmanifest <- 4
nlatent <- 2
nsubjects<-20

#random effects
age <- rnorm(nsubjects) #standardised
cint1<-rnorm(nsubjects,2,.3)+age*.5
cint2 <- cint1*.5+rnorm(nsubjects,1,.2)+age*.5
tdpredeffect <- rnorm(nsubjects,5,.3)+age*.5

for(i in 1:nsubjects){
  #generating model
  gm<-ctModel(Tpoints=Tpoints,n.manifest = nmanifest,n.latent = nlatent,n.TDpred = 1,
  type='omx',
    LAMBDA = matrix(c(1,0,0,0, 0,1,.8,1.3),nrow=nmanifest,ncol=nlatent),
    DRIFT=matrix(c(-.3, .2, 0, -.5),nlatent,nlatent),
    TDPREDMEANS=matrix(c(rep(0,Tpoints-10),1,rep(0,9)),ncol=1),
    TDPREDEFFECT=matrix(c(tdpredeffect[i],0),nrow=nlatent),
    DIFFUSION = matrix(c(1, 0, 0, .5),2,2),
    CINT = matrix(c(cint1[i],cint2[i]),ncol=1),
    T0VAR=diag(2,nlatent,nlatent),
    MANIFESTVAR = diag(.5, nmanifest))

  #generate data
  newdat <- ctGenerate(ctmodelobj = gm,n = 1,burnin = 2,
    dtmat=rbind(c(rep(.5,8),3,rep(.5,Tpoints-9))))
  newdat[,'id'] <- i #set id for each subject
  newdat <- cbind(newdat,age[i]) #include time independent predictor
  if(i ==1) {
    dat <- newdat[1:(Tpoints-10),] #pre intervention data
    dat2 <- newdat #including post intervention data
  }
  if(i > 1) {
    dat <- rbind(dat, newdat[1:(Tpoints-10),])
    dat2 <- rbind(dat2,newdat)
  }
}
colnames(dat)[ncol(dat)] <- 'age'
colnames(dat2)[ncol(dat)] <- 'age'


#plot generated data for sanity
plot(age)
matplot(dat[,gm$manifestNames],type='l',pch=1)
plotvar <- 'Y1'
plot(dat[dat[,'id']==1,'time'],dat[dat[,'id']==1,plotvar],type='l',
  ylim=range(dat[,plotvar],na.rm=TRUE))
for(i in 2:nsubjects){
  points(dat[dat[,'id']==i,'time'],dat[dat[,'id']==i,plotvar],type='l',col=i)
}


dat2[,gm$manifestNames][sample(1:length(dat2[,gm$manifestNames]),size = 100)] <- NA


#data structure
head(dat2)


# Model fitting -----------------------------------------------------------

##simple univariate default model

m <- ctModel(type = 'ct', manifestNames = c('Y1'), LAMBDA = diag(1))
ctModelLatex(m)

#Specify univariate linear growth curve

m1 <- ctModel(type = 'ct',
  manifestNames = c('Y1'), latentNames=c('eta1'),
  DRIFT=matrix(0,nrow=1,ncol=1),
  DIFFUSION=matrix(0,nrow=1,ncol=1),
  T0VAR=matrix(0,nrow=1,ncol=1),
  CINT=matrix(c('cint1'),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  LAMBDA = diag(1),
  MANIFESTMEANS=matrix(0,ncol=1),
  MANIFESTVAR=matrix(c('merror'),nrow=1,ncol=1))

ctModelLatex(m1)

#fit
if (isTRUE(ctJuliaStatus()$available)) {
  f1 <- ctFit(datalong = dat2, model = m1, optimize=TRUE, priors=FALSE)

  summary(f1)

  #plots of individual subject models v data
  ctPredict(f1,plot=TRUE,subjects=1,kalmanvec=c('y','yprior'),timestep=.01)
  ctPredict(f1,plot=TRUE,subjects=1:3,kalmanvec=c('y','ysmooth'),timestep=.01,errorvec=NA)

  #compare randomly generated data from the posterior to the observed data,
  #including the lagged covariance structure and the mean trajectory over time
  ctPostPredict(f1, wait=FALSE)
}

 ### Further example models

#Include intervention
m2 <- ctModel(type = 'ct',
  manifestNames = c('Y1'), latentNames=c('eta1'),
  n.TDpred=1,TDpredNames = 'TD1', #this line includes the intervention
  TDPREDEFFECT=matrix(c('tdpredeffect'),nrow=1,ncol=1), #intervention effect
  DRIFT=matrix(-1e-5,nrow=1,ncol=1),
  DIFFUSION=matrix(0,nrow=1,ncol=1),
  CINT=matrix(c('cint1'),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  T0VAR=matrix(0,nrow=1,ncol=1),
  LAMBDA = diag(1),
  MANIFESTMEANS=matrix(0,ncol=1),
  MANIFESTVAR=matrix(c('merror'),nrow=1,ncol=1))



#Individual differences in intervention, Bayesian estimation, covariates
m2i <- ctModel(type = 'ct',
  manifestNames = c('Y1'), latentNames=c('eta1'),
  TIpredNames = 'age',
  TDpredNames = 'TD1', #this line includes the intervention
  TDPREDEFFECT=matrix(c('tdpredeffect||TRUE'),nrow=1,ncol=1), #intervention effect
  DRIFT=matrix(-1e-5,nrow=1,ncol=1),
  DIFFUSION=matrix(0,nrow=1,ncol=1),
  CINT=matrix(c('cint1'),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  T0VAR=matrix(0,nrow=1,ncol=1),
  LAMBDA = diag(1),
  MANIFESTMEANS=matrix(0,ncol=1),
  MANIFESTVAR=matrix(c('merror'),nrow=1,ncol=1))


#Including covariate effects
m2ic <- ctModel(type = 'ct',
  manifestNames = c('Y1'), latentNames=c('eta1'),
  n.TIpred = 1, TIpredNames = 'age',
  n.TDpred=1,TDpredNames = 'TD1', #this line includes the intervention
  TDPREDEFFECT=matrix(c('tdpredeffect'),nrow=1,ncol=1), #intervention effect
  DRIFT=matrix(-1e-5,nrow=1,ncol=1),
  DIFFUSION=matrix(0,nrow=1,ncol=1),
  CINT=matrix(c('cint1'),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  T0VAR=matrix(0,nrow=1,ncol=1),
  LAMBDA = diag(1),
  MANIFESTMEANS=matrix(0,ncol=1),
  MANIFESTVAR=matrix(c('merror'),nrow=1,ncol=1))

m2ic$pars$indvarying[m2ic$pars$matrix %in% 'TDPREDEFFECT'] <- TRUE


#Include deterministic dynamics
m3 <- ctModel(type = 'ct',
  manifestNames = c('Y1'), latentNames=c('eta1'),
  n.TDpred=1,TDpredNames = 'TD1', #this line includes the intervention
  TDPREDEFFECT=matrix(c('tdpredeffect'),nrow=1,ncol=1), #intervention effect
  DRIFT=matrix('drift11',nrow=1,ncol=1),
  DIFFUSION=matrix(0,nrow=1,ncol=1),
  CINT=matrix(c('cint1'),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  T0VAR=matrix('t0var11',nrow=1,ncol=1),
  LAMBDA = diag(1),
  MANIFESTMEANS=matrix(0,ncol=1),
  MANIFESTVAR=matrix(c('merror1'),nrow=1,ncol=1))





#Add system noise to allow for fluctuations that persist in time
m3n <- ctModel(type = 'ct',
  manifestNames = c('Y1'), latentNames=c('eta1'),
  n.TDpred=1,TDpredNames = 'TD1', #this line includes the intervention
  TDPREDEFFECT=matrix(c('tdpredeffect'),nrow=1,ncol=1), #intervention effect
  DRIFT=matrix('drift11',nrow=1,ncol=1),
  DIFFUSION=matrix('diffusion',nrow=1,ncol=1),
  CINT=matrix(c('cint1'),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  T0VAR=matrix('t0var11',nrow=1,ncol=1),
  LAMBDA = diag(1),
  MANIFESTMEANS=matrix(0,ncol=1),
  MANIFESTVAR=matrix(c(0),nrow=1,ncol=1))



#include 2nd latent process

m4 <- ctModel(n.manifest = 2,n.latent = 2, type = 'ct',
  manifestNames = c('Y1','Y2'), latentNames=c('L1','L2'),
  n.TDpred=1,TDpredNames = 'TD1',
  TDPREDEFFECT=matrix(c('tdpredeffect1','tdpredeffect2'),nrow=2,ncol=1),
  DRIFT=matrix(c('drift11','drift21','drift12','drift22'),nrow=2,ncol=2),
  DIFFUSION=matrix(c('diffusion11','diffusion21',0,'diffusion22'),nrow=2,ncol=2),
  CINT=matrix(c('cint1','cint2'),nrow=2,ncol=1),
  T0MEANS=matrix(c('t0m1','t0m2'),nrow=2,ncol=1),
  T0VAR=matrix(c('t0var11','t0var21',0,'t0var22'),nrow=2,ncol=2),
  LAMBDA = matrix(c(1,0,0,1),nrow=2,ncol=2),
  MANIFESTMEANS=matrix(c(0,0),nrow=2,ncol=1),
  MANIFESTVAR=matrix(c('merror1',0,0,'merror2'),nrow=2,ncol=2))

#dynamic factor model -- fixing CINT to 0 and freeing indicator level intercepts

m3df <- ctModel(type = 'ct',
  manifestNames = c('Y2','Y3'), latentNames=c('eta1'),
  n.TDpred=1,TDpredNames = 'TD1', #this line includes the intervention
  TDPREDEFFECT=matrix(c('tdpredeffect'),nrow=1,ncol=1), #intervention effect
  DRIFT=matrix('drift11',nrow=1,ncol=1),
  DIFFUSION=matrix('diffusion',nrow=1,ncol=1),
  CINT=matrix(c(0),ncol=1),
  T0MEANS=matrix(c('t0m1'),ncol=1),
  T0VAR=matrix('t0var11',nrow=1,ncol=1),
  LAMBDA = matrix(c(1,'Y3loading'),nrow=2,ncol=1),
  MANIFESTMEANS=matrix(c('Y2_int','Y3_int'),nrow=2,ncol=1),
  MANIFESTVAR=matrix(c('Y2residual',0,0,'Y3residual'),nrow=2,ncol=2))

# }