Skip to content

fit.optimization

Optimization of parameter fitting problem.

RuntimeErrorOptimizeResult dataclass

RuntimeErrorOptimizeResult(
    status=-1,
    success=False,
    duration=-1.0,
    cost=inf,
    optimality=inf,
    x=None,
    x0=None,
    message="RuntimeError in ODE integration.",
)

Result of an optimization which failed with a RuntimeError.

Carries the same attributes as the scipy.optimize.OptimizeResult of a successful optimization, so that the results can be processed together.

OptimizationProblem

OptimizationProblem(
    opid,
    fit_experiments,
    fit_parameters,
    base_path=None,
    data_path=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.

:param opid: id for optimization problem :param fit_experiments: :param fit_parameters:

training_indices property

training_indices

Indices of the fit mappings which are fitted.

validation_indices property

validation_indices

Indices of the fit mappings which are only evaluated.

is_initialized property

is_initialized

Check if the problem was initialized, i.e., the data is resolved.

settings_initialized property

settings_initialized

Settings of the problem, set in initialize.

Raises:

Type Description
ValueError

if the problem was not initialized.

residual property

residual

Handling of the residuals, see FitSettings.

loss_function property

loss_function

Loss function of the fit, see FitSettings.

weighting_curves property

weighting_curves

Weighting of the curves, see FitSettings.

weighting_points property

weighting_points

Weighting of the data points, see FitSettings.

runner_initialized property

runner_initialized

Runner of the problem, created in initialize.

indices

indices(kind=None)

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.

None

Returns:

Type Description
list[int]

Indices into the resolved data of the mappings.

mapping_counts

mapping_counts()

Get the number of resolved fit mappings per kind.

to_dict

to_dict()

Convert to dictionary.

to_json

to_json(path=None)

Store OptimizationResult as json.

Uses the to_dict method.

report

report(path=None, print_output=True)

Print and write report.

Can only be called after initialization.

initialize

initialize(settings, force=False)

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: a fit and the report of the fit use the same problem, and resolving the data twice repeats the work and every message about the data.

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 FitSettings.

parameter_set_model

parameter_set_model(sid='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.

set_simulator

set_simulator(simulator)

Set the simulator on the runner and the experiments.

optimize

optimize(
    size=5,
    algorithm=LEAST_SQUARE,
    sampling=UNIFORM,
    seed=None,
    on_run_finished=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.

UNIFORM
seed int | None

seed of the sampling.

None
on_run_finished Callable[[], None] | None

called after every finished optimization, used to report the progress of a fit.

None
kwargs

additional arguments of the optimizer.

{}

Returns:

Type Description
tuple[list[OptimizeResult], list]

The fits and the trajectories of the optimizations.

cost_least_square

cost_least_square(xlog)

Get least square costs for parameters.

residuals

residuals(xlog, complete_data=False)

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_loss_function(residuals, 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.