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 ofWeighting cov(q) = s² (JᵀJ)⁻¹,s² = Σ r² / (n - k), in the scaled spaceqse(p) = se(q) |dp/dq|, intervalq ± t_{n-k} se(q)transformed back- derived parameters by the delta method with a central difference gradient
R²,RMSEon the unweighted residuals;AIC,AICc,BICon the weighted ones, withK = k + 1estimated 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 reportedn_parametersstaysk, 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 ( |
ci_low |
ndarray
|
lower end of the confidence interval per parameter (a
bootstrap percentile under the same condition as |
ci_high |
ndarray
|
upper end of the confidence interval per parameter (a
bootstrap percentile under the same condition as |
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 |
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 |
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 |
r2 |
float
|
coefficient of determination of the unweighted residuals |
rmse |
float
|
root mean squared error of the unweighted residuals |
aic |
float
|
Akaike information criterion, |
aicc |
float
|
Akaike information criterion with the small sample correction,
|
bic |
float
|
Bayesian information criterion, |
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 ( |
residuals |
ndarray
|
the weighted residual per point ( |
flags |
int
|
the |
nfev |
int
|
number of function evaluations over all starts |
n_bootstrap |
int
|
number of successful residual bootstrap replicates, 0 without bootstrap |
residual_sd
¶
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), 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 |
required |
weighting
|
Weighting
|
the variance model. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The standard deviation per point. |
Raises:
| Type | Description |
|---|---|
ValueError
|
for |
to_scale
¶
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
¶
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
¶
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 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 |
covariance
¶
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, |
required |
cost
|
float
|
the scipy cost |
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
|
|
tuple[ndarray, FitFlag]
|
negative variance) or |
replicate_statistics
¶
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, |
required |
alpha
|
float
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
|
fit_row
¶
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 |
required |
y
|
ndarray
|
dependent variable |
required |
sd
|
ndarray | None
|
standard deviation per point for |
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 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 |
required |
y
|
ndarray
|
dependent variable |
required |
sd
|
ndarray | None
|
standard deviations |
required |
options
|
FitOptions
|
the options |
required |
Returns:
| Type | Description |
|---|---|
list[RowFit]
|
One |
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, |
required |
y
|
Any
|
dependent variable, |
required |
sd
|
Any | None
|
standard deviation per point (needed for |
None
|
options
|
FitOptions | None
|
the options, defaults for |
None
|
x_unit
|
str
|
unit of |
'dimensionless'
|
y_unit
|
str
|
unit of |
'dimensionless'
|
x_name
|
str | None
|
name of the independent variable, stored as |
None
|
y_name
|
str | None
|
name of the dependent variable, stored as |
None
|
dims
|
Sequence[str] | None
|
sample dimension names for a 2-D |
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 |
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
¶
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 |
required |
x
|
ndarray
|
|
required |
y
|
ndarray
|
|
required |
sd
|
ndarray | None
|
|
required |
x_unit
|
str
|
unit of |
required |
y_unit
|
str
|
unit of |
required |
dims
|
tuple[str, ...]
|
sample dimension names ( |
required |
coords
|
dict[str, Any]
|
coordinates of the sample dimensions |
required |
options
|
FitOptions
|
the options (stored in |
required |
shape
|
tuple[int, ...] | None
|
sample shape for several sample dimensions ( |
None
|
Returns:
| Type | Description |
|---|---|
FitResult
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
if a parameter or derived name of the model ends in a
reserved suffix ( |
fit.result¶
Result of a fit: parameters, uncertainties, statistics, data and predictions.
FitResult
¶
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 |
required |
parameter_vector
¶
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
¶
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 |
predict_all
¶
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
¶
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 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 ( |
required |
timecourse
|
Timecourse
|
the curve; its |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
options |
FitOptions | None
|
the options, defaults for |
Returns:
| Type | Description |
|---|---|
FitResult
|
The result of the single curve, without a sample dimension. |
fit_timecourses
¶
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 ( |
required |
timecourses
|
Timecourses
|
the batch; |
required |
Other Parameters:
| Name | Type | Description |
|---|---|---|
options |
FitOptions | None
|
the options, defaults for |
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 ( |
fit_table
¶
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 |
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. |
required |
sd
|
str | None
|
name of the standard deviation variable of |
None
|
options
|
FitOptions | None
|
the options, defaults for |
None
|
Returns:
| Type | Description |
|---|---|
FitResult
|
The result over the remaining dimensions of |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
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 |
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). |
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, |
ftol |
float
|
scipy |
xtol |
float
|
scipy |
gtol |
float
|
scipy |
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 |
scale_of
¶
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
|
|
decode_fit_flags
¶
Names of the flags set in an integer value, in bit order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
integer value of a |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The names of the flags set in |
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
¶
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 |
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
¶
The parameter of a name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
name of the parameter. |
required |
Returns:
| Type | Description |
|---|---|
ModelParameter
|
The |
Raises:
| Type | Description |
|---|---|
KeyError
|
for an unknown name. |
bounds
¶
Lower and upper bounds as arrays.
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
A |
predict
abstractmethod
¶
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 |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The predicted values at |
derived
¶
Derived parameters of p, empty by default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
ndarray
|
parameters in the order of |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A mapping of derived parameter name to value. |
initial_guess
abstractmethod
¶
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 |
parameter_unit_expression
¶
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 |
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. |