piglot package

Subpackages

Submodules

piglot.objective module

Module containing optimisation objective primites

class Composition[source]

Bases: ABC

Abstract class for defining composition functionals with gradients

composition(inner: ndarray, params: ndarray) ndarray[source]

Abstract method for computing the outer function of the composition

Parameters

innernp.ndarray

Return value from the inner function

paramsnp.ndarray

Parameters for the given responses

Returns

np.ndarray

Composition result

abstract composition_torch(inner: Tensor, params: Tensor) Tensor[source]

Abstract method for computing the outer function of the composition with gradients

Parameters

innertorch.Tensor

Return value from the inner function

paramstorch.Tensor

Parameters for the given responses

Returns

torch.Tensor

Composition result

class DynamicPlotter[source]

Bases: ABC

Abstract class for dynamically-updating plots

abstract update() None[source]

Update the plot with the most recent data

class GenericObjective(parameters: ParameterSet, stochastic: bool = False, composition: Composition | None = None, scalarisation: Scalarisation | None = None, num_objectives: int = 1, multi_objective: bool = False, output_dir: str | None = None)[source]

Bases: Objective

Class for generic objectives.

get_history() Dict[str, Dict[str, Any]][source]

Get the objective history.

Returns

Dict[str, Dict[str, Any]]

Dictionary of objective history.

plot_best() List[Figure][source]

Plot the current best case.

Returns

List[Figure]

List of figures with the plot.

prepare() None[source]

Prepare output directories for the optimsation.

class IndividualObjective(maximise: bool = False, weight: float = 1.0, bounds: Tuple[float, float] | None = None)[source]

Bases: ABC

Base class for individual objectives for generic optimisation problems.

class Objective[source]

Bases: ABC

Abstract class for optimisation objectives

get_history() Dict[str, Dict[str, Any]][source]

Get the objective history

Returns

Dict[str, Dict[str, Any]]

Dictionary of objective history

plot_best() List[Figure][source]

Plot the current best case

Returns

List[Figure]

List of figures with the plot

plot_case(case_hash: str, options: Dict[str, Any] | None = None) List[Figure][source]

Plot a given function call given the parameter hash

Parameters

case_hashstr, optional

Parameter hash for the case to plot

optionsDict[str, Any], optional

Options to pass to the plotting function, by default None

Returns

List[Figure]

List of figures with the plot

plot_current() List[DynamicPlotter][source]

Plot the currently running function call

Returns

List[DynamicPlotter]

List of instances of a updatable plots

abstract prepare() None[source]

Generic method to prepare output files before optimising the problem

abstract classmethod read(config: Dict[str, Any], parameters: ParameterSet, output_dir: str) T[source]

Read the objective from a configuration dictionary.

Parameters

configDict[str, Any]

Terms from the configuration dictionary.

parametersParameterSet

Set of parameters for this problem.

output_dirstr

Path to the output directory.

Returns

Objective

Objective function to optimise.

class ObjectiveResult(params: ndarray, values: ndarray, obj_values: ndarray, covariances: ndarray | None = None, obj_variances: ndarray | None = None, scalar_value: float | None = None, scalar_variance: float | None = None)[source]

Bases: object

Container for objective results.

covariances: ndarray | None = None
obj_values: ndarray
obj_variances: ndarray | None = None
params: ndarray
scalar_value: float | None = None
scalar_variance: float | None = None
values: ndarray
class Scalarisation(objectives: List[IndividualObjective])[source]

Bases: ABC

Base class for scalarisations.

scalarise(values: ndarray, variances: ndarray | None = None) Tuple[float, float | None][source]

Scalarise a set of objectives.

Parameters

valuesnp.ndarray

Mean objective values.

variancesOptional[np.ndarray]

Optional variances of the objectives.

Returns

Tuple[float, Optional[float]]

Mean and variance of the scalarised objective.

abstract scalarise_torch(values: Tensor, variances: Tensor | None = None) Tuple[Tensor, Tensor | None][source]

Scalarise a set of objectives with gradients.

Parameters

valuestorch.Tensor

Mean objective values.

variancesOptional[torch.Tensor]

Optional variances of the objectives.

Returns

Tuple[torch.Tensor, Optional[torch.Tensor]]

Mean and variance of the scalarised objective.

piglot.optimiser module

Main optimiser module

exception InvalidOptimiserException[source]

Bases: Exception

Exception signaling invalid combination of optimiser and objective function.

class Optimiser(name: str, objective: Objective)[source]

Bases: ABC

Interface for implementing different optimization algorithms.

Methods

_init_optimiser(n_iter, parameters, pbar, loss, stop_criteria):

constructs the attributes for the optimiser.

optimise(loss, n_iter, parameters, stop_criteria = StoppingCriteria()):

initiates optimiser.

_optimise(self, func, n_dim, n_iter, bound, init_shot):

performs the optimization.

_progress_check(self, i_iter, curr_value, curr_solution):

evaluates the optimiser progress.

optimise(n_iter: int, parameters: ~piglot.parameter.ParameterSet, output_dir: str, stop_criteria: ~piglot.optimiser.StoppingCriteria = <piglot.optimiser.StoppingCriteria object>, verbose: bool = True) Tuple[float, ndarray][source]

Optimiser for the outside world.

Parameters

objectiveObjective

Objective function to optimise.

n_iterint

Maximum number of iterations.

parametersParameterSet

Set of parameters to optimise.

output_dirstr

Whether to write output to the output directory, by default None.

stop_criteriaStoppingCriteria

List of stopping criteria, by default none attributed.

verbosebool

Whether to output progress status, by default True.

Returns

float

Best observed objective value.

np.ndarray

Observed optimum of the objective.

class ScalarOptimiser(name: str, objective: Objective)[source]

Bases: Optimiser

Base class for scalar optimisers.

class StoppingCriteria(conv_tol: float | None = None, max_iters_no_improv: int | None = None, max_func_calls: int | None = None, max_timeout: float | None = None)[source]

Bases: object

Implements different stopping criteria.

Attributes

conv_tolfloat

Stop the optimiser if the loss becomes small than this value.

max_iters_no_improvint

Stop the optimiser if the loss does not improve after this number of iterations in a row.

max_func_callsint

Stop the optimiser after this number of function calls.

max_timeoutfloat

Stop the optimiser after this elapsed time (in seconds).

Methods

check_criteria(loss_value, iters_no_improv, func_calls):

check the status of the stopping criteria.

check_criteria(loss_value: float, iters_no_improv: int, func_calls: int, elapsed: float) bool[source]

Check the status of the stopping criteria.

Parameters

loss_valuefloat

Current loss value.

iters_no_improvint

Current number of iterations without improvement.

func_callsint

Current number of function calls.

elapsedfloat

Elapsed time in seconds.

Returns

bool

Whether any of the criteria are satisfied.

static read(config: Dict[str, Any]) StoppingCriteria[source]

Read the stopping criteria from the configuration dictionary.

Parameters

configDict[str, Any]

Configuration dictionary.

Returns

StoppingCriteria

Stopping criteria.

boundary_check(arg, bounds)[source]

Check if the values are within the bounds and correct them if not.

Parameters

argarray

Values to check.

boundsarray

Lower and upper bounds.

Returns

array

Corrected values.

missing_method(name, package)[source]

Class generator for missing packages.

Parameters

namestr

Name of the missing method.

packagestr

Name of the package to install.

piglot.parameter module

Optimisation parameter module.

class DualParameterSet[source]

Bases: ParameterSet

Container class for a set of parameters with distinct internal and output parameters.

This type should be used if the internal optimised parameters and the output parameters are not equal. Output names are used for output name resolution. All output fields must have a mapping function to internal parameters.

add_output(name: str, mapping: Callable[[Dict[str, float]], float]) None[source]

Adds an output parameter to the set.

Parameters

namestr

Parameter name

mappingCallable[[Dict[str, float]], float]

Mapping function from internal parameters to this output parameter’s value. Internal parameters are passed as arguments for this function as an expanded dict.

Raises

RuntimeError

If an output parameter is repeated.

clone_output(name: str) None[source]

Creates an output parameter identical to a given internal parameter.

Parameters

namestr

Name of the internal parameter to clone.

to_dict(values: ndarray) Dict[str, float][source]

Build a dict with name-value pairs for output parameters given a list of values.

Parameters

valuesnp.ndarray

Values to pack. Their order is used for parameter resolution.

Returns

Dict[str, float]

Name-value pair for each output parameter.

to_output(values: ndarray) ndarray[source]

Compute the output parameters’ values given an array of internal inputs.

Parameters

valuesnp.ndarray

Values to pack. Their order is used for parameter resolution.

Returns

np.ndarray

Values of the output parameters.

class OutputParameter(name: str, mapping: Callable[[Dict[str, float]], float])[source]

Bases: object

Base class for output parameters.

class Parameter(name: str, inital_value: float, lbound: float, ubound: float)[source]

Bases: object

Base parameter class.

clip(value: float) float[source]

Clamp a value to the [lbound,ubound] interval.

Parameters

valuefloat

Value to clip.

Returns

float

Clamped value.

class ParameterSet[source]

Bases: object

Container class for a set of parameters.

This type should be used if the internal optimised parameters and the output parameters are equal. By default, the internal names are used for output name resolution.

add(name: str, inital_value: float, lbound: float, ubound: float) None[source]

Add a parameter to this set.

Parameters

namestr

Parameter name.

inital_valuefloat

Initial value for the parameter.

lboundfloat

Lower bound of the parameter.

uboundfloat

Upper bound of the parameter.

Raises

RuntimeError

If a repeated parameter is given.

clip(values: ndarray) ndarray[source]

Clamp the parameter set to the [lbound,ubound] interval.

Parameters

valuesnp.ndarray

Values to clip. Their order is used for parameter resolution.

Returns

np.ndarray

Clamped parameters.

static hash(values) str[source]

Build the hash for the current parameter values.

Parameters

valuesarray

Parameters to hash.

Returns

str

Hex digest of the hash.

to_dict(values: ndarray) Dict[str, float][source]

Build a dict with name-value pairs given a list of values.

Parameters

valuesnp.ndarray

Values to pack. Their order is used for parameter resolution.

Returns

Dict[str, float]

Name-value pair for each parameter.

read_parameters(config: Dict[str, Any]) ParameterSet[source]

Parse the parameters from the configuration dictionary.

Parameters

configDict[str, Any]

Configuration dictionary.

Returns

ParameterSet

Parameter set for this problem.

Module contents

Main piglot module.