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.
|
| | __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.
|
| |
| 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.
| 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.
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
-
| simulation | Callable receiving {name: value} and returning a :class:ConstrainedResult |
| parameters | Parameters to optimize, keyed by name |
| constraint_count | Number 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
-
| ValueError | If the arguments are invalid, or the selected algorithm is not SLSQP |
| TypeError | If simulation is not callable |
| ParameterOptimizationError | If 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.