Optimize Module
- class corrai.optimize.SciOptimizer(parameters, model)[source]
Bases:
SampleMethodsMixinOptimization 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:
- 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])
- 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|tuple[str,Union[str,Callable]] |tuple[str,Union[str,Callable],Series|None]) –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) – 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|tuple[str,Union[str,Callable]] |tuple[str,Union[str,Callable],Series]) –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) – Options for the simulation (e.g., stop time, solver settings).simulation_kwargs (dict, optional) – Additional keyword arguments for simulation.
x0 (
list[float]) – 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|tuple[str,Union[str,Callable]] |tuple[str,Union[str,Callable],Series]) –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) – 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.
- curve_fit(indicator_config, simulation_options=None, simulation_kwargs=None, p0=None, bounds=None, **kwargs)[source]
Use non-linear least squares to fit model parameters.
This method wraps
scipy.optimize.curve_fit()to calibrate the parameters of the underlying model so that simulated outputs best match reference data.- Parameters:
indicator_config (list or tuple) –
Configuration(s) describing the outputs to match. Each config should be: (col, func, reference), where:
col : str Column name in simulation results.
func : str or Callable Aggregation function (currently unused here but kept for consistency).
reference : pd.Series Reference data to fit against.
Multiple configs can be provided as a list.
simulation_options (dict, optional) – Options passed to the simulation routine.
simulation_kwargs (dict, optional) – Additional keyword arguments passed to the simulation.
p0 (array-like, optional) – Initial guess for the parameters. If None, uses the midpoint of intervals.
bounds (2-tuple of array-like, optional) – Lower and upper bounds on parameters. If None, derived from self.model_evaluator.intervals.
**kwargs – Additional keyword arguments passed to
scipy.optimize.curve_fit().
- Returns:
popt (array) – Optimal values for the parameters.
pcov (2-D array) – Estimated covariance of popt.
Notes
The function being fitted internally runs a full model simulation.
The independent variable is a dummy index, as only the output values matter.
Multiple indicators are concatenated into a single residual vector.
- class corrai.optimize.ModelEvaluator(parameters, model, store_results=True)[source]
Bases:
objectEvaluate 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:
- Variables:
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
- property intervals: list[tuple[int | float, 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[tuple[Parameter,str|int|float]]) – List of parameters and their values to simulate.indicators_configs (
list[str] |list[tuple[str,Union[str,Callable]] |tuple[str,Union[str,Callable],Series]] |None) –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) – 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:
Series- Raises:
ValueError – If indicators_configs is invalid for the model type.
- class corrai.optimize.RealContinuousProblem(*, parameters, evaluators, objective_ids, constraint_ids=None)[source]
Bases:
CorraiProblemContinuous optimization problem for real-valued parameters in pymoo.
This class extends
CorraiProblemandpymoo.ElementwiseProblemto represent optimization problems where all decision variables are real-valued. It wraps corraiParameterobjects, model evaluators, and objective/constraint definitions into a pymoo-compatible interface.- Parameters:
parameters (
list[Parameter]) – ListParameterwith a Real ptypeevaluators (
list[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[str]) – Names of the indicators to be minimized or maximized as objectives. The order defines their position in the objective vectorF.constraint_ids (
list[str] |None) – 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
intervalattribute of each parameter.The class automatically constructs the pymoo-compatible problem with
n_var,n_obj,n_ieq_constr,xl, andxu.
- __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:
CorraiProblemMixed-variable optimization problem for real, integer, binary, and choice parameters in pymoo.
MixedProblemextendsCorraiProblemandpymoo.ElementwiseProblemto 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[Parameter]) – List ofParameterobjects defining the optimization variables. Supported types areReal,Integer,Binary, andChoice.evaluators (
list[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[str]) – Names of the indicators to be minimized or maximized as objectives. The order defines their position in the objective vectorF.constraint_ids (
list[str] |None) – 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:
Real→pymoo.core.variable.Realwith bounds.Integer→pymoo.core.variable.Integerwith bounds.Binary→pymoo.core.variable.Binary.Choice→pymoo.core.variable.Choicewith enumerated options.
If a
Choiceparameter does not definevalues, aValueErroris raised.Objective and constraint values are automatically extracted from evaluator results.
See
CorraiProblemfor 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.