algorithm module

Define the Abstract Base Class of optimisation algorithms.

Abstract methods are mandatory and a TypeError will be raised if you try to create your own algorithm and omit them.

When you add you own optimisation algorithm, do not forget to add it to the list of implemented algorithms in the algorithm module.

Todo

Check if it is necessary to pass out the whole elts to OptimisationAlgorithm?

Todo

Methods and flags to keep the optimisation history or not, and also to save it or not. See Explorator.

Todo

Better handling of the attribute folder. In particular, a correct value should be set at the OptimisationAlgorithm instanciation.

class OptiSol[source]

Bases: TypedDict

Hold information on the solution.

var: ndarray[tuple[Any, ...], dtype[float64]] | list[float]

Value of variables

cavity_settings: dict[FieldMap, CavitySettings]

Value of var, but more logical

fun: ndarray[tuple[Any, ...], dtype[float64]] | list[float]

Value of objectives

objectives: dict[str, float]

Maps name of objectives with their value.

cv: NotRequired[float]

Value of constraint violation

constraints: NotRequired[dict[str, float]]

Maps name of constaint with cv value.

success: bool

If optimization was successful

info: list[str]

Complementary information

class OptimisationAlgorithm(*, compensating_elements, objective_factory, design_space, compute_beam_propagation, cavity_settings_factory, reference_simulation_output, optimisation_algorithm_kwargs=None, history_kwargs=None, **kwargs)[source]

Bases: ABC

Holds the optimization parameters, the methods to optimize.

Parameters:
__init__(*, compensating_elements, objective_factory, design_space, compute_beam_propagation, cavity_settings_factory, reference_simulation_output, optimisation_algorithm_kwargs=None, history_kwargs=None, **kwargs)[source]

Instantiate the object.

Parameters:
Return type:

None

supports_constraints: bool
__str__()[source]

Concatenate _str__ of variables, constraints, objectives.

Return type:

str

property variable_names: list[str]

Give name of all variables.

property n_var: int

Give number of variables.

property n_obj: int

Give number of objectives.

property n_constr: int

Return number of (inequality) constraints.

property _default_kwargs: dict[str, Any]

Give the default optimisation algorithm kwargs.

abstractmethod optimize()[source]

Set up optimization parameters and solve the problem.

Return type:

OptiSol

Returns:

Gives list of solutions, corresponding objective, convergence violation if applicable, etc.

abstractmethod _generate_opti_sol(*args, **kwargs)[source]

Takes the results of the optimization in any form, returns dict.

Return type:

OptiSol

_format_variables()[source]

Adapt all Variable to this optimisation algorithm.

Return type:

Any

_format_objectives()[source]

Adapt all Objective to this optimisation algorithm.

Return type:

Any

_format_constraints()[source]

Adapt all Constraint to this optimisation algorithm.

Return type:

Any

_wrapper_residuals(var)[source]

Compute residuals from an array of variable values.

Parameters:

var (ndarray[tuple[Any, ...], dtype[double]])

Return type:

ndarray[tuple[Any, ...], dtype[double]]

_norm_wrapper_residuals(var)[source]

Compute norm of residuals vector from array of variable values.

Parameters:

var (ndarray[tuple[Any, ...], dtype[double]])

Return type:

float

final _finalize(opti_sol)[source]

End the optimization process.

In particular:
  • Save the optimization history if applicable.

  • Store final residual values in the appropriate Objective instances.

  • Record final constraint values in history if applicable.

Parameters:

opti_sol (OptiSol)

Return type:

None

_to_cavity_settings(var)[source]

Transform var into CavitySettings.

Parameters:

var (ndarray[tuple[Any, ...], dtype[double]]) – A (2n,) array holding the settings to try, where first half holds the amplitudes and second the phases.

Return type:

dict[FieldMap, CavitySettings]

Returns:

Maps compensating elements with their CavitySettings.

final _evaluate_solution(var)[source]

Evaluate objectives and constraints for a single solution.

Runs the simulation once and returns both, avoiding redundant beam propagation calls when both are needed (e.g. in _finalize()).

Parameters:

var (ndarray[tuple[Any, ...], dtype[double]]) – Array of variable values.

Return type:

tuple[dict[str, float], dict[str, float] | None]

Returns:

  • objectives – Maps objective names to their values.

  • constraints – Constraint violation array, or None if no constraints defined.

final _check_consistency(opti_sol, fresh_objectives)[source]

Compare stored objectives with a fresh evaluation.

Parameters:
Return type:

None

_abc_impl = <_abc._abc_data object at 0x7318f91bc640>
class OptimizationHistory(reference_simulation_output, objectives_names, get_args=(), get_kwargs=None, folder=None, save_interval=100, **kwargs)[source]

Bases: object

Keep all the settings that were tried.

Parameters:
_settings_filename = 'settings.csv'
_objectives_filename = 'objectives.csv'
_constraints_filename = 'constraints.csv'
__init__(reference_simulation_output, objectives_names, get_args=(), get_kwargs=None, folder=None, save_interval=100, **kwargs)[source]

Instantiate the object.

Parameters:
  • get_args (tuple[str, ...], default: ()) – args and kwargs passed to the SimulationOutput.get method. Used to add some values to the output files.

  • get_kwargs (dict[str, Any] | None, default: None) – args and kwargs passed to the SimulationOutput.get method. Used to add some values to the output files.

  • get_kwargs – Keyword arguments for the SimulationOutput.get method.

  • folder (Path | str | None, default: None) – Where the histories will be saved. If not provided or None is given, this class will not have any effect and every public method wil be overriden with dummy methods.

  • save_interval (int, default: 100) – Files will be saved every save_interval iteration.

  • reference_simulation_output (SimulationOutput)

  • objectives_names (Collection[str])

Return type:

None

_make_public_methods_useless()[source]

Override some methods so that they do not do anything.

Return type:

None

add_settings(var)[source]

Add a new set of cavity settings.

Parameters:

var (ndarray[tuple[Any, ...], dtype[double]])

Return type:

None

_init_objective_hist(objectives_names, reference_simulation_output)[source]

Create the objective history, with header and reference values.

Parameters:
Return type:

tuple[list[str], list[None | float]]

_simulation_output_to_objectives(simulation_output)[source]

Extract and format desired values from simulation_output.

Parameters:

simulation_output (SimulationOutput)

Return type:

list[float]

_objective_headers(objectives_names)[source]

Get the objective headers.

Parameters:

objectives_names (Collection[str])

Return type:

tuple[list[str], list[str]]

add_objective_values(objectives, simulation_output)[source]

Add some objective values.

Parameters:
Return type:

None

add_constraint_values(constraints)[source]

Add some constraint values.

Parameters:

constraints (list | ndarray[tuple[Any, ...], dtype[double]] | None)

Return type:

None

save()[source]

Save the three histories in their respective files.

All files will be in self.history_folder.

Return type:

None

_rename_previous_files()[source]

Rename the previous history files.

Return type:

None

_empty_histories()[source]

Empty the histories.

Return type:

None

checkpoint()[source]

Save periodically based on the defined interval.

Return type:

None

_save_values(filepath, values)[source]

Save the values to filepath (can be objectives or constraints).

Parameters:
  • filepath (Path) – Where to save the values.

  • values (list[list[float] | ndarray[tuple[Any, ...], dtype[double]] | None]) – The list of values to save (objectives or constraints), starting in the third column. If a value is None, it is represented as ‘None’ in the file.

Return type:

None