Repository navigation
Releases
pynlme v0.5.1
Fixed
- The source distribution includes
LICENSE, which its metadata names; PyPI rejected
0.5.0's source distribution without it (0.5.0's wheels are on PyPI).
pynlme v0.5.0
Rewrite: nlmefit and nlmefitsa are now real implementations, validated against
MATLAB R2023b, R nlme and R saemix. The earlier versions did not fit mixed-effects
models correctly.
Changed
sund_model: an integrator failure (e.g. a stiff system at extreme parameters)
gives non-finite predictions, which the fitting methods reject like any other
non-finite step, instead of stopping the fit with an exception.- nlmefit rewritten as a Lindstrom-Bates implementation (LME step via QR decompositions with a log-Cholesky covariance parameterisation and an analytic gradient; restarts for collapsed variance components; damping for cycling iterations) for
ApproximationType"LME" and "RELME", the algorithm used by MATLAB nlmefit and R nlme. The previous Rust and Python MLE code did not estimate random effects (psi was fixed at 0.1*I and b at zero) and has been removed. - MATLAB name-value arguments are accepted directly (
ParamTransform=...,REParamsSelect=[2, 3],FEGroupDesign=...,CovPattern=...,Options={...}), with MATLAB's 1-based indices.modelfunis called with two arguments whenVis empty, as in MATLAB.bis returned r-by-m. - Options that are not implemented raise
NotImplementedErrorinstead of being silently ignored. Failed fits raise instead of returningbeta0, and there is no silent switch between backends. - Probit
ParamTransformuses the exact normal CDF instead of a tanh approximation. - nlmefitsa rewritten as a SAEM implementation in Python (three Metropolis-Hastings kernels with adaptive scales, simulated annealing, closed-form M-step, saemix-style updates for parameters without random effects, multiple chains, importance-sampling and linearisation log-likelihoods, linearisation standard errors). It replaces the previous Rust and Python SAEM code, which is no longer used.
stats.rmsefollows MATLAB: sqrt(sum(ires^2)/dfe). The error standard deviation is instats.errorparam. For RELME, psi, the error variance and covb are reported as MATLAB does (RSS/N scaling) and BIC uses log(m - f).- The Rust code is now only the compiled kernels (
rust/, modulepynlme._kernels);
the package is still built with maturin, one abi3 wheel per platform, and installing
from source needs a Rust toolchain. compat="matlab"(the default) with"LME"/"RELME"reproduces MATLAB nlmefit's
iteration step by step (matlab_lb.py: LMfit pre-fit, Gauss-Newton PNLS, fminsearch
LME step onlogm/chol, tolFac schedule, error-model weights, forward-difference
derivatives) with MATLAB's default options (TolX = TolFun = 1e-4).
Results agree with MATLAB R2023b's to ~1e-10 on most data, also at its default
options.CovParameterization("logm","chol") takes effect;OptimFun
"fminunc"raises.- A warning when a random-effects variance collapses to zero during the iterations
(results there depend on rounding, in MATLAB too). compat="r"with"LME"/"RELME"(constant or exponential error model) reproduces
R nlme's iteration step by step: PNLS with the covariance updated by EM and nlm
(optif9) and at mostpnlsMaxItersteps, and nlmeControl's defaults (max_iter=50,
tol_x=1e-5, new optionspnls_tol=1e-3,pnls_max_iter=7,min_scale=1e-3). The
fit is R's, also where several local solutions exist and formethod="REML", which
in nlme is not a restricted-likelihood fit.pynlme.r.nlmeacceptscontrol={"pnlsTol": ..., "tolerance": ..., "maxIter": ...}.- The randomized comparison with R requires the same fit (log-likelihood to 1e-3,
estimates to 1e-4), not just one at least as good.
Added
-
An empty
V([], as in MATLAB code) means no group-level predictors. -
Documentation rewritten around three audiences: MATLAB users, Python users, and R users.
-
Proportional, combined and exponential error models for FO/FOCE (reweighting as MATLAB does); with
compat="matlab"the exponential FO/FOCE log-likelihood follows MATLAB in omitting -sum(log y). -
Analytic model derivatives: a model function with a
jacobianattribute (orpynlme.with_jacobian(f, jac)) is differentiated analytically in all methods instead of by finite differences; prepares for SUND sensitivities. -
DataFormat="stacked"|"grouped". Without it the layout follows from the shape of y only; the previous X-based guess (which treated small stacked datasets without a group as grouped) is no longer used. -
ODE models:
pynlme.sund_model(compiled SUND models; optional extrapynlme[sund]) andpynlme.ode_model(SciPy, batched over subjects withVectorization="Full"); Michaelis-Menten validation case with MATLAB references;examples/sund_ode_model.py. -
SAEM samples parameters without random effects during annealing (MATLAB/saemix scheme); the Lindstrom-Bates loop stops when changes only jitter at the model's numerical noise level.
-
nlmefitApproximationType "FO" and "FOCE" (direct maximisation of the linearised marginal likelihood; FOCE with conditional modes). -
Error models "proportional", "combined" and "exponential" for
nlmefit(LME/RELME) andnlmefitsa, andErrorParameters, with MATLAB's definitions. -
stats.pwresandstats.cwres, and MATLAB's definitions for all weighted residuals. -
Vectorization="Full": the model is called once for many groups (one parameter row per observation). SAEM and LME internals work on flat/padded arrays. -
compat="matlab"|"r": MATLAB (default) or R (nlme/saemix) defaults and reporting conventions. -
NChainsfornlmefitsa, defaulting to MATLAB's max(1, round(100/m)). -
R timing benchmark (
validation/r/benchmark.R) and MATLAB error-model, FO and FOCE references. -
Randomized comparison against R nlme on freshly simulated datasets each run (
tests/validation/test_random_vs_r.py) and simulation studies of bias and coverage (tests/validation/test_simulation_recovery.py,--runslow); a CI job runs both with R installed. -
MATLAB R2023b reference fits for nlmefit (LME, RELME, FO, FOCE) and nlmefitsa, and R saemix references; tests compare against both.
-
validation/: reference datasets, R nlme reference fits, MATLAB documentation values, a MATLAB script to generate MATLAB references, and a benchmark against R timings. -
tests/validation/: nlmefit compared against R nlme on six cases and against the MATLAB documentation indomethacin example. -
pynlme.fit: named parameters, data as a dict or Polars DataFrame, results as a
dict (natural-scale estimates, named random effects), withcovariates=for
group-level covariate models. -
pynlme.r: R'snlme()with string formulas,pdDiag/pdSymm,SSfoland other
SS*models, andsummary,fixef,ranef,VarCorr,vcov,logLik,AIC,
BIC,fitted,resid,predict; matches R nlme on the validation cases. -
pynlme.rsaemix interface:saemixData,saemixModel,saemixwith saemix's
control names and defaults,summary,coef,psi/phi/eta(modes or
conditional means),predict(ipred, icpred, ppred, ypred); agrees with R saemix. -
pynlme.predictforfitresults (new data, population or individual level). -
Several observed features per subject:
sund_model(feature=[...])andode_modelwith
a multi-columnoutputread out each row's feature (index in a column ofX) from
one simulation per subject, for stacked data as in MATLAB. -
Model inputs from SUND activities, one set per experiment:
sund_model(activities={experiment: builder}, ...)with the experiment ID in a column
ofV. A buildercontainer -> Activityletssund_modelsimulate the experiment's
subjects in batches; readyActivityobjects are simulated one subject at a time. -
Compiled kernels in Rust (
rust/, modulepynlme._kernels) for the inner loops of
every algorithm: the LME solve and gradient, the EM and nlm (optif9) steps of the R
mode; the QR decompositions, objective,expmandfminsearchLME step of the
MATLAB mode; FOCE's conditional modes and linearised likelihood; SAEM's
Metropolis-Hastings sampler (same chain for a givenrandom_state). The model
function stays Python and is called once per step for all subjects. Same arithmetic
as the NumPy code, which runs without them or withPYNLME_KERNELS=0. -
Benchmarks against MATLAB, R (nlme, saemix) and nlmixr2, all scripted
(validation/run_benchmarks.shruns them with what is installed): speed on the
validation cases (README), scaling to 1000 subjects with a closed-form, an ODE and a
multiple-dose ODE model (validation/scaling/), and accuracy (bias, RMSE and
confidence-interval coverage over simulated datasets,validation/accuracy/). -
Faster with many subjects: the rows of many groups are gathered in one indexing
operation, and the residuals instatsevaluate the model for all groups at once. -
FOCE solves all subjects' conditional modes in lock-step (one model call per step
withVectorization="Full"instead of one per subject).
Removed
- Tests of the removed MLE backends (
test_backend_comparison,test_batched_ffi_optimization,test_performance_optimization) andtest_matlab_baseline(its group-predictor data was incomplete);examples/performance_benchmark.py.
Fixed
- Test Suite: Fixed backend consistency test to properly compare Rust vs Python backends
- Corrected pharmacokinetic model function signature to be static method
- Fixed backend switching mechanism using module-level RUST_AVAILABLE flag
- Adjusted tolerance for backend comparison to account for optimization differences
PyNLME v0.3.0
Added
- Multi-Dimensional Input Format: New support for grouped data format where each row represents a subject/group
stack_grouped_data()function to convert grouped format to stacked formatdetect_data_format()function to automatically detect input format- Automatic format detection and conversion in
validate_inputs() - Support for both 2D (single predictor) and 3D (multiple predictors) grouped input
- Complete backwards compatibility with existing stacked format
- New utility functions exported in main package API
- Enhanced User Experience: Users can now provide data in natural matrix format instead of manually stacking
- Comprehensive Testing: Added
test_multidimensional_input.pywith 7 test cases covering all scenarios - Documentation: Added detailed documentation and examples for multi-dimensional input format
- Examples: Added demonstration scripts showing both traditional and new input formats
Fixed
- SAEM Numerical Stability: Fixed overflow warning in Metropolis-Hastings acceptance probability calculation
- Implemented numerically stable log-space computation to avoid
exp()overflow - Ensures robust SAEM algorithm performance with extreme parameter values
- Implemented numerically stable log-space computation to avoid
PyNLME v0.2.3
Changed
- Rust Backend Architecture - Completely removed hardcoded model logic
- Eliminated all fallback hardcoded exponential decay models from MLE and SAEM
- Refactored all internal methods to require explicit Python model functions
- Removed Optional wrapper types, ensuring clean dependency injection
- Updated
fit_internal,evaluate_model,sample_random_effects, etc. - Improved code maintainability by removing dead code paths
- Backend now exclusively uses user-supplied Python model functions
Removed
- Deprecated Methods - Removed unused
fitmethods with hardcoded models - Legacy Code - Eliminated hardcoded model paths and conditional logic
PyNLME v0.2.2
Fixed
- Rust Backend Integration - Fixed critical issues preventing Rust backend from working correctly
- Corrected model function interface to handle Python functions properly
- Fixed array dimension mismatches (2D → 1D) between Python and Rust
- Removed inappropriate parameter constraints that prevented convergence
- MATLAB Baseline Compatibility - Achieved compatibility with MATLAB nlmefit/nlmefitsa
- Implemented correct bi-exponential model with log parameter transformations
- Fixed parameterization to match MATLAB's
ParamTransform=[0 1 0 1]specification - Updated indomethacin pharmacokinetic model to use proper exponential transforms
- Parameter Optimization - Fixed optimization initialization and convergence
- Corrected parameter passing from initial values (
beta0) to optimizer - Improved gradient computation and parameter updates in Rust backend
- Fixed mixed-effects parameter estimation for both MLE and SAEM algorithms
- Corrected parameter passing from initial values (
Changed
- Test Tolerance - Adjusted MATLAB baseline test tolerance to 0.3 for realistic
algorithmic differences in mixed-effects optimization - Model Implementation - Updated indomethacin model to bi-exponential form with
proper parameter transformations matching MATLAB documentation
Improved
- Algorithm Accuracy - Both nlmefit and nlmefitsa now converge to parameters
close to MATLAB baseline values (within 0.3 tolerance) - Cross-platform Compatibility - Fixed optimization issues specific to macOS
and other platforms - Backend Reliability - Rust backend now properly handles all test cases
without falling back to Python implementation
PyNLME v0.1.15
Fixed
- Wheel Configuration - Fixed PyO3 configuration to use
abi3-py311instead of
abi3-py38, ensuring wheels target the correct minimum Python version - Wheel Building - Cleaned up cibuildwheel configuration to avoid conflicts
between workflow environment variables and pyproject.toml settings - Platform Support - Ensured wheels are built correctly for Python 3.11+
across all platforms (Linux, Windows, macOS)
PyNLME v0.1.14
Changed
- Pipeline Testing - Testing the unified CI/CD pipeline to validate end-to-end
workflow from version detection through automated release creation - Workflow Validation - Confirming that all 8 pipeline stages work correctly:
version check → testing → release → wheel building → GitHub release