fit.optimization¶
Optimization of parameter fitting problem.
ObservationKind
¶
Bases: StrEnum
What the observable of a fit mapping is, see OptimizationProblem.initialize.
The kind is decided from the dimensions of the observable after its sel:
a timecourse over the time (or another selection), a value per
simulation of a plain simulation or of a scan with every dimension
selected, or values over the one dimension of a scan which is left, which
are matched to the reference data by the values of the dimension.
GroupResult
dataclass
¶
The simulation of a group of fit mappings which keeps its output.
The output has the states before and after a change after the start at
its time, see sbmlsim.simulator.executor, also at a change between the
output times of explicit times, which the plan of a group with a
timecourse gets (OptimizationProblem._compile_plans).
Attributes:
| Name | Type | Description |
|---|---|---|
time |
ndarray
|
the time points of every simulated point of the group, |
outputs |
dict[str, ndarray]
|
the observables and selections the mappings of the group read,
a timecourse |
changes |
ndarray
|
the times of the changes after the start of the first point
in the time of the output, see |
tolerance |
float
|
the resolution of the time of the simulation, time points
of the output closer than it are a jump, see
|
DataTimesResult
dataclass
¶
The simulation of a group of fit mappings which outputs the times of its data.
Attributes:
| Name | Type | Description |
|---|---|---|
output |
TimecourseResult
|
a row per output time of the data and per time of a change
within them, two rows at a change after the start: the state
before the change and the state after it; the data takes one of
them, see |
MappingEvaluation
dataclass
¶
The simulation of a fit mapping at its reference data.
Attributes:
| Name | Type | Description |
|---|---|---|
prediction |
ndarray
|
the observable at every data point. |
selections |
dict[str, ndarray]
|
the selections the noise model of the mapping reads, at
every data point, see |
FitTimeout
¶
Bases: Exception
A single optimization ran longer than its budget.
The optimizers of scipy cannot be interrupted, so the objective raises this
once the budget is spent, which ends the optimization. The runs which
finished are kept, see OptimizationProblem.optimize.
PoolError
¶
Bases: RuntimeError
The workers which evaluate the points of a run failed.
E.g. a worker could not initialize the problem, the pool could not be
started again, or workers died while several points were in flight once
the restarts of a generation or of a jacobian were spent, see
sbmlsim.fit.runner.FitPool. The run ends and keeps the best parameters
it reached.
PopulationEvaluator
¶
Bases: Protocol
Evaluates the members of a population of differential evolution.
A fit which evaluates the population of differential evolution on its
workers hands one to the run, see sbmlsim.fit.runner.PopulationPool.
The run records the costs it returns in its trajectory, see
OptimizationProblem.optimize_run.
start
¶
Prepare the workers before the budget of a run starts.
E.g. start the workers and initialize the problem in them, so the timeout of a run is not spent on the start of its workers.
ResidualsEvaluator
¶
Bases: Protocol
Evaluates the points of the jacobian of a least squares run.
A fit which evaluates the finite differences of a run on its workers hands
one to the run, see sbmlsim.fit.runner.JacobianPool. The points of a
jacobian are independent evaluations of the residuals at the same step,
so the jacobian of the workers is the jacobian of a serial run bitwise;
the run records the costs of the points in its trajectory in the order of
the points, see OptimizationProblem.jacobian_map.
start
¶
Prepare the workers before the budget of a run starts.
E.g. start the workers and initialize the problem in them, so the timeout of a run is not spent on the start of its workers.
RuntimeErrorOptimizeResult
¶
RuntimeErrorOptimizeResult(
x=None,
x0=None,
cost=inf,
message="RuntimeError in ODE integration.",
duration=-1.0,
)
Bases: OptimizeResult
Result of an optimization which did not finish.
An optimization fails with an error of the integrator, with a timeout or
with any other error of the objective. This is a
scipy.optimize.OptimizeResult, i.e., a dictionary with attribute access,
so that a failed run is stored, serialized and reported like a successful
one and a fit keeps the runs which worked.
Initialize the result of an optimization which did not finish.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray | None
|
parameters the optimization reached. |
None
|
x0
|
ndarray | None
|
parameters it started from. |
None
|
cost
|
float
|
cost of |
inf
|
message
|
str
|
what went wrong. |
'RuntimeError in ODE integration.'
|
duration
|
float
|
seconds the optimization ran. |
-1.0
|
OptimizationProblem
¶
OptimizationProblem(
opid,
mapping_collections,
fit_parameters,
base_path=None,
data_path=None,
hybridizations=None,
jit_optimization=None,
engine=DEFAULT_ENGINE,
prior_correlation=None,
fixed_values=None,
)
Bases: ObjectJSONEncoder
Parameter optimization problem.
Optimization problem.
The problem must be pickable for parallelization ! So initialize must be run to create the non-pickable instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opid
|
str
|
id for optimization problem. |
required |
mapping_collections
|
list[FitMappingCollection]
|
the fit mappings of the problem. |
required |
fit_parameters
|
list[FitParameter]
|
the parameters of the fit. |
required |
base_path
|
Path | None
|
directory the models of the experiments are relative to. |
None
|
data_path
|
Path | Sequence[Path] | None
|
directory or directories of the data of the experiments. |
None
|
hybridizations
|
Sequence[DerivedChanges] | None
|
the derived changes of the problem, i.e. changes
of a simulation which are calculated from the parameters of
the fit, see |
None
|
jit_optimization
|
JitOptimization | str | None
|
the optimization level the models are compiled
with, see |
None
|
engine
|
Engine | str
|
the engine or its name which the problem simulates with,
|
DEFAULT_ENGINE
|
prior_correlation
|
Covariance | None
|
the correlation of the normal scores of the
priors of some parameters, |
None
|
fixed_values
|
Mapping[str, float] | None
|
the values the problem keeps fixed by the id of their
entity in the model, in the units of the model, e.g. the
fitted values of the adopted fits of the other subsets of a
project ( |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem has no parameters or two parameters of one id, the engine is no engine or the priors do not take the correlation. |
TypeError
|
if a hybridization does not provide the derived changes. |
validation_indices
property
¶
Indices of the fit mappings which are only evaluated.
outlier_indices
property
¶
Indices of the fit mappings whose data a fit dropped as unusable.
is_initialized
property
¶
Check if the problem was initialized, i.e., the data is resolved.
settings_initialized
property
¶
Settings of the problem, set in initialize.
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem was not initialized. |
scales_initialized
property
¶
Get the space the optimizer searches every parameter in.
The scale of a parameter is its FitParameter.scale and the
parameter_scale of the settings for a parameter without one.
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem was not initialized. |
parameter_units
property
¶
Get the unit of every parameter in the units of pint, by parameter id.
A unit id of the model of the target of a parameter is replaced by its
expression, see ParameterMapping.parameter_units, so the units are
the ones of the values of the parameter sets, the Fisher information
and the designs of sbmlsim.simulation.sampling, which have no model.
None is the unit of the model.
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem was not initialized. |
parameter_mapping_initialized
property
¶
Binding of the parameters to the simulations, created in initialize.
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem was not initialized. |
prior_residual_count
property
¶
Get the number of residuals of the priors, the last ones of residuals.
They are part of the residuals of a fit of ObjectiveType.POSTERIOR
only, the others have none.
files
¶
Get the files a fit of the problem reads, the models and the data.
The models are the SBML files of the experiments, the data are the files
below data_path without python code and caches (data_files). An
uninitialized problem is initialized first, with the settings of the
problem or the default settings.
Returns:
| Type | Description |
|---|---|
list[Path]
|
The sorted paths of the files. |
indices
¶
Get the indices of the fit mappings of a kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
MappingKind | None
|
kind of the mappings, all mappings if |
None
|
Returns:
| Type | Description |
|---|---|
list[int]
|
Indices into the resolved data of the mappings. |
times_before_changes
¶
Get the times of the data of a mapping compared before a change.
A data point of a timecourse over the time whose time is the time of
a change after the start of its simulation, up to the resolution of
the time (sbmlsim.simulator.plan.time_tolerance), is compared with
the state before the change, except the first point of the curve,
see FitSettings.data_at_change.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
int
|
index of the fit mapping. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The times of the reference data which are compared with the state |
ndarray
|
before a change, in the time of the data; empty for a mapping |
ndarray
|
which is no timecourse over the time and with |
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem is not initialized. |
report
¶
Print and write report.
Can only be called after initialization.
initialize
¶
Initialize the optimization problem for the given settings.
Resolves the data of the fit mappings, converts it to the units of the model, calculates the weights and attaches a simulator. The problem is only initialized once for a given set of settings. New runtime state is committed after initialization succeeds. Reports copy the definition and initialize their own runtime, preserving the original fit session.
Every fit mapping is one of three kinds, see ObservationKind,
decided from the dimensions of its observable after its sel
(observation_kinds, observation_dims): a timecourse, whose
reference x are times; a value per simulation, whose reference has
no x (x_references is NaN) and every row of which compares with
the one simulated value; or values over one dimension of a scan,
whose reference x are values of the target of the dimension, which
the values of the dimension must cover. The groups, the plans of the
points of a scan and the observables are built here, also in every
worker of a parallel fit, which initializes the pickled definition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
FitSettings
|
settings of the fit, they decide how the residuals and the weights are calculated. |
required |
force
|
bool
|
initialize again even if the settings did not change. |
False
|
Raises:
| Type | Description |
|---|---|
TypeError
|
if the settings are not a |
ValueError
|
if a mapping is none of the kinds (see
|
integrating
¶
Evaluate the problem with other settings of the integrator.
Within the context every model of the problem integrates with the
settings of the integrator of settings (its tolerances, and the step
settings of roadrunner, see _simulator) and the extra settings,
e.g. maximum_bdf_order; the state of the integrator of every model
(SBMLModel.integrator_state) is set back when the context exits,
also after an error. Nothing else of the problem depends on the
integrator: its data, weights, groups and plans are kept, so an
evaluation within the context is the one of the problem initialized
with settings (and the models given the extra settings), without
initializing it again. The checks of the verification of a
credibility assessment evaluate the adopted fits so, see
sbmlsim.credibility.verification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings
|
FitSettings
|
the settings whose integrator settings are used; the other settings, e.g. the residuals, stay the ones the problem was initialized with. |
required |
**extra
|
IntegratorSetting
|
further settings of the integrator by their names in
roadrunner, set after the ones of |
{}
|
Yields:
| Type | Description |
|---|---|
Generator[None]
|
Nothing; the evaluations of the problem in the context use the |
Generator[None]
|
settings. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem was not initialized, or the engine of a model has no setting of a name (nothing is changed then). |
to_scale
¶
Transform parameters of the model into the space of the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
one value per parameter, in the units of the model. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The values in the space the optimizer searches, every parameter |
ndarray
|
with its own scale. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
from_scale
¶
Transform parameters of the optimizer into the units of the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Any
|
one value per parameter, in the space the optimizer searches. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The values in the units of the model. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
fixed_changes
¶
Get the fixed values of the problem which apply to a model.
They are the defaults of the pre-initialization changes of every
simulation of the model, below the changes of the model, see
_simulation_of; a value of an entity the model does not have, e.g.
of a parameter of another model of the project, is left out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
SBMLModel
|
the loaded model. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
The fixed values of the entities of the model, in its units. |
parameter_set_model
¶
Get the initial values of the fitted parameters in the model.
The set is the reference a fitted set is compared against in a report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sid
|
str
|
identifier of the set. |
'model'
|
Returns:
| Type | Description |
|---|---|
ParameterSet
|
Parameter set of the values the models start from. |
bind_parameter_set
¶
Convert a set to fit units, resolving declared model unit aliases.
A value which the problem neither fits nor uses in its noise models
changes nothing: the model keeps its own value. The set of a joint fit
reported on one of its subsets carries such values, and the report
would name them and simulate the model instead, so they are logged
(#641). They stay in the set, which the report stores, and the bound
set names them in ParameterSet.unapplied, so the stored
parameters.json, the record of an adopted fit and the
credibility.json of an assessment say which of their numbers took
effect (#643).
set_simulator
¶
Set the simulator on the runner and the experiments.
A simulator of another engine than the one of the problem loads the
models again in its engine, see ExperimentRunner.set_simulator: the
engine of the simulator becomes the engine of the problem, which a
pickled problem keeps, the models of the mappings are the ones of the
runner and the plans are compiled against them. A simulator of the
same engine keeps the models. None keeps the simulator.
The evaluations of the problem integrate with the settings of the
integrator of its FitSettings of initialize, not with the ones of
the simulator: the models of another engine get the settings of the
fit as well, see _simulator.
A failure leaves the problem and its runner as they were.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulator
|
Simulator | None
|
the simulator of the experiments. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem was not initialized. |
optimize
¶
optimize(
size=5,
algorithm=LEAST_SQUARE,
sampling=LOGUNIFORM_LHS,
seed=None,
timeout=None,
on_run_finished=None,
population=None,
jacobian=None,
indices=None,
**kwargs,
)
Run parameter optimization.
The problem must be initialized, i.e., the settings of the fit are the settings it was initialized with.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
number of optimizations, every one starts from its own sample. |
5
|
algorithm
|
OptimizationAlgorithmType
|
optimization algorithm. |
LEAST_SQUARE
|
sampling
|
SamplingType
|
sampling of the start values of the local optimizer. |
LOGUNIFORM_LHS
|
seed
|
int | None
|
seed of the sampling. |
None
|
timeout
|
float | None
|
seconds a single optimization may run, no limit if |
None
|
on_run_finished
|
Callable[[int, OptimizeResult, list[float]], None] | None
|
called with the index, the fit and the trajectory of every finished optimization, i.e., to report the progress of a fit and to store the runs while it runs. |
None
|
population
|
PopulationEvaluator | None
|
evaluates the population of differential evolution,
e.g. on the workers of a fit, see |
None
|
jacobian
|
ResidualsEvaluator | None
|
evaluates the points of the jacobian of a least squares
run, e.g. on the workers of a fit, see |
None
|
indices
|
Sequence[int] | None
|
the runs which run, all |
None
|
**kwargs
|
Any
|
additional arguments of the optimizer. |
{}
|
Returns:
| Type | Description |
|---|---|
list[OptimizeResult]
|
The fits and the trajectories of the optimizations, in the order |
list[list[float]]
|
of their index. A run which failed is a |
tuple[list[OptimizeResult], list[list[float]]]
|
with its message, the other runs are unaffected. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the indices are invalid, see |
start_values
¶
Create the start values of the optimization runs.
The start values are created for all runs at once, so that they only depend on the seed and the number of runs and not on how the runs are distributed over the workers of a parallel fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
number of optimizations. |
required |
algorithm
|
OptimizationAlgorithmType
|
optimization algorithm. The global optimizer draws its
own samples, its runs start from |
LEAST_SQUARE
|
sampling
|
SamplingType
|
sampling of the start values of the local optimizer. |
LOGUNIFORM_LHS
|
seed
|
int | None
|
seed of the sampling. |
None
|
Returns:
| Type | Description |
|---|---|
list[ndarray | None]
|
One start vector per run, |
run_seeds
staticmethod
¶
Create the seed of every optimization run.
The global optimizer draws its own population, so every run needs its own seed: with one seed for all runs they all return the same result. The local optimizer is deterministic, its runs differ in the start values and do not need a seed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
number of optimizations. |
required |
algorithm
|
OptimizationAlgorithmType
|
optimization algorithm. |
LEAST_SQUARE
|
seed
|
int | None
|
seed of the fit, |
None
|
Returns:
| Type | Description |
|---|---|
list[int | None]
|
One seed per run, |
check_optimizer_arguments
staticmethod
¶
Check that the optimizer of the algorithm accepts the arguments.
The additional arguments of a fit are handed to scipy.optimize.least_squares
or scipy.optimize.differential_evolution in every run. An argument they
do not accept would fail every run, so it is found before the first run.
What the problem passes itself, i.e., the objective, the start values and
the bounds, is not an additional argument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
algorithm
|
OptimizationAlgorithmType
|
optimization algorithm. |
required |
arguments
|
Iterable[str] | Mapping[str, Any]
|
names of the additional arguments of the optimizer. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
if an argument is not an argument of the optimizer. |
optimizer_arguments
¶
Get the arguments of the optimizer with the defaults of the problem.
A least squares optimization with a jacobian of finite differences
gets the step default_diff_step of the relative tolerance of the
integrator of the settings, unless diff_step is given, and the
tolerances ftol, xtol and gtol of default_tolerance, unless
given. Its workers=1 or workers=None, the default of scipy, is
dropped; the fit sets the workers of the jacobian, see
sbmlsim.fit.runner.split_cores. Differential evolution updates its
population once per
generation, updating="deferred", unless updating is given: the
members of a generation are evaluated together, serially or on
workers, so the result of a seed does not depend on the number of
workers. Its workers=1, the default of scipy, is dropped; the fit
sets the workers. Its population is DE_POPSIZE members per parameter
and its best member is polished by least squares
(LEAST_SQUARES_POLISH), unless popsize or polish is given: on
the fits of the HCTZ example this found the optimum of every seed at a
quarter of the evaluations of scipy's defaults, whose polishing by
L-BFGS-B on the cost did not improve it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
algorithm
|
OptimizationAlgorithmType
|
optimization algorithm. |
required |
kwargs
|
Mapping[str, Any]
|
the arguments given for the optimizer. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The arguments. |
optimize_run
¶
optimize_run(
x0=None,
algorithm=LEAST_SQUARE,
timeout=None,
run=0,
size=1,
run_seed=None,
population=None,
jacobian=None,
**kwargs,
)
Run a single optimization, which never raises.
This is one repeat of a fit, i.e., what the serial runner loops over and
what a worker of a parallel fit executes. An optimization which fails is
a RuntimeErrorOptimizeResult with its message, so that the repeat is
stored and reported like a successful one and the other repeats are
unaffected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x0
|
ndarray | None
|
start values of the run, |
None
|
algorithm
|
OptimizationAlgorithmType
|
optimization algorithm. |
LEAST_SQUARE
|
timeout
|
float | None
|
seconds the optimization may run, no limit if |
None
|
run
|
int
|
index of the run, for the log messages. |
0
|
size
|
int
|
number of runs, for the log messages. |
1
|
run_seed
|
int | None
|
seed of the run, |
None
|
population
|
PopulationEvaluator | None
|
evaluates the members of the population of
differential evolution, e.g. on the workers of a fit, instead
of the calling process; it is the |
None
|
jacobian
|
ResidualsEvaluator | None
|
evaluates the points of the finite differences of the
jacobian of a least squares run, e.g. on the workers of a fit,
instead of the calling process; it is the |
None
|
**kwargs
|
Any
|
additional arguments of the optimizer. |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[OptimizeResult, list[float]]
|
The fit and the cost of every step of the optimization. |
evaluated_plan
¶
Get the plan a group is simulated with for the given parameters.
The values of the parameters are applied first; for a group of a scan
the values of the point follow, so a dimension wins over a fitted
value of its target; the derived changes come last and read the
values of the point, e.g. a covariate of a population dimension. The
factors of a subject apply last, to the values of their targets the
plan has then, see Plan.scaled, and to the value of the model of a
target which it does not set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k_group
|
int
|
index of the simulation group. |
required |
x
|
ndarray
|
parameter values in the units of the parameters. |
required |
quantities
|
Sequence[Quantity] | None
|
the quantity of every parameter, built from |
None
|
point
|
int
|
the point of a group of a scan, in the order of its points; a group of a simulation has one. |
0
|
curve
|
bool
|
the plan of the output of the simulation of a group which
outputs the times of its data, the curve of its evaluation,
see |
False
|
factors
|
Mapping[str, float] | None
|
target -> the factor of its value, the inputs of a
subject relative to the inputs of the simulation, see
|
None
|
Returns:
| Type | Description |
|---|---|
Plan
|
The plan of the group with the values of the parameters, of the |
Plan
|
point and the derived changes in the units of the model, times the |
Plan
|
factors; a group which outputs the times of its data ends at its |
Plan
|
last output time, see |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the group keeps its output and a curve is asked
for, or a target of the factors is set by a formula or is no
target of the model, see |
predictions
¶
Get the simulation of fit mappings at their reference data.
See evaluations, whose predictions these are; a prediction without a
value is NaN.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
values of the parameters in the units of the model. |
required |
indices
|
Sequence[int] | None
|
indices of the fit mappings, the training data by default. |
None
|
factors
|
Mapping[str, float] | None
|
the factors of the values of targets of a subject, see
|
None
|
Returns:
| Type | Description |
|---|---|
dict[int, ndarray]
|
The prediction at the reference data of every mapping, by the |
dict[int, ndarray]
|
index of the mapping. |
evaluations
¶
Get the simulation of fit mappings at their reference data.
The predictions are the values of the observable as they are
simulated, i.e. the baseline of a curve is not subtracted, whatever
the residual of the settings is. A prediction without a value, e.g. a
PK parameter of a point without a terminal phase, stays NaN here, so
that a likelihood sees it, while residuals gives the failure residual
for it, which keeps an optimizer going.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
values of the parameters in the units of the model, i.e. on the linear scale, in the order of the parameters of the problem. |
required |
indices
|
Sequence[int] | None
|
indices of the fit mappings, the training data by default. |
None
|
factors
|
Mapping[str, float] | None
|
target -> the factor of its value in every simulation,
the inputs of a subject relative to the inputs of the
simulations (e.g. a body weight 1.2 times the one of every
study group), applied after the parameters, see
|
None
|
Returns:
| Type | Description |
|---|---|
dict[int, MappingEvaluation]
|
The prediction and the selections of the noise model at the |
dict[int, MappingEvaluation]
|
reference data of every mapping, by the index of the mapping. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the problem is not initialized, if no simulator is
set, if |
cost_least_square
¶
Get the cost of parameters, 0.5 * sum(r**2) of the residuals.
The cost of a likelihood objective is the negative log-likelihood or
log posterior, the half sum of squares of its residuals without the
constant of their offsets, see _likelihood_terms.
log_prior_density
¶
Get the log density of the prior of the parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
values of the parameters on the linear scale. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The log density of the joint prior, see |
float
|
for an objective which does not use it. |
evaluate_cost
¶
Get the cost of parameters without recording it, cost_least_square.
This is what a worker evaluates for a member of the population of
differential evolution, the run in the parent records the cost, see
_population_map. The trajectory and the best parameters of the
problem are left as they are.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xlog
|
ndarray
|
the parameters in the space the optimizer searches. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The cost, infinite for a simulation which failed. |
evaluate_residuals
¶
Get the residuals and the cost of parameters without recording them.
This is what a worker evaluates for a point of the jacobian of a least
squares run, the run in the parent records the cost, see
jacobian_map. The trajectory and the best parameters of the problem
are left as they are.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xlog
|
ndarray
|
the parameters in the space the optimizer searches. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
The weighted residuals and the cost the run records, which is |
float
|
infinite for a simulation which failed. |
evaluate_residuals_many
¶
Get the residuals and the cost of a batch of parameter vectors.
What evaluate_residuals is for one vector: the evaluations of the
vectors of a batch do not depend on each other, so the simulations of
the whole batch run as one batch of the engine before any vector is
evaluated, and sbmlsim-core fans them out over threads of its own
(_simulate_batch). The points of the jacobian of a step of a least
squares run are such a batch, see
sbmlsim.fit.runner.JacobianPool.
The value of a vector is the one of its own evaluation: the engine
holds no state between two requests and every thread simulates on an
instance of its own, so the batch changes no number, see
tests/fit/test_evaluation_batch.py.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vectors
|
Sequence[ndarray]
|
the parameter vectors in the space the optimizer searches. |
required |
threads
|
int | None
|
the threads of the engine the batch runs on, the CPUs of
the process by default, see |
None
|
Returns:
| Type | Description |
|---|---|
list[tuple[ndarray, float]]
|
The weighted residuals and the cost of every vector, in the order |
list[tuple[ndarray, float]]
|
of the vectors. |
evaluate_cost_many
¶
Get the cost of a batch of parameter vectors, see evaluate_residuals_many.
The members of a population of differential evolution are such a
batch, see sbmlsim.fit.runner.PopulationPool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vectors
|
Sequence[ndarray]
|
the parameter vectors in the space the optimizer searches. |
required |
threads
|
int | None
|
the threads of the engine the batch runs on, the CPUs of the process by default. |
None
|
Returns:
| Type | Description |
|---|---|
list[float]
|
The cost of every vector, in the order of the vectors, infinite |
list[float]
|
for a simulation which failed. |
jacobian_map
¶
Get the map of scipy which evaluates a jacobian with an evaluator.
The map of scipy.optimize.least_squares (its workers) gets the
objective and the points of the finite differences of one jacobian,
one point per parameter for a forward difference and two for a central
one. The objective is residuals of this problem, which the evaluator
evaluates instead, e.g. on the workers of a fit. The residuals come
back in the order of the points, which is the order scipy builds the
columns of the jacobian from, so the jacobian is the jacobian of a
serial run bitwise, and their costs are recorded in that order, like
the evaluations of a serial run. A jacobian which starts after the
deadline of the run raises FitTimeout, like a serial evaluation, and
the evaluator gives up the points which are not evaluated at the
deadline; the points which were evaluated are recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
jacobian
|
ResidualsEvaluator
|
evaluates the residuals of the points. |
required |
embed
|
Callable[[ndarray], ndarray] | None
|
turns a point of the optimizer into the parameter vector of
the problem, for an optimization of some of the parameters,
e.g. a scan of a profile which fixes one of them; the points
are the parameters of the problem if |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[Any, Iterable[ndarray]], list[ndarray]]
|
The map, |
residuals
¶
Calculate residuals for given parameter vector.
Optimization is performed in logarithmic parameter space to account for xtol in largely varying parameters. see https://github.com/scipy/scipy/issues/7632
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xlog
|
ndarray
|
logarithmic parameter vector. |
required |
complete_data
|
bool
|
return the simulations, residuals and costs of every fit mapping instead of the vector of weighted residuals. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | dict[str, list[Any]]
|
Vector of weighted residuals, or the complete data of the mappings. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if no simulator is set or the residuals are not supported. |
apply_loss_function
¶
Apply the loss function to the residuals.
The cost of the optimization is 0.5 * sum(rho(residuals**2)) with rho the
loss function. The optimizers minimize 0.5 * sum(f**2), so the residuals are
transformed to sign(r) * sqrt(rho(r**2)), which gives exactly this cost and
keeps the sign of the residual. The loss functions are the loss functions of
scipy.optimize.least_squares.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residuals
|
ndarray
|
weighted residuals of a fit mapping. |
required |
loss_function
|
LossFunctionType
|
loss function to apply. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Transformed residuals. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if the loss function is not supported. |
default_diff_step
¶
Get the relative step of the finite differences of the jacobian of a fit.
A simulation is exact only to the relative tolerance of its integrator, so the residuals have a noise of about that size, and the step of a forward difference balances this error against the truncation error at the square root of the noise. The default of SciPy, the square root of the machine epsilon, is far below the noise: the jacobian is noise, and the optimizer stops next to its start.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_tolerance
|
float
|
relative tolerance of the integrator of the fit. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The step, relative to the parameters in the space the optimizer |
float
|
searches. |
default_tolerance
¶
Get the tolerances ftol, xtol and gtol of the least squares of a fit.
A simulation is exact only to the relative tolerance of its integrator, so
the cost has a noise of about that size: scipy's default of 1e-8 below
it only adds the steps which chase the noise. The tolerances are the
relative tolerance of the integrator, at least the default of scipy. On
the fits of the HCTZ example this took 13 to 27 % fewer evaluations to
the same optima.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relative_tolerance
|
float
|
relative tolerance of the integrator of the fit. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The tolerance. |
run_indices
¶
Get the repeats of a fit which run, all of them by default.
A fit draws the start values and the seeds of all its size repeats and
runs the given ones of them, every one with its index, so a fit split into
pieces of repeats gives the repeats of the whole fit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size
|
int
|
number of repeats of the fit. |
required |
indices
|
Sequence[int] | None
|
the repeats which run, all if |
None
|
Returns:
| Type | Description |
|---|---|
list[int]
|
The indices of the repeats which run, ascending: a serial and a |
list[int]
|
parallel fit return their repeats in the order of their index. |
Raises:
| Type | Description |
|---|---|
ValueError
|
if no index is given, if an index is no integer (a bool is
none), or if an index is outside of |
minimal_result
¶
Reduce the result of an optimization to what is reported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
opt_result
|
OptimizeResult
|
result of one of the optimizers of scipy. |
required |
Returns:
| Type | Description |
|---|---|
OptimizeResult
|
A result with the keys of |