Optimize Module

class corrai.optimize.SciOptimizer(parameters, model)[source]

Bases: SampleMethodsMixin

Optimization wrapper for models using SciPy.

This class provides a convenient interface to optimize model parameters with respect to specified indicators. It leverages the ModelEvaluator for simulation and evaluation, and uses SciPy’s global optimization algorithm such as differential_evolution to find optimal parameter sets.

Parameters:
  • parameters (list of Parameter) – List of corrai Parameters to be optimized.

  • model (Model) – Corrai Model object that provides simulation capabilities.

Variables:

model_evaluator (ModelEvaluator) – Underlying evaluator used for simulations and objective evaluation and results storage.

Examples

>>> from corrai.optimize import SciOptimizer
>>> from corrai.base.model import Ishigami
>>> param_list = [
...     Parameter("par_x1", (-3.14159265359, 3.14159265359), model_property="x1"),
...     Parameter("par_x2", (-3.14159265359, 3.14159265359), model_property="x2"),
...     Parameter("par_x3", (-3.14159265359, 3.14159265359), model_property="x3"),
... ]
>>> sci_opt = SciOptimizer(
...     parameters=param_list,
...     model=Ishigami(),
... )
>>> res_opt = sci_opt.diff_evo_minimize("res")
>>> res_opt.fun
-10.74090910277037
>>> res_opt.x
array([-1.57080718e+00, -2.46536703e-07,  3.14159265e+00])
__init__(parameters, model)[source]
property parameters
property sample
property values
property results
scalar_minimize(indicator_config, simulation_options=None, simulation_kwargs=None, bracket=None, method=None, tol=None, options=None)[source]

Minimize a scalar indicator using SciPy’s scalar optimization routines.

This method is suitable for problems with a single parameter only.

Parameters:
  • indicator_config (str or tuple) –

    Indicator specification passed to the objective function: - If the model is static: a string representing the indicator name. - If the model is dynamic: a tuple of the form

    (col, func) or (col, func, reference) where:
    • col : str Column name in the simulation results.

    • func : str or Callable Aggregation function (either a method name registered in METHODS or a Python callable).

    • reference : optional reference time series for error function (eg. nmbe, cv_rmse).

  • simulation_options (dict, optional) – Options for the simulation (e.g., stop time, solver settings).

  • simulation_kwargs (dict, optional) – Additional keyword arguments for simulation.

  • bracket (tuple of float, optional) – Bracketing interval for methods that require it (e.g., “brent”).

  • method (str, optional) – Optimization method to use. Can be one of {“brent”, “bounded”, “golden”}. See scipy.optimize.minimize_scalar() for details.

  • tol (float, optional) – Tolerance for termination. Interpretation depends on the method.

  • options (dict, optional) – Additional solver-specific options.

Returns:

Result of the optimization, including optimal parameter value x and corresponding function value fun.

Return type:

scipy.optimize.OptimizeResult

Raises:

ValueError – If more than one parameter is defined, since scalar optimization only supports a single variable.

Notes

  • Only use a list of one parameter.

  • Uses scipy.optimize.minimize_scalar().

minimize(indicator_config, simulation_options=None, simulation_kwargs=None, x0=None, method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)[source]

This method wraps scipy.optimize.minimize

Parameters:
  • indicator_config (str or tuple) –

    Indicator configuration passed to ModelEvaluator.scipy_obj_function: - If the model is static: a string representing the indicator name. - If the model is dynamic: a tuple of the form

    (indicator, func) or (indicator, func, reference) where:
    • indicator : str Indicator name in the simulation results.

    • func : str or Callable Aggregation function (method name registered in METHODS or a Python callable).

    • reference : optional Reference time series if the aggregation function is an error metric such as nmbe, cv_rmse, or mean_squared_error.

  • simulation_options (dict, optional) – Options for the simulation (e.g., stop time, solver settings).

  • simulation_kwargs (dict, optional) – Additional keyword arguments for simulation.

  • x0 (list of float, optional) – Initial guess for the optimization variables. If None, the initial values are set to the mean of each parameter interval.

  • method (str or callable, optional) – Optimization method to use (e.g., ‘BFGS’, ‘L-BFGS-B’, ‘SLSQP’). Passed directly to scipy.optimize.minimize.

  • jac (callable or bool, optional) – Function computing the gradient of the objective, or a boolean indicating whether the objective returns the gradient.

  • hess (callable, optional) – Function computing the Hessian matrix of the objective.

  • hessp (callable, optional) – Function computing the Hessian-vector product.

  • bounds (sequence, optional) – Bounds on variables for bounded optimization methods.

  • constraints (sequence, optional) – Constraints definition for constrained optimization.

  • tol (float, optional) – Tolerance for convergence.

  • callback (callable, optional) – Function called after each iteration.

  • options (dict, optional) – Additional solver-specific options.

Returns:

Result of the optimization. Accessible also via the result attribute.

Return type:

scipy.optimize.OptimizeResult

Notes

This method relies on scipy.optimize.minimize, which implements gradient-based and derivative-free local optimization algorithms. It is best suited for smooth problems and may converge to a local minimum depending on the initial guess.

For global optimization, consider using diff_evo_minimize.

diff_evo_minimize(indicator_config, simulation_options=None, simulation_kwargs=None, maxiter=1000, tol=0.01, rng=None, workers=1)[source]

Minimize an indicator using SciPy’s differential evolution algorithm.

Parameters:
  • indicator_config (str or tuple) –

    Indicator configuration passed to ModelEvaluator.scipy_obj_function: - If the model is static: a string representing the indicator name. - If the model is dynamic: a tuple of the form

    (indicator, func) or (indicator, func, reference) where:
    • indicator : str indicator name in the simulation results.

    • func : str or Callable Aggregation function (method name registered in METHODS or a Python callable).

    • reference : optional reference time series if aggregation function is an error function such as nmbe, cv_rmse, mean_squared_error.

  • simulation_options (dict, optional) – Options for the simulation (e.g., stop time, solver settings).

  • simulation_kwargs (dict, optional) – Additional keyword arguments for simulation.

  • maxiter (int, optional) – Maximum number of generations for the optimizer. Default is 1000.

  • tol (float, optional) – Tolerance for convergence. Default is 0.01.

  • rng (int or RandomState or Generator, optional) – Random number generator seed or instance. Default is None.

  • workers (int or map-like callable, optional) – Number of parallel workers. Can be set to -1 to use all processors. Default is 1 (no parallelism).

Returns:

Result of the optimization. Accessible also via the result attribute.

Return type:

scipy.optimize.OptimizeResult

Notes

This method uses scipy.optimize.differential_evolution, which is a global optimization algorithm suitable for continuous parameter spaces.

class corrai.optimize.ModelEvaluator(parameters, model, store_results=True)[source]

Bases: object

Evaluate a model with respect to a set of parameters and compute indicators Series from simulation results.

This class acts as an interface between parameters, the model, and an optimizer. It provides and objective function suitable for SciPy optimizers.

Parameters:
  • parameters (list of Parameter) – List of corrai Parameters.

  • model (Model) – Corrai Model object. get_property_values method must be implemented to use get_initial_values method.

  • store_results (bool, optional) – If True, stores results in an internal Sample instance. Default is True.

Variables:
  • parameters (list of Parameter) – Model parameters used in evaluation.

  • model (Model) – The underlying model being evaluated.

  • sample (Sample) – Stores samples and simulation results if store_results=True.

Examples

>>> from corrai.base.model import Ishigami
>>> from corrai.optimize import ModelEvaluator
>>> param_list = [
...     Parameter("par_x1", (-3.14159265359, 3.14159265359), model_property="x1"),
...     Parameter("par_x2", (-3.14159265359, 3.14159265359), model_property="x2"),
...     Parameter("par_x3", (-3.14159265359, 3.14159265359), model_property="x3"),
... ]
>>> my_evaluator = ModelEvaluator(
...     parameters=param_list,
...     model=Ishigami(),
... )
>>> my_evaluator.intervals
[(-3.14159265359, 3.14159265359),
(-3.14159265359, 3.14159265359),
(-3.14159265359, 3.14159265359)]
>>> my_evaluator.get_initial_values()
[1, 2, 3]
>>> my_evaluator.evaluate(
...     parameter_value_pairs=[
...         (param_list[0], -3.14 / 2),
...         (param_list[1], 0),
...         (param_list[2], -3.14),
...     ],
...     indicators_configs=["res"],
... )
res   -10.721168
>>> my_evaluator.scipy_obj_function([-3.14 / 2, 0, -3.14], "res", None, None)
-10.721167816657914
__init__(parameters, model, store_results=True)[source]
property intervals: list[tuple[int | float, int | float]]
get_initial_values(relative_is_one=True)[source]
Return type:

list[int | float]

evaluate(parameter_value_pairs, indicators_configs, simulation_options=None, simulation_kwargs=None)[source]

Run a model simulation and compute indicators. Return a pandas Series with indicators name as index.

Parameters:
  • parameter_value_pairs (list of tuple(Parameter, str or int or float)) – List of parameters and their values to simulate.

  • indicators_configs (list of str or list of tuple) –

    • If the model is static: list of indicator names (strings).

    • If the model is dynamic: list of tuples specifying how to aggregate results. Each tuple has the form: - (col, func) - (col, func, reference)

      where:
      • col : str Column name in the simulation results.

      • func : str or Callable Aggregation function (either a method name registered in METHODS or a callable).

      • reference : optional time series that will be a reference for error aggreation method (eg. nmbe, cv_rmse, mean_squarred_error).

  • simulation_options (dict, optional) – Simulation options passed to the model.

  • simulation_kwargs (dict, optional) – Additional keyword arguments for the simulation.

Returns:

  • For static models: direct simulation results.

  • For dynamic models: aggregated indicator results.

Return type:

pandas.Series

Raises:

ValueError – If indicators_configs is invalid for the model type.

scipy_obj_function(x, *args)[source]
Return type:

float

scipy_scalar_obj_function(x, *args)[source]
class corrai.optimize.RealContinuousProblem(*, parameters, evaluators, objective_ids, constraint_ids=None)[source]

Bases: CorraiProblem

Continuous optimization problem for real-valued parameters in pymoo.

This class extends CorraiProblem and pymoo.ElementwiseProblem to represent optimization problems where all decision variables are real-valued. It wraps corrai Parameter objects, model evaluators, and objective/constraint definitions into a pymoo-compatible interface.

Parameters:
  • parameters (list of Parameter) – List Parameter with a Real ptype

  • evaluators (list of PymooModelEvaluator) – Evaluator objects that run models and compute performance indicators (objectives and/or constraints) given simulation options simulation kwargs and indicators configurations.

  • objective_ids (list of str) – Names of the indicators to be minimized or maximized as objectives. The order defines their position in the objective vector F.

  • constraint_ids (list of str, optional) – Names of the indicators to be treated as inequality constraints. If None (default), no constraints are applied.

Variables:
  • parameters (list of Parameter) – Problem decision variables.

  • evaluators (list of PymooModelEvaluator) – Model evaluators associated with the problem.

  • objective_ids (list of str) – Ordered list of objective indicator names.

  • constraint_ids (list of str) – Ordered list of constraint indicator names.

  • sample (Sample) – Stores past evaluations (parameter values and results).

  • parameters_names (list of str) – Names of all parameters.

  • values (dict) – Current sample values keyed by parameter name.

  • results (pandas.DataFrame) – Static results collected from evaluations.

_evaluate(x, out, \*args, \*\*kwargs)[source]

Evaluate objectives and constraints at the given point x.

Notes

  • All parameters must be real-valued (ptype="Real").

  • Lower and upper bounds are extracted from the interval attribute of each parameter.

  • The class automatically constructs the pymoo-compatible problem with n_var, n_obj, n_ieq_constr, xl, and xu.

__init__(*, parameters, evaluators, objective_ids, constraint_ids=None)[source]
Parameters:
  • n_var (int) – Number of Variables

  • n_obj (int) – Number of Objectives

  • n_ieq_constr (int) – Number of Inequality Constraints

  • n_eq_constr (int) – Number of Equality Constraints

  • xl (np.array, float, int) – Lower bounds for the variables. if integer all lower bounds are equal.

  • xu (np.array, float, int) – Upper bounds for the variable. if integer all upper bounds are equal.

  • vtype (type) – The variable type. So far, just used as a type hint.

class corrai.optimize.MixedProblem(*, parameters, evaluators, objective_ids, constraint_ids=None)[source]

Bases: CorraiProblem

Mixed-variable optimization problem for real, integer, binary, and choice parameters in pymoo.

MixedProblem extends CorraiProblem and pymoo.ElementwiseProblem to represent optimization problems where decision variables may be heterogeneous. It builds a pymoo-compatible variable dictionary with the appropriate type (Real, Integer, Binary, or Choice) for each parameter.

Parameters:
  • parameters (list of Parameter) – List of Parameter objects defining the optimization variables. Supported types are Real, Integer, Binary, and Choice.

  • evaluators (list of PymooModelEvaluator) –

    Evaluator objects that run models and compute performance indicators

    (objectives and/or constraints) given simulation options simulation kwargs and indicators configurations.

  • objective_ids (list of str) – Names of the indicators to be minimized or maximized as objectives. The order defines their position in the objective vector F.

  • constraint_ids (list of str, optional) – Names of the indicators to be treated as inequality constraints. Defaults to an empty list if not provided.

Variables:
  • parameters (list of Parameter) – Problem decision variables.

  • evaluators (list of PymooModelEvaluator) – Model evaluators associated with the problem.

  • objective_ids (list of str) – Ordered list of objective indicator names.

  • constraint_ids (list of str) – Ordered list of constraint indicator names.

  • sample (Sample) – Stores past evaluations (parameter values and results).

  • parameters_names (list of str) – Names of all parameters.

  • values (dict) – Current sample values keyed by parameter name.

  • results (pandas.DataFrame) – Static results collected from evaluations.

_evaluate(x, out, \*args, \*\*kwargs)[source]

Evaluate objectives and constraints at the given point x.

Notes

  • Each parameter type is mapped internally to the corresponding pymoo variable:

    • Realpymoo.core.variable.Real with bounds.

    • Integerpymoo.core.variable.Integer with bounds.

    • Binarypymoo.core.variable.Binary.

    • Choicepymoo.core.variable.Choice with enumerated options.

  • If a Choice parameter does not define values, a ValueError is raised.

  • Objective and constraint values are automatically extracted from evaluator results.

  • See CorraiProblem for common attributes and evaluation workflow.

__init__(*, parameters, evaluators, objective_ids, constraint_ids=None)[source]
Parameters:
  • n_var (int) – Number of Variables

  • n_obj (int) – Number of Objectives

  • n_ieq_constr (int) – Number of Inequality Constraints

  • n_eq_constr (int) – Number of Equality Constraints

  • xl (np.array, float, int) – Lower bounds for the variables. if integer all lower bounds are equal.

  • xu (np.array, float, int) – Upper bounds for the variable. if integer all upper bounds are equal.

  • vtype (type) – The variable type. So far, just used as a type hint.