Skip to content

fit

fit.engine

The fitting engine.

fit fits a Model to one or many (x, y) rows with scipy.optimize.least_squares (trust region reflective, bounds) in a scaled parameter space, derives the standard errors from the Jacobian, transforms the t-based intervals back to the linear scale, and computes the goodness-of-fit statistics (Seber & Wild 1989, ch. 2; Gabrielsson & Weiner 2016, ch. 6):

  • weighted residuals r = (y - f) / sqrt(var) with the variance model of Weighting
  • cov(q) = s² (JᵀJ)⁻¹, s² = Σ r² / (n - k), in the scaled space q
  • se(p) = se(q) |dp/dq|, interval q ± t_{n-k} se(q) transformed back
  • derived parameters by the delta method with a central difference gradient
  • , RMSE on the unweighted residuals; AIC, AICc, BIC on the weighted ones, with K = k + 1 estimated parameters (the residual variance is one of them, Burnham & Anderson 2002, sec. 2.2, 6.9.6): AIC = n ln(Σr²/n) + 2K, AICc = AIC + 2K(K+1)/(n-K-1), BIC = n ln(Σr²/n) + K ln n; the reported n_parameters stays k, the free model parameters

When options.bootstrap > 0, fit_row also runs a residual bootstrap (Efron & Tibshirani 1993, ch. 9): the weighted residuals of the fit are centered and inflated by sqrt(n / (n - k)) and resampled with replacement B times, each replicate is refitted from the fitted p, and the standard errors, the confidence intervals and the correlation matrix are the empirical statistics of the replicate parameters, an alternative to the Jacobian-based ones above that does not rely on the local linear approximation; fewer than two converged replicates fall back to the Jacobian-based statistics and set FitFlag.BOOTSTRAP_FALLBACK. fit_rows distributes the rows over the shared process pool (pkpdutils.parallel) for a batch of more than FIT_WORKER_THRESHOLD rows or an explicit options.n_workers > 1, with one child seed per row drawn up front so serial and pooled runs agree; pkpdutils.fit.compare ranks several models on the same data by the corrected Akaike information criterion (Burnham & Anderson 2002).

A row whose numbers leave the range of double precision (unweighted values beyond about 1e154, whose squares overflow) is guarded rather than computed: the initial guess, the start box, the trust region search, the covariance, the statistics and the bootstrap run under numpy.errstate, so no floating-point warning escapes and aborts a batch under a strict warning filter, and a start, a covariance or a statistic which is not finite is NaN and flagged FitFlag.OVERFLOW. The other rows of a batch are not affected.

RowFit dataclass

RowFit(
    p,
    q,
    se_p,
    ci_low,
    ci_high,
    cov_q,
    correlation,
    derived,
    derived_se,
    derived_ci_low,
    derived_ci_high,
    cost,
    r2,
    rmse,
    aic,
    aicc,
    bic,
    n_points,
    n_starts_converged,
    y_pred,
    residuals,
    flags,
    nfev,
    n_bootstrap=0,
)

The fit of one row; arrays are in model parameter order (fixed parameters included).

Attributes:

Name Type Description
p ndarray

the fitted parameters on the linear scale

q ndarray

the fitted parameters on the search scale

se_p ndarray

standard error per parameter (NaN for a fixed one); the residual bootstrap replicate standard deviation when options.bootstrap > 0 produced at least 2 converged replicates, else the Jacobian-based one (FitFlag. BOOTSTRAP_FALLBACK is set in that case)

ci_low ndarray

lower end of the confidence interval per parameter (a bootstrap percentile under the same condition as se_p)

ci_high ndarray

upper end of the confidence interval per parameter (a bootstrap percentile under the same condition as se_p)

cov_q ndarray

covariance of the parameters on the search scale; always the Jacobian-based covariance, never replaced by the bootstrap (the bootstrap does not produce a covariance in the search scale, only replicate statistics of the linear-scale parameters)

correlation ndarray

correlation matrix of the parameters; from the bootstrap replicates under the same condition as se_p, else from cov_q

derived dict[str, float]

the derived parameters of the model

derived_se dict[str, float]

standard error per derived parameter (delta method, or the bootstrap replicate standard deviation, under the same condition as se_p)

derived_ci_low dict[str, float]

lower end of the interval per derived parameter

derived_ci_high dict[str, float]

upper end of the interval per derived parameter

cost float

the value of the scipy cost function 0.5 Σ ρ(r²)

r2 float

coefficient of determination of the unweighted residuals

rmse float

root mean squared error of the unweighted residuals

aic float

Akaike information criterion, K = k + 1 estimated parameters

aicc float

Akaike information criterion with the small sample correction, NaN when n - K - 1 <= 0

bic float

Bayesian information criterion, K = k + 1 estimated parameters

n_points int

number of points used in the fit

n_starts_converged int

number of start points which converged

y_pred ndarray

the prediction per point of the row (NaN for unused points)

residuals ndarray

the weighted residual per point (NaN for unused points)

flags int

the FitFlag combination of the row

nfev int

number of function evaluations over all starts

n_bootstrap int

number of successful residual bootstrap replicates, 0 without bootstrap

residual_sd

residual_sd(y, sd, weighting)

Standard deviation sqrt(var) of every point under the weighting (y <= 0 uses the smallest positive |y|).

The weighted residual is (y - f) / sqrt(var) with var = 1 (NONE), |y| (INV_Y), (INV_Y2) or sd² (INV_SD). The square root is taken analytically, |y| rather than sqrt(y²): the square of a value beyond 1e154 overflows and the square of one below 1e-154 underflows to zero, which would give the point no weight at all or divide by zero.

Parameters:

Name Type Description Default
y ndarray

the dependent variable of the row.

required
sd ndarray | None

standard deviation per point, needed for Weighting.INV_SD.

required
weighting Weighting

the variance model.

required

Returns:

Type Description
ndarray

The standard deviation per point.

Raises:

Type Description
ValueError

for Weighting.INV_SD without sd.

to_scale

to_scale(p, scales)

Linear parameters to the scaled space.

A positive parameter which underflowed to exactly zero (or which a fixed value or a bound put at zero or below) has no logarithm; the logarithm is evaluated under numpy.errstate(divide="ignore", invalid="ignore") and becomes -inf or NaN silently rather than raising a RuntimeWarning under a strict warning filter, the counterpart of the overflow guard of from_scale. The callers treat a non-finite search-scale parameter as an uncertainty that cannot be computed.

Parameters:

Name Type Description Default
p ndarray

the parameters on the linear scale.

required
scales Sequence[ParameterScale]

the scale per parameter.

required

Returns:

Type Description
ndarray

The parameters on the search scale.

from_scale

from_scale(q, scales)

Scaled parameters back to the linear space.

A wildly out-of-range search point (a bad start, or a step the optimizer proposes before it is rejected) can make 10 ** q or exp(q) overflow; that overflow is evaluated under numpy.errstate(over="ignore") and becomes inf silently rather than raising a RuntimeWarning, which would otherwise escape as an exception under a strict warning filter and is not one of the exceptions the caller expects from a failed start. The resulting non-finite parameter makes the residuals non-finite too, which scipy.optimize.least_squares already turns into a ValueError the caller catches, so the start fails cleanly instead of the process crashing.

Parameters:

Name Type Description Default
q ndarray

the parameters on the search scale.

required
scales Sequence[ParameterScale]

the scale per parameter.

required

Returns:

Type Description
ndarray

The parameters on the linear scale.

scale_derivative

scale_derivative(p, scales)

dp/dq per parameter.

Parameters:

Name Type Description Default
p ndarray

the parameters on the linear scale.

required
scales Sequence[ParameterScale]

the scale per parameter.

required

Returns:

Type Description
ndarray

The derivative of the linear parameter with respect to the scaled one.

bounds_in_scale

bounds_in_scale(lower, upper, scales)

Bounds in the scaled space (a non-positive lower bound of a log parameter becomes -inf).

Parameters:

Name Type Description Default
lower ndarray

lower bounds on the linear scale.

required
upper ndarray

upper bounds on the linear scale.

required
scales Sequence[ParameterScale]

the scale per parameter.

required

Returns:

Type Description
tuple[ndarray, ndarray]

The (lower, upper) bounds on the search scale.

covariance

covariance(jac, cost, n, k)

s² (JᵀJ)⁻¹ with s² = 2 cost / (n - k).

This is the least-squares covariance and it is exact only for loss="linear"; for a robust loss (soft_l1, huber, cauchy, arctan) scipy returns the Jacobian and the cost of the transformed problem, so the covariance, the standard errors and the intervals derived from it are approximations.

A numerically singular JᵀJ is reported as singular, and so is an inverse with a negative variance on the diagonal (the covariance is then not positive semidefinite, the standard errors are meaningless); the values are returned unchanged and the caller clips the variances at zero so that the standard errors stay finite. A Jacobian, a cost, JᵀJ or a covariance which is not finite (a row beyond the range of double precision) is an overflow; the products run under numpy.errstate.

Parameters:

Name Type Description Default
jac ndarray

the Jacobian of the residuals in the scaled space, (n, k).

required
cost float

the scipy cost 0.5 Σ r².

required
n int

number of points.

required
k int

number of free parameters.

required

Returns:

Type Description
ndarray

The covariance of the free parameters and its condition:

FitFlag

FitFlag.NONE, FitFlag.SINGULAR (NaN, or the values with a

tuple[ndarray, FitFlag]

negative variance) or FitFlag.OVERFLOW (NaN).

replicate_statistics

replicate_statistics(values, alpha)

Standard deviation and percentile interval of bootstrap replicates, column by column.

The finite replicates of a column are counted first and a column with fewer than two of them is reported as NaN, the guard pkpdutils.result.ParameterResult.summarize uses: numpy.nanstd with ddof=1 on such a column has no degrees of freedom left (and would warn, and abort the batch under a strict warning filter) and the percentiles of an all-NaN column have nothing to interpolate, so neither returns a meaningful number.

Parameters:

Name Type Description Default
values ndarray

the replicates, (B, m), NaN where a replicate has no value.

required
alpha float

1 - ci_level, the total tail probability of the interval.

required

Returns:

Type Description
tuple[ndarray, ndarray, ndarray]

(sd, ci_low, ci_high), one value per column.

fit_row

fit_row(model, x, y, sd, options, rng)

Fit one row from one or several start points and compute its statistics.

A model which defines parameter_order (the sums of exponentials) has its parameters permuted after the fit, together with every positional array (the free mask, the bounds, the scales, the fixed values, the start vector and the columns of the Jacobian), so the standard errors, the intervals, the correlation matrix and the AT_BOUND flag describe the parameter they are labelled with. The permutation is skipped when options.fixed or options.bounds names a parameter of the model: the user pinned that label, so the phases keep the labelling of the options even when they are then not ordered by decreasing rate.

Parameters:

Name Type Description Default
model Model

the model

required
x ndarray

independent variable (n,)

required
y ndarray

dependent variable (n,), NaN for missing points

required
sd ndarray | None

standard deviation per point for Weighting.INV_SD, else None

required
options FitOptions

the options

required
rng Generator

random generator of the start points

required

Returns:

Type Description
RowFit

The fit of the row.

fit_rows

fit_rows(model, x, y, sd, options)

Fit every row of (N, n) arrays, serially or in the shared process pool.

Row seeds are drawn from options.seed before the rows are distributed, one child seed per row, so the result does not depend on options.n_workers or the order the rows finish in.

options.n_workers decides how many workers run the rows (pkpdutils.parallel.resolve_workers): None is automatic and stays in the calling process below FIT_WORKER_THRESHOLD rows, 1 is serial and any other number is taken as given. A row is a python-heavy scipy.optimize.least_squares search, so a parallel run maps the rows over the shared process pool (pkpdutils.parallel.executor) in batches of about a quarter of the rows of a worker, which keeps the number of tasks (and with them the pickling of the model and the options) small. A worker that dies takes the pool with it (BrokenProcessPool): the pool is then evicted and the batch is fitted once more in a fresh one, with a warning. A pooled call must run under an if __name__ == "__main__": guard, since the pool starts its workers with forkserver or spawn on every python version (pkpdutils.parallel.PROCESS_START_METHOD), which re-import the module without re-running it.

Parameters:

Name Type Description Default
model Model

the model

required
x ndarray

independent variable (N, n)

required
y ndarray

dependent variable (N, n)

required
sd ndarray | None

standard deviations (N, n) or None

required
options FitOptions

the options

required

Returns:

Type Description
list[RowFit]

One RowFit per row, in row order.

fit

fit(
    model,
    x,
    y,
    *,
    sd=None,
    options=None,
    x_unit="dimensionless",
    y_unit="dimensionless",
    x_name=None,
    y_name=None,
    dims=None,
    coords=None,
)

Fit a model to one or many rows of data.

Parameters:

Name Type Description Default
model Model

the model

required
x Any

independent variable, (n,) shared by all rows or (N, n)

required
y Any

dependent variable, (n,) for one sample or (N, n); NaN for missing points

required
sd Any | None

standard deviation per point (needed for Weighting.INV_SD), like y

None
options FitOptions | None

the options, defaults for None

None
x_unit str

unit of x

'dimensionless'
y_unit str

unit of y

'dimensionless'
x_name str | None

name of the independent variable, stored as attrs["x_name"] and used as the axis label by the figures of the fit (concentration, dose, weight); the figures fall back to x without it, as the arrays carry no name of their own

None
y_name str | None

name of the dependent variable, stored as attrs["y_name"], the label of the value axis (effect, auc_inf_obs)

None
dims Sequence[str] | None

sample dimension names for a 2-D y, ("sample",) by default

None
coords dict[str, Any] | None

coordinate labels of the sample dimensions

None

Returns:

Type Description
FitResult

The result over the sample dimensions (none for a 1-D y).

Raises:

Type Description
ValueError

for 2-D data with more than one sample dimension, or if the sample dimension or a coordinate collides with a variable or a dimension of the result (see build_result).

build_result

build_result(
    model,
    rows,
    *,
    x,
    y,
    sd,
    x_unit,
    y_unit,
    dims,
    coords,
    options,
    shape=None,
)

Assemble the result dataset of the fitted rows.

The parameters, their uncertainties and the derived parameters are reported in the raw units of x and y (parameter_unit_expression), so they are on the same scale as y_data and y_pred. residuals holds the weighted residuals (y - f) / sqrt(var), which are dimensionless only under Weighting.INV_SD and otherwise carry the unit of y divided by the square root of the variance model; rmse is the root mean square of the unweighted residuals y - f and carries the unit of y. Both are reported as dimensionless, like the other goodness-of-fit statistics. Derived parameters listed in FitResult.discrete_parameters (indicators such as flip_flop) are written without _se, _ci_low, _ci_high and _cv.

Parameters:

Name Type Description Default
model Model

the model

required
rows list[RowFit]

one RowFit per row

required
x ndarray

(N, n) independent variable

required
y ndarray

(N, n) dependent variable

required
sd ndarray | None

(N, n) standard deviations or None, reported as sd_data (NaN for every point when None)

required
x_unit str

unit of x

required
y_unit str

unit of y

required
dims tuple[str, ...]

sample dimension names (() for a single row)

required
coords dict[str, Any]

coordinates of the sample dimensions

required
options FitOptions

the options (stored in attrs)

required
shape tuple[int, ...] | None

sample shape for several sample dimensions (N = prod(shape)), (N,) by default

None

Returns:

Type Description
FitResult

The FitResult.

Raises:

Type Description
ValueError

if a parameter or derived name of the model ends in a reserved suffix (_check_no_reserved_suffix), or if a name in dims or in coords collides with a data variable of the result or with one of the dimensions point, parameter and parameter_ it adds (check_coordinate_collision, which reads the variables and the dimensions from the assembled layout).

fit.result

Result of a fit: parameters, uncertainties, statistics, data and predictions.

FitResult

FitResult(ds, model)

Bases: ParameterResult

Parameters of a fit as an xarray.Dataset over the sample dimensions.

Variables: every parameter p with p_se, p_ci_low, p_ci_high, p_cv (the relative standard error as a fraction, as every coefficient of variation of the package); the derived parameters likewise; the statistics cost, r2, rmse, aic, aicc, bic, n_points, n_parameters, n_starts_converged, n_bootstrap (number of successful residual bootstrap replicates, 0 without bootstrap; attrs["bootstrap"] holds the requested count); the data and the prediction per point (x_data, y_data, sd_data - NaN when the fit had no sd -, y_pred, residuals over point); the correlation matrix over (parameter, parameter_); and the integer flags (FitFlag). The model object is kept for predict.

The parameters are reported in the raw units of the data, so they are on the same scale as y_data and y_pred. The interval of a parameter is symmetric in its search space (symmetric in the logarithm for a parameter fitted on a log scale, so asymmetric around the estimate), while the interval of a derived parameter is the delta method interval d +- t se(d) and is always symmetric around d, even for a strongly non-linear function of the parameters such as a half-life. aic, aicc and bic count the residual variance as an estimated parameter, K = k + 1 (Burnham & Anderson 2002, sec. 2.2, 6.9.6), while n_parameters stays k, the free model parameters; aicc is NaN when n - K - 1 <= 0.

When the fit was run with FitOptions.bootstrap > 0 (Efron & Tibshirani 1993, ch. 9), p_se and the derived standard errors are the standard deviation of the n_bootstrap converged residual bootstrap replicates and the intervals are their percentiles at ci_level, so they need not be symmetric around the estimate; the correlation matrix is likewise from the replicates. Non-converged replicates are skipped, so a low n_bootstrap relative to attrs["bootstrap"] (the requested count) signals an unstable fit. Fewer than 2 converged replicates cannot estimate an uncertainty at all: p_se, the intervals and the correlation then fall back to the Jacobian-based ones and FitFlag.BOOTSTRAP_FALLBACK is set in flags. The parameter covariance cov_q of RowFit (not part of this dataset) is always Jacobian-based, bootstrap or not. Discrete derived parameters (discrete_parameters, e.g. flip_flop) carry no uncertainty variables at all.

The goodness of fit and the counts are statistic_variables: they describe the fit of one sample, not a parameter of it, so parameters leaves them out and summarize drops them instead of averaging them over the samples. to_dataframe, which reports the individual fits, keeps them.

Wrap the dataset of a fit of model.

Parameters:

Name Type Description Default
ds Dataset

the result dataset of the fit.

required
model Model

the fitted model, kept for predict.

required

parameter_vector

parameter_vector(**indexers)

The fitted parameters of one sample in the order of the model.

Parameters:

Name Type Description Default
**indexers Any

coordinate label per sample dimension.

{}

Returns:

Type Description
ndarray

The parameter vector, fixed parameters included.

predict

predict(x, **indexers)

The fitted curve of one sample at x.

Parameters:

Name Type Description Default
x ndarray

the independent variable to predict at.

required
**indexers Any

coordinate label per sample dimension.

{}

Returns:

Type Description
ndarray

The predicted values at x.

predict_all

predict_all(x)

The fitted curves of every sample at x, over (*sample_dims, "x").

Parameters:

Name Type Description Default
x ndarray

the independent variable to predict at.

required

Returns:

Type Description
DataArray

The predicted curves of every sample.

correlation

correlation(**indexers)

The correlation matrix of the fitted parameters of one sample.

Parameters:

Name Type Description Default
**indexers Any

coordinate label per sample dimension.

{}

Returns:

Type Description
DataFrame

The correlation matrix indexed by the parameter names.

fit.frontends

Front ends of the engine for one timecourse, for batches of timecourses and for tables of parameters.

fit_timecourse

fit_timecourse(model, timecourse, *, options=None)

Fit a model to one timecourse, with the times relative to the first dose.

The curve is fitted as a batch of one (fit_timecourses) and the single sample is dropped from the result, so the result has no sample dimension and to_quantities, flags, predict and correlation need no indexer.

Parameters:

Name Type Description Default
model Model

the model (x is the time relative to the first dose, y the value)

required
timecourse Timecourse

the curve; its sd is used for Weighting.INV_SD

required

Other Parameters:

Name Type Description
options FitOptions | None

the options, defaults for None

Returns:

Type Description
FitResult

The result of the single curve, without a sample dimension.

fit_timecourses

fit_timecourses(model, timecourses, *, options=None)

Fit a model to every curve of a batch, with the times relative to the first dose.

The batch is flattened to (N, n_time) rows over its sample dimensions (any number of them) and fitted with fit_rows; the result is then reshaped back to timecourses.sample_shape. x is the time relative to the first dose of the protocol when the batch carries doses, else times unchanged; NaN-padded (ragged) times stay NaN and are dropped by the engine. Parameters are reported in the raw units of the batch, x_unit = timecourses.time_unit and y_unit = timecourses.unit.

The result names what was fitted in attrs["x_name"] = "time" and attrs["y_name"], the substance of the batch ("value" when it does not name one), which the figures of the fit use to label their axes.

Parameters:

Name Type Description Default
model Model

the model (x is the time relative to the first dose, y the value)

required
timecourses Timecourses

the batch; sd is used for Weighting.INV_SD

required

Other Parameters:

Name Type Description
options FitOptions | None

the options, defaults for None

Returns:

Type Description
FitResult

The result over the sample dimensions of the batch.

Raises:

Type Description
ValueError

if a sample dimension or a coordinate of the batch collides with a variable or a dimension (point, parameter, parameter_) of the result.

fit_table

fit_table(model, ds, x, y, *, dim, sd=None, options=None)

Fit y against x along one dimension of a dataset, for every combination of the other dimensions.

x may be a coordinate or a variable of ds; it is broadcast to the dimensions of y (e.g. a dose coordinate against an auc_inf_obs variable that also carries an individual dimension). The units are read from attrs["units"] of x and y, "dimensionless" when absent (a coordinate such as the dose of an NCAResult.ds need not carry units; a model whose parameter units depend on [x] then reports that parameter without the x part of its unit). This works directly on the dataset of another result, e.g. fit_table(Power(), result.ds, "dose", "auc_inf_obs", dim="dose") on an NCAResult. NaN in x or y drops the point, as does any point the engine already drops as non-finite.

The result names what was fitted against what in attrs["x_name"] and attrs["y_name"] (x and y), which the figures of the fit use to label their axes.

Parameters:

Name Type Description Default
model Model

the model

required
ds Dataset

dataset with the variable y and the coordinate or variable x

required
x str

name of the independent variable

required
y str

name of the dependent variable

required
dim str

the dimension along which the points of one fit lie (e.g. "dose")

required
sd str | None

name of the standard deviation variable of y, for Weighting.INV_SD

None
options FitOptions | None

the options, defaults for None

None

Returns:

Type Description
FitResult

The result over the remaining dimensions of y (0-D when y has only dim).

Raises:

Type Description
ValueError

if y has no dimension dim, if x (or sd) has a dimension y does not have, or if a remaining dimension of y collides with a variable or a dimension (point, parameter, parameter_) of the result.

fit.options

Options and flags of the curve fitting.

ParameterScale

Bases: StrEnum

Space the optimizer searches; bounds, start values and results stay linear.

Weighting

Bases: StrEnum

Variance model of the residuals; the weighted residual is (y - f) / sqrt(var).

FitFlag

Bases: IntFlag

Conditions reported per sample in the flags variable of a fit result.

FitOptions

Bases: BaseModel

Options of a fit.

Attributes:

Name Type Description
parameter_scale ParameterScale

space of the search for positive parameters

weighting Weighting

variance model of the residuals

loss str

loss function of scipy.optimize.least_squares; the covariance, the standard errors and the confidence intervals of a fit are the least-squares quantities and are exact only for "linear", for a robust loss they are approximations

n_starts int

number of start points (Latin hypercube in the start box)

seed int | None

seed of the start point sampling and the bootstrap

n_workers int | None

worker processes of a batch fit, one row per job (never the starts of a single row). None is automatic: the calling process up to 2 000 rows, where a batch does not earn back the start-up of the workers, and one worker per core, at most 8, above it; 1 is always serial and n > 1 uses that many workers, which is how a smaller batch of expensive rows (several starts, a residual bootstrap) asks for the pool. The workers start with forkserver or spawn on every python version (pkpdutils.parallel.PROCESS_START_METHOD), which re-import the main module without re-running it, so a pooled call must run under an if __name__ == "__main__": guard and its model must be importable, not defined in an interactive session; the NCA (NCAOptions.n_workers) runs in threads and needs no guard

ci_level float

level of the confidence intervals

bootstrap int

number of residual bootstrap replicates, 0 for none

max_nfev int | None

maximal function evaluations per start, None for the scipy default

ftol float

scipy ftol

xtol float

scipy xtol

gtol float

scipy gtol

fixed dict[str, float]

parameters held at a value (not fitted)

bounds dict[str, tuple[float, float]]

bounds overriding the model's, per parameter

initial dict[str, float]

start values overriding the model's guess, per parameter

start_spread float

half width of the start box around the initial guess, as a factor for log scale parameters and as a multiple of the guess for linear ones

at_bound_tolerance float

distance to a bound that sets AT_BOUND. A parameter p which started at p0 rests on a bound b when |p - b| <= at_bound_tolerance * (|b| + max(|p0|, 1e-300)), so the distance is relative to the bound and to the start value. The start value is needed for a lower bound of 0, which is -inf in a log search space and can never be reached exactly.

scale_of

scale_of(parameter)

The scale a parameter is searched on: linear unless it is positive.

Parameters:

Name Type Description Default
parameter ModelParameter

the model parameter.

required

Returns:

Type Description
ParameterScale

ParameterScale.LINEAR for a non-positive parameter, else parameter_scale.

decode_fit_flags

decode_fit_flags(value)

Names of the flags set in an integer value, in bit order.

Parameters:

Name Type Description Default
value int

integer value of a FitFlag combination.

required

Returns:

Type Description
list[str]

The names of the flags set in value, in bit order.

fit.model

Models of the curve fitting.

A Model names its parameters (ModelParameter: name, unit expression, bounds, whether it is positive and therefore fitted on the log scale) and computes the curve predict(x, p), the derived parameters derived(p) and an initial_guess(x, y). The unit of a parameter is derived from the units of x and y with parameter_unit_expression, e.g. "[y]/[x]" for a slope.

ModelParameter dataclass

ModelParameter(
    name,
    unit_expr,
    lower=-inf,
    upper=inf,
    positive=True,
    description="",
)

A parameter of a model.

Attributes:

Name Type Description
name str

name of the parameter, the variable name in the result

unit_expr str

unit expression with [x] and [y] for the units of the data, e.g. "[y]", "1/[x]", "[y]/[x]", "dimensionless"

lower float

lower bound (linear scale)

upper float

upper bound (linear scale)

positive bool

whether the parameter is positive and fitted on the log scale

description str

one line for the documentation

Model

Bases: ABC

A curve y = f(x; p) with named parameters.

Subclasses set name, parameters (and optionally derived_units) and implement predict, initial_guess and, when they report derived parameters, derived. Parameters are passed as a 1-D array in the order of parameters.

parameter_names property

parameter_names

Names of the parameters in order.

n_parameters property

n_parameters

Number of parameters.

parameter

parameter(name)

The parameter of a name.

Parameters:

Name Type Description Default
name str

name of the parameter.

required

Returns:

Type Description
ModelParameter

The ModelParameter of that name.

Raises:

Type Description
KeyError

for an unknown name.

bounds

bounds()

Lower and upper bounds as arrays.

Returns:

Type Description
tuple[ndarray, ndarray]

A (lower, upper) tuple of arrays in the order of parameters.

predict abstractmethod

predict(x, p)

The curve at x for the parameters p.

Parameters:

Name Type Description Default
x ndarray

independent variable, vectorized.

required
p ndarray

parameters in the order of parameters.

required

Returns:

Type Description
ndarray

The predicted values at x.

derived

derived(p)

Derived parameters of p, empty by default.

Parameters:

Name Type Description Default
p ndarray

parameters in the order of parameters.

required

Returns:

Type Description
dict[str, float]

A mapping of derived parameter name to value.

initial_guess abstractmethod

initial_guess(x, y)

A start vector from the data (finite points only).

The engine evaluates the guess under numpy.errstate and replaces an entry which is not finite by a default start, as it does for every entry when the guess raises numpy.linalg.LinAlgError or ValueError; the OverflowError of the math module is not caught.

Parameters:

Name Type Description Default
x ndarray

independent variable.

required
y ndarray

dependent variable.

required

Returns:

Type Description
ndarray

A start vector in the order of parameters.

parameter_unit_expression

parameter_unit_expression(unit_expr, *, x_unit, y_unit)

Unit of a parameter from its expression and the units of the data.

The unit is the raw combination of the units of the data, without any normalization: a fit reports its parameters in the units the data was given in (a of a monoexponential fit of milliliters is in milliliter, its auc in milliliter hour), so the parameters and the predicted curve always live on the same scale.

Parameters:

Name Type Description Default
unit_expr str

expression with [x] and [y], e.g. "[y]/[x]"

required
x_unit str

unit of the independent variable

required
y_unit str

unit of the dependent variable

required

Returns:

Type Description
str

The unit string of the parameter.