nlmixr2est 7.0.3
New features
-
foceiControl(fast = TRUE)now uses the analytic outer gradient for general-likelihood models with more than one endpoint, which previously fell back to finite differences. It was gated off as unverifiable, but what did not verify was the objective below rather than the gradient; against central differences of the corrected objective it agrees to 8e-3 relative.
Bug fixes
Estimation
Fixed the objective function for a model that has a general-likelihood endpoint (
ll(),pois(),binom(), …) alongside any other endpoint. Each observation’s distribution was read one row before the model had been evaluated for that row, so a subject’s FIRST observation was scored as normal: its log-density was treated as a prediction ofDVagainst a variance forced to 1. On a two-endpoint warfarin model the objective read 11,463,666 where the correct value is 53,697, and the conditional estimates were shifted with it. This affected such fits at anyfoceiControl(fast=)setting. Models with a single endpoint, and models whose endpoints are all Gaussian, are unchanged.Fixed the
est="imp"/"impmap"/"qrpem"theta score for endpoints with differentDVtransforms, e.g. anlnorm()PK endpoint alongside anadd()PD one. The M-step read each observation’s transform and distribution without evaluating the model for that row, and the theta-sensitivity model did not emitrx_yj_/rx_lambda_at all, so every observation was scored with one arbitrary endpoint’s transform – on a 2-endpoint PK/PD fit that puttkaat -47.6 and the residual sigma at 2.8e4 where FOCEI gives 0.53 and 0.11. The two now agree to 1e-3. Models with a single endpoint, or whose endpoints share a transform, are unchanged.foceiControl(fo=TRUE)now rejects a general-likelihood endpoint or a censored observation wherever it appears in a subject, not only on that subject’s last observation. Both guards tested the last row’s value, so a subject whose final observation was Gaussian and uncensored slipped past them and was fit with an objective FO does not support.
nlmixr2est 7.0.2
CRAN release: 2026-08-04
Breaking changes
est="vae": naming a covariate invaeControl(shapes=)now also limits the search to it. The list form gained afixCovelement defaulting toTRUE, soshapes = list(WT = "power")searchesWTand nothing else, where previously it searched every covariate withWTrestricted to"power". AddfixCov = FALSEto restore the old meaning. Excluded covariates are listed in$runInfo. A character vector (shapes = c("power", "lin")) names no covariate and is unaffected.Dropped the
qs2dependency (and with itstringfish, which no longer loads against RcppParallel >= 6.0.0): the focei model disk cache now uses RDS files and compressed fit components use base R serialization (rxode2::rxGetDefaultSerialize(), “bzip2” by default). Old fits holding qs2-serialized components can still be read when theqs2package is installed; otherwise accessing them warns and returnsNULL. Requires rxode2 (>= 5.1.5) forrxDeserialize().
New features
-
The mu-referenced FOCEi family is experimental.
est = "mfocei","ifocei","mfoce","ifoce","mfocep","ifocep","magq","iagq","mlaplace","ilaplace"and theirfast=TRUEsiblings ("mfoceif"and relatives) are research methods. They are not validated to the standard of the established estimation methods, their results should not be relied on without independent checking, and their interface and defaults may change or be withdrawn in a future release without a deprecation cycle.- The same machinery is reachable from the ordinary methods with
foceiControl(muModel=)("lin"or"irls", default"none"), which is where it will continue to live.
- The same machinery is reachable from the ordinary methods with
-
The default
sigdigis now3(was4) for every estimation method exceptest="nls".sigdigdrives the ODE solver tolerances asrtol = 10^-sigdigandatol = 10^(-sigdig-3), so the default solve is nowrtol = 1e-3,atol = 1e-6– what most open-source ODE solvers default to, and still tighter than the precision the optimizer targets. Fits are faster. Passsigdig = 4to any control function to restore the previous tolerances.est="nls"keepssigdig = 4: its Levenberg-Marquardt step is sensitive to solver noise, and it already requests a solve three orders tighter than the optimizer target.The optimizer tolerances that are tuned values rather than the
10^-sigdigformula (est="nlm",est="nlme") stay anchored atsigdig = 4, so at the new default they also sit one order looser.Printed parameter tables now show 3 significant digits rather than 4.
sigdigTablefollowssigdigwhen it is not set explicitly, and that coupling is deliberate: a fit converged to about 3 digits should not report 4. SetsigdigTable = 4to keep the previous output.
-
Importance-sampling EM (
est="imp"/"impmap"/"qrpem"): the proposal density is adapted per subject rather than by one global setting, and a diagnostic is reported that can tell when it matters.The proposal scale is adapted from the second iteration on. The first iteration normalizes its weights against the starting mode, which is not yet a meaningful reference, so its coverage statistic reads far worse than the truth and would otherwise inflate the proposal for the whole fit.
fit$env$impPsisKgives a Pareto k-hat per subject – the tail index of that subject’s importance weights.k > 0.7means those weights have infinite variance and that subject’s contribution is untrustworthy. This is worth checking because the two statistics already reported cannot detect the problem:xi(NONMEM’sIACCEPTquantity) and the Kish effective sample size are both means over samples drawn from the proposal, so neither sees a tail the proposal rarely visits. On plain theophylline, two of twelve subjects have k-hat of 2.60 and 1.28 whilexireads ~0.97 and the effective-sample fraction ~0.99 for those same subjects.impmapControl(df=)switches the proposal from a multivariate normal to a multivariate t (NONMEMDF). This is the remedy for a bad k-hat, because it changes the proposal’s tails rather than its width, and tail weight is what decides whether the weights are well behaved. More samples does not help – boosting a failing subject tenfold moved its k-hat from 0.76 to 3.28 – whereasdf = 20cleared every failing subject for 0.25% of the effective sample size.impmapControl(isample=)additionally accepts one count per subject.impmapControl(gammaMethod=)selects how the proposal scale is adapted: one shared value, or per subject two-sided towardiaccepton that subject’s ownxi(NONMEM’s rule)."auto", the default, uses the per-subject law only for models that are not transformably normal, sincegamma = 1is already efficient when the individual posterior is close to Gaussian.impmapControl(auto=)is NONMEM’sAUTO=1: choosedf,isampleandiacceptper subject. It defaults toTRUE. It escalatesdfonly for subjects whose k-hat says they need it, leaving the rest on the cheaper Gaussian, and shifts sample budget from data-rich subjects to difficult ones. Measured on theophylline against a high-accuracy reference, it takes the worst k-hat from 2.44 to 0.49 and improvesOmegaaccuracy about 20%, for about 19% more Monte-Carlo noise on the objective; infinite-variance weights are a correctness problem whose error is unbounded in the worst case, while the added noise is bounded and measurable. Setauto = FALSEfor the un-adapted behaviour, which is the better choice whenfit$env$impPsisKis already comfortably below 0.7 everywhere and the tightest possible objective is wanted.
Note NONMEM does not publish the values its
AUTO=1uses; only thenobs < netatrigger andIACCEPT ~ 0.2are documented. The concrete numbers here (df = 30, the k-hat thresholds, the sample-budget rule) are nlmixr2’s own, tuned on the measurements above. Importance-sampling EM: the
covMethod="imp"covariance is now evaluated at the proposal the fit actually converged on, rather than at the control’s initialgammawith a Gaussian proposal.Importance-sampling EM:
$runInfonow names which sampling-efficiency statistic a fit is reporting, and states thatxiand the Kish effective-sample fraction are not comparable with each other.foceiControl()gainsouterMaxOdeRecalc,outerOdeRecalcFactorandouterStickyRecalcN, which loosen ODE tolerances and retry the analytic outer (augmented sensitivity) solve for a single subject that fails at the requested tolerance. Previously one subject’s failed augmented solve dropped the whole gradient to finite differences; now that subject can still contribute an analytic gradient, which is generally more accurate than the FD approximation. The loosening is per subject, so it is safe under the parallel outer solve, and it is tracked separately from the inner problem’smaxOdeRecalc/odeRecalcFactor/stickyRecalcN– a fit may loosen one and not the other, and the warning names whichever applied.-
est="vae":vaeControl(shapes=)list elements are now dispatched individually, so the covariate-named andlist(var=, covar=, shapes=)forms can be mixed in one list. A named element is exact shorthand for the covariate-wide rule, and a shape value ofTRUEmeans “eligible, default shapes” – which is how a categorical covariate is named, since it takes no parameterization:vaeControl(shapes = list(list(var = "cl", covar = "WT", shapes = "power"), SEX = TRUE))This is also how a covariate is restricted to particular parameters without writing the effect into the model: a
var+covarrule makes only that pair eligible. -
The
est="vae"automatic covariate search gained a"hockey"shape, a two-armed piecewise-linear relationship knotted at the covariate’s centering value and written aska <- exp(tka + beta.tka.WT.hockey.low * (WT < 70.5) * (WT - 70.5) + beta.tka.WT.hockey.hi * (WT >= 70.5) * (WT - 70.5) + eta.ka)It is continuous at the knot, so the structural theta keeps its meaning as the parameter value there. Both arms enter or neither does, and hockey competes with the covariate’s other shapes for the same slot, so a parameter never carries two parameterizations of one covariate. It costs two coefficients against a linear shape’s one, so BICc only takes it when the bend earns its keep.
"hockey"is part of the defaultshapes=; nameshapes=without it to opt out. A covariate with fewer thancatCutoffof the subjects on one side of the knot is skipped, with a note in$runInfo– reachable only with acovCenter=override, since the median splits the subjects in half.A hockey stick you write yourself already worked and is unchanged: each arm is independently a mu2 reference, so
vaeControl(pinCovariates=TRUE)(the default) keeps your model text and coefficient names exactly as written. L0Learnmoved fromSuggeststoImports. The covariate search already errored rather than fall back when it neededL0Learnand the package was absent, so it was effectively required; making that explicit removes the failure mode.The covariate coefficients
est="vae"injects after covariate selection are now named with.separators instead of_:beta.tka.WT.linrather thanbeta_tka_WT_lin. This matches the separator the rest ofnlmixr2uses for generated and conventional parameter names (eta.cl,add.sd,prop.sd). A categorical coefficient is built from the covariate and its level directly (beta.tka.SEX.M), so the separator is consistent there too. Coefficients you write yourself are untouched – withvaeControl(pinCovariates=TRUE)(the default) the model keeps your names exactly as written.The
est="vae"automatic covariate search now explores several parameterizations (“shapes”) of each covariate rather than the single hard-codedlog(cov/mean)form.vaeControl(shapes=)takes the same vocabulary asnlmixr2scm::runSCM()–"power"(beta*log(COV/ctr)),"lin"(beta*(COV - ctr)),"log"(beta*log(COV)),"identity"(beta*COV) – plus a new"center"(beta*(COV/ctr)). At most one shape of a covariate may enter a given parameter, as in a stepwise covariate search.shapes=also accepts a list named by covariate, or a list oflist(var=, covar=, shapes=)items restricting a single parameter/covariate pair; which covariates are searched is still governed bypinCovariates. Because the selection objective is a least-squares fit with a free intercept,"power"and"log"span the same model, as do"lin","identity"and"center"; the search chooses between the two families andshapes=chooses how the winner is written back, with the coefficient and the structural parameter adjusted together so the prediction is unchanged.est="vae"gainsvaeControl(covCenterType=)("median", the new default, or"mean"),vaeControl(covCenter=)for per-covariate centering values such asc(WT = 70), andvaeControl(catCutoff=).The
est="vae"covariate search now considers factor and character data columns, which were previously dropped without comment. Each becomes a set of 0/1 indicators against the most frequent level per subject, with levels held by fewer thancatCutoff(default 5%) of subjects lumped into that reference. Several levels of one factor may enter a parameter together; only alternate shapes of one covariate are mutually exclusive.-
vaeCovariates()now returns one row per candidate search column, addingraw,shape,levelandgroupcolumns, and takes the sameshapes,covCenterType,covCenterandcatCutoffarguments as the fit.Together these change the default
est="vae"covariate search: more candidate forms are considered and centering moves from the mean to the median, so selected covariates and estimates may differ from 7.0.1. SettingvaeControl(shapes="power", covCenterType="mean")reproduces the previous search. vaeControl(covSelectMaxExact=)is now measured in bits of feasible-support space (sum over covariates of log2(1 + shapes tried)) rather than a plain candidate count, so the exact branch-and-bound keeps the same worst-case node budget whether a covariate carries one shape or several. With a single shape per covariate the setting means exactly what it did before. The default stays17: re-measuring withtools/benchVaeCovSelect.Rputs the exact-vs-L0Learn crossover at roughly 16 bits in BOTH regimes (one shape per covariate and two), which is what makes a single threshold in these units meaningful.The variational inference method previously called
est="advi"is now two methods,est="emvi"(variational EM) andest="fbvi"(full Bayes), sharing a shared control –emviControl()withfbviControl()as its thin wrapper, the wayimpmapControl()/impControl()already work (wasadviControl()). The old name was wrong on both halves: there is no automatic differentiation in the implementation (the gradients come from the FOCEi forward sensitivities), and the default mode was never the published algorithm but a variational-EM hybrid. The two modes were previously selected bypointEstimate=, which is kept but now defaults to whichever the chosenestimplies;estwins over a contradicting value and says so.covMethod="advi"is likewise nowcovMethod="vi".est="advi"never appeared in a released version, so no deprecation shim is provided.est="vae"andest="emvi"now estimate the omega off-diagonals of a correlated random-effect block (eta.cl + eta.v ~ c(0.1, 0.01, 0.1)), likesaemand thefoceifamily. Both previously kept only the variances and reported the ini correlation unchanged. The estimated block appears infit$omegaand in the updated model’sini(). Only the declared off-diagonals are estimated – a diagonal model is unchanged, andest="fbvi"(full Bayes) errors on a correlated block rather than silently dropping it.est="vae"gainsvaeControl(covSelectMethod=)andvaeControl(covSelectMaxExact=), which make covariate selection practical on large candidate sets. The exact branch-and-bound blows up past a few dozen covariates (a single 30-covariate latent dimension takes ~43s, and the M-step runs one per dimension per iteration). With the suggestedL0Learnpackage installed,covSelectMethod="auto"(the default) hasL0Learnpropose candidate supports for any latent dimension holding at leastcovSelectMaxExact(default 17, the measured wall-clock crossover) candidates, counted afterpinCovariatestrimming. Those are candidates only: each is scored with the same exactRSS/omega + penalty*|S|objective, the same OLS and the same tie-break the branch-and-bound uses, then improved by an add/drop/swap local search – soL0Learn’s own objective and scaling cannot shift a selection. Below the threshold the search stays exact and unchanged. When the exact search would be impractical butL0Learnis not installed, the fit errors rather than run it silently;covSelectMaxExact = Infforces the exact branch-and-bound everywhere. A fit that used the approximate search says so in$runInfoand records it infit$vae$covSelectMethodUsed.est="vae"gainsvaeControl(nonMuTheta="grad"), which estimates a structural populationthetawith no random effect using the exact analytic outer gradient (the machinery behindfoceiControl(fast=TRUE)) rather than the boundedbobyqaregressionnonMuTheta="regress"uses: one augmented sensitivity solve per M-step replaces the derivative-free sweep. Both modes target the same (full outer) objective, so this is an optimizer change: ontheo_sdwith a non-mu-referencedtvit reaches a slightly better objective than"regress"and lands within 0.0005 of the FOCEi maximum-likelihood value. It is chosen for that accuracy, not for speed – it runs slower than"regress"(1.47x with one non-mu theta, 1.13x with three). It covers a conditionally Gaussian model and a single non-Gaussian (ll()/generalized) endpoint, which differentiates the log-density directly. A model outside analytic scope (linCmt(), IOV,fo, a multi-endpoint or censoredll()model) reverts to"regress"with a note in$runInfo.est="vae"residOptimize="twoStage"now applies to a log-likelihood (ll()) or generalized endpoint. Stage two eligibility was “the parameter has a slot in the error-parameter vector”, and such a model has none, so stage two never ran and"twoStage"silently behaved like the experimental joint"optimize"solve. Eligibility is now decided per parameter – an error parameter (as before), OR a parameter nod/dt()right-hand side, initial condition or dosing modifier can reach – so a theta read only by the log-density is optimized in its own frozen-ODE block as intended. A multi-endpoint model with one Gaussian and onell()endpoint gets both its error parameter and its log-density-only theta into stage two.The
est="vae"ELBO now includes the transform-both-sides Jacobian, so a model withlnorm()/boxCox()/yeoJohnson()reports its objective on the DV scale – matching whatest="focei"already does – instead of the transformed scale. No effect on a model without a both-sides transform.est="vae"’s non-mu theta M-step (bothnonMuTheta="regress"and"grad") now optimizes the FULL outer objective – the Laplace determinant,0.5*log|Omega^-1|and the transform-both-sides Jacobian – rather than the joint likelihood at frozen encoder etas. Every mu-referenced theta is held at its current M-step value, so the two modes now differ only in optimizer (exact analytic gradient vs derivative-freebobyqa) and are directly comparable. Ontheo_sdwith a non-mutvthis moves"regress"from 3.4175 to 3.4324 against a FOCEi maximum-likelihood value of 3.4299.Fixed
est="vae"diverging when a structuralthetawith no random effect had noini()bounds. With infinite bounds nothing constrained the non-mu theta M-step, and a parameter whose likelihood is flat in one direction ran away (an unboundedtvontheo_sdreached ~1e68). An unbounded such theta now falls back to a generous finite window around itsini()estimate, chosen wide enough not to bind at a sane optimum; a userini()bound still wins. The unbounded model now converges to the same value as the bounded one (tv3.4324 fornonMuTheta="regress", 3.4294 for"grad", against a FOCEi maximum-likelihood value of 3.4293).est="vae"gainsvaeControl(residRhoend=), the convergence tolerance of the bounded optimizer that estimates the residual parameters (defaults torhoend). Worth setting separately because that step runs with the ODE frozen, so tightening it is far cheaper than tighteningrhoend, which also tightens the structural regression.est="vae"gains an experimentalvaeControl(residOptimize="twoStage"), which estimates the residual-error parameters by block coordinate descent: the non-mu-referenced structural thetas first (driven bydv - f), then the residual parameters alone against the extended least-squares objective over the cached(y, f)pairs, needing no ODE re-solve. It is the only path that can estimate an error model with no closed form, and it beats the moment estimator on both additive (131.79 vs 131.81) and combined (121.03 vs 122.47)theo_sdfits. It is now the DEFAULT, so anest="vae"fit with a residual-error parameter changes;residOptimize="moment"restores the previous estimator. It is also the only path that estimates an error model with no closed form.pow()andlnorm()residuals were previously classified “other” and left SILENTLY at theirini()values – ontheo_sd,pow(prop.err, pw)returned 0.300/0.800 unchanged (objective 154.4 against 134.8 estimated) andlnorm(add.err)returned 0.500 unchanged (objective 26163 against 849). A transform-both-sidesboxCox()/yeoJohnson()lambda was frozen the same way and is now estimated too, bounded to(-2, 2)(boxCox181.6 -> 43.1,yeoJohnson131.8 -> 108.4,boxCox181.6 -> -29.2 ontheo_sd). Residual scale parameters are also floored strictly above zero, since the likelihood’s zero-variance floor (r == 0 -> r = 1) would otherwise make a collapsed residual look attractive to the optimizer.est="vae"gainsvaeControl(sigma0Interp=)for howsigma0becomes the encoder’s initial posterior spread."sd"(default) makes the initial posterior SDsigma0, as documented;"reference"makes itsigma0squared, reproducing the reference implementation (which documentssigma0as a standard deviation, so its squaring appears unintended).est="vae"’s encoder is now conditioned on the covariates, as in Rohleff et al. (2025), which concatenates them to the LSTM’s final hidden state before the head that emits the posterior (torch.cat((hidden[-1], covariates), dim=1)). The covariates were previously not passed to the encoder at all, so the approximate posterior could not express a covariate relationship and the covariate M-step had a weaker signal to read off the posterior means. Fixing it moves the neonatal case study’s covariate estimates close to the reference’s (kin ~ GA3.51 against its 3.45, previously 2.45) and removes a spurious effect. This changes the results of anyest="vae"fit on a model with covariates.est="vae"gainsvaeControl(gammaSeries=), selecting the decaying step-size series used in the smoothing phase:"reference"(default)1/(iter - gammaIter), the textbook Kuhn-Lavielle series the reference uses, or"saem"1/(1 + iter - gammaIter), the continuation formsaemControl()uses (its decay starts at1/2rather than repeating a gain of 1).est="vae"aligns three more details with Rohleff et al. (2025): the smoothing gain is now1/(iter - gammaIter)(it was1/(1 + iter - gammaIter), smoothing a step harder than the reference throughout the tail); newvaeControl(omegaUpdate="suffStat")(default) forms the population variances from the EMA sufficient statistics and assigns them instead of blending them a second time at the M-step gain (omegaonly – the residual error is still smoothed on the SD scale, a documented remaining difference); and newvaeControl(inputScale="reference")(default) computes the encoder-input centering/scaling across the whole padded observation matrix as the reference does, rather than over the observed values only – on a ragged dataset the two differ materially (neonatal SD 1582 vs 506).omegaUpdate="blend"andinputScale="observed"restore the previous behavior.est="vae"covariate selection now regresses the SAEM sufficient statistic (an exponential moving average of the posterior means) rather than the current posterior means, matching Rohleff et al. (2025);vaeControl(covSelectSmooth=)restores the previous behavior. The effect is small in practice, since the M-step gain is 1 untilgammaIter.est="vae"gainsvaeControl(mStepObjective=), selecting the objective the M-step for a structural theta with no random effect is optimized against:"outer"(default) uses the full FOCEi outer objective (the frozen-eta joint likelihood plus the Laplace determinant,0.5*log|Omega^-1|and the transform Jacobian), while"elbo"reproduces the plain variational bound of Rohleff et al. (2025). The default is a deliberate deviation from the reference: the Laplace term is what makes an analytic gradient available for those parameters (the gradient differentiates the marginal likelihood), so under"elbo"nonMuTheta="grad"is downgraded to"regress"with a note in$runInfo. The deviation is confined to that M-step – it does not touch the encoder, the ELBO training step or the covariate-selection criterion – so a model whose structural parameters are all mu-referenced fits identically under either setting.est="vae"gainsvaeControl(pinCovariates=)(defaultTRUE) to respect the covariates already written in the model. When the model declares covariate effects, the automatic BICc covariate search is restricted to those covariate/parameter pairs – it may still drop a declared covariate, but never adds one on a parameter the model did not specify – and the original model is updated with the estimates, writing a dropped covariate’s coefficient as0. A declared covariate that cannot be searched (time-varying, or a raw-linear form on a continuous covariate) is estimated in place by the regress M-step. WithpinCovariates=FALSEa model’s declared covariates are estimated in place and the search is turned off; with no declared covariates the full search runs. Each case is noted in$runInfo. (Time-varying covariates are still reported as excluded from the search regardless of the setting.)est="vae"now honors mu2/mu3 (algebraic/centered) covariate references, likesaemand the mu-focei family, viavaeControl(muRefCovAlg=)(defaultTRUE). A centered covariate such aswt.cl*(WT/70)orwt.cl*log(WT/70)is evaluated into an internal linearnlmixrMuDerCov#column – the centering is carried by the mu2/mu3 data rather than re-applied by the VAE covariate search – so it can be pinned and selected like any other covariate; the original expression is restored in the reported model.The
est="vae"covariate search no longer adds its own centering on top of the model’s. A pinned covariate is searched at its MODEL value (the centering the model specifies – typically already applied by mu2/mu3 referencing – is retained), so the structural theta is the model’s intercept directly. A0/1indicator covariate (e.g.SEXF) is never centered, since it is already in its natural parameterization; other categorical covariates remain mean-centered and continuous ones remainlog(cov/mean).The optimization
sigdignow sets both the ODE solver tolerances and every estimation method’s optimizer convergence tolerance with one consistent formula, so the optimizer converges to exactly the precision the solve supports. The ODErtolexponent ISsigdigandatolsits three orders below –rtol = 10^-sigdig,atol = 10^(-sigdig-3)– the same for every solver (stiff, non-stiff, auto-switching); the sensitivity (atolSens/rtolSens) solves match the main solve (the outer gradient and covariance are built from them, so a looser sensitivity tolerance would degrade analytic gradient/covariance accuracy), while steady-state (ssAtol/ssRtol) solves run one order looser. Every optimizer’s convergence tolerance is10^-sigdigto match (n1qn1epsilon;bobyqa/newuoa/uobyqarhoend;nlminbrel.tol/x.tol;lbfgsb3c/optimfactras10^-sigdig/eps; the FOCEi outer optimizer;saem’s inner residualtol; the standalonenlmandoptim). At the defaultsigdig = 4this is ODEatol = 1e-7, rtol = 1e-4and optimizer tolerance1e-4(previously a symmetric ODE5e-7with optimizer1e-5).sigdigis routed through all of focei/foce/fo/laplace, saem, emvi/fbvi, vae, nlme, nls, and the nlm family.est="nls"keeps a tighter ODE (three orders below the shared target) because its Levenberg-Marquardt step is sensitive to solver noise. An explicitatol/rtolpassed throughrxControlstill overrides thesigdig-derived value.The default
sigdigis now4for every estimation method. The FOCE family (foce/fo/foi/focep),agq/laplace,impmap,posthoc, and the mu-referenced / IRLS variants previously defaulted tosigdig = 3; withsigdignow driving the ODE tolerances, that inconsistency solved those methods a decimal looser thanfocei. A single default keeps every method atrtol = 1e-4.Added sugar aliases for the
optim()methods soest = "neldermead","bfgs","cg","lbfgsb","sann"and"brent"stand in forest = "optim"withoptimControl(method = ...). Any otheroptimControl()options still apply; the alias only sets the method (and its bounded/unbounded handling, so"brent"/"lbfgsb"honor bounds).The inner bounded-
bobyqaoptimizer that fits the residual-error thetas inest="npag",est="npb"and theest="vae"regress M-step now takes a configurablerhoend(final trust-region radius) vianpagControl(rhoend=),npbControl(rhoend=)andvaeControl(rhoend=), threaded to the C++ engine. It defaults to1e-4, matching the optimizer convergence tolerance10^(-sigdig)at the defaultsigdig=4;vaeControlderives it fromsigdigwhen set (npag/npbhave nosigdig, so they use the fixed default). (est="saem"already routes its inner tolerance throughsaemControl(tol=).)FOCEi guards each
theta’s scaling constant per transform, keeping the derivative-basedscaleCwhere it is well-behaved and falling back only in that transform’s singular / out-of-range region. Each parameter keeps1/|init|(linear/additive),1(log-normal), or its transform-specific formula while the value stays inside a band tailored to that transform (the linear band isfoceiControl(scaleCband=), defaultc(0.1, 10)). Outside the band it falls back to the parameter’s native magnitude|init|(NONMEM7 Appendix K, eq 15.2); for a bounded transform (logit/expit/probit/probitInv), if|init|is also out of range it uses the geometric middle of the band. This fixes the singular cases that froze or destabilized the fit –1/|init|blowing up for a small covariate initial estimate (and the issue-641 large-additive case, whose special handling this subsumes),log()at init1,logitat the interval midpoint,factorial/gammaat a digamma zero – while leaving the well-scaled common case, and its results, unchanged.The bounded-transform (
logit/expit/probit/probitInv)scaleCband is now built from each parameter’s OWN low and high bound instead of a fixed cutoff. The derivative-basedscaleCfactors asN * M, whereNis a per-parameter scale using the distance to each bound ((x-low)(hi-x)/(hi-low)forlogit/probit,E/(hi-low)forexpit/probitInv) andMis a bounds-invariant factor that carries the singularity. GuardingscaleCtoN * [lo, hi]applies the same dimensionless band at every bound, sologit(x, 0, 1)andlogit(x, 1, 100)are guarded identically at equal fractional position. Previously a wide interval (e.g.logit(x, 1, 100)) had its healthy largescaleCclipped by the fixedc(1e-4, 10)band and slammed to the midpoint;(0, 1)results are unchanged.Fixed FOCEi
scaleCfor agamma()-transformed population parameter: rxode2 reports it ascurEval="lgammafn", which the scaling setup did not recognize, so it silently received the linear1/|init|default instead of its1/digammascaling.The FOCEi family nudges a structural population parameter (
theta) initialized at exactly0off zero before estimation, controlled byfoceiControl(zeroTheta=)(default0.001), since a zero initial estimate has no native scale to scale by.+zeroThetais used when within the parameter’s bounds, otherwise-zeroTheta; if neither is within the bounds it errors. Fixed parameters (including those fixed at0) are left untouched. Residual error parameters are also left untouched: they carry their own scaleC, so an errorsdset to exactly0still disables that component and a combined error model reduces to the smaller model as before.foceiControl()gainsshi21hMaxandshi21hMin(defaults2.0and1e-4), the upper and lower bounds on the adaptive shi21 finite-difference step used for FOCEi gradients (both the inner eta and, whenshi21maxOuter != 0, the outer theta/covariate finite differences). A larger upper bound lets the gradient of a flat, small-magnitude parameter clear the ODE-solver noise floor. The NLM family keeps its own fixed bounds.The
imp/impmap/qrpemimportance-sampling family is faster: the theta-score M-step, the Monte-Carlo covariance (covMethod="imp", the default) and the per-subject proposal build in the E-step are now parallelized over subjects, using thecoresset in the control’srxControl(defaulting torxode2::getRxThreads()), joining the already-threaded E-step weight loop. All are bit-identical to the single-threaded run at any thread count. This also fixes a latent bug in the theta-sensitivity M-step whered(V)/d(theta)was read from an under-sized per-thread lhs buffer, so a residual-error variance that depends on a structural parameter now contributes the correct M-step gradient.est="vae"now runs multi-threaded. The per-subject encoder forward pass and the exact branch-and-bound covariate M-step (previously serial, dominating the EM and covariate-selection phases) are parallelized over thecoresset invaeControl(rxControl=rxode2::rxControl(cores=))(defaulting torxode2::getRxThreads()), joining the already-threaded decoder solve. The encoder forward pass and the covariate branch-and-bound are bit-identical to the single-threaded run. The encoder backward (gradient) pass is also parallelized by default (vaeControl(parEncoderBackward=TRUE)); its cross-subject sum cannot be reduced in parallel bit-identically, so it is deterministic for a fixedcoresbut differs slightly from the serial path. A note is added to the fit’s$runInfowhen it is active. For bit-identical, fully reproducible results setoptions(nlmixr2.identical=TRUE)(flips the default to serial) orvaeControl(parEncoderBackward=FALSE).The SAEM Louis stochastic-approximation FIM (
covMethod="sa") and the importance-sampling Monte-Carlo observed information (covMethod="imp") are no longer tied toest="saem"/est="imp". They can now be requested as thecovMethodof any mixed-effects estimation method (computed post-fit at the converged estimates) and switched onto any completed fit withsetCov(fit, "sa")/setCov(fit, "imp"). (The population-only NLM family has no random effects, sosa/impdo not apply there.)-
Several estimation families changed their default
covMethodnow that any covariance can be applied to any mixed-effects method:- the FOCEI family (
focei/foce/laplace/agq) now defaults to the"r,s"sandwich (was"analytic"); -
est="vae"now defaults to"r,s"(was"analytic"); -
est="nlme"now keeps nlme’s own covariance ("nlme") by default; - the nonparametric family (
npag/npb) now defaults to the importance-sampling covariance ("imp").est="saem"("sa"), the importance-sampling family ("imp"), the NLM family ("r"/optimizer Hessian),est="emvi"/est="fbvi"("vi") andfo/foi(no covariance) keep their previous defaults.
- the FOCEI family (
vaeControl(bnbStrategy=)selects the frontier discipline for the exact branch-and-bound covariate selection inest="vae":"lifo"(default, the existing last-in-first-out depth-first search),"fifo"(first-in-first-out) or"lc"(least cost / best-first). The solver is exact, so the selected covariates are identical for every strategy; only the search order differs.est="vae"can now estimate structural population parameters that have no random effect (are not mu-referenced). Previously such athetawas frozen at itsini()value because the VAE only estimates parameters in the latent space.vaeControl(nonMuTheta=)selects the treatment:"regress"(default, matchingsaemControl(nonMuTheta=)) injects no eta and estimates each such theta directly by a boundedbobyqaregression against the FOCEi inner likelihood every M-step (bounds from theini()lower/upper, blended with the M-step gain), recovering a no-random-effect population parameter without adding a spurious random effect. The eta-injection alternatives estimate it astheta + mean(eta)(the temporary eta is dropped from the output model):"eta"estimates the injected omega and the typical value;"fix"holds both the injected omega AND the typical-value theta fixed at theirini()values (nothing about the parameter is estimated, so it does not appear in the iteration table);"none"keeps the old freeze behavior. A$runInfonote lists which parameters were converted.-
The analytic observed-information covariance is now the preferred
covMethodacross the mixed-model estimation methods, falling back to each method’s previous default when a model is out of analytic scope:-
est="saem"keeps the stochastic-approximation FIM ("sa") as the defaultcovMethod, now followed by"analytic"and"linFim".covMethod="analytic"computes the FOCEI analytic covariance at the converged SAEM estimates and falls back to the linearized FIM ("linFim") with a message when out of scope or not positive definite; the"linFim"covariance stays selectable viasetCov(fit, "linFim"). -
est="nlme"gains acovMethodargument (c("analytic", "r,s", "r", "s", "nlme", ""), default"analytic") that recomputes the covariance at the converged nlme estimates;"nlme"keeps nlme’s own standard errors (also available viasetCov(fit, "nlme")). -
est="npag"/"npb"(and theirm/ivariants), which previously reported no covariance, now compute one post-fit at the converged estimates (default"analytic"with the finite-difference fallback chain). -
est="imp"/"impmap"/"qrpem"gain acovMethodargument (c("imp", "analytic", "r,s", "r", "s", ""), default"imp")."imp"is the Monte-Carlo importance-sampling covariance that the oldimpCov=TRUEselected (theimpCovargument is removed); the other tokens compute the post-fit FOCEI covariance. -
est="emvi"/est="fbvi"keep their variational covariance ("vi") as the default but now honors an explicitcovMethod(e.g."analytic") without overwriting it with the variational covariance. -
setCov()/getVarCov()acceptcovMethod="analytic"post-fit.
-
A general FOCE-family per-subject log-likelihood can now be built from an
rxode2UI model and used outside of a fit, for MCMC/SAMBA-style algorithms (issue #414).foceiLikLoad()compiles the inner model and sets up the problem (including the data) in memory,foceiLikRun()evaluates the individual log-likelihood at a supplied population parameter vector and eta matrix – in parallel per subject – andfoceiLikUnload()frees it. The likelihood type may be"focei"(with interaction),"focep"(FOCE+) or"foce"(NONMEM-style), andfoceiLikRun(type=)selects the individual joint densitylog p(y_i, eta_i)("joint", the default) or the conditional data log-likelihoodlog p(y_i | eta_i)alone ("cond"). Only one likelihood system may be loaded at a time; loading a second errors until the first is unloaded.fit$etaCIreturns per-subject confidence intervals for each individual’s eta, complementing the existingfit$etaSEandfit$etaRSE. The intervals are the empirical-Bayes estimate plus/minus a normal quantile times the eta standard error, using the fit’scilevel (default 0.95). LikeetaSE, it requiresCWRESin the fit (add withaddCwres()for non-focei methods).est="agq"now supports the analytic outer gradient (agqControl(fast=TRUE)), which was previously available only to the FOCEi family. The AGQ objective is the FOCEi objective with one term swapped –l(etahat)becomeslog(sum_k a_k)over the quadrature nodes, while thelog det, Omega and tbs terms are unchanged – so its gradient reuses the same sensitivity solve and adds the node terms plustr(Ht^-1 dHt/dp)for the node placement. As with FOCEi this replaces the finite-difference outer gradient, so it is exact rather than a difference approximation and costs one augmented solve instead of one extra solve per parameter. The quadrature nodes solve a cheaper 1st-order model than the eta-hat point needs (they never read the 2nd-order block), which is where most of the node cost goes once the grid grows. Requiresinteraction=TRUE; a fit that cannot use it falls back to finite differences rather than failing.FOCEi
fast=TRUE(and the*fwrappers) now handle general log-likelihood (ll()) and generalized (Poisson, binomial, …) endpoints analytically, where they previously fell back to finite differences. For such an endpoint the per-observation prediction is the log-density, so the inner Hessian is the exactH = Omega^-1 - sum d2(logLik)/deta2assembled from a second-order sensitivity model at the empirical Bayes estimate. Both the objective’slog|H|and the Almquist outer gradient use it; the gradient’s parameter derivative ofHcomes from a batched central finite difference of the analytic second-order sensitivities (no third-order tensor). This is markedly faster than the finite-difference outer gradient for models with many subjects. Endpoints outside the analytic gradient’s scope (multiple endpoints, censored observations,linCmt(), IOV,nAGQ>1, or a bounded parameter transform) fall back to the finite-difference gradient, and a model whose second-order expansion is unsupported keeps the finite-difference inner Hessian – all transparently, rather than failing.covType="analytic"now coversest="agq"as well (it previously declined fornAGQ > 1and fell back to the finite-difference covariance). The AGQ observed information is the FOCEi one with the same single term swapped, so thelog dethalf is reused unchanged and only the data half becomes an expectation over the quadrature nodes plus a covariance between their score contributions. AtnAGQ=1it reduces to the FOCEi observed information exactly, and the FOCEi and Laplace results are unchanged. Validated against a finite-difference oracle (tight ODE tolerance, Richardson extrapolation): the AGQ standard errors agree to that oracle’s own noise floor. As with the gradient, a model outside its scope – a general or multi-endpoint residual variance, censoring, IOV, a finiteagqLow/agqHiclamp,cholSECov=TRUE, orinteraction=FALSE– reports why and keeps the finite-difference covariance.Requesting an unsupported
est=method (e.g. a typo) now prints the available estimation methods grouped by category (Linearized, Integral approximation, Stochastic EM, Nonparametric, Machine learning, Optimizer (NLM family)) with a short description of each, instead of a single flat list. Callingnlmixr2()with no arguments prints the same grouped list (and invisibly returns it). The newnlmixr2AllEstType()returns the same information as a data frame, and each built-in method carriestypeanddescriptionattributes (e.g.attr(nlmixr2Est.focei, "type")) that third-party methods can set to join the list.est="npag"/est="npb"now PIN the current ODE solve during the residual-error (err) parameter optimization instead of re-integrating. Those parameters do not change the predictionf, so each subject’s states are cached at its posterior etas and the ODE is frozen (op_focei.freezeOde) while onlyris recomputed – for a mixture the frozen recompute reuses each component’s cached states rather than re-solving them. A structural regressor (which does movef, including an estimated per-component clearance) still re-solves. Results are unchanged.SAEM mixture models now fix per-subject membership by default (
saemControl(mixProbMethod="regress"), the new default): each subject is hard-classified to its best component once, held fixed, and the soft-EM responsibility step is skipped (reusing the existing responsibility-weighted machinery via a 0/1mixWeights). This avoids the soft-EM collapse (a component running away to a degenerate value) and is lower-bias on both well-separated and overlapping component evaluations; on heavily overlapping components it can be higher-variance, so the previous soft-EM behavior remains available withmixProbMethod="regularized". Because membership is fixed, the S-step solves each subject once under its own component (a per-subject mixest regressor) instead of running one MCMC chain per component – roughly annMix-fold reduction in ODE solves per iteration. Split-ETA mixtures (a separate eta per component, which start symmetric and must differentiate during the fit) automatically fall back to soft-EM (regularized).SAEM warm-starts its residual-error parameters from the observed per-endpoint moments at the initial predictions (additive SD from
sqrt(mean(err^2)), proportional SD fromsqrt(mean((err/f)^2))), the same moment estimateest="npag"/est="npb"use –saemControl(residWarmStart=TRUE), the default. Because SAEM forms this at the unconverged population prediction, the proportional moment excludes near-zero predictions (where between-subject variability dominates) and the warm-started value is clamped to a sane multiple of theinivalue. SetresidWarmStart=FALSEto start from theiniresidual values. For mixture models the warm-start is disabled (the poor population initial fit would inflate the residual and stop the components from separating).The proportional residual moment used to warm-start
est="npag"/est="npb"(and now SAEM) guards against a near-zero prediction: the ratio iserr / (abs(f) <= 1e-6 ? 1 : f), so anfat (or near) zero no longer blows up the proportional moment.SAEM now estimates population
thetaparameters that have no associated random effect (the SAEMphi0fixed effects) by a bounded direct optimization of the observation likelihood each iteration –saemControl(nonMuTheta="regress"), now the DEFAULT – keeping them as plain directly-estimated regressors instead of stochasticphi0draws with a shrinking variance. The optimization uses robust coordinate descent within a local trust region, honoring each theta’sini-block bounds, and holdsphi0fixed once the optimizer owns it. On a simulated model with three no-eta thetas (ka,V, a Hill power) this recovered them far more accurately than the old handling (e.g. the absorption theta RMSE dropped ~16x), at some extra runtime (the objective re-solves the ODE). The previous behavior is available withsaemControl(nonMuTheta="eta"). For mixture models this falls back to the stochasticphi0block (the direct optimizer cannot partition a per-component structural theta by subject membership).est="npag"/est="npb"now ESTIMATE a mixture (mix()) model’s component structural parameters (e.g. a per-subpopulation clearance) instead of holding them at their initial values. The residual/regressor step optimizes them against the exact mixture negative log-likelihood-sum_i log(sum_m a_m exp(cll_m))(NONMEM7 eq 1.182), marginalizing over the components with the current proportionsa_m(which the proportion update step moves); each per-component conditional log-likelihood carries the-0.5*log(r)penalty, so the additive residual does not collapse. Verified: a two-subpopulation clearance model recovers both component clearances and the mixing proportion, with a non-zero additive SD.The per-endpoint residual moment warm start now attributes each observation to its endpoint via a new rxode2 accessor (
getIndCmt, reading the CMT time-varying covariate), so a multi-endpoint model warm-starts each endpoint’s residual from its own moment. Requires the matching rxode2 (function-pointer table index 82).est="npag"/est="npb"now estimate the residual-error parameters with EXTENDED LEAST SQUARES at the individual predictions instead of the marginal likelihood. The marginal likelihood over a flexible nonparametric support rewards a vanishing residual (each support point can then fit its subjects arbitrarily well), so the residual could drift toward zero. The residual step now minimizes the exact conditional normal negative log-likelihoodsum_obs(0.5*(f-dv)^2/r + 0.5*log(r) + 0.5*log(2*pi))at the posterior-mean etas (equivalently extended least squares – same minimizer) – the0.5*log(r)term penalizesr -> 0, giving the saem/focei residual (e.g. theophylline add.sd ~ 0.73, prop.sd ~ 0.15) rather than a collapsed one. Each variance-scale parameter is warm-started (and, for a single scale per endpoint, set) from the saem-style per-endpoint moment: an additive SD fromsqrt(mean(err^2)), a proportional SD fromsqrt(mean((err/f)^2)), both on the transform-both-sides scale (so lognormal / box-cox are handled on the transformed residual). A non-mu structural “regressor” is optimized in the same step, with the posterior-mean etas re-derived per candidate so the eta grid cannot stale-absorb the structural shift (this identifies it, e.g. recovering theophylline’s clearance from a deliberately-wrong start). After the residual + regressor thetas converge, a final adaptive-grid pass re-optimizes the support with those thetas held CONSTANT, so the support is the nonparametric MLE of the mixing distribution for the fitted residual and the D(F) global-optimality certificate is restored (~0). npb runs the same residual/regressor step inside its sampler. (A mix() model’s structural component parameters are held at their initial values – the ELS step is not mixture-aware; the components are handled by the mixture marginalization and proportion update.)est="npag"now picks the initial grid size automatically from the model’s dimensionality whennpagControl(points=)is not supplied:max(2028, 512 * n_eta)(2028 is the Pmetrics NPAG default, which covers a low-dimensional model but grows sparse and can collapse in high dimensions). Theophylline (3 etas) resolves to 2028 (matching Pmetrics); warfarin (8 etas) to 4096. Supplypointsto override.est="npag"is more robust on high-dimensional models (many etas), validated by a golden comparison against Pmetrics NPAG on the Warfarin PK/PD model (transit absorption + Emax turnover, 8 parameters): the per-cycle Psi build is now per-row log-sum-exp normalized on the non-gamma path too, so a hard subject’s conditional density cannot underflow a whole row to zero (which aborted condensation); the Burke interior-point solve ridges the Newton matrix and retries instead of aborting when it is ill-conditioned; andnpagControl()exposesgridWidthandgridBounds("auto"/"ini"/"both") so a bounded, high-dimensional grid can be focused on the plausible region (an unbounded box collapses the support). These are numerically transparent for well-conditioned fits (the normalization restores the exact objective; Burke weights are scale-invariant).est="npag"/est="npb"now estimate non-mu structural fixed-effect parameters (a theta with no eta, e.g.ke <- exp(tke), which npag’s grid otherwise does not cover – it covers only mu-referenced and residual/likelihood parameters). By default they are optimized as “regressors” in the residual step: the boundedbobyqamoves them alongside the residual parameters, re-solving the ODE per candidate (they feed the states, so the ODE freeze is turned off for that step). This identifies them sharply – e.g. recovering theophylline’s clearance from a deliberately-wrong start, and a bimodal mixture proportion (p1 = 0.70) that the grid alternative recovered only weakly. The opt-innpagControl(muExpand=TRUE)instead uses the saem-style mu-expansion: inject a pseudo-eta (ke <- exp(tke + eta.tke)), grid-estimate, and recover it as a fixed effect at finalization (support-mean folded into the theta, injected random effect collapsed; the injected eta carries a FIXED omega, excluded from the free omega objective like IOV, so it also works in mixture models).residOptimize="none"holds the structural regressors together with the residual parameters. (A non-mu-referenced ETA – an eta with no paired theta – needs neither: the npag box already covers every eta, so it is a grid dimension estimated as a pure random effect.)est="npag"now supports generalized (non-normal) / user-ll()likelihoods. The nonparametric objective sums the inner per-observation llikObs, which for a non-normal endpoint is exactly the user’s log-likelihood, so the objective is already correct; the residual/likelihood parameters (e.g. a Student-t’s degrees of freedom,iniDf$errnon-NA) are estimated with the same frozen-ODE bounded step as the residual parameters. Freezing the ODE during that step is valid only when every optimized parameter feeds the post-solve f/r alone (err-tagged) – if a non-err parameter ever enters the optimized set the step re-solves instead. gamma is forced off (a non-normal endpoint has r == 1). A non-mu-referenced structural fixed-effect parameter cannot be placed on the grid and is held at its initial value, reported in the fit’s$runInfo.est="npb"handles non-normal endpoints too (the Gibbs sweep sums the same llikObs).est="npb"now runs the residual/regressor optimization (previously it held the residual-error and non-mu structural “regressor” thetas at their initial values and only sampled the mixing distribution). With the sampled mixing distribution held fixed, the same boundedbobyqastep npag uses fits the residual thetas (add/prop/ lnorm/lambda/ar) and any structural regressor – recovering, e.g., theophylline’s clearance from a deliberately-wrong start.npbControl(residOptimize=)selects it:"alternate"(default) re-fits during burn-in and then holds the thetas fixed for the sampling phase (so every collected draw shares the converged residual scale),"final"fits once at the converged draw,"none"holds them at their initial values. Unlike npag, npb does not optimize the assay-error multiplier (gamma) – the residual thetas are fit directly.est="npag"andest="npb"now support mixture (sub-population)mix()models. Each subject is split into per-component pseudo-subjects and the conditional likelihood is marginalized over the components using the mixture proportions (p(y_i | phi) = sum_m mixProb_m * p(y_i | phi, component m)). npag updates an estimated proportion each cycle by an EM step (support points and weights held fixed); npb samples the proportions inside the blocked Gibbs sweep – each subject draws a component from its posterior responsibility and the proportions are drawn from Dirichlet(1 + component counts), with the posterior-mean proportions reported in$env$npbMixProb. Afix()ed proportion is held at its ini value in both.est="npb"now supports multiple independent chains (npbControl(nchains=)): the stick-breaking Gibbs sampler runs once per chain (seed offset per chain), the posterior-mean draws are pooled, and a Gelman-Rubin R-hat per eta is reported in$env$npbRhat(~1 at convergence; > ~1.1 flags non-convergence).est="npb"is faster: the two per-sweep loops that re-solve the ODE serially (the support-location Metropolis-Hastings step, and the mixture-proportion Gibbs step formix()models) now solve their per-subject conditional likelihoods in parallel over subjects, matching the already-parallel Psi build. The proposal and accept/reject draws stay serial in their original order, so a fixed-seed fit is bit-for-bit identical regardless of thread count.est="npag"is faster: it no longer does a redundant full conditional-density build at the first cycle (the degeneracy check now reads the working build’s per-subject maxima), and the one-time D(F) global-optimality scan is smaller by default and configurable vianpagControl(dfScan=)(-1auto,0to skip the certificate, or an explicit scan size). Neither change affects the fitted support, Omega, thetas, or objective.npagControl(cores=)andnpbControl(cores=)set the number of threads used for the parallel per-subject conditional-likelihood solves. The default (NULL) uses the currentrxode2thread count (rxode2::getRxThreads()); an integer sets the thread count for the fit and restores it afterwards.est="saem"now fits general log-likelihood (ll() ~ expr) models the saemix way (the model returns the per-observation loglik; the standard MCMC kernels use-llas the observation loss). The solve event data keepsDVwhen the model references it (previously dropped, so the likelihood solve errored “parameter(s) required for solving: DV”); the fixed-effect-only (phi0) parameters are optimized with the boundedbobyqahonoring the ini-block bounds (so a likelihood SD stays non-negative). Normal-endpoint saem is unchanged.Nonparametric engines (cont.):
est="npag"optimizes the residual parameters with the boundedminqa::bobyqa, honoring the ini-block lower/upper bounds of each residual parameter (e.g. an additive SD stays >= 0, an AR correlation in (-1,1)). An unbounded optimizer could wander into an invalid region, so newuoa / nelder-mead are no longer used for the residual step (theresidTypecontrol is removed).SAEM general log-likelihood: the fixed-effect-only (phi0) refinement step (saemix “ind.fix10”,
distribution=general) is now optimized with the same derivative-free optimizers as the residual step (nelder-mead / newuoa, selected bytype) instead of L-BFGS-B – the model emits no analytic d(ll)/d(phi0), so the previous finite-difference-gradient L-BFGS was pure overhead. phi0 does not enter the ODE, so the states are solved once and held fixed while phi0 is optimized (ODE-freeze), each evaluation recomputing only the log-likelihood. The SAEM-side L-BFGS plumbing (phi0 gradient, trampolines,lbfgs*config) is removed; FOCEI’souterOpt="lbfgsb"is unaffected.Nonparametric engines (cont.): the
npagresidual-parameter optimization now freezes the ODE states – the inner likelihood solves each (support point, subject) once and re-evaluates only the outputf/rfor each candidate residual theta, skipping the (costly) re-integration. Results are identical to the full re-solve; on a combined-error theo fit it is ~35% faster, and much more for models with expensive ODEs. Exposed as a generalfreezeOdeoption on the inner likelihood (off by default, so all other engines are bit-identical).Nonparametric engines (cont.):
est="npag"now estimates the residual-error parameters generally. A single variance-scale parameter (pure additive or proportional) is handled by the fast gamma up/down search folded into that theta; anything else – combined additive+proportional (the add/prop ratio a single gamma cannot recover), multiple endpoints (eachadd.sd/prop.sd), and transform (boxCox/yeoJohnsonlambda) or autocorrelation (ar) parameters – is optimized against the nonparametric objective with the support points and weights held fixed, using the same optimizers as SAEM (residType:"newuoa"default, or"nelder-mead"), with gamma as a warm start. TheresidOptimizecontrol selects"alternate"(default, every cycle),"final"(once at the converged support), or"none"(hold at ini). On a simulated two-endpoint model npag recoversadd.sd1=0.20 andadd.sd2=1.47 (truth 0.20 / 1.50), matching FOCEI, where a single global gamma had forced them equal; on simulated AR(1) data (truear1.cor=0.6) it recovers ~0.54 from a 0 start where gradient FOCEI stalls at thear1.cor=0 saddle. The reported residual reflects the estimate. Note: because the support distribution is flexible it can absorb additive residual scatter, so the additive term of a combined error model may be smaller than a parametric fit (documented in?npagControl).-
Nonparametric engines (cont.): the
npag/npbconditional likelihood now folds in the transform-both-sides (dTBS) per-observation Jacobian, solnorm,boxCox, andyeoJohnsonresidual models are handled correctly and lambda-type transform parameters are estimable. Proportional and combined additive + proportional error are supported, and the global-optimality certificate D(F) is now evaluated at the fitted gamma (so it reaches ~0 for proportional/combined models with gamma optimization on). A model whose transform link sees a non-positive prediction (e.g.lnormat an observation where the prediction is- now raises a clear error instead of an Armadillo empty-matrix crash.
Nonparametric engines (cont.): the
npag/npbengines now support fixed parameters. Fixed populationthetas (including fixed residual parameters such asadd.sd <- fix(0.7)) are held at their ini value. Fixed-Omegaetas – for example a fixed inter-occasion varianceiov.ka ~ fix(0.05) | occ– remain support-point dimensions but keep their variance held at the fixed value instead of being estimated, so IOV models fit.Nonparametric engines (cont.):
est="npag"now reports the global-optimality certificate D(F) ($env$npagDF; ~0 certifies the nonparametric maximum likelihood), records a per-cycle parameter-history trace through the shared scale.h printer ($parHistData), and installs the reportedOmegamasked by the model’s sparsity so correlated-eta models keep their off-diagonal terms. AR(1) and other transform-both-sides / structured residual models are supported (the residual enters asf + sqrt(r)*eps, so any structure carried inrflows through the conditional likelihood).Validation: a bimodal-recovery test confirms
est="npag"recovers a two-subpopulation (fast/slow absorption) parameter distribution – both modes carry substantial weight and the recovered cluster means land near the simulated truth – the defining nonparametric capability a single-mode parametric random-effect model cannot reproduce.est="npb"(nonparametric Bayes) is now a usable engine: a truncated stick-breaking Dirichlet-process mixture sampled by a blocked Metropolis-within-Gibbs sampler (cluster assignments, stick weights, MH support locations). It reuses the same conditional-likelihood primitive as npag and returns anlmixr2FitDatawith the posterior mixing distribution ($env$npbSupport/npbWeights), per-subject posterior-mean etas, and posterior draws of the population mean (npbMeanDraws) for Bayesian credible intervals.npbControl()exposespoints(truncation K),alpha,burnin,nsamp,propSd, andseed. (Gelman-Rubin multi-chain convergence is a follow-up.)est="npag"is now a usable engine: it returns a standardnlmixr2FitDataobject with the nonparametric population summary (mean + variance mapped to the reportedtheta/Omega), per-subject posterior-mean etas, and the discrete support-point distribution attached to the fit ($env$npagSupport,npagWeights,npagPosteriorEta,npagGamma,npagNspp).npagControl()exposespoints,cycles, andgammaOptimize. (The reportedOmegauses the support-point variances; correlated-Omega models and the global-optimality certificate are follow-ups.)Nonparametric engines (cont.): added the residual-error magnitude (gamma) optimization inside the NPAG cycle (per-cycle up/down search). Gamma scales the residual variance inside the FOCEi inner likelihood, so censoring (BLQ/ALQ via the M3 censored likelihood – the normal tail probability below/above the limit) and transform-both-sides are handled correctly at the scaled error. The objective uses a log-sum-exp row normalization for numerical stability. Generalized (non-normal) likelihoods are not supported and are rejected with an error. Note: the npag/npb objective is the nonparametric marginal log-likelihood and is NOT comparable to NONMEM/FOCEI -2LL.
Nonparametric engines (cont.): assembled the NPAG adaptive-grid cycle (Yamada Alg 1) – Sobol grid, Psi, Burke IPM, weight/QR condensation, adaptive-grid expansion (
npExpandGrid), and the eps/F convergence controller. Runs end-to-end on Theophylline (exposed asnpagCycle_ahead of the full fit-object wiring).Nonparametric engines (cont.): added the Sobol initial grid (
npSobolGrid), weight-threshold and QR rank-revealing condensation (npCondenseWeights/npCondenseQR), and the eta-space support-point box (.npEtaBox, control-selectable viagridBounds/gridWidth).Nonparametric engines (cont.): added the conditional-likelihood primitive (
npEvalCondLik) and the parallel Psi-matrix builder (npBuildPsi), reusing the FOCEi inner solve so residual-error models, transform-both-sides and censoring carry over unchanged.Scaffolding for two native nonparametric estimation engines,
est="npag"(nonparametric adaptive grid) andest="npb"(nonparametric Bayes), plus their mu-referenced sugar variantsmnpag/inpagandmnpb/inpb(OLS and IRLS covariate M-step). Both reuse the FOCEI inner likelihood machinery; the estimation loop runs in C++. The algorithm itself is added in subsequent releases (the drivers currently report that estimation is not yet implemented).Fix the covariance matrix (
$cov) of a bounded-parameter fit run with an unbounded method (e.g.saem): the internalrxBoundedTr.<name>name leaked into$covand the back-transform Jacobian was not applied to it, so the reported standard errors were on the internal (transformed) scale.$cov(and the stashed full theta+Omega covariance) are now renamed to the original parameter names and Jacobian-corrected; Omega and residual terms are untransformed so they pass through unchanged.The nlm parameter-history machinery can now be driven by an external optimizer.
nlmerSolveGrad()gains arecordargument that logs the evaluation’s population parameter estimate (the per-subject mean of thephicolumns) into the resident scale, andnlmGetParHist()is now exported so an externally-optimized engine (e.g.babelmixr2’s nlmer, driven bylme4::nlmer) can recover the accumulated parameter history before.nlmFreeEnv(). A new optionalshowOfvfield in the nlm solve control hides the objective column for these engines (they record parameters only).
New estimation methods
est = "emvi"andest = "fbvi"(emviControl()/fbviControl()): variational inference in the style of Kucukelbir et al. (2017), mean-field or block full-rank family.emviis variational EM (variational posterior over the etas, population parameters point-estimated by an M-step);fbviadds the population vector to the variational posterior under flat priors. Neither is the published ADVI algorithm and neither is named for it: the gradient comes from the FOCEi forward sensitivities rather than automatic differentiation, and evenfbvicarries omega as per-eta log-variances rather than freely. The whole optimization runs in one C++ call, reproducibly and independent of the thread count.est = "impmap"andest = "imp"(impmapControl()/impControl()): importance-sampling EM in the style of NONMEMMETHOD=IMP, with the E-step proposal at each subject’s MAP mode (impmap) or running conditional mean (imp). Supports mu-referenced, mixture, bounded andfix()ed models; the reported objective is a FOCEi evaluation at the EM estimate. Quasi-random (Sobol) importance sampling (qr=, Leary & Dunlavey 2012) and SIR M-step acceleration (sir=) are available and stay thread-count independent.est = "qrpem"(qrpemControl()): sugar for the impmap EM withqr = TRUEandsir = TRUE.Mu-referenced FOCEI family:
mfocei/ifocei,mfoce/ifoce,mfocep/ifocep,magq/iagq,mlaplace/ilaplace(with matching*Control()functions). Mu-referenced population and covariate-coefficient thetas are profiled out of the outer optimizer by an in-C++ OLS (m*) or IRLS (i*) regression; bounded mu parameters are regression-updated with a clamped step. NewfoceiControl()optionsmuModel,muRefCovAlg,muModelTol,muModelMaxCycles,muModelClampRetries.focep/mfocep/ifocep: thefoce/mfoce/ifocemethods withfoce = "foce+"forced.*fconvenience methods (focef,foceif,focepfand the mu/irls variants): the base method withfoceiControl(fast = TRUE)as the default.
FOCEI / FOCE
-
foceiControl(fast = TRUE): analytic FOCEI/FOCE outer gradient from Almquist- sensitivity equations, solved for all subjects in one threaded rxode2 solve; out-of-scope models fall back to finite differences. Covers censored M2/M3/M4, an estimated boxCox/yeoJohnson lambda,
matExp()/indLin(), foce+, modeled dosing (f()/lag()/rate()/dur()), and mu-referenced covariate reuse. Underfastthe outer optimizer defaults tolbfgsb3candmcetadefaults to-2(Eq-48 warm-start of the next inner problem).
- sensitivity equations, solved for all subjects in one threaded rxode2 solve; out-of-scope models fall back to finite differences. Covers censored M2/M3/M4, an estimated boxCox/yeoJohnson lambda,
covMethod = "analytic"(folding in the oldcovType): exact analytic observed-information covariance for FOCEI/FOCE matching NONMEM$COV MATRIX=R, covering additive/proportional/combined error, censored M2/M3/M4 (censOption = "gauss"), estimated lambda, foce+,matExp()/indLin(), and mu-referenced/covariate parameters; out-of-scope fits fall back to the finite-difference sandwich.covFull = TRUE(now the default) reports the full theta + residual + Omega covariance for both the analytic and finite-difference methods, with Omega rows named by the random effect (om.eta.cl/cov.eta.cl.eta.v).covMethod = "r,s"is a true sandwichsolve(Rfull) %*% Sfull %*% solve(Rfull),"s"issolve(Sfull),"r"issolve(Rfull);covFull = FALSEkeeps the theta-only shape.foceiControl(foce = c("nonmem", "foce+")):"nonmem"(default) freezes the FOCE residual variance at theeta = 0prediction to match NONMEM;"foce+"keeps the live conditional variance.foceiControl(censOption = c("gauss", "laplace")): censored (M2/M3/M4/BLQ) inner-Hessian treatment;"gauss"(default) matches common tools,"laplace"uses the exact censored second derivative.foceiControl(warm = c("calc", "save")):"calc"(default) warm-starts eachn1qn1inner problem from the eta Hessian recalculated at the current theta.Residual (error-model) parameters are now included in the focei-family covariance (only fixed, IOV and mixture-probability thetas skip).
Mixture (
mix()) support forfocei/foce/fo/foi.
SAEM
saemControl(covFull = TRUE)(default): full theta + residual + Omega covariance from the linearized FIM. NewcovMethod = "sa"(stochastic-approximation Fisher information, Kuhn & Lavielle 2005).parHistDatarecords off-diagonal Omega block covariances.saemfits general log-likelihood endpoints (ll(name) ~ <expr>, e.g. time-to-event); fixed-effect-only parameters are refined by bounded L-BFGS-B (saemControl()gainslbfgsLmm/lbfgsFactr/lbfgsPgtol/lbfgsMaxIter).
matExp() / indLin()
- Matrix-exponential / inductive-linearization models estimate with the focei, nlm and SAEM families, matching the equivalent ODE model; compartments are ordered source-first from the
k_<from>_<to>graph so default dosing is placed correctly.
Output and utilities
The nonparametric eta-space outputs now carry the eta names: for
est = "npag"the support-point matrix (fit$env$npagSupport) and posterior eta matrix (fit$env$npagPosteriorEta) get eta column names; forest = "npb"the same two matrices plus the posterior mean draws (fit$env$npbMeanDraws) get eta column names, and the per-eta R-hat vector (fit$env$npbRhat) gets eta row names.est = "npb"now prints its per-sweep iteration history through the shared iteration printer (like every other method) and stores it on the fit asparHistData; the sampler’s results are unchanged (bit-identical).The importance-sampling (
covMethod = "imp") covariance step now shows a progress bar over its finite-difference evaluations, like the focei covariance step (shown when iteration printing is on).New
vaeCovariates()returns the covariatesest = "vae"would explore.New
formatMinWidth()for shorter$parFixeddisplay;$parFixedis rebuilt with data.frame operations (#346, #516).All estimators share one iteration printer (
iterPrintControl(),src/scale.h) with a common row layout; analytic gradients are tracked as their ownparHisttype and the fit header reports the gradient and mu-model used, e.g.(outer: lbfgsb3c; grad: analytic; mu: irls).est = "vae"training runs entirely in C++ (vaeTrainCpp_) and reparameterizes the inner problem in place, so fits are substantially faster.
Bug fixes
Estimation
covMethod="analytic"now works for models with an estimatedboxCox()oryeoJohnson()lambda, which previously always fell back to the finite-difference covariance. The augmented model emits a residual-variance sensitivity for every sigma parameter including lambda, while the shared gradient/covariance model drops only the non-lambda sigma directions; the extra column widened the per-subject sensitivities past the covariance buffers and the assembly errored. Only the dropped directions are restored now.The analytic covariance says why it declined. Errors raised while it is assembled were caught and reported as the generic “not available for this model”, which is indistinguishable from a genuine out-of-scope model; they are now reported as
analytic err<n>: <message>in$runInfo, where<n>identifies the entry point. A dozen internal bail-outs that returned silently now name their reason too.-
The FOCEi-family objective function is now reproducible, and no longer depends on how the ETAs were reached. The inner problem uses finite-difference steps (
etahf/etahrfor the ETA gradient,etahhfor the FD Hessian) that are searched once per subject and then reused, so whichever call came first fixed them – during optimization that is the warm-start Hessian (foceiControl(warm="calc")) or an early inner iterate, at an ETA that is not the one being reported. All three are now re-searched at the reported ETAs before the final objective is computed. Two consequences:Repeating a fit now gives the same objective function value, and the same value regardless of the number of threads. It previously varied between runs of the same model on the same data, and differed between a threaded and a single-threaded run.
Objective function values change, most visibly for models with a non-normal endpoint (
ll(),dnorm(),t(),cauchy(), count or ordinal), which difference the whole inner Hessian. A fit evaluated at supplied ETAs (etaMat=,maxInnerIterations=0) and the same fit optimized to those ETAs now agree exactly, where before they could differ by more than 100 objective units on an 8-ETA model.
-
The mu-referenced methods (
est="mfocei","ifocei","mfoce","ifoce","mfocep","ifocep","magq","iagq","mlaplace","ilaplace") no longer discard a control belonging to another method in the FOCEi family. Each*Control()replaces its class rather than appending, so afoceControl(),focepControl(),agqControl()orlaplaceControl()was treated as invalid and silently replaced with defaults –sigdig,covMethod,fast, the tolerances and the iteration caps were all dropped, reported only as a note in the fit output. Such a control is now converted and the settings are kept.- The conversion keeps the METHOD’s identity. A setting is carried over only when it differs from the defaults of the control it came from, so a
foceControl()cannot quietly runest="mfocei"as FOCE, norest="magq"as FOCE in place of the quadrature – while a deliberateagqControl(nAGQ=5)orfoceiControl(interaction=FALSE)is still honored.
- The conversion keeps the METHOD’s identity. A setting is carried over only when it differs from the defaults of the control it came from, so a
The ETA-drift theta reset (
foceiControl(resetThetaP=),resetThetaFinalP=) now defaults to OFF. It re-centered a mu-referenced theta by the mean ETA and restarted the fit, but when the ETAs cannot re-center – every omega fixed, or a model whose misfit the ETAs must absorb – the shift did not stick and the reset repeated until the restart cap errored the fit out (“Maximum number of theta resets (10) exceeded”). Where it did converge it reached a worse optimum than leaving it off. SetresetThetaP=to restore the old behavior.Fixed a theta-reset restart reporting the PREVIOUS attempt’s objective function. The restart reuses the fit environment, and the objective was only computed when the environment did not already carry one, so a restarted fit could report an objective (and the
OBJF/AIC/BIC/log-likelihood derived from it) belonging to the aborted attempt rather than to its own parameters.The nlm family (
est="nlm","nlminb", …),est="nls"and the importance-sampling EM sensitivity model now honor the covariate interpolation declared in the model (nocb(),linear(),midpoint()). Their gradient and prediction models were generated without those lines, so they always used the defaultlocf()interpolation.Fitting many models in one R session uses far less memory. Each compiled model retained a source reference back to the session it was built in, and compiled models are kept for the life of the session, so the retained state grew with every model fitted. A compiled model now retains well under a megabyte instead of tens of megabytes.
foceiControl(fast=TRUE)now solves its augmented outer-gradient model in the shared FOCEi solve pool (single-endpoint models), sized for the augmented model and with that model’s event (“jump”) sensitivities installed for the batch. This makes the analytic gradient exact for modeled dosing (f()/lag()), which previously crashed or fell back to finite differences on that path; multiple-endpoint models keep the previousrxSolveroute.est="vae"withnonMuTheta="grad"solved its augmented outer-gradient model throughrxode2::rxSolveon every M-step iteration instead of the shared FOCEi solve pool. The pooled and fallback routes are numerically equivalent, so this cost time rather than accuracy.The analytic outer gradient could silently degrade to finite differences.
vaeOuterSolve_()returnedR_NilValuefrom aList-returning function, which builds an empty list rather thanNULL, so every refusal and every failed augmented solve looked to the caller like a successful solve that returned nothing. Affectsest="vae"withnonMuTheta="grad"and any caller sharing that path.foceiControl(fast=TRUE)now computes the analytic outer gradient entirely in C++ forest="foce"/"focep",est="agq"and general-likelihood (ll()) endpoints, asest="focei"already did. Those three shapes previously returned to R on every gradient evaluation to rebuild the fit’s etas, omega and setup as R objects; besides the cost, that let R run between the augmented solve and the assembly, where it could disturb the shared solve pool.foceiControl(fast=TRUE)fell back to finite differences for every model with nod/dt()– a purely algebraicll()/generalized endpoint such as a Poisson or logistic regression. Such a model has no ODE state sensitivities and needs none (its prediction derivatives are plain symbolic ones), but the augmented sensitivity model refused to build on the empty expansion, and the pooled solve additionally required a non-zero ODE state count. Both are fixed, so these models now get the analytic gradient; measured against central differences of the objective, agreement is within 6e-7 relative.foceiControl(fast=TRUE)no longer returns to R for the outer gradient at all. The R implementation it used to fall through to has been removed: it was a second copy of the same mathematics that had to be kept in step by hand, and reaching it rebuilt the fit’s etas, omega and setup as R objects on every gradient evaluation. A model the analytic gradient cannot handle now goes straight to finite differences, as before, just without the intervening attempt.est="vae"withnonMuTheta="grad"evaluates the same C++ gradient.The
est="nlm"family (nlm,nlminb,bobyqa,nlsand relatives) solved its prediction model without compacting the shared solve pool to that model’s own state count. The pool is sized for the larger sensitivity model, so the predictions were read back at the wrong stride whenever the two differ. No current result changes – for the models covered by the tests the two size the same, so no compaction was needed – but the mismatch is removed rather than left latent.-
foceiControl(fast=TRUE)now uses the analytic outer gradient for multiple-endpoint models, which previously took the slower finite-difference route. Enabling this needed a fix: rxode2 normalizesCMTinside each compiled model by subtracting that model’s own sensitivity-compartment count, which is right for a standalone solve but means peers of different sensitivity depth cannot share one translated event table. Pooled, the inner model resolved every observation to no endpoint at all, so its prediction, residual variance and eta sensitivities evaluated to zero – the conditional estimates collapsed toward zero andDVwas silently log-transformed. The shared solve pool now re-bases theCMTcovariate for whichever model is reading. Single-endpoint models were never affected.- General-likelihood models (
ll(), and named distributions such aspois()/binom()) with more than one endpoint likewise use the finite-difference gradient, with a message saying so. Single-endpoint models of that kind are unaffected and use the analytic gradient (nlmixr2/nlmixr2est#838).
- General-likelihood models (
The FOCE EBE Newton convergence tolerance is no longer derived from
sigdig; it is fixed at1e-9, the value it shipped with, andfoceiControl(foceEbeTol=)overrides it. Deriving it made the analytic FOCE gradient available or not depending on the requested digits.-
FOCEi: the inner eta-reset / eta-nudge machinery could make the objective function depend on the optimizer’s history rather than on
thetaalone, so the samethetacould return values hundreds of objective-function units apart. With a derivative-free outer optimizer (the defaultbobyqa) this corrupts the interpolation model and the fit stalls, oscillates, and can exit “normally” at a point worse than one it already visited. Fixed by:- Making the inner restart cascade monotone: each nudge restart is now a candidate and the best eta found is the one kept. Previously every
n1qn1restart overwrote the previous result, so the last restart won even when it was worse. - Repairing the
if (!tryAgain)re-check guards in that cascade, which were unreachable (always evaluated insideif (tryAgain)). Once the first nudge fired, every remaining restart ran unconditionally and the eta was then zeroed regardless of the result. - Making the standardized-eta reset per component. A single eta in its tail previously zeroed the subject’s entire eta vector, discarding every converged EBE that subject had.
- Fixing
eta1SD, which was computed as1/sqrt(etaS)whereetaSis Welford’s sum of squared deviations rather than the variance. It is now divided byn - 1, and a zero/non-finite variance disables that criterion for the component instead of producingInf(which made it fire for every nonzero eta).
- Making the inner restart cascade monotone: each nudge restart is now a candidate and the best eta found is the one kept. Previously every
The per-subject “did this ODE solve fail” check now scans only the part of the solve buffer that the subject’s solve actually wrote. When a method sizes the shared solve buffer for a larger model and runs the inner solves compacted against it (
est="impmap","imp","qrpem","advi","emvi","fbvi",est="vae"withnonMuTheta="grad", andfoceiControl(fast=TRUE)with a generalll()endpoint), the check read past that point into slots holding stale values left by an earlier, wider solve of the same reused buffer. A staleNaN/Infthere was reported as a failed solve that had not happened, needlessly loosening ODE tolerances and, once the retry budget was spent, latching the loosened tolerance for the rest of the fit. Objective values for those methods may change slightly as a result.Fixed
est="vae"freezing a declared covariate effect when the covariate reaches its coefficient’s model line only through an intermediate variable (e.g.wt70 <- WT/70; ka <- exp(lka + beta*log(wt70) + eta.ka)). The coefficient was mis-classified as a plain non-mu-referenced structural theta: frozen at its initial value undernonMuTheta="none"and, undernonMuTheta="eta"/"fix", an eta was injected into the mu-referenced expression, erroring the fit (“2+ single population parameters in a single mu-referenced expression”). Covariate-coefficient detection now reads rxode2’s ownmu2RefCovariateReplaceDataFrame(the same table.uiModifyForCovsfolds into annlmixrMuDerCov#column), which already recognizes the coefficient through the intermediate, so the declared effect is estimated in everynonMuThetamode (issue #801).Fixed
est="vae"withvaeControl(nonMuTheta="grad")silently discarding every update to a residual-error parameter. An error parameter’s live value is the internalavector, and the theta slot is rebuilt from it on each evaluation, so the gradient M-step’s theta-only write was overwritten before it was read (the"regress"path already wrote both). The residual was left near its starting value – ontheo_sd,add.sdconverged to 1.70 against 0.80 for"regress", with an objective ~86 units worse – while the structural theta still looked correct. The gradient step now writes the error parameter back toa, and"grad"reaches a slightly better objective than"regress".est="vae"withvaeControl(nonMuTheta="grad")now warm-starts a residual parameter from the closed-form moment estimate on its first gradient step, as the"regress"path already did. While the regress optimizer owns the error parameters the closed-form M-step leaves them alone, so a residual held itsini()value for the whole KL warmup and the gradient steps had to reach the optimum from there – a residual started far from it never arrived, and the result got worse the longerklWarmupwas (ontheo_sdstartingadd.sdat 3.0: 1.99 atklWarmup=50and 2.50 at 150, against 0.80 for"regress").est="nlme"now honorssigdigfor the ODE solver tolerances. A reversed condition madenlmeControl()fall back toatol=rtol=1e-4wheneversigdigwas set (i.e. always, since it defaults to4) and only passsigdigthrough when it wasNULL; the tolerances are now derived fromsigdiglike every other method.Fixed the FOCEi
scaleCband guard corruptingest="vae"covariate selection. The guard only rescues a genuinely-computed derivative-based scaling constant (> 0) now; an uninitializedscaleCof exactly0is left for the usual min/max clamp instead of being overwritten with|init|. The overwrite had broken VAE covariate discovery on theophylline (no covariates selected, betas collapsed to0).est="vae"withcovariateSelection=FALSEnow estimates the covariate coefficients written into the model – both linear (beta*WT) and transformed (beta*log(WT/70)) effects – rather than holding them at theirini()value. They are fit in place by the regress M-step regardless ofnonMuTheta(previously fixed undernonMuTheta="none"and errored under"fix"/"eta"); a coefficient set withini(... ~ fix())still stays fixed.est="impmap"now estimates the non-mu structural and residual-error thetas of a general (customll()) likelihood model. For such an endpointrx_pred_is the log-likelihood itself andrx_r_is0, so the Gauss-Newton M-step skipped every observation (V<=0) and left those thetas frozen at their initial values; the M-step now uses the analyticd(ll)/d(theta)directly (empirical-Fisher information), so a rawll()fit recovers the same parameters as the equivalentadd()model.est="npag"/est="npb"no longer error withunused argument: 'dfScan'when the post-fit importance-sampling covariance is recomputed (thedfScanfield leaked into the down-convertedfoceiControl).est="npag"/est="npb"with a transform-both-sides (lnorm/log/box-Cox) endpoint whose model prediction is non-positive at some observation (e.g. a pre-dose observation where the structural prediction is0) now records a note in the fit’s$runInfoinstead of silently fitting the rxode2-floored value with no indication.est="vae"withnonMuTheta="regress"now shows the regressed non-mu-referenced thetas in the iteration table and parameter history. The M-stepbobyqaregression already estimated them, but they were omitted from the printed parameter walk (only the latent-space thetas, omega, and residual error were shown), so their progress was invisible; they are now appended to each row with the correct back-transform.est="vae"covariate selection no longer silently selects nothing at 32 candidate covariates. The best-subset step enumerated all2^nCovsubsets, which is undefined behavior atnCov = 32(1u << 32wraps to1, so only the empty model was ever tried) and intractable well before that. It now uses an exact branch-and-bound over the same L0/BIC objective, returning the identical optimum while scaling to a few dozen covariates. The selection penalty now also follows the reference implementation’s warmup ramp, tunable viavaeControl(covSelectAlpha=)(default2, ramped to1overklWarmupiterations); ramp iterations are labeledCovSel rampin the iteration table.est="vae"no longer errors withreplacement has 0 rowson data that has noAMTcolumn (dose-free datasets such as the neonate weight data); such rows are now treated as observations (EVID = 0).est="saem"no longer dies withargument is of length zerowhen building the SAEM model list. Somerxode2versions omit thearcolumn from a model’spredDf, and the SAEM autocorrelation helpers indexed that column directly; they now fall back to theiniDf(err == "ar") representation when the column is absent.A mu-referenced or method-variant FOCEi fit (
ifocei,mfocei,foce,focep,agq,laplace, and the*ffast variants such asifoceif) that needed to restart – for example after a zero/bad-gradient theta reset – died withfocei$control must be a focei control object. These controls are all built byfoceiControl()and then reclassed to their own class, so they do not carry"foceiControl"in their class vector, and the restart-path environment check rejected them even though the fit had been set up from a valid control. The check now recognises the whole FOCEi control family.Models that combine
linCmt()with ODEs (for example a solved PK driving an effect-compartment ODE) now estimate correctly with the FOCEi and nlm families; the linear compartments are solved as ODEs for those methods. Previously the sensitivity compartments those methods add (one per eta for FOCEi, one per theta for nlm) shifteddepot/centralpast the compartment numbers the data was translated against, so the dose silently landed in a sensitivity compartment, every prediction came back0and the objective function was meaningless. Since the model is then no longer mixing a solved system with ODEs, these fits now warn (recorded infit$runInfo) that the analyticlinCmt()could not be used.est="saem"was never affected, keeps the analyticlinCmt()and does not warn, as dolinCmt()models with no other ODE (#286).est="saem"no longer estimates afix()ed theta that has no eta attached to it; such a parameter now stays at its initial estimate, as it already did for the FOCEi family. The direct phi0 optimization (nonMuTheta="regress", and general-likelihood models) takes over phi0 partway through the fit and skips the update that restores fixed values, so a fixed non-mu-referenced theta drifted off its initial estimate. Estimates of non-fixed parameters are unchanged.foceiControl(freezeResidGrad=TRUE)(the default) no longer makes a fit die with “maximum number of theta resets (10) exceeded”. The base solve that caches the states/EBEs for the frozen gradient ran without the gradient flag set, so an ETA-drift theta reset raised inside a gradient restarted the whole fit – on every gradient, until the reset limit tripped (#641).A model that combines an inter-occasion variability (IOV) term with a zero inter-individual variability eta on another parameter (for example
eta.ka ~ 0alongsideiov.cl ~ 0.1 | occ) no longer fails with “initial ‘omega’ matrix inverse is non-positive definite”. With IOV present the omega is a per-condition list, so the zero-eta detector could not read the eta names and left the zero eta in the matrix, making it singular; the zero eta is now detected and removed as usual. Restoring the original model after such a fit also no longer errors forest="saem"(includingtable=list(cwres=TRUE)), where the IOV eta is re-expressed as per-occasion id-level etas (#627).est="saem"no longer collapses subjects that combine two dosing episodes with overlapping clock times separated by anevid=4reset – for example a crossover where an IV arm and a depot (f(depot)) arm share the same times. SAEM solves each subject in the ODE solver’s internal time-sorted order, which relocated the reset ahead of the first episode’s observations and merged the two episodes into one trajectory; SAEM then reported a nearly constantPREDand a grossly inflated residual (focei/posthocalready handled this correctly). The reset episodes are now offset internally so the solve times increase within a subject, matchingrxSolve()/focei; predictions are unchanged because only time-since-reset matters (#455).The
est="fo"/est="foi"linearization pass returned an intermediate fit object with an emptycontrol, so.updateParFixed()silently fell back to default table settings (ci/sigdigTable) instead of the fit’s control (#517). The FO/FOI fit now carries its control, and an intermediate fit without a method-specificnmObjGetControlsurfaces its stored control rather than returningNULL.est="nlme"now accepts the commonprintcontrol alias, sonlmixr2(..., "nlme", list(print=0))no longer errors withunused argument: 'print'.nlmeprints through its ownverboseoption, soprintmaps to it (print=0runs quietly, any positive value is verbose); an explicitverboseis still honored whenprintis not supplied.FOCEi/FOCE models with a trigonometric term whose argument is a compound expression divided by something (for example a sinusoidal enterohepatic-cycle release
sin(2 * 3.14 * (time - mtime1) / period)) no longer fail to build with “too few arguments to function ‘sin’”. The fix is inrxode2’srxFromSE()(which was dropping the whole argument, emittingsin()); a regression test is added here (nlmixr2/nlmixr2est#513).FOCEi now estimates a population parameter that is initialized at exactly
0(e.g. a covariate effect or an additive term) instead of leaving it frozen at its starting value. The default scaling constant is1/|initPar|, which isInfwheninitParis0; it clamped toscaleCmaxand made the parameter effectively unoptimizable.getScaleC()now falls back to unit scaling when the initial estimate is0.A single-subject / fixed-effect (“N of 1”) model – one whose only random effects are fixed to zero, which are dropped before estimation – now gives an actionable error when a method that requires random effects (
fo,foi,saem,nlme) is used, pointing to methods that can fit it (focei,foce, or a population method such asnlminb,bobyqaornls). The error also keeps the user’s original model name instead of reporting the internal.mod(issue #493).A focei model whose predictions do not depend on any random effect (for example
y ~ dpois(rate)whererateis a fixed population parameter rather than a model-predicted value) no longer reports the generic “Aborted calculation” message. The underlying cause is raised directly with guidance on linking each endpoint’s distribution parameter to an eta-varying model quantity (#515).est="saem"’s “mis-match in nbr endpoints in model & in data” error is now actionable: it reports the number of endpoints in the model versus the data, lists the observation compartments found in the data, and points the user to check that theCMT/DVIDvalues match the number of model endpoints (error terms). This is the common case of a dataset with extraDVIDlevels that the model has no matching endpoint for (issue #579).est="emvi"/est="fbvi"now reject a mixture (mix()) model up front with a clear message (rxode2::assertRxUiNoMix) instead of running a wrong fit that ignored the mixture structure and then failed late in the output tables with a cryptic “the probabilities in a mixture must sum to a number between 0 and 1, they sum to: 0”.
Estimation and convergence
A FOCEI fit that hits a theta reset and then restarts no longer aborts with
Assertion on 'fitEnv$etaObj$ID' failed: Must be of type 'integer', not 'factor'. The restart re-validated the previous attempt’setaObf, whoseIDcolumn is a factor of the original subject IDs; it is now coerced back to an integer so a genuinely non-converging fit reports its real reason instead of this spurious assertion (#470).Fixed the
est = "agq"quadrature node scaling. The adaptive Gauss-Hermite nodes were placed without the change-of-variable factor, so increasingnAGQdid not converge to the marginal likelihood – it converged to a wrong value (still better than Laplace, so the objective looked reasonable). The nodes are Gauss-Hermite for thee^{-x^2}kernel while the integral has ane^{-z'z/2}kernel, so they belong atsqrt(2) * chol(Ht)^-1 * xwith anexp(x'x)untilt. With the fix the objective converges to the exact marginal likelihood asnAGQgrows. EverynAGQ > 1objective value (and any standard errors derived from it) changes;focei/foce/fo/laplaceare unaffected.The analytic covariance (
covType = "analytic") now falls back to finite differences undercholSECov = TRUE: the covariance step re-factors the eta Hessian with the generalized Cholesky, which for a non-positive-definiteHtdiffers from thechol()the analytic observed information assumes.Fixed the
fast = TRUEanalytic gradient for models whose residual variance depends on the prediction (prop,add+prop,combined1,pow,add+pow): a determinant chain-rule aliasing injected a spurious term.Fixed the
fast = TRUEanalytic gradient/covariance for a random effect shared across parameters, enabled sensitivity reuse for a covariate on an eta-less parameter, and fixed the gradient never being used live (it read finalize-only state and silently fell back to finite differences).Fixed the FOCE (
interaction = FALSE) objective and empirical-Bayes estimates: the residual variance is now supplied at theeta = 0prediction, so ODE andlinCmt()FOCE agree and match the NONMEM reference.Bounded the Shi (2021) finite-difference step so a curvature-free search can no longer corrupt the shared solver state.
Fixed
muModel = "lin"/"irls"erroring with two or more covariate expressions (#711) and the user-fixed covariate-coefficient regression bias.Fixed
impmapControl(impSeed = )being ignored.FOCEI now updates additive mu-referenced population parameters with large-magnitude initial estimates (#641).
FOCEI theta resets now keep every reset population parameter inside its bounds instead of restarting the optimization out of range, and stop with an informative error when a parameter’s bounds are infeasible (#454).
Covariance and standard errors
setCov(fit, "analytic")no longer silently installs (and mislabels) the"r,s"finite-difference covariance when the analytic covariance cannot be computed for the model; the fit’s covariance is left unchanged instead.fit$etaSEcolumns are now labeledse(<eta>)(matchingfit$etaRSE’srse(<eta>)%); the label was previously applied to a matrix’snames()(a no-op) so the columns came back as bare eta names.covMethod = "r"/"s"/"r,s"standard errors were inflated by a constant factor (sqrt(2)for"r",2for"s") from using2*R^-1/4*S^-1; they now match NONMEM$COV(#666).A bounded-parameter fit under an unbounded method (e.g.
saem) leaked the internalrxBoundedTr.<name>into$covwithout the back-transform Jacobian;$covis now renamed to the original parameters and Jacobian-corrected.The analytic FOCE/foce+ covariance no longer falls out of bounds (from dropped
eta = 0solve slots) to the finite-difference Hessian; the general(f,R)covariance reportscovMethod = "analytic"(was"r"), andfoceiCovAnalytic()/getVarCov()reproduce it instead of falling back.Fixed a segfault in the analytic covariance for out-of-scope models (the augmented build freed the fit’s solve before the finite-difference fallback ran), and the sign of the M2 upper-tail term in the censored inner gradient.
The mu-referenced/irls FOCEI-family fits (
mfocei/ifocei/…) now reportCondition#(Cov)/Condition#(Cor)in$objDf; the post-fit covariance install skipped them because the fit tables were rendered before the full-model covariance was recomputed.Converting a fit to a different covariance (
setCov(),getVarCov()) now refreshesCondition#(Cov)/Condition#(Cor)and the eigen diagnostics from the newly installed covariance instead of leaving the previous method’s values in place.SAEM
covMethod = "fim"adds the mu-block Hessian (was indefinite / NaN SEs), and"fim"/"sa"report off-diagonal Omega and combined residual SEs. FixedcovMethod = "linFim"and the SAEM covariance erroring for a single population/covariate parameter, andcov2corfor a one-nonzero-diagonal Omega.
Crashes and stability
Fixed a Windows heap-corruption segfault at more than one core (rxode2 saw every worker as thread 0); the inner loops now pass the real thread id.
Fixed a segfault in
est = "vae"(thread count capped at the solve’s core count) and innlmSetupon the first estimator call of a session.Fixed FOCEi aborting with
Cube::slice(): index out of boundswhenmceta >= 1andmaxInnerIterations == 0, and a heap-buffer overflow / wrong back-transform in SAEM Box-Cox residual models.A non-positive-definite
Omegais projected to the nearest PD matrix (SAEM mid-run, with afit$runInfowarning; and the sym-inv-chol setup for a degenerate fit) so residual/table diagnostics still run; NPDE with a degenerate simulated covariance sets the subject’s NPDE toNAinstead of aborting.Fixed a segfault when a dataset has no observed subject at all (every subject is a placeholder with no
EVID==0row, as in an aggregate-data output eval such asbabelmixr2/admixr2). The no-observation-subject drop now keeps the rows when there is no observed subject to fall back to, andfoceiSetup_no longer reads an empty id vector out of bounds..nlmSetupEnv()also now supplies a defaultiterPrintControlwhen an external caller omits it, instead of erroring withIndex out of bounds: [index='iterPrintControl'].
Output, tables, and printing
vpcSimExpand()no longer merges the entire observed dataset into the simulation when a requestedextracolumn is missing: a dropped filter result meant an unknown column (e.g. a misspelledstratifyinvpcPlot()) spliced every observed column into the simulation, and valid columns dragged the rest of the observed data along with them (colliding with the simulation’s own, e.g.time.x/time.y). Only the requested columns are merged now, and a column found in neither the simulation nor the data warns and is ignored (#830).For models without etas, the
BSV(SD)andShrink(SD)%columns are no longer added to$parFixedand$parFixedDf; they were always blank for these models (#355).Model-defined variables (e.g.
ka,cl,v,tad,dosenum, and any user-added line such asWT.OUT <- WT) are now included in the output table whether or notcwresis requested. PreviouslytableControl(cwres=FALSE)dropped these columns whilecwres=TRUE(the default) kept them, so the same model produced different output columns depending on the residual request (#497).A zero-fixed eta (e.g.
bsva ~ 0) is again restored into the fitted model’sini()/model()blocks when the estimation makes a nestednlmixr2()call (e.g. adding the focei objective or CWRES), sofit |> ini(bsva ~ 0.1)works; the nested call used to wipe the restore info held in a global (#741).augPred()now works on afoceifit whose model has a zero-fixed eta that appears in the prediction (e.g.eta.v ~ 0used in both the ODE and the residual), instead of erroring withparameter(s) are required for solving: eta.v; the simulation model drops the zero eta consistently withsaem(#514).laplace/agqfamily fits label their$objDfrowLaplace/AGQ<n>(matching$ofvType) instead ofFOCEi; previously the defaultinteraction=TRUEmade the interaction label win over the quadrature one. The quadrature objective stays the active one after CWRES;setOfv(fit, "focei")(andaddCwres()) now evaluate the true focei objective on a quadrature fit instead of re-labeling its quadrature value.Restored the
Function Val.objective column and the$parFixedshrinkage coloring; periodic headers now repeat only the column labels.$parFixedhonors a usersigdig/cifor fits with literally-fixed parameters.Literally-fixed population parameters now report their back-transformed value (
exp/expit/probitInv) in theBack-transformedcolumn instead of the raw log/logit-scale estimate.augPred()now keeps the fit’s original subject ids: the returnedidfactor carries the actual (character/factor) ids from the fit instead of the internal integer re-numbering (#450).vpcSim(fit, pred=TRUE)(and hence VPC plots with apredline) now works for models with IOV. With IOV the fit’somegais a list of matrices (idplus one per occasion level), which thepredpath treated as a single matrix and errored withinvalid 'times' argument; the population prediction now zeros every random effect across all omega levels (#629).fit$timeagain attributes model build/compile tosetup/configure(and the nlm family times setup/optimize) instead ofother.Aggregated ODE-solve warnings report the real subject id;
parHistDatashows mixture-probability parameters on the natural scale andfit$mixListreturns all components; iteration printing labels the estimation phase (Burn in/KL anneal/EM/Smoothfor vae,SA/EMfor saem).fast = TRUEwith alinCmt()model downgrades tofast = FALSEwith a message instead of silently falling back per gradient call.est = "vae"with automatic covariate selection now reports the selected covariate coefficients (beta_<par>_<cov>) in$parFixed/$parFixedDfinstead of dropping them when a population parameter is fixed, and the covariate-bearing mu-parameters back-transform (exp) instead of printing on the raw log scale.est = "vae"no longer errors withcannot find parameter 'NA'when a structural (mu-referenced) parameter is fixed withfix(); its random effect is kept (variance estimated) with the fixed value carried in the model.
Data handling
SAEM no longer errors with
No data with IDfor a dose-only subject; observation-less subjects are dropped before estimation and re-inserted into the output with a populationPREDandNAindividual columns, like FOCEi (#687).FOCEi no longer errors with
'names' attribute [n] must be the same length as the vector [m]when a subject’s records are all removed during data translation (e.g. everyTIMEisNA). Such a subject vanishes from the processed data entirely rather than losing only its observations, so it is now detected and dropped from the subject index alongside observation-less subjects (#606).Fixed
nlmControl()listingeventSens/sensMethodtwice. The “initial ETAs were nudged” warning fires only when a nudge actually happened, and a non-defaultmcetaon a fully mu-referenced model falls back to the default with a warning.saemControl(covMethod = "")(skip covariance) no longer errors.
Other
nlmixr2fix()now actually repairs serialized fit components: it previously tested the component name (not the object) for rawness, so the repair loop never ran, and a successful qs2 read was discarded.Fixed
$parFixedreporting an uninitialized-memory denormal (e.g.9.4e-323) as a residual-error parameter’sSE/%RSEfor SAEM fits (#816). The finalization filled theta SEs positionally from a covariance that does not span the residual thetas, reading past the end of its diagonal; the SE fill now maps by the covariance dimnames. Post-fit covariance installs also refresh the displayed$parFixed(previously only$parFixedDfwas updated), so the residualSE,%RSE, and confidence interval now carrysqrt(diag(fit$cov)); a theta with no covariance row gets a blankSEinstead of garbage.A non-default confidence level (e.g.
saemControl(ci=0.8)) is now honored when a covariance install refreshes$parFixed. The refresh readcifrom the model rather than the fit’s control, so it fell back to0.95: the column was labeledBack-transformed(95%CI)over an 80% interval, and any interval it recomputed used the wrong level.
Internal
Removed an unreachable duplicate
missingTabledefault assignment innlmixr2Est0()(issue #385); the earlier default already fixes the value, so the second block could never run. No change to fit results.Removed the last bare
Rf_errorcall from the C++ sources (issue #632): theRcpp::compileAttributes()output now emits the parenthesized(Rf_error)form, and the internalrxErrormacro was switched to(Rf_error)as well, so the package no longer trips Rcpp’s upcomingRf_errordeprecation warning (RcppCore/Rcpp#1247). The C.Callentry-point validators keep their justifiedRf_errorcalluses.Consolidated data preparation and the nlm-family control/fit functions, and the analytic-covariance augmented model now uses rxode2’s chunked
rxOptExpr(); no change to fit results. The test suite runs a single testthat worker on CI/CRAN and parallel elsewhere, with within-solve threads capped to 2 on CRAN.
nlmixr2est 6.1.0
Added focei, foce, foi, fo mixture support in
nlmixr2estFix
foceimixture models with llik residual distributions erroring when a model had exactly one mixture probability parameterFix
fit$mixListreturning only the first mixture componentparHistDataBack-Transformed rows now show mixture probability parameters on the natural probability scale (0, 1) instead of the raw mlogit estimation scale.Fix issue 641: FOCEI now updates additive mu-referenced population parameters whose initial estimates are large in magnitude. Previously a missing branch in
.foceiOptEnvSetupScaleC()letscaleCfall through to the C++ default of1/|init|, which mapped unit steps in scaled space to negligible steps in unscaled space and effectively pinned such parameters at their initial value (e.g.tvemax <- -40with no transform).When model estimation fails, all errors raised during the run are now collected and reported together, instead of only the last error. This is supported by a new
collectErrargument to the internal.collectWarn()helper, which captures errors alongside warnings and returns them in theerrorelement of its result list. As a result, errors hidden byon.exit({rxode2::rxProgressAbort()})handlers (such as the “Aborted calculation” message reported in issue 607) no longer mask the underlying cause; both the inner stop message and any follow-up error fromon.exitare now reported to the user. parameters on the natural probability scale instead of the raw mlogit scale. parameters on the natural probability scaleHardened mixture-model (
mix()) estimation: clearer errors forest="nlme"and invalid initial probabilities, warnings for underflowing/collapsing mixture probabilities, and a fix for the SAEM omega-diagonal floor being raised outside mixture fitsFix segfault in
nlmSetupon the first estimator call of a fresh R session for pooled estimatorsGuard against null pointer arithmetic in inner.cpp
Use OpenMP threading for S matrix calculation
Use OpenMP threading while calculating NPDEs
nlmixr2est 6.0.1
CRAN release: 2026-06-03
Fix LTO violation as requested by CRAN by adding -DARMA_DONT_USE_OPENMP to PKG_CXXFLAGS in src/Makevars.in
Require rxode2 5.1.2 which has the fixed M1-san issues observed here.
nlmixr2est 6.0.0
CRAN release: 2026-05-31
focei,foce,fo,laplace, andagqhave all been successfully made thread safe and parallelized (for a single CPU). The default tolerance relaxation for difficult to solve ODEs has been changed to per individual instead of for the entire population (which is a breaking change, so major release). This should allow more precision for a majority of the subjects in the optimization process.Add
predict(fit, level="ipred"),predict(fit, level="individual")orpredict(fit, level=1)to predict individual fits (with possibly a new dataset).Change test files to
.rdsfilesDrop magrittr
%>%in favor of|>.Breaking change: Minimum R version increased from 4.0 to 4.1.0. This change is required to support the native pipe operator
|>. Users on R < 4.1.0 will need to upgrade R to install this version of nlmixr2est.Bug fixes for deparsing nlmixr2 control objects
nlmand related pooled methods now run in parallel (based on ID)Tests are optimized to reduce redundant fits and run in parallel.
nlm(and related pooled optimizers:bobyqa,newuoa,uobyqa,n1qn1,lbfgsb3c,optim,nlminb) now support the same censoring behavior (M2/M3/M4) as FOCEI and SAEM. The$censInformationfield is populated for these fits in the same way as FOCEI/SAEM.agqControl()andlaplaceControl()now haverxUiDeparse()methods so they can be saved better in packages likenlmixr2saveandshinyMixR.Added new
outerOpt; methods tofoceiand related methods (agq,laplace,foce,fo,foi): “uobyqa” and “newuoa”.-
saemand other methods now respect bounds by default by internally adding the appropriate transform and then applying the back-transformation just before returning.For parameters that are mu-referenced, this breaks mu-referencing. When it breaks mu-referencing there is a warning issued. The best practice is still to have unbounded parameters with mu-referencing.
If you want to ignore this behavior you may use
control=list(boundedTransform=FALSE)or for saemcontrol=saemControl(boundedTransform=FALSE) The mu referencing covariate procedure was made less fragile to support mu referencing in conjunction with iov and bounded parameter transformations.
Add some bench-marking capabilities and small speed fixes for focei/saem
nlmixr2est 5.0.0
Remove
qsand change toqs2. This breaks backward compatibility.Default to non-compressed nlmixr2 objects
nlmixr2est 4.1.1
CRAN release: 2025-10-09
Request nlmixr2est’s pre-processing hooks for
augPred(),vpcSim()and$simInfo, which fixes augPred in cases whereetas=0are used innlmixr2(#587)Fix scale.h so that
scaleType="none"does not also requirescaleTo=0Request Armadillo 15 with the special flag in the new
RcppArmadilloFix
foceiwithout etas (and without log-likelihood normal) to runELS(See #590).-
Change the IOV implementation (#596):
- Now shows estimates as
CV%orsdwithout shrinkage calculation. - Allow different forms of
iovestimation, controlled byiovXform. - Retains the
iovparameter(s) in the outputdata.frame. - With
iov, the$omegashows a list of variability by the conditioning variable(s). -
fit$iovwill show the IOV deviations by the conditioning variables(s) with the exception ofid - IOV models can be used in other estimation methods and inherits the ETA values.
- Now shows estimates as
Added
$etaMatmethod fornlmixr2fits to give the value that needs to be passed between each estimation method (related to iov #596)
nlmixr2est 4.1.0
CRAN release: 2025-08-29
Updated inferring the estimation method from the control object. Requires the control object to have a class of length one and match the estimation method. For example
foceiControl()would assume that the estimation method is related tofocei.Changed Rstudio completion to not evaluate (in case it gets turned on for data.frames) (See #568)
Turned on data completion for items like
$fitMergeInnerBreaking change: Changed the estimation method
posthocto add tables and calculate the covariance by default. It is now a method with it’s own control,posthocControl(). As previously the default is not to include the interaction term (but you can turn it on withposthocControl(interaction=TRUE)).Added
foceControl(),foControl()andfoiControl()for thefoce,foandfoimethods, respectively. They try to convert the related control structures to the correct control structure for the estimation method.Added iov support for
focei,foce, andsaem(#614)Added new estimation method
agqwhich uses adaptive Gauss-Hermite Quadrature to fit a nonlinear-mixed effect model. In this method, you can choose the number of quadrature points to estimate the likelihood, with higher numbers giving more accurate likelihoods. The AGQ implementation in nlmixr2est allows you to specify the number of quadrature points via theagqControl()function, and supports both single and multiple subject models. This method is particularly useful for models where accurate likelihood estimation is critical.Also added a
laplacemethod which is the same asagqwith 1 node (and is numerically the same asfocei,foceor log-likelihoodfocei/laplace, etc), but uses theagqroutine.Fixed saem mu-reference display by not compressing the internal item
saem0.
nlmixr2est 4.0.2
CRAN release: 2025-07-24
The loading and unloading of DLLs has been minimized in this version of nlmixr2est. This avoids loading/reloading the same DLLs and causing the CRAN mac m1 ASAN/USBAN false positive issue observed in CRAN.
Additionally a new function
nlmixr2fix(fit)has been added tonlmixr2est. It attempts to make the fit loaded from a different version of nlmixr2 compatible with nlmixr2 4.0. It also prints out the versions ofnlmixr2that were used when creating this fit. With this information you are more likely to find a way to use the fit in your current session (or in an old session). (Issue #562)
nlmixr2est 4.0.1
CRAN release: 2025-07-19
- Initialize lbfgsb3 error message to an empty string to address valgrind finding (as requested by CRAN).
nlmixr2est 4.0.0
CRAN release: 2025-07-15
When using a model to start a new focei model, the ETAs from the last fit are used as the starting point. Now you can use
foceiControl(etaMat=NA)to skip this and useeta=0for all items.When using
foceiControl(etaMat=fit), this will extract the ETAs from a fit for use in the next optimization.When using a
foceiControl(etaMat=)option nlmixr2 no longer only evaluates the inner problem with theetaMatvalue.-
Add
mcetaoption to"focei".-
mceta=-1is the default; the eta restarts at the best eta from the last step to start the inner optimization. -
mceta=0the eta starts at0to start the inner optimization. -
mceta=1the eta starts at either0or the besteta, which ever gives the lowest objective function to start the inner optimization. -
mceta=nunder the assumption ofomegasamplen-1etavalues and use the lowest objective function of eta sampled, last best eta and eta=0 to start the inner optimization.
-
Fix Rstudio print (issue #536)
Support rxode2’s new
+var()definition insaemSupport literal fixing of residuals (#524). All methods that support a literal fix of residuals have an option
literalFixReswhich defaults toTRUE. To get the behavior from older models you can useliteralFixRes=FALSEMore detailed error messages will be reported for models with errors
nlmixr2est 3.0.4
CRAN release: 2025-02-18
More robust covariance calculation in
focei.Allow hook mechanism to handle piped arguments.
Fix for when output message from optimizing doesn’t print well (#325)
nlmixr2est 3.0.3
CRAN release: 2025-01-18
Moved data check for covariates and required data items to a pre-processing step. This fixes #499. Each method that needs to have a covariate check needs to have a property
covPresent. For example to apply the covariate data check to thefoceimethod you needattr(nlmixr2Est.focei, "covPresent") <- TRUE.Bug fix for non-mu referenced etas when combined with mu referenced covariate values. (See #498)
Changed option for
"saem"to haveliteralFix=FALSE. This makes mu-referencing work better when fixing a population value.
nlmixr2est 3.0.2
CRAN release: 2024-11-23
Fix bug where models where omega boundary warnings caused problems in estimation (#490)
Created a new api for pre-processing ui, allowing adding arbitrary hooks. As written now, this includes literal fix and zero omega as well as added the new rxode2 ui processing.
Fixed compilation to only use -I in most systems for maximum compatibility
nlmixr2est 3.0.1
CRAN release: 2024-10-22
New features
Now when optimizing only a single parameter with
focei-family, will change to usestats::optimize()for the outer problem (#481)When estimating with all fixed population parameters, do a posthoc estimation.
Internally removed
assignInMyNamespace()replacing withnlmixr2global, which fixes some edge case bugs where the nlmixr2 environment was not reset properly.Treated edge case where all initial parameters are zero and change scaling from scaled to unscaled (#486)
Added
mu4 referencing that will change string expressions torxode2numeric values. This allows derived strings to also be treated asmuexpressions (#484)
Bug Fixes
- Fix
foceicovariance step when manyomegavalues are fixed #482
nlmixr2est 3.0.0
CRAN release: 2024-09-18
No binary linking to
rxode2,lbfgsb3candn1q1, which means that updating these will not makenlmixr2estcrash without recompiling.New
mu3 referencing will take context from the model to see if the algebraic expression can be completed from defined model variables; These variable would have to be unique.
nlmixr2est 2.2.2
CRAN release: 2024-05-28
Breaking changes
Saem non-mu reference input parameters/covariates were fixed so they work correctly with fixed parameters (Issue #445)
Focei changed back to having a lower bound for standard deviations when not specified. This means that best model fits may change. You can revert to the old settings by using
foceiControl(sdLowerFact=0.0). You can also change the factors to other values than the default value, that isfoceiControl(sdLowerFact=0.000001)for instance which would multiply the initial value by0.000001when either the lower bound isn’t specified or the lower bound is specified as zero for the error estimates related to error-based standard deviations.-
In
nlmixr2, expressions are optimized. Because of that optimization, numerical rounding differences can cause different directions in optimization when fixing parameters in the model vs. fixing the parameters manually.This means that the fixed parameters in a model vs hard-coded fixed parameters could give different values in the final model.
A new option
literalFixwas introduced which change the fixed population parameters to constants in the model while running the optimization. This makes the output of fixing within the model and fixing manually the same (which is what is likely expected). The default is for this to be turned on (ie.literalFix=TRUE). You can get back the old behavior by using the optionliteralFix=FALSE. In
saem, the monte-carlo sampling occurs for all parameters including non-informative ETAs. A fix ensure that non-informative etas insaemare fixed to zero while sampling thephivalues. This may change results for models with uninformative etas. To ignore the uninformative etas withsaemyou ca use use the priorsaemhandling withsaemControl(handleUninformativeEtas=FALSE).
New features
Gracefully degrade when $cov is not in the right form (see #423)
Add support for PopED in place solving (used in babelmixr2)
If
est=foceiControl()or other nlmixr2 control with the classfoceiControlinfer the estimation method isfoceiAdd back the warnings when estimation methods ignore the boundaries
When using
rxSolve, now respects the values fromtableControl()(#465 and #297)
Bug fixes
- Will emit warnings when the return object is not a nlmixr2 fit (#453)
nlmixr2est 2.2.1
CRAN release: 2024-01-31
- Align with the possibility that linCmt sensitivities may not be present (like intel c++)
Bug fix
-
foceicache needs to be based on the parameter order as well as the model information (#415)
nlmixr2est 2.2.0
CRAN release: 2023-12-12
New Features
Algebraic mu referencing has been implemented in
nlmeandsaem.New estimation method “nlm” has been added to estimate population only likelihoods using
stats::nlmand possibly return a standardizednlmixr2fit.New estimation method “nls” has been added to estimate population only problems. This uses
minpack.lm::nlsNMby default if present, or thestats::nlsNew estimation method “optim” has been added to estimate population only likelihoods. This uses
stats::optimand returns a standardizednlmixr2fit.New estimation method “nlminb” has been added to estimate population only likelihoods. This uses
stats::nlminband returns a standardizednlmixr2fit.New estimation methods from the
minqapackage: “bobyqa”, “uobyqa” and “newuoa” have been added to estimate population only likelihoods. These methods returns a standardizednlmixr2fit.New estimation method “lbfgsb3c” to estimate population only likelihoods. This returns a standardized
nlmixr2fit.New estimation method “n1qn1” to estimate population only likelihoods. This returns a standardized
nlmixr2fit.Added new feature for
vpcSim()where a minimum number of subjects are simulated from the model when trying to fill in ODEs that were not solved successfully. By default this is10. This also works-around a bug when there is only one subject simulated and thedata.framehas a slightly different output.
Breaking changes
Removed
fit$saemTransformedDatasince it isn’t actually used insaemanymore (but will break anyone’s code who is using it)Now the internal function
.foceiPreProcessData()requires the rxode2 controlrxControl()because some of the new steady state lag features need to translate the data differently based onrxControl()options.
Bug fixes
Printing models with correlated omega values and omega values fixed to zero no longer fails (#359)
Add back values for $parHistData (#368)
This requires a new
rxode2which will fix multiple endpoint issues observed (#394)Manual back-transformed values in
$parFixedare now displaying correctly and are calculated based on the confidence interval in the control instead of 95% confidence no matter what (#397)
nlmixr2est 2.1.8
CRAN release: 2023-10-08
- Version bump and a minor documentation update (same as nlmixr2est 2.1.7). This version bump is to simply allow correct binary linkage to rxode2 2.0.14. Otherwise
nlmixr2models will crash R.
nlmixr2est 2.1.7
CRAN release: 2023-09-18
As requested by CRAN, remove
RvmminValues in
$parFixedfor BSV without exponential transformation are now correctly shown (#366)
nlmixr2est 2.1.6
CRAN release: 2023-05-25
Breaking changes
- Since
rxode2now allows simulation withomegahaving diagonal zero elements,$omegaand$omegaRnow reflects this information including the zero omega elements in the output. On the other hand, the other eta-information and standard error information for zero etas are still excluded in$phiR,$phiSE,$etaetc.
nlmixr2est 2.1.5
CRAN release: 2023-04-22
Add
$fitMergeFull,$fitMergInner,$fitMergeLeft,$fitMergeRightas a complement to$dataMergeFull,$dataMergInner,$dataMergeLeft,$dataMergeRight. The fit variants prefer columns in the fit dataset instead of the original dataset. This is useful for goodness of fit plots with censoring since theDVin the fit simulates values under the ipred/residual assumption and will give more appropriate goodness of fits, otherwise these values are the limit of whatever censoring is appliedMoved the mu reference fix for the split mu referenced model here (from babelmixr2)
nlmixr2est 2.1.4
CRAN release: 2023-04-02
Breaking change, now calculate condition number based on covariance and correlation, the names have changed to be more explicit.
conditionNumberchanged toconditionNumberCovand a new metricconditionNumberCorhas been added.A bug in boundary value detection prevented automatic covariance calculation with FOCEi estimation (#318)
Fix
vpcSimso that it will be a bit more robust when it is difficult to simulate.A bug in model piping which did not allow models to be appended to was fixed (rxode2#364)
An internal change was made in
nlmixr2.rxUi()to better support the babelmixr2 PKNCA estimation method (babelmixr2#75)Fixed bug where
$iniUidid not return the initial ui when running nonfoceirelated methods. Also added alias of$uiInito the same function.Dropped Stan headers for this package, also updated to C++17
nlmixr2est 2.1.3
CRAN release: 2022-11-10
Allows
$etaHand related family to be integrated into asaemfit ifcwresis calculated.Fixed a bug where
nlmixrLlikObsin the merged dataset is sometimes namedllikObs, now it is always namednlmixrLlikObsFixed a bug where
nlmixrLlikObsshows up in merged dataset whencwresis not calculated (it was always0), also allowcwrescalculation to pick upnlmixrLlikObsin merged dataset.Dropped
dparserdependency
nlmixr2est 2.1.2
CRAN release: 2022-11-02
Fixes
$etaHmemory corruption so the standard errors of etas are now correctRemoved the memory requirements for focei by
neta*neta*nsubFixed character based covariates so the work correctly (again) with focei. Added a test for this as well.
nlmixr2est 2.1.1
CRAN release: 2022-10-22
Fixes
$dataMergeInnerso that observation-based log-likelihoods work with infusions. Should fix tests withggPMXFixes
$etaSEand$etaRSEto work correctly when there is only 1 eta.Fixes npde valgrind observed on CRAN machines
nlmixr2est 2.1.0
CRAN release: 2022-10-19
Breaking changes
FOCEi
Gill forward differences will not repeat now (by default), You can change back to prior behavior with
foceiControl(repeatGillMax=3)Number of sticky recalculation is reduced to 4; to have the old behavior use
foceiControl(stickyRecalcN=5)n2llhas been changed tollto specify individual log-likelihoods. This was only used in simulation and was not well documented.Generalized log-likelihood is only supported with
rxode22.0.8or later.
FOCEi covariance calculation
The
Smatrix calculation was made a bit more robust to errors in individual gradients. When there are errors in the individual gradient calculation, assume the gradient is the same as the overall gradient. In the tests cases, were reasonable using this adjusted S matrix. This means if some individuals do not have very much data to support a specific parameter, aSmatrix calculation for the population will still be generated. When there is some patients/subject combinations that do not have sufficient data, we will add the following to the run information:S matrix had problems solving for some subject and parameters. TheSmatrix calculation will still fail if the percentage of parameters that are being reset is lower thanfoceiControl(smatPer=0.6)or whatever you specify.The
r,scovariance matrix will now also check for unreasonably small values (controlled byfoceiControl(covSmall=...)) and select a different covariance estimate method even when the “r” and “s” matrices are calculated “correctly”.
New features
What type(s) censoring (if any) is now stored in
fit$censInformationStandard errors of
$etascan now be obtained withfit$phiSE, also available arefit$phiRSE(relative standard error),fit$phiH, (individual hessian),fit$phiC(individual covariances),fit$phiR(individual correlation matrices)Can also use Shi 2021 differences in addition to Gill differences. In our tests (using the same datasets as CPT) these produced worse estimates than the Gill 1983, though it is unclear why since it should be a faster more accurate method. A modified version is used in calculating the individual Hessians of numerically for the generalized likelihood approach.
Generalized likelihood estimation is now present in
nlmixr2estforfocei,foceandposthocnmNearPD()is a function you may use for nearest positive definite matrix. This is derived fromMatrix::nearPD()but is implemented in C/C++ to be used in (possibly threaded) optimization.Individual Hessians can be accessed by
$phiH, covariance by$phiC, eta standard errors by$phiSEand eta RSEs can be accessed by$phiRSE. There areetaaliases for these as well ($etaH,$etaC,$etaSE, and$etaRSE).-
Can now access the individual point’s contribution to the overall likelihood when merging to the original dataset. These merges can be accessed with
$dataMergeFull,$dataMergeLeft,$dataMergeRight, and$dataMergeInner. The columns with the individual data column isnlmixrLlikObs.To calculate the total
focei/foceobjective function, the sum of the likelihoods still need to be adjusted by the omega/eta contribution, and the individual Hessians, and possibly the NONMEM objective function offset constant.
Censoring fixes
- Fixed bug where datasets with censoring that are not lower case
censandlimitdo not produce the correct table output (#180)
nlmixr2est 2.0.8
CRAN release: 2022-06-22
SAEM bug fix
- When loading a
nlmixr2“saem” fit from another R session,nlmixr2will no longer crash withfit$objf
NPDE/NPD fixes
-
NPDEwas identical toNPDeven with correlated models, this was fixed (prior output was actuallyNPDE).
nlmixr2est 2.0.7
CRAN release: 2022-05-23
Use
.zeros()for the matrices in armadillo in addition to relying oncallocto give zero matrices.Fixed one uninitialized object
Fix for
augPredso it works on population only modelsnlmeno longer sets options to treat all covariates as non mu-referenced covariates, but directly calls a function that can turn on or off the mu-reference covariate selection.vpcSimnow tries to simulate IDs that didn’t simulate correctly (with a warning)Export nmObjHandleControlObject
nlmixr2est 2.0.6 – new package
CRAN release: 2022-05-12
nlmixr2est contains the estimation functions within nlmixr2.
FOCEI family changes
Remove lower level
foceiFitfunction. Focei, foce, fo, foi, and posthoc now directly takes rxode2 ui objectsNew error types are supported in focei including mixing theta and etas in residual errors and different types of proportional errors
Different types of additive and proportional errors can be used for each endpoint using
+ combined1()or+ combined2()otherwise it takes the suppliedaddPropoption to figure out which type of combined model is run (by defaultcombined2())Focei model cache is now named
focei-md5Digest.qsand usesqscompression/saving/loading.foceiControl()aligned between other methods.foceiControl(adjLik=TRUE)uses the NONMEM-style objective function throughout.foceiControl(adjLik=FALSE)uses the adjusted objective function throughout, and adjusts it back to the NONMEM objective function.Lag time and other between subject variability differences no longer calculate an ideal relative step size, but an absolute step size when using Gill differences (default)
Objective function checks for infinite/NaN/NA values for the entire solving space and ensures no overflow occurs when calculating the inner hessian
SAEM changes
mu referencing is no longer required for
saem; Internally non mu-referenced values are converted to mu referenced values and the converted back when calculating the nlmixr2 object.-
nlmixr2forced the parameter ordering to (1) population effects,- non mu-referenced between subject effects (3) omega estimates and (4) residual effects. This changes the order that
nlmixr2sees the parameters. Since this is based on a random number generator, the optimization trajectory will be different and have different results thannlmixr
- non mu-referenced between subject effects (3) omega estimates and (4) residual effects. This changes the order that
Components of
omegacan now be fixed.Residual error components can also be fixed.
When optimizing only one residual value, nlmixr2’s saem uses
nlmfrom R, which is more efficient than the nealder-meade method.Lower level
saemfunctions (likeconfigsaem()) are not exported because they are increasingly difficult to use and convert to something standard; a few methods (likeprint,summaryetc) are maintained to view the lower level object and for debugging it.Parameter history and print-out no longer includes fixed parameters.
The model to calculate the residuals more closely matches the model used for estimation to remove small rounding differences that may occur in the models.
Different types of additive and proportional errors can be used for each endpoint using
+ combined1()or+ combined2()otherwise it takes the suppliedaddPropoption to figure out which type of combined model is run (by defaultcombined2())Parameter history and printout now uses standard deviation for additive only components, matching the estimation of the components.
rxode2solving options are now saved in therxControlpart of thesaemControl(). That issaemControl(rxControl=rxControl(...)); This fixes any conflicting option names as well as allowing alignment between the control structures infocei,nlmeandsaemsaemControl()aligned between other methods.
nlme changes
nlmehas been completely rewritten to directly run from therxode2UInlmealways tries to use mu-referencing (when available)Internally
nlmenow uses parallel processing for solving so it should be faster.nlmixr2NlmeControl()(which will overwritenlmeControl()) documents and adds more options tonlme. Also aligned with other methods.weights,fixed,randomcan be specified innlmixr2NlmeControl(). If so, then thenlmeobject will be returned.returnNlmeis a new option that will return thenlmeobject instead of the traditionalnlmeobject.nlme_odeandlme_lin_cmptare both removed.rxode2solving options are now saved in therxControlpart of thesaemControl(). That isnlmeControl(rxControl=rxControl(...)); This fixes any conflicting option names as well as allowing alignment between the control structures infocei,nlmeandsaem
nlmixr2 object change
With
saem, the nlmixr2 function now saves/compresses thephiMinformation. This means the gaussian and Laplacians likelihoods can be calculated when you save the nlmixr object and then restore it later.The nlmixr2 object compresses infrequently used and removes many unneeded objects. Even with compression, the
saemobjects are often a bit bigger since they include the largephiMobject.nlmixr2now supports non-mu referenced ETAs in thefit$parFixedandfit$parFixedDf
nlmixr2 interface change
nlmixr2interface changed to userxode2UIkeepanddropare added totableControlto influence the end data-frame$simInfouses a quoted expression for$rxinstead of a string$simInfo$sigmais a diagonal matrix since now the normal simulation is controlled by the variability modeled as a population value.nlmixr2now allows etas that have initial omega estimates of zero to be dropped from the model (instead of issuing an error about a non-positive definite$omegamatrix)
NPDE changes
- Fixed a bug where the number of simulations for a NPDE calculation are correctly passed by
addNpde(fit, table=tableControl(nsim=500))
VPC changes
vpcfunction rewritten and split out tovpcSim()andvpcPlot()(which is a replacement forvpc()).There were too many mismatches between
vpc::vpcandnlmixr::vpcwhich caused inconsistencies in code based on load order ofvpcandnlmixr. This way both coexist, and you can use thevpcsimulation for other packages more easily (likeggPMX) without creating or summarizing data sinceggPMXhas its own methods for summarizing and creating plots.VPC now directly uses
rxode2::rxSolve
augPred() changes
augPred()has been written to use the new fit object.nlmixr2AugPredwas changed tonlmixr2AugPredSolve()augPreduses the new interface and supports multiple endpoints. The endpoint name is now always on theplot(augPred(fit)).
getFitMethod() change
- Internally, fit estimation method is saved in
fit$est, and nowgetFitMethod(fit)simply returnsfit$est
Delete methods
Many methods lower level utility functions have been deleted.
nmDocx,nmLstandnmSavehave been removed.
Bug fixes
- Now will reset the cache when items cannot be loaded. In the past error messages like
function 'rx_0ba247452048de33b1ffb8af516714fc__calc_lhs' not provided by package 'rx_0ba247452048de33b1ffb8af516714fc_'would cause the estimation to stop. Nowrxode2::rxClean()is run when this occurs.
