ModelBuilder

class openpkpd.api.model_builder.ModelBuilder[source]

Bases: object

Fluent builder API for constructing openpkpd models in pure Python.

Chain method calls to configure the model, then call .build() to produce a BuiltModel ready for estimation.

__init__()[source]
Return type:

None

problem(title)[source]

Set the problem title.

Return type:

ModelBuilder

Parameters:

title (str)

data(path, id='ID', time='TIME', dv='DV', amt='AMT', evid='EVID', **kwargs)[source]

Specify the dataset file path and column mappings.

Parameters:
  • path (str) – Path to CSV data file.

  • id (str) – Column name overrides.

  • time (str) – Column name overrides.

  • dv (str) – Column name overrides.

  • amt (str) – Column name overrides.

  • evid (str | None) – Column name overrides.

  • **kwargs (Any) – Additional keyword arguments for NONMEMDataset.from_csv().

Return type:

ModelBuilder

dataset(ds)[source]

Provide a pre-loaded NONMEMDataset directly.

Return type:

ModelBuilder

Parameters:

ds (NONMEMDataset)

subroutines(advan=2, trans=2, **kwargs)[source]

Set ADVAN and TRANS subroutine numbers and optional subroutine kwargs.

Return type:

ModelBuilder

Parameters:
pk(code)[source]

Set the $PK code block (NM-TRAN syntax).

Return type:

ModelBuilder

Parameters:

code (str)

error(code)[source]

Set the $ERROR code block (NM-TRAN syntax).

Return type:

ModelBuilder

Parameters:

code (str)

des(code)[source]

Set the $DES code block for ODE models (NM-TRAN syntax).

Return type:

ModelBuilder

Parameters:

code (str)

theta(specs, labels=None)[source]

Set THETA initial estimates and bounds.

Return type:

ModelBuilder

Parameters:
Each element can be:
  • A float: initial value, unbounded

  • A 2-tuple (lower, init): lower-bounded

  • A 3-tuple (lower, init, upper): fully bounded

  • A ThetaSpec instance

Examples

.theta([1.5, (0, 0.1, 1), (0, 30)])

omega(values, fixed=False)[source]

Set OMEGA initial values.

Parameters:
  • values (Any) – 2D matrix (full or lower-triangle). Can also be a list of diagonal values [v1, v2, …] for a diagonal OMEGA.

  • fixed (bool) – Fix OMEGA values.

Return type:

ModelBuilder

sigma(values, fixed=False)[source]

Set SIGMA initial values.

Parameters:
  • values (Any) – Scalar, 1D list of diagonal values, or 2D matrix.

  • fixed (bool) – Fix SIGMA values.

Return type:

ModelBuilder

estimation(method='FOCE', **kwargs)[source]

Set estimation method and options.

Parameters:
  • method (str) – Method name (FO, FOCE, FOCEI, LAPLACIAN, SAEM, IMP).

  • **kwargs (Any) – Method-specific options (maxeval, interaction, sigdig, etc.)

Return type:

ModelBuilder

covariance(matrix='SR', **kwargs)[source]

Enable covariance step after estimation.

Return type:

ModelBuilder

Parameters:
covariates(columns)[source]

Specify time-varying covariate column names.

Return type:

ModelBuilder

Parameters:

columns (list[str])

impute_covariates(columns, method='locf')[source]

Impute missing covariate values after loading the dataset.

Applied automatically during build() before model assembly.

Parameters:
  • columns (list[str]) – Column names to impute (must exist in the dataset).

  • method (str) – Imputation strategy: 'locf' (default), 'nocb', 'mean', 'median', or 'knn'.

Return type:

ModelBuilder

Returns:

self (fluent interface).

clone()[source]

Return a copy of this builder. Callable attributes are shared by reference.

Return type:

ModelBuilder

build()[source]

Assemble and validate the model, returning a BuiltModel ready to fit.

Return type:

BuiltModel

class openpkpd.api.model_builder.BuiltModel(population_model, params, estimation_kwargs=<factory>, do_covariance=False, covariance_kwargs=<factory>)[source]

Bases: object

A fully assembled model ready to fit.

Returned by ModelBuilder.build(). Call .fit() to run estimation.

Parameters:
population_model: PopulationModel
params: ParameterSet
estimation_kwargs: dict[str, Any]
do_covariance: bool = False
covariance_kwargs: dict[str, Any]
design(sampling_times=None)[source]

Return a PFIMEngine wired to this model.

The engine can then evaluate or optimise the population Fisher Information Matrix (FIM) for the current parameters and model.

Parameters:

sampling_times (list[float] | ndarray | None) – Default sampling times (hours). If None, a 24-hour hourly grid is used as a starting point for compute_fim / optimize_design.

Return type:

PFIMEngine

Returns:

PFIMEngine ready to call .compute_fim() or .optimize_design().

Example:

built = ModelBuilder()...build()
result = built.fit()
engine = built.design()
fim = engine.compute_fim(np.linspace(0.5, 24, 8))
optimal = engine.optimize_design(n_samples=6, t_min=0, t_max=24)
print(optimal.summary())
simulate(n_replicates=1, seed=42, result=None)[source]

Simulate replicate datasets from the fitted model.

Convenience wrapper around SimulationEngine that optionally runs estimation first if no EstimationResult is provided.

Parameters:
  • n_replicates (int) – Number of simulated datasets to generate (default 1).

  • seed (int) – Random seed for reproducibility (default 42).

  • result (EstimationResult | None) – Pre-computed EstimationResult. If None, calls fit() first.

Return type:

SimulationResult

Returns:

SimulationResult with simulated_df, seed, and n_replicates.

Example

model = ModelBuilder()…build() result = model.fit() sim = model.simulate(n_replicates=500, result=result) print(sim.simulated_df.head())

fit()[source]

Run estimation and return results.

Return type:

EstimationResult

__init__(population_model, params, estimation_kwargs=<factory>, do_covariance=False, covariance_kwargs=<factory>)
Parameters:
Return type:

None