0.1.33
Loading...
Searching...
No Matches
pyhelios.ParameterOptimization.ParameterOptimization Class Reference

Optimize named model parameters against an objective function. More...

Detailed Description

Optimize named model parameters against an objective function.

The objective receives a {name: value} dict and returns a scalar cost to minimize. It may close over a :class:~pyhelios.Context and run a full Helios simulation; the plugin itself takes no Context.

This class requires the native Helios library built with the parameteroptimization plugin. Use it as a context manager so the C++ instance is released promptly.

Example
>>> with ParameterOptimization() as opt: ... opt.setAlgorithm(CMAES(max_evaluations=200, random_seed=1)) ... result = opt.run(objective, {"x": Parameter.continuous(0.0, -5.0, 5.0)}) ... print(result.fitness, result["x"])

Definition at line 580 of file ParameterOptimization.py.

Public Member Functions

 __init__ (self)
 Create a ParameterOptimization instance.
 
 __enter__ (self)
 Context manager entry.
 
 __exit__ (self, exc_type, exc_value, traceback)
 Context manager exit with proper cleanup.
 
 __del__ (self)
 Destructor to ensure C++ resources freed even without 'with' statement.
 
 getNativePtr (self)
 Get the native pointer for advanced operations.
 
None setAlgorithm (self, AlgorithmSettings algorithm)
 Select the optimization algorithm and its hyperparameters.
 
None setPrintProgress (self, bool enable)
 Enable or disable the plugin's progress printout to stdout.
 
None setResultFile (self, Optional[str] path)
 Write the final result to a CSV file.
 
None setProgressFile (self, Optional[str] path)
 Write per-generation progress to a CSV file.
 
None setInputFile (self, Optional[str] path)
 Read the initial parameter set from a file.
 
OptimizationResult run (self, Callable[[Dict[str, float]], float] objective, Mapping[str, Parameter] parameters, Optional[Callable[[Dict[str, float]], Dict[str, float]]] gradient=None, *, bool finite_difference=False, float fd_step=0.0)
 Run the optimization.
 
OptimizationResult runConstrained (self, Callable[[Dict[str, float]], ConstrainedResult] simulation, Mapping[str, Parameter] parameters, *, int constraint_count)
 Run a constrained optimization: minimize f(x) subject to c_i(x) <= 0.
 
bool is_available (self)
 Check if the parameteroptimization plugin is available in this build.
 

Static Public Member Functions

Dict[str, bool] availableAlgorithms ()
 Report which algorithms can run in this build.
 

Public Attributes

 optimizer = None
 

Protected Member Functions

None _check_alive (self)
 Raise if this instance has already been destroyed.
 

Static Protected Member Functions

list _validate_parameters (Mapping[str, Parameter] parameters)
 Check the parameter mapping and flatten it for the wrapper.
 
None _validate_parameter_types_for_algorithm (Mapping[str, "Parameter"] parameters, "AlgorithmSettings" algorithm)
 Reject discrete parameters given to an algorithm that cannot handle them.
 

Protected Attributes

bool _running = False
 
 _algorithm = algorithm
 

Constructor & Destructor Documentation

◆ __init__()

pyhelios.ParameterOptimization.ParameterOptimization.__init__ ( self)

Create a ParameterOptimization instance.

Exceptions
ParameterOptimizationErrorIf the plugin is unavailable in this build

Definition at line 588 of file ParameterOptimization.py.

◆ __del__()

pyhelios.ParameterOptimization.ParameterOptimization.__del__ ( self)

Destructor to ensure C++ resources freed even without 'with' statement.

Definition at line 637 of file ParameterOptimization.py.

Member Function Documentation

◆ __enter__()

pyhelios.ParameterOptimization.ParameterOptimization.__enter__ ( self)

Context manager entry.

Definition at line 622 of file ParameterOptimization.py.

◆ __exit__()

pyhelios.ParameterOptimization.ParameterOptimization.__exit__ ( self,
exc_type,
exc_value,
traceback )

Context manager exit with proper cleanup.

Definition at line 626 of file ParameterOptimization.py.

◆ _check_alive()

None pyhelios.ParameterOptimization.ParameterOptimization._check_alive ( self)
protected

Raise if this instance has already been destroyed.

Definition at line 653 of file ParameterOptimization.py.

◆ _validate_parameter_types_for_algorithm()

None pyhelios.ParameterOptimization.ParameterOptimization._validate_parameter_types_for_algorithm ( Mapping[str, "Parameter"] parameters,
"AlgorithmSettings" algorithm )
staticprotected

Reject discrete parameters given to an algorithm that cannot handle them.

   Only the genetic algorithm implements INTEGER and CATEGORICAL parameters.
   The rest search a continuous space, so a discrete parameter would be
   optimized as a plain float and the result would not be a whole number, or
   not one of the allowed categories.

   helios-core enforces this for L-BFGS, Adam, BOBYQA and SLSQP, but not for
   CMA-ES or Bayesian optimization, where a CATEGORICAL parameter instead
   collapses to 0.0 with no diagnostic: its min and max are documented as
   ignored and so are conventionally left at zero, which those two algorithms
   read as the bounds [0, 0]. Checking here covers that gap on every core
   version, and reports the parameter and the remedy rather than leaving the
   message to the layer that happens to catch it first.

Definition at line 1048 of file ParameterOptimization.py.

◆ _validate_parameters()

list pyhelios.ParameterOptimization.ParameterOptimization._validate_parameters ( Mapping[str, Parameter] parameters)
staticprotected

Check the parameter mapping and flatten it for the wrapper.

   Only conditions that are memory-safety preconditions, or that produce a
   materially better message here than from C++, are checked. Bound
   consistency (min == max, min > max, NaN bounds, empty categories) is left
   to the plugin's own validation so the two cannot drift apart.

Definition at line 974 of file ParameterOptimization.py.

◆ availableAlgorithms()

Dict[str, bool] pyhelios.ParameterOptimization.ParameterOptimization.availableAlgorithms ( )
static

Report which algorithms can run in this build.

   L-BFGS, BOBYQA and SLSQP depend on NLopt, and L-BFGS additionally on the
   LGPL Luksan solvers, which PyHelios disables by default.
Returns
Mapping of algorithm name to availability

Definition at line 672 of file ParameterOptimization.py.

◆ getNativePtr()

pyhelios.ParameterOptimization.ParameterOptimization.getNativePtr ( self)

Get the native pointer for advanced operations.

Definition at line 647 of file ParameterOptimization.py.

◆ is_available()

bool pyhelios.ParameterOptimization.ParameterOptimization.is_available ( self)

Check if the parameteroptimization plugin is available in this build.

Definition at line 1073 of file ParameterOptimization.py.

◆ run()

OptimizationResult pyhelios.ParameterOptimization.ParameterOptimization.run ( self,
Callable[[Dict[str, float]], float] objective,
Mapping[str, Parameter] parameters,
Optional[Callable[[Dict[str, float]], Dict[str, float]]] gradient = None,
* ,
bool finite_difference = False,
float fd_step = 0.0 )

Run the optimization.

Parameters
objectiveCallable receiving {name: value} and returning a scalar cost to minimize. Invoked once per candidate parameter set.
parametersParameters to optimize, keyed by name
gradientOptional callable receiving {name: value} and returning {name: partial derivative} for every parameter. Required by Adam, L-BFGS, and SLSQP unless finite_difference is used.
finite_differenceEstimate the gradient by centered finite differences instead of supplying one. Costs 2N extra objective evaluations per gradient.
fd_stepRelative perturbation for finite differences; 0 uses the default
Returns
The optimized parameters and the objective value at the optimum
Exceptions
ValueErrorIf the arguments are invalid
TypeErrorIf objective or gradient is not callable
ParameterOptimizationErrorIf the optimization fails
Note
An exception raised inside the objective aborts the run and is re-raised here with its original traceback. Partial results are not
Exceptions
recoverable.

Definition at line 802 of file ParameterOptimization.py.

◆ runConstrained()

OptimizationResult pyhelios.ParameterOptimization.ParameterOptimization.runConstrained ( self,
Callable[[Dict[str, float]], ConstrainedResult] simulation,
Mapping[str, Parameter] parameters,
* ,
int constraint_count )

Run a constrained optimization: minimize f(x) subject to c_i(x) <= 0.

   Requires ``setAlgorithm(SLSQP(...))``. SLSQP is the only algorithm in the
   plugin that handles nonlinear inequality constraints, and it needs every
   parameter to be ``FLOAT``.

   The simulation returns the objective, the constraints, and all gradients
   together. The optimizer caches each result, so the simulation runs once per
   parameter point no matter how many constraints there are -- which is what
   makes this practical for objectives that run a full Helios simulation.
Parameters
simulationCallable receiving {name: value} and returning a :class:ConstrainedResult
parametersParameters to optimize, keyed by name
constraint_countNumber of constraints. Required, and fixed for the whole run: the buffers the simulation writes into are sized before the first call, so the count cannot be discovered by calling it.
Returns
The optimized parameters and the objective value at the optimum
Exceptions
ValueErrorIf the arguments are invalid, or the selected algorithm is not SLSQP
TypeErrorIf simulation is not callable
ParameterOptimizationErrorIf the optimization fails
Note
Constraints are satisfied to the plugin's tolerance rather than exactly. Check feasibility of the returned parameters if it matters.
Example
>>> # minimize x^2 + y^2 subject to x + y >= 1 >>> def simulation(p): ... return ConstrainedResult( ... objective=p["x"] ** 2 + p["y"] ** 2, ... objective_gradient={"x": 2 * p["x"], "y": 2 * p["y"]}, ... constraints=[1.0 - p["x"] - p["y"]], ... constraint_gradients=[{"x": -1.0, "y": -1.0}], ... ) >>> with ParameterOptimization() as opt: ... opt.setAlgorithm(SLSQP()) ... result = opt.runConstrained( ... simulation, ... {"x": Parameter.continuous(0.0, -5.0, 5.0), ... "y": Parameter.continuous(0.0, -5.0, 5.0)}, ... constraint_count=1)

Definition at line 909 of file ParameterOptimization.py.

◆ setAlgorithm()

None pyhelios.ParameterOptimization.ParameterOptimization.setAlgorithm ( self,
AlgorithmSettings algorithm )

Select the optimization algorithm and its hyperparameters.

   If never called, the plugin picks a default based on the parameter types
   and whether a gradient was supplied.
Parameters
algorithmOne of the algorithm settings dataclasses
Exceptions
TypeErrorIf algorithm is not a recognized settings type
ParameterOptimizationErrorIf the algorithm is unavailable in this build

Definition at line 689 of file ParameterOptimization.py.

◆ setInputFile()

None pyhelios.ParameterOptimization.ParameterOptimization.setInputFile ( self,
Optional[str] path )

Read the initial parameter set from a file.

   Only the genetic algorithm consults this file.
Parameters
pathHeaderless CSV of "name,value,min,max" rows; None disables reading

Definition at line 766 of file ParameterOptimization.py.

◆ setPrintProgress()

None pyhelios.ParameterOptimization.ParameterOptimization.setPrintProgress ( self,
bool enable )

Enable or disable the plugin's progress printout to stdout.

Parameters
enableTrue to print progress during optimization

Definition at line 734 of file ParameterOptimization.py.

◆ setProgressFile()

None pyhelios.ParameterOptimization.ParameterOptimization.setProgressFile ( self,
Optional[str] path )

Write per-generation progress to a CSV file.

Parameters
pathOutput path ending in .csv or .txt; None disables writing

Definition at line 754 of file ParameterOptimization.py.

◆ setResultFile()

None pyhelios.ParameterOptimization.ParameterOptimization.setResultFile ( self,
Optional[str] path )

Write the final result to a CSV file.

Parameters
pathOutput path ending in .csv or .txt; None disables writing

Definition at line 744 of file ParameterOptimization.py.

Member Data Documentation

◆ _algorithm

pyhelios.ParameterOptimization.ParameterOptimization._algorithm = algorithm
protected

Definition at line 722 of file ParameterOptimization.py.

◆ _running

bool pyhelios.ParameterOptimization.ParameterOptimization._running = False
protected

Definition at line 590 of file ParameterOptimization.py.

◆ optimizer

pyhelios.ParameterOptimization.ParameterOptimization.optimizer = None

Definition at line 589 of file ParameterOptimization.py.


The documentation for this class was generated from the following file: