Simulation Parameters

The two classes Simulation Parameters and Dictionary are a key component of the interface between AIDO and user-defined programs. There are two ingredients:

  1. SimulationParameter: Represents a single parameter with all its features and settings. It has the following properties

    • Name: For unique identification

    • Values: Both a starting value (set by the user) and the current value (as adjusted by the optimizer)

    • Units (optional)

    • Optimizable (optional): Whether this parameter is constant or not

    • Min / Max values (optional but recommended): Constrains the possible values that this parameter can adopt. For example thicknesses cannot be smaller than zero.

    • Discrete: Some parameters are categorical and cannot be easily represented by a floating point number. For these cases, the possible values have to be listed in an Iterable from which to choose the current value.

    • Cost (optional): Use for computing additional penalties

  2. SimulationParameterDictionary: The container that stores multiple SimulationParameters in a dict-style object

    • Can be indexed as a list or a dict

    • Converted to list, dict and pandas.DataFrame

    • Written and read from and to json files. This feature is important to pass it to non-python programs, e.g. Geant4.

    • Additional metadata about a given training step.

class aido.simulation_helpers.SimulationParameter(name: str, starting_value: Any, current_value: Any | None = None, units: str | None = None, optimizable: bool = True, min_value: float | None = None, max_value: float | None = None, sigma: float | None = None, sigma_mode: Literal['flat', 'scale'] | None = None, discrete_values: Iterable | None = None, probabilities: Iterable[float] | None = None, cost: float | Iterable | None = None)[source]

Bases: object

Base class for all parameters used in the simulation.

A simulation parameter represents a single variable that can be optimized during the simulation process.

__init__(name: str, starting_value: Any, current_value: Any | None = None, units: str | None = None, optimizable: bool = True, min_value: float | None = None, max_value: float | None = None, sigma: float | None = None, sigma_mode: Literal['flat', 'scale'] | None = None, discrete_values: Iterable | None = None, probabilities: Iterable[float] | None = None, cost: float | Iterable | None = None)[source]

Create a new Simulation Parameter.

Parameters:
  • name (str) – The name of the parameter.

  • starting_value (Any) – The starting value of the parameter.

  • current_value (Any, optional) – The current value of the parameter. Defaults to None, in which case it set to the starting value instead.

  • units (str, optional) – The units of the parameter. Defaults to None.

  • optimizable (bool, optional) – Whether the parameter is optimizable. Defaults to True.

  • min_value (float, optional) – The minimum value of the parameter. Defaults to None.

  • max_value (float, optional) – The maximum value of the parameter. Defaults to None.

  • sigma (float, optional) – The standard deviation of the parameter. Defaults to 0.5 for continuous (float) parameters and remains None otherwise.

  • sigma_mode ({“flat”, “scale”}, optional) – Whether to set the sampling distribution standard deviation to sigma (“flat”) or scale sigma with the current value (“scale”). Defaults to “flat”. If “sigma” is not defined, this parameter has no action. Can be changed class-wide using the cls.set_sigma_mode() classmethod.

  • discrete_values (Iterable, optional) – The allowed discrete values of the parameter. Defaults to None.

  • probabilities (Iterable[float], optional) – A list of the same length as ‘discrete_values’ used to sample from ‘discrete_values’. If set to None, an equally-distributed array is created. Only for discrete parameters. Defaults to None.

  • cost (float or Iterable, optional) – A float that quantifies the cost per unit of this Parameter. Defaults to None. For discrete parameters, this parameter must be an Iterable (e.g. list) of the same length as ‘discrete_values’.

property current_value: Any

Get the value stored in this instance

Example

>>> sim_param = SimulationParameter("foo", 1.0)
>>> sim_param.current_value
1.0
classmethod from_dict(attribute_dict: Dict) Self[source]

Create from dictionary

Parameters:

attribute_dict (Dict) – A dict whose keys match the names of the parameters found in SimulationParameter.__init__().

Returns:

SimulationParameter – Instance of this class

property optimizable: bool

Whether this parameter is constant or optimizable.

Tip

Non-optimizable parameters can be used to store constants, for example the number of events to simulate.

property probabilities: List[float]

List of normalized probabilities that convey the confidence of the Optimizer in the individual choice.

Note

Used for generating new values by sampling from this distribution. See SimulationParameterDictionary.generate_new().

property sigma: float | None

The standard deviation of the Gaussian distribution used to generate new values for this parameter.

Note

The starting value must be provided by the user (or left to be the default from the AIDOConfig). Afterwards, the optimization loop might adjust the sigma to explore some regions quicker.

to_dict() Dict[source]

Convert to dictionary

Returns:

Dict – A dict with all the attributes of this class

Note

Protected attributes are written to file as public attributes.

property weighted_cost: None | float

Helper property that returns the expected cost for a given parameter.

Returns:

  • None if SimulationParameter.cost was not defined

  • float otherwise (without any unit)

Note

This weighted cost is either current_value * cost if the parameter is continuous, or the scalar product of SimulationParameter.probabilities and SimulationParameter.cost.

Tip

This value can be used to calculate penalty costs to apply to the Optimizer loss function.

class aido.simulation_helpers.SimulationParameterDictionary(parameter_list: List[SimulationParameter] = [])[source]

Bases: object

Container for storing SimulationParameters

__getitem__(key: str | int) SimulationParameter | Dict[source]

Access a SimulationParameter either by name (dict-style) or by index (list-style)

__init__(parameter_list: List[SimulationParameter] = [])[source]

Initialize with a list of parameters ‘SimulationParameter’

Parameters:

parameter_list – List[SimulationParameter]

property covariance: ndarray

Get the current covariance matrix. If no covariance was set, it defaults to the ‘sigma_array’ squared (covariance matrix with no correlations).

classmethod from_dict(parameter_dict: Dict) SimulationParameterDictionary[source]

Creates a SimulationParameterDictionary instance from a dictionary.

Parameters:

parameter_dict (Dict) – A dictionary containing serialized SimulationParameters and metadata. Must contain a ‘metadata’ key with simulation metadata.

Returns:

SimulationParameterDictionary

A new instance initialized with the parameters and metadata

from the dictionary.

Note

The input dictionary must contain serialized SimulationParameter data, not SimulationParameter instances.

classmethod from_json(file_path: str) SimulationParameterDictionary[source]

Creates a SimulationParameterDictionary instance from a JSON file.

Parameters:

file_path (str) – Path to the JSON file containing serialized parameters and metadata.

Returns:

SimulationParameterDictionary

A new instance initialized with the parameters and metadata

from the JSON file.

generate_new(rng_seed: int | None = None, discrete_index: int | None = None, scaling_factor: float = 1.0) SimulationParameterDictionary[source]

Generates a new instance with newly sampled parameter values.

Generates new values bounded by specified minimum and maximum values for float parameters. For discrete parameters, the new value is randomly chosen from the list of allowed values.

Parameters:
  • rng_seed (int | None, optional) – Seed for the random number generator. If provided, ensures reproducible results. If None, a random seed is generated. Defaults to None.

  • discrete_index (int | None, optional) – Force specific index for discrete parameters. - If > len(parameter.discrete_values), falls back to random sampling. - If valid index, uses parameter.discrete_values[discrete_index]. Defaults to None.

  • scaling_factor (float, optional) – Scale factor applied to covariance matrix when generating new values. Defaults to 1.0.

Returns:

SimulationParameterDictionary – A new instance with sampled parameter values.

get_current_values(format: Literal['list', 'dict'] = 'dict', include_non_optimizables: bool = False, display_discrete: Literal['default', 'as_probabilities', 'as_one_hot'] = 'default', types: Literal['all', 'continuous', 'discrete'] = 'all') List | Dict[source]

Obtain all the current values of each parameter in a list or dict format.

Parameters:
  • format (str) –

    • list: Returns a list of the current values

    • dict: Returns a dict of name, current value pairs

  • include_non_optimizables (bool) – Whether to include constant parameters in the returned object

  • display_discrete (str) – How to display the categorical parameters - default: Current value of the discrete parameter. Compatible with format=”list” - as_probabilities: Injects a dict of with pairs of the sort

    {<name>_<value>: <probability>} Where name is the name of parameter, value is the corresponding value from the list of all possible values listed in SimulationParameter.probabilities. Not compatible with format=”list”.

    • as_one_hot: Same as as_probabilities but replaces the probabilities with a one-hot-encoding scheme

      where the likeliest categorical value is one and all other entries are zero. Not compatible with format=”list”.

  • types (str) – Which types of parameters to include

Example

>>> sim_param = SimulationParameterDictionary([
... SimulationParameter("foo", 1, discrete_parameters=[0, 1, 2, 3])],
... SimulationParameter("bar", 10.0)
... )
>>> sim_param.get_current_values(display_discrete="default", format="list")
[1, 10.0]
>>> sim_param.get_current_values(display_discrete="default", format="dict")
{"foo": 1, "bar": 10.0}
>>> sim_param.get_current_values(display_discrete="as_probabilities", format="dict")
{"foo_0": 0.25, "foo_1": 0.25, "foo_2": 0.25, "foo_3": 0.25, "bar": 10.0}
get_probabilities() dict[str, List[float]][source]

Returns a dict whose values are the probabilities of each discrete parameter

Note: More information about the usage of probabilities for one-hot encoded parameters is listed in the docstring of SimulationParameter.

property metadata: Dict[str, Any]

Gets the metadata dictionary containing simulation state information.

Returns:

Dict

Dictionary containing
  • iteration (int): Current iteration number

  • creation_time (str): Timestamp of creation

  • rng_seed (int | None): Random number generator seed

  • description (str): Optional description

  • covariance (List[List[float]]): Covariance matrix as nested list

property sigma_array: ndarray

Diagonal matrix with the standard deviation of each continuous parameter

to_df(df_length: int | None = 1, include_non_optimizables: bool = False, display_discrete: Literal['default', 'as_probabilities', 'as_one_hot'] = 'default', types: Literal['all', 'continuous', 'discrete'] = 'all', **kwargs) DataFrame[source]

Convert parameter dictionary to a pd.DataFrame

Parameters:
  • df_length (int) – The length of the DataFrame to be created. Default is None.

  • include_non_optimizables (bool) – Whether to include non-optimizable parameters in the df. Defaults to False.

  • display_discrete (Literal) –

    • ‘default’: Simply write the current value of the Parameter (default)

    • ‘as_probabilities’: Write the probability of each category (from the list of available

      discrete parameter).

    • ‘as_one_hot’: Write the current value as a one-hot encoded array. All categories are set

      to zero except for the ‘current_value’ which is set to one. Ref. https://pytorch.org/docs/stable/generated/torch.nn.functional.one_hot.html

  • types (str) – Choose what kind of parameters will be added to the pd.DataFrame. All includes all parameters, continuous only those with no ‘discrete_values’ and discrete only those with ‘discrete_values’.

  • kwargs – Additional keyword arguments to be passed to the pd.DataFrame constructor.

Returns:

pd.DataFrame – A pandas DataFrame containing the current parameter values.

to_dict(serialized: bool = True) Dict[str, SimulationParameter | Any][source]

Convert the parameter list to a dictionary.

Parameters:

serialized (bool, default=True) – If True, returns a Dict of Dicts by serializing each SimulationParameter too. If False, returns a Dict of SimulationParameters, which is used by this class

to allow dictionary-style access to the individual parameters.

Returns:

Dict

A dictionary where the keys are parameter names and the values are either

serialized dictionaries or SimulationParameter objects.

to_json(file_path: str)[source]

Write the parameter list to a .json file

TODO Check for the existence of the file path or otherwise set as default to ../

update_current_values(current_values_parameter_dict: dict)[source]

Updates the current values of parameters in the dictionary.

Parameters:

current_values_parameter_dict (dict) – Dictionary with parameter names as keys and their new values.

Returns:

SimulationParameterDictionary

Raises:

AssertionError – If a key in current_values_parameter_dict doesn’t exist in the parameter dictionary.

update_probabilities(probabilities_dict: dict[str, List | ndarray])[source]

Updates the probabilities of discrete parameters.

Parameters:

probabilities_dict (dict[str, List | np.ndarray]) – Dictionary containing parameter names as keys and their new probability distributions as values.

Returns:

SimulationParameterDictionary

Raises:

AssertionError – If a key in probabilities_dict doesn’t exist in the parameter dictionary.