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

Bases: TypedDict

Hold information on the solution.

var: ndarray | list[float]
cavity_settings: SetOfCavitySettings
fun: ndarray | list[float]
objectives: dict[str, float]
success: bool
class OptimisationAlgorithm(*, compensating_elements: Collection[Element], elts: ListOfElements, objectives: Collection[Objective], variables: Collection[Variable], compute_beam_propagation: Callable[[SetOfCavitySettings], SimulationOutput], compute_residuals: Callable[[SimulationOutput], Any], cavity_settings_factory: CavitySettingsFactory, reference_simulation_output: SimulationOutput, constraints: Collection[Constraint] | None = None, compute_constraints: Callable[[SimulationOutput], ndarray] | None = None, optimisation_algorithm_kwargs: dict[str, Any] | None = None, history_kwargs: dict[str, Any] | None = None, **kwargs)

Bases: ABC

Holds the optimization parameters, the methods to optimize.

Parameters:
  • compensating_elements (list[Element]) – Cavity objects used to compensate for the faults.

  • elts (ListOfElements) – Holds the whole compensation zone under study.

  • objectives (list[Objective]) – Holds objectives, initial values, bounds.

  • variables (list[Variable]) – Holds variables, their initial values, their limits.

  • constraints (list[Constraint] | None, optional) – Holds constraints and their limits. The default is None.

  • opti_sol (OptiSol) – Holds information on the solution that was found.

  • supports_constraints (bool) – If the method handles constraints or not.

  • compute_beam_propagation (ComputeBeamPropagationT) – Method to compute propagation of the beam with the given settings. Defined by a BeamCalculator.run_with_this() method, the positional argument elts being set by a functools.partial.

  • compute_residuals (ComputeResidualsT) – Method to compute residuals from a SimulationOutput.

  • compute_constraints (ComputeConstraintsT | None, optional) – Method to compute constraint violation. The default is None.

  • cavity_settings_factory (CavitySettingsFactory) – A factory to easily create the cavity settings to try at each iteration of the optimisation algorithm.

  • history_kwargs (dict | None, optional) – kwargs for the OptimizationHistory creation.

  • reference_simulation_output (SimulationOutput) – Used for the OptimizationHistory.

__init__(*, compensating_elements: Collection[Element], elts: ListOfElements, objectives: Collection[Objective], variables: Collection[Variable], compute_beam_propagation: Callable[[SetOfCavitySettings], SimulationOutput], compute_residuals: Callable[[SimulationOutput], Any], cavity_settings_factory: CavitySettingsFactory, reference_simulation_output: SimulationOutput, constraints: Collection[Constraint] | None = None, compute_constraints: Callable[[SimulationOutput], ndarray] | None = None, optimisation_algorithm_kwargs: dict[str, Any] | None = None, history_kwargs: dict[str, Any] | None = None, **kwargs) None

Instantiate the object.

supports_constraints: bool
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.

abstract optimize() OptiSol

Set up optimization parameters and solve the problem.

Returns:

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

Return type:

OptiSol

abstract _generate_opti_sol(*args, **kwargs) OptiSol

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

_format_variables() Any

Adapt all Variable to this optimisation algorithm.

_format_objectives() Any

Adapt all Objective to this optimisation algorithm.

_format_constraints() Any

Adapt all Constraint to this optimisation algorithm.

_wrapper_residuals(var: ndarray) ndarray

Compute residuals from an array of variable values.

_norm_wrapper_residuals(var: ndarray) float

Compute norm of residues vector from an array of variable values.

_finalize(opti_sol: OptiSol, *complementary_info: str) None

End the optimization process.

_create_set_of_cavity_settings(var: ndarray, status: Literal['nominal', 'rephased (in progress)', 'rephased (ok)', 'failed', 'compensate (in progress)', 'compensate (ok)', 'compensate (not ok)'] = 'compensate (in progress)') SetOfCavitySettings

Transform var into generic SetOfCavitySettings.

Parameters:
  • var – An array holding the variables to try.

  • status (str, optional) – mmmh

Returns:

Object holding the settings of all the cavities.

Return type:

SetOfCavitySettings

_get_objective_values(var: ndarray) dict[str, float]

Save the full array of objective values.

_output_some_info(opti_sol: OptiSol, *complementary_info: str) None

Show the most useful data from optimization.

_abc_impl = <_abc._abc_data object at 0x7f36f755d480>
class OptimizationHistory(reference_simulation_output: SimulationOutput, objectives_names: Collection[str], get_args: tuple[str, ...] = (), get_kwargs: dict[str, Any] | None = None, folder: Path | str | None = None, save_interval: int = 100, **kwargs)

Bases: object

Keep all the settings that were tried.

_settings_filename = 'settings.csv'
_objectives_filename = 'objectives.csv'
_constraints_filename = 'constraints.csv'
__init__(reference_simulation_output: SimulationOutput, objectives_names: Collection[str], get_args: tuple[str, ...] = (), get_kwargs: dict[str, Any] | None = None, folder: Path | str | None = None, save_interval: int = 100, **kwargs) None

Instantiate the object.

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

  • get_kwargs (dict[str, Any] | None, optional) – 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 (pathlib.Path | str | None, optional) – 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, optional) – Files will be saved every save_interval iteration.

_make_public_methods_useless() None

Override some methods so that they do not do anything.

add_settings(var: ndarray) None

Add a new set of cavity settings.

_init_objective_hist(objectives_names: Collection[str], reference_simulation_output: SimulationOutput) tuple[list[str], list[None | float]]

Create the objective history, with header and reference values.

_simulation_output_to_objectives(simulation_output: SimulationOutput) list[float]

Extract and format desired values from simulation_output.

_objective_headers(objectives_names: Collection[str]) tuple[list[str], list[str]]

Get the objective headers.

add_objective_values(objectives: list, simulation_output: SimulationOutput) None

Add some objective values.

add_constraint_values(constraints: list | ndarray | None) None

Add some constraint values.

save() None

Save the three histories in their respective files.

All files will be in self.history_folder.

_rename_previous_files() None

Rename the previous history files.

_empty_histories() None

Empty the histories.

checkpoint() None

Save periodically based on the defined interval.

_save_values(filepath: Path, values: list[list[float] | ndarray | None]) None

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

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

  • values (list[list[float] | numpy.ndarray | 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.