simba.Framework_objects module

SIMBA Objects Module

Various objects and functions to handle simulation lattices, commands, and elements.

Classes:
  • runSetup: Defines simulation run settings, allowing for single runs, element scans or jitter/error studies.

  • frameworkObject: Base class for generic objects in SIMBA, including lattice elements and simulation code commands.

  • frameworkLattice: Base class for simulation lattices, consisting of a line of LAURA elements.

  • frameworkCounter: Used for counting elements of the same type in ASTRA and CSRTrack

  • frameworkGroup: Used for grouping elements together and controlling them all simultaneously.

  • element_group: Subclass of frameworkGroup for grouping elements.

# TODO is this ever used?

# TODO is this ever used?

  • chicane: Subclass of frameworkGroup for a 4-dipole bunch compressor chicane.

  • getGrids: Used for determining the appropriate number of space charge grids given a number of particles.

class chicane(name, elementObjects, type, elements, **kwargs)[source]

Bases: frameworkGroup

Class defining a 4-dipole chicane.

property angle: float

Bending angle of the chicane

Returns:

The bending angle

Return type:

float

set_angle(a)[source]

Set the chicane bending angle, including updating the inter-dipole drift lengths.

Parameters:

a (float) – The angle to be set

Return type:

None

update(**kwargs)[source]

Update the bending angle and/or dipole width and/or dipole gap of all magnets in the chicane.

Parameters:

**kwargs (Dict) – Dictionary containing parameters to be updated – must be in [“dipoleangle”, “width”, “gap”]

Return type:

None

class element_group(name, elementObjects, type, elements, **kwargs)[source]

Bases: frameworkGroup

Class defining a group of elements, which is used to group together elements to perform coordinated actions on them.

class frameworkCommand(*args, **kwargs)[source]

Bases: frameworkObject

Class defining a framework command, which is used to generate commands used in setup files for various simulation codes.

Parameters:
  • args (Any)

  • kwargs (Any)

write_Elegant()[source]

Writes the command string for ELEGANT.

Returns:

String representation of the command for ELEGANT

Return type:

str

write_Genesis()[source]

Writes the command string for Genesis. # TODO deprecated?

Returns:

String representation of the command for Genesis

Return type:

str

write_MAD8()[source]

Writes the command string for MAD8. # TODO deprecated?

Returns:

String representation of the command for MAD8

Return type:

str

class frameworkCounter(sub={})[source]

Bases: dict

Class defining a counter object, used for numbering elements of the same type in ASTRA and CSRTrack

add(typ, n=1)[source]

Add to count of elements of a given type in the lattice.

Parameters:
  • typ (str) – Element type

  • n (PositiveInt, optional) – Add more than one element at a time

Returns:

The number of elements of a given type defined so far

Return type:

int

counter(typ)[source]

Increment count of elements of a given type in the lattice.

Parameters:

typ (str) – Element type

Returns:

The updated number of elements of a given type defined so far

Return type:

int

subtract(typ)[source]

Reduce count of elements of a given type in the lattice.

Parameters:

typ (str) – Element type

Returns:

The updated number of elements of a given type defined so far

Return type:

int

value(typ)[source]

Number of elements of a given type in the lattice.

Parameters:

typ (str) – Element type

Returns:

The number of elements of a given type defined so far

Return type:

int

class frameworkGroup(name, framework, type, elements, **kwargs)[source]

Bases: object

Class defining a framework group, which is used to group together elements to perform coordinated actions on them.

property allElementObjects
property allGroupObjects
change_Parameter(p, v)[source]

Set a parameter on all elements in the group.

Parameters:
  • p (str) – The parameter to be set

  • v (Any) – The value to be set.

Return type:

None

get_Parameter(p)[source]

Get a specific parameter associated with the group, i.e. bunch compressor angle

Parameters:

p (str) – A parameter associated with the group

Returns:

The parameter, if defined.

Return type:

Any

update(**kwargs)[source]
class frameworkLattice(*args, **kwargs)[source]

Bases: BaseModel

Class defining a framework lattice object, which contains all elements and groups of elements in a simulation lattice. It also contains methods to manipulate and retrieve information about the elements and groups, as well as methods to run simulations and process results.

See Getting started with SIMBA and Loading in a Lattice File.

Parameters:
  • args (Any)

  • kwargs (Any)

allElements: List = []

List of all element names in the lattice.

allow_negative_drifts: bool = False

If True, allows negative drifts in the lattice.

property apertures: list

Property to get all aperture and collimator elements in the lattice.

Returns:

A list of aperture and collimator elements in the lattice.

Return type:

list

property cavities: list

Property to get all cavity elements in the lattice.

Returns:

A list of cavity elements in the lattice.

Return type:

list

connect_remote()[source]

Set up an SSH connection to a remote server using the parameters defined in remote_setup. These keys must include host, username, and password.

Returns:

The SSH client for the established connection.

Return type:

paramiko.SSHClient

Raises:
  • KeyError – If the remote_setup attribute of this class does not contain the required keys.

  • paramiko.AuthenticationException – If the SSH authentication fails (i.e. due to incorrect credentials).

  • TimeoutError – If the SSH connection fails, for example if the server is unreachable.

createDrifts(drift_elements=('screen', 'beam_position_monitor'))[source]

Insert drifts into a sequence of ‘elements’. This method creates drifts for elements that are not subelements and have a length greater than zero. It calculates the start and end positions of each element and creates drift elements accordingly.

Parameters:

drift_elements (tuple, optional) – A tuple of element types for which drifts should be created. Default is (“screen”, “beam_position_monitor”).

Returns:

A dictionary containing the new drift elements created for the lattice. The keys are the names of the new drift elements, and the values are the corresponding drift objects.

Return type:

dict

property csr_bins: int

Property to get or set the number of bins for CSR calculations.

property csr_enable: bool

Property to get or set the CSR enable flag.

property dipoles: list

Property to get all dipole elements in the lattice.

Returns:

A list of dipole elements in the lattice.

Return type:

list

property dipoles_and_kickers: list

Property to get all dipole and kicker elements in the lattice.

Returns:

A list of dipole and kicker elements in the lattice.

Return type:

list

elementObjects: Dict

Dictionary of element objects, where keys are element names and values are element instances.

property elements: dict

Property to get a dictionary of elements in the lattice.

Returns:

A dictionary where keys are element names and values are the corresponding element objects.

Return type:

dict

property end: str

Property to get the name of the ending element of the lattice. This method checks if the file block contains an “end_element” key or a “zstop” key. If “end_element” is present, it returns the corresponding element. If “zstop” is present, it iterates through the elementObjects to find the element with the matching end position. If no match is found, it returns the last element in the elementObjects.

Returns:

The name of final element of the lattice.

Return type:

str

property endObject: PhysicalBaseElement

Property to get the final element of the lattice. See end() for more details.

Returns:

The final element of the lattice.

Return type:

Element

executables: Executables

Executable commands for running simulations, defined in the Executables class. See Executables for more details.

file_block: Dict

File block containing input and output settings for the lattice.

files: List = []

List of all files needed to run the lattice.

findS(elem)[source]

Find the S values for a specific element in the lattice.

Parameters:

elem (str) – The name of the element to find in the lattice.

Returns:

A list of tuples, where each tuple contains the name of the element and its corresponding S value. If the element does not exist in the lattice, returns an empty list.

Return type:

list

getElement(element, param=None)[source]

Get an element or group object by its name and optionally a specific parameter. This method checks if the element exists in the allElements dictionary or in the groupObjects dictionary. If the element exists, it returns the element object or the specified parameter of the element.

Parameters:
  • element (str)

  • param (str, optional) – The parameter to retrieve from the element object. If None, returns the entire element object.

Returns:

The element object or the specified parameter of the element.

Return type:

dict | Element

getElementType(typ, param=None)[source]

Get all elements of a specific type or types from the lattice.

Parameters:
  • typ (list, tuple, or str) – The type or types of elements to retrieve. If a list or tuple is provided, it retrieves elements of all specified types.

  • param (list, tuple, or str, optional) – The specific parameter to retrieve from each element.

Returns:

A list or tuple of elements of the specified type(s), or a zip object if multiple parameters are specified. If param is provided, it returns the specified parameter for each element.

Return type:

list | tuple | zip

getElems(drifts=True, as_dict=False)[source]

Get the elements in the lattice.

Parameters:
  • drifts (bool, optional) – If True, includes drift elements in the list of elements.

  • as_dict (bool, optional) – If True, returns a dictionary with element names as keys and their corresponding element objects as values.

Returns:

A list or dictionary of elements in the lattice.

Return type:

list | dict

getInitialTwiss()[source]

Get the initial Twiss parameters from the file block This method checks if the file block contains an “input” key with a “twiss” subkey. If the “twiss” subkey exists and contains values, it retrieves the alpha, beta, and normalized emittance parameters for both horizontal and vertical planes.

Returns:

A dictionary containing the initial Twiss parameters for horizontal and vertical planes. If the parameters are not found, it returns False for each parameter.

Return type:

dict

getNames(drifts=True)[source]

Get the names of the elements in the lattice.

Parameters:

drifts (bool, optional) – If True, includes drift elements in the list of names.

Returns:

A list of names of the elements in the lattice. If drifts is True, includes drift elements; otherwise, only includes main elements.

Return type:

list

getSNames()[source]

Get the names and S values of the elements in the lattice.

Returns:

A list of tuples, where each tuple contains the name of an element and its corresponding S value.

Return type:

list

getSNamesElems()[source]

Get the names, elements, and S values of the elements in the lattice.

Returns:

A tuple containing three elements: - A list of names of the elements. - A list of element objects. - A list of S values corresponding to the elements.

Return type:

tuple

getSValues(as_dict=False, at_entrance=False, drifts=True)[source]

Get the S values for the elements in the lattice. This method calculates the cumulative length of the elements in the lattice, starting from the entrance or the first element, depending on the at_entrance parameter. It returns a list or dict of S values, which represent the positions of the elements along the lattice.

Parameters:
  • as_dict (bool, optional) – If True, returns a dictionary with element names as keys and their S values as values.

  • at_entrance (bool, optional) – If True, calculates S values starting from the entrance of the lattice. If False, calculates S values starting from the first element.

  • drifts (bool, optional) – If True, include s-values for drift elements

Returns:

A list or dictionary of S values for the elements in the lattice. If as_dict is True, returns a dictionary with element names as keys and their S values as values. If as_dict is False, returns a list of S values.

Return type:

list | dict

getZNamesElems()[source]

Get the names, elements, and Z values of the elements in the lattice.

Returns:

A tuple containing three elements: - A list of names of the elements. - A list of element objects. - A list of Z values corresponding to the elements.

Return type:

tuple

getZValues(drifts=True, as_dict=False)[source]

Get the Z values for the elements in the lattice. This method calculates the cumulative length of the elements in the lattice, starting from the entrance or the first element, depending on the at_entrance parameter. It returns a list or dict of S values, which represent the positions of the elements along the lattice.

Parameters:
  • drifts (bool, optional) – If True, includes drift elements in the calculation. If False, only considers the main elements in the lattice.

  • as_dict (bool, optional) – If True, returns a dictionary with element names as keys and their Z values as values.

Returns:

A list or dictionary of Z values for the elements in the lattice. If as_dict is True, returns a dictionary with element names as keys and their Z values as values. If as_dict is False, returns a list of Z values.

Return type:

list | dict

get_prefix()[source]

Get the prefix from the input file block.

Returns:

The prefix string used in the input file block.

Return type:

str

globalSettings: Dict = {'charge': None}

Global settings for the lattice, including charge and other parameters.

global_parameters: Dict

Global parameters for the lattice, including master subdirectory and other configuration settings.

groupObjects: Dict

Dictionary of group objects, where keys are group names and values are group instances.

groupSettings: Dict = {}

Group settings for the lattice, including group-specific parameters.

initial_twiss: Dict = {}

Initial Twiss parameters for the lattice, used for tracking and analysis.

insert_element(index, element)[source]

Insert an element at a specific index in the elements dictionary.

Parameters:
  • index (int) – The index at which to insert the element.

  • element (Element) – The element to insert into the elements dictionary.

Return type:

None

property kickers: list

Property to get all kicker elements in the lattice.

Returns:

A list of kicker elements in the lattice.

Return type:

list

property lines: list

Property to get all lines in the lattice.

Returns:

A list of lines in the lattice.

Return type:

list

longitudinal_match(settings)[source]
Return type:

None

property lsc_bins: int

Property to get or set the number of bins for LSC calculations.

property lsc_enable: bool

Property to get or set the LSC enable flag.

lsc_high_frequency_cutoff_end: float = -1

Spatial frequency at which smoothing filter is 0. See Elegant manual LSC drift

lsc_high_frequency_cutoff_start: float = -1

Spatial frequency at which smoothing filter begins. If not positive, no frequency filter smoothing is done. See Elegant manual LSC drift

lsc_low_frequency_cutoff_end: float = -1

Lowest spatial frequency at which low-frequency cutoff filter is 1. See Elegant manual LSC drift

lsc_low_frequency_cutoff_start: float = -1

Highest spatial frequency at which low-frequency cutoff filter is zero. See Elegant manual LSC drift

machine: LAURA

LAURA model of the lattice

match(params)[source]

Perform transverse matching of the lattice using Ocelot’s built-in matching algorithm.

The params dictionary should contain the following keys:

  • “variables”: A list of element names (magnets only).

  • “targets”: A dictionary where keys are element names and values are dictionaries with keys corresponding to Twiss parameters (“beta_x”, “beta_y”, “alpha_x”, “alpha_y”, “eta_x”, “eta_y”, “eta_xp”, “eta_yp”, “mux”, “muy”) and their target values.

  • “start”: (optional) The name of the starting element for matching. Defaults to the first element.

  • “end”: (optional) The name of the ending element for matching. Defaults to the last element.

The matching dictionary should have this structure within the lattice file block:

files:
  line:
    <.....>
    match:
      variables:
        Q1
        Q2
        S1
      targets:
        SCR1: {beta_x: 10.0, alpha_x: 0.0}
        SCR2: {beta_y: 12.0, alpha_y: 0.0}
        SCR3: {beta_x: {mode: greaterthan, value: 8.0}}
      start: Q1
      end: SCR3
Parameters:

params (Dict) – Dictionary containing matching variables, targets, and optional start and end elements.

Returns:

Updated elementObjects if matching is successful, None otherwise.

Return type:

Dict | None

Raises:
  • ValueError – If required keys are missing in the params dictionary or if specified elements are not found in the lattice.

  • RuntimeError – If the matching process fails.

name: str

Name of the lattice, used as a prefix for output files and commands.

objectname: str | None = ''

Name of the lattice, used as a prefix for output files and commands.

objecttype: str | None = ''

Type of the lattice, used as a prefix for output files and commands.

postProcess()[source]
preProcess()[source]

Pre-process the lattice before running the simulation. This method initializes the initial Twiss parameters by calling the getInitialTwiss method.

Return type:

None

prefix(prefix)
Parameters:

prefix (str)

Return type:

None

property quadrupoles: list

Property to get all quadrupole elements in the lattice.

Returns:

A list of quadrupole elements in the lattice.

Return type:

list

r_matrix(start=None, end=None, element_by_element=True)[source]

Compute the one-turn transfer matrix for the lattice using Xsuite. This method sets up an Xsuite Line object from the current lattice elements and computes the one-turn transfer matrix using finite differences.

Parameters:
  • start (str, optional) – The first element from which to compute the transfer matrix (first element by default).

  • end (str, optional) – The last element from which to compute the transfer matrix (last element by default).

  • element_by_element (bool, optional) – Return the element-by-element transfer matrices if True; if not return the full transfer matrix for the entire line

Returns:

Transfer matrix (or matrices) as a NumPy array.

Return type:

np.ndarray

read_input_file(prefix, particle_definition, read_file=True)[source]
remote_setup: Dict = {}

Dictionary containing parameters for running executables remotely.

run()[source]

Run the code with input ‘filename’ This method constructs the command to run the simulation using the specified executable and the name of the lattice. It redirects the output to a log file in the master subdirectory.

If remote_setup is set, then run_remote() will be called instead.

Raises:

FileNotFoundError – If the executable for the specified code is not found in the executables dictionary.

Return type:

None

runSettings: runSetup

Run settings for the lattice, including number of runs and random seed.

run_remote()[source]

Run the simulation on a remote server using SSH and SFTP, following these steps: :rtype: None

  1. Connect to the remote server using connect_remote().

  2. Create a subdirectory on the remote server with the same name as master_subdir.

3. Send the required files (simulation input file(s), initial beam distribution file, field/wakefield files).

  1. Execute the simulation and wait for completion.

  2. Retrieve all output files created since the start of the simulation back into master_subdir

sample_interval: int = 1

Sample interval for downsampling particles, in units of 2**(3*sample_interval)

property screens: list

Property to get all screen elements in the lattice.

Returns:

A list of screen elements in the lattice.

Return type:

list

property screens_and_bpms: list

Property to get all screen and BPM elements in the lattice.

Returns:

A list of screen and BPM elements in the lattice.

Return type:

list

property screens_and_markers_and_bpms: list

Property to get all screen and BPM and marker elements in the lattice.

Returns:

A list of screen and BPM and marker elements in the lattice.

Return type:

list

property section: SectionLatticeTranslator

Property to get the lattice elements as a SectionLatticeTranslator.

Returns:

LAURA SectionLatticeTranslator

Return type:

SectionLatticeTranslator

setElementType(typ, setting, values)[source]

Set a specific setting for all elements of a specific type or types in the lattice.

Parameters:
  • typ (list, tuple, or str) – The type or types of elements to set the setting for.

  • setting (str) – The setting to be updated for the elements. This can be a single setting or a list of settings.

  • values (list, tuple, or Any) – The values to set for the specified setting.

Raises:

ValueError – If the number of elements of the specified type does not match the number of values provided.

Return type:

None

set_prefix(prefix)[source]

Set the prefix for the input file block.

Parameters:

prefix (str) – The prefix string used in the input file block.

Return type:

None

settings: FrameworkSettings

Instance of FrameworkSettings

setup_xsuite_line()[source]

Set up an Xsuite Line object from the current lattice elements.

Returns:

  • An Xsuite Line object representing the current lattice.

  • An rbf.beam object containing the beam parameters.

  • A list of element names in the Xsuite Line.

Return type:

tuple (xt.Line, rbf.beam, List)

property solenoids: list

Property to get all solenoid elements in the lattice.

Returns:

A list of solenoid elements in the lattice.

Return type:

list

property start: str

Property to get the name of the starting element of the lattice. This method checks if the file block contains a “start_element” key or a “zstart” key. If “start_element” is present, it returns the corresponding element. If “zstart” is present, it iterates through the elementObjects to find the element with the matching start position. If no match is found, it returns the first element in the elementObjects.

Returns:

The name of the starting element of the lattice.

Return type:

str

property startObject: PhysicalBaseElement

Property to get the starting element of the lattice. See start() for more details.

Returns:

The starting element of the lattice.

Return type:

Element

updateRunSettings(runSettings)[source]

Update the run settings for the lattice.

Parameters:

runSettings (runSetup) – An instance of runSetup containing the new run settings.

Raises:

TypeError – If the runSettings argument is not an instance of runSetup.

Return type:

None

update_groups()[source]

Update the group objects in the lattice with their settings.

Return type:

None

property wakefields: list

Property to get all wakefield elements in the lattice.

Returns:

A list of wakefield elements in the lattice.

Return type:

list

property wakefields_and_cavity_wakefields: list

Property to get all wakefield and cavity wakefield elements in the lattice.

Returns:

A list of wakefield and cavity wakefield elements in the lattice.

Return type:

list

property wigglers: list

Property to get all wiggler elements in the lattice.

Returns:

A list of wiggler elements in the lattice.

Return type:

list

write()[source]
class frameworkObject(*args, **kwargs)[source]

Bases: BaseModel

Class defining a framework object, which is the base class for all elements in a simulation lattice. It provides methods to add properties, validate parameters, and handle various simulation-specific functionalities.

Parameters:
  • args (Any)

  • kwargs (Any)

add_default(key, value)[source]

Add a default value for a property of the object, updating objectdefaults.

Parameters:
  • key (str) – The name of the property to set a default value for.

  • value (Any) – The name of the property to set a default value for and the value to set.

Return type:

None

add_properties(**keyvalues)[source]

Add multiple properties to the object by setting attributes for each key-value pair.

Parameters:

**keyvalues (dict) – A dictionary of key-value pairs where keys are property names and values are the corresponding values to set.

Return type:

None

add_property(key, value)[source]

Add a property to the object by setting an attribute if the key is allowed.

Parameters:
  • key (str) – The name of the property to add.

  • value (Any) – The value to set for the property.

Return type:

None

allowedkeywords: Union[List, Dict] = {}

List of allowed keywords for the object, which defines what properties can be set.

change_Parameter(key, value)[source]

Change a parameter of the object by setting an attribute.

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

  • value (Any) – The new value to set for the parameter.

Return type:

None

global_parameters: Dict = {}

Global parameters to be cascaded through all objects.

objectdefaults: Dict = {}

Default values for the object’s properties, used when no specific value is provided.

property objectproperties

Returns a dictionary of the object’s properties, excluding disallowed keywords.

Returns:

The object itself, allowing for method chaining.

Return type:

frameworkObject

property parameters: list

Returns a list of all parameters (keys) of the object.

Returns:

A list of keys representing the parameters of the object.

Return type:

list

validate_objectname()

Validate the objectname to ensure it is a string.

validate_objecttype()

Validate the objecttype to ensure it is a string.

class getGrids[source]

Bases: object

Class defining the appropriate number of space charge bins given the number of particles, defined as the closest power of 8 to the cube root of the number of particles.

find_nearest(array, value)[source]

Get the nearest value in an array to the value provided; in this case the array should be a list of powers of 8.

Parameters:
  • array (np.ndarray or list) – Array of values to be checked

  • value (Value to be found in the array)

Returns:

The closest value in array to value

Return type:

int

getGridSizes(x)[source]

Calculate the 3D space charge grid size given the number of particles, minimum of 4

Parameters:

x (PositiveInt) – Number of particles

Returns:

The number of space charge grids

Return type:

int

class global_error(*args: Any, **kwargs: Any)[source]

Bases: frameworkObject

Class defining a global error element.

add_Error(type, sigma)[source]
class r56_group(name, elementObjects, type, elements, ratios, keys, **kwargs)[source]

Bases: frameworkGroup

Class defining a group of elements with a total R56.

get_Parameter(p)[source]

Get a parameter associated with the group.

Parameters:

p (str) – The parameter to be retrieved.

Returns:

The parameter.

Return type:

Any

property r56: float

Get the R56 of the group of elements

Returns:

The R56 pararmeter

Return type:

float

updateElements(element, key, value)[source]

Update one or more elements in the group.

Parameters:
  • element (str, list or tuple) – The element(s) to be updated

  • key (str) – The parameter in the element or group of elements to be changed

  • value (Any) – The value to which the parameter should be set

Return type:

None

class runSetup[source]

Bases: object

Class defining settings for simulations that include multiple runs such as error studies or parameter scans.

loadElementErrors(file)[source]

Load error definitions from a file or dictionary and assign them to the elementErrors attribute. This method can handle both a YAML file and a dictionary containing error definitions.

Parameters:

file (str or dict) –

  • str: Path to a YAML file containing error definitions.

  • dict: A dictionary containing error definitions.

Return type:

None

setElementScan(name, item, scanrange, multiplicative=False)[source]

Define a parameter scan for a single parameter of a given machine element

Parameters:
  • name (str) – Name of the machine element to be scanned.

  • item (str) – Name of the item (parameter) to be scanned within the machine element.

  • scanrange (list or tuple or np.ndarray) – A list or tuple containing two floats, representing the minimum and maximum values of the scan range.

  • multiplicative (bool, optional) – If True, the scan will be multiplicative; otherwise, it will be additive. Default is False.

Return type:

None

setNRuns(nruns)[source]

Sets the number of simulation runs to a new value.

Parameters:

nruns (int or float) – The number of runs to set. If a float is passed, it will be converted to an integer.

Raises:

TypeError – If nruns is not an integer or float.

Return type:

None

setSeedValue(seed)[source]

Sets the random number seed to a new value for all lattice objects

Parameters:

seed (int or float) – The random number seed to set. If a float is passed, it will be converted to an integer.

Raises:

TypeError – If seed is not an integer or float.

Return type:

None

class s_chicane(name, elementObjects, type, elements, **kwargs)[source]

Bases: chicane

Class defining an s-type chicane; in this case the bending ratios for set_angle() are different.