simba package

Subpackages

Submodules

simba.Framework module

SIMBA Framework Module

The main class for handling the tracking of a particle distribution through a lattice.

Settings files can be loaded in, consisting of one or more LAURA YAML files. This creates frameworkLattice objects.

These objects can be modified directly through the Framework class.

Based on the tracking code(s) provided to the framework, the particle distribution is tracked through the lattice sequentially, and output beam distributions are generated and converted to the standard OpenPMD HDF5 format.

Summary files containing Twiss parameters, and a summary of the beam files, are generated after tracking.

Classes:
  • Framework: Top-level class for loading and modifying lattice settings and tracking through them

  • frameworkDirectory: Class to load a tracking run from a directory and reading the Beam and Twiss files and making them available.

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

Bases: BaseModel

The main class for handling the tracking of a particle distribution through a lattice.

Settings files can be loaded in, consisting of one or more LAURA YAML files. This creates frameworkLattice objects, each of which contains Element objects.

These objects can be modified directly through the Framework class.

Based on the tracking code(s) provided to the framework, the particle distribution is tracked through the lattice sequentially, and output beam distributions are generated and converted to the standard OpenPMD HDF5 format.

Summary files containing Twiss parameters, and a summary of the beam files, are generated after tracking.

Parameters:
  • args (Any)

  • kwargs (Any)

add_Generator(default=None, **kwargs)[source]

Add a file generator based on a keyword dictionary. Sets generator to the frameworkGenerator.

Also sets the “generator” in latticeObjects to this generator.

Parameters:

default (str or None) – Name of generator code

Return type:

None

apply_changes(changes, verbose=False)[source]

Applies a dictionary of changes to the current lattice.

Parameters:
  • changes (dict) – Dictionary of changes to elements, keyed by element name and containing parameters and values to change

  • verbose (bool) – Flag to indicate which elements are being modified

Return type:

None

change_Lattice_Code(latticename, code, exclude=None, nowarn=False)[source]

Changes the tracking code for a given lattice.

Parameters:
  • latticename (str) – Name of the lattice line defined in the latticeObjects

  • code (str) – Simulation code to use for latticename; can be All

  • exclude (str or list or tuple, optional) – Exclude certain lines from this function

  • nowarn (bool) – If True, disable warning about resetting the execution location

Return type:

None

change_generator(generator)[source]

Changes the generator from one type to another.

Parameters:

generator (str) – The generator code to which the generator object should be changed.

Return type:

None

change_subdirectory(*args, **kwargs)[source]

Change the subdirectory and master_subdir in global_parameters to which lattice and beam files will be written.

Return type:

None

check_lattice(decimals=4)[source]

Checks that there are no positioning errors in the lattice.

Parameters:

decimals (int) – Number of decimals to check errors

Returns:

True if errors are detected

Return type:

bool

clean: bool = False

Flag to indicate whether all files in the existing directory are to be removed

clear()[source]

Clear out elementObjects, latticeObjects, commandObjects, groupObjects

Return type:

None

commandObjects: Dict = {}

Dictionary containing all frameworkCommand objects

property commands: list

Returns a list of all command object names

Returns:

List of command object names

Return type:

list

delete_output_files: bool = False

Flag to indicate whether output files are to be deleted after tracking

detect_changes(elementtype=None, elements=None)[source]

Detect lattice changes from the original loaded lattice and return a dictionary of changes.

Parameters:
  • elementtype (str or None) – Element type to check; check all if None

  • elements (list or None) – Elements to check; check all if None

Returns:

Dictionary containing changes in the lattice, with element names and changed parameters

Return type:

dict

directory: str

The directory into which simulation files will be placed

eager_mode: bool = False

Bypass lazy loading for LAURA

elementObjects: Dict = {}

Dictionary containing all Element objects

property elements: list

Returns a list of all element names from elementObjects

Returns:

List of element names

Return type:

list

fileSettings: Dict = {}

Dictionary containing all file settings

generator: frameworkGenerator | None = None

The frameworkGenerator object

generatorSettings: Dict = {}

Dictionary containing all generator settings

generator_defaults: str | None = None

File pointing to defaults for constructing the frameworkGenerator

generator_keywords: Dict = {}

Default keywords for the frameworkGenerator loaded from generator_defaults in master_lattice/Generators

getElement(element, param=None)[source]

Returns the element object or a parameter of that element

Parameters:
  • element (str) – Name of element to get

  • param (str or None) – Parameter to retrieve; if None, return the entire element

Returns:

dict or Any or – Get the param associated with element, or the entire element, or an empty dictionary if the element does not exist in the entire lattice

Return type:

class:`~laura.models.element.Element

getElementType(typ, param=None)[source]

Gets all elements of the specified type, or the parameter of each of those elements

Parameters:
  • typ (list or str or tuple) – Type or list of types to get

  • param (str or None) – Parameters to retrieve; if None, get the entire object

Returns:

Get param for all elements, or all elements, or recall this function recursively if param is a list or tuple

Return type:

dict or list or Any

getSValues()[source]

Returns a list of S values for the current lattice from latticeObjects; see getSValues().

Returns:

S values for all elements

Return type:

list

getSValuesElements()[source]

Returns a list of (name, element, s) tuples for the current machine from latticeObjects; see getSNamesElems().

Returns:

Element names, element object and its S position

Return type:

list

getZValuesElements()[source]

Returns a list of (name, element, z) tuples for the current machine from latticeObjects; see getZNamesElems().

Returns:

Element names, element object and its Z position

Return type:

list

globalSettings: Dict = {}

Dictionary containing all global settings

global_parameters: Dict = {}

Dictionary containing global parameters accessible to all classes

groupObjects: Dict = {}

Dictionary containing all frameworkGroup objects

property groups: list

Returns a list of all group names from groupObjects

Returns:

List of group names

Return type:

list

latticeObjects: Dict = {}

Dictionary containing all frameworkLattice objects

property lattices: list

Returns a list of all lattice names

Returns:

List of lattice names

Return type:

list

property lines: list

Returns a list of all lattice names

Returns:

List of lattice names

Return type:

list

loadElementErrors(file)[source]

Load element errors file; see loadElementErrors()

Parameters:

file (str) – Errors file

Return type:

None

loadParametersFile(file)[source]
loadSettings(filename=None, settings=None)[source]

Load Lattice Settings from file or dictionary. These settings contain the lattice lines and their respective settings, YAML files and global parameters.

Parameters:
  • filename (str or None) – Name of .def file containing lattice definitions

  • settings (FrameworkSettings or None) – Settings for the lattice

Return type:

None

load_Elements_File(inp)[source]

Load a YAML file or list of YAML files with element definitions. The elements entry in this file(s) are then parsed and read into elementObjects in order to build up the frameworkLattice object.

Parameters:

inp (str or list or tuple or dict) – Input file or dict containing the lattice elements

Return type:

None

load_changes_file(filename=None, apply=True, verbose=False)[source]

Loads a saved changes file and applies the settings to the current lattice. Returns a list of changes. See apply_changes().

Parameters:
  • filename (str or list or tuple or None) – Changes filename to save; if None, base it on the settings filename

  • apply (bool) – Flag to apply the changes

  • verbose (bool) – Flag to print the changes applied

Returns:

If filename is a list or tuple, call this function again If filename is None or a str, return the dictionary of changes.

Return type:

dict or list

machine: LAURA = None

LAURA model of lattice

master_lattice: str | None = None

Location of the master lattice files. If the package is installed, this will be configured automatically

modifyElement(elementName, parameter, value=None)[source]

Modifies an element parameter

Parameters:
  • elementName (str) – Name of element to modify

  • parameter (list or str or dict) – Parameter to modify

  • value (Optional[Any]) – Value to set on that element

Return type:

None

modifyElementType(elementType, parameter, value)[source]

Modifies an element or a list of elements of a given type

Parameters:
  • elementType (str) – Type of element to modify

  • parameter (str) – Parameter of that element type to modify

  • value (Any) – Value to set on that element(s)

Return type:

None

modifyElements(elementNames, parameter, value=None)[source]

Modifies parameters for multiple elements

Parameters:
  • elementNames (str or list) – Name(s) of element to modify

  • parameter (list or str or dict) – Parameter to modify

  • value (Optional[Any]) – Value to set on those elements

Return type:

None

modifyLattice(latticeName, parameter, value=None)[source]

Modify a lattice definition,

Parameters:
  • latticeName (str) – Name of lattice to modify

  • parameter (str or list or dict) – Parameter(s) to update with their values

  • value (Any) – Value to update

Return type:

None

modifyLattices(latticeNames, parameter, value=None)[source]

Modify a lattice definition for a list of lattices

Parameters:
  • latticeNames (str or list) – Name of lattice(s) to modify

  • parameter (str or list or dict) – Parameter(s) to update with their values

  • value (Any) – Value to update

Return type:

None

offsetElements(x=0, y=0, z=0)[source]

Moves all elements by the set amount in (x, y, z) space. Updates elementObjects.

Parameters:
  • x (int | float) – x offset

  • y (int | float) – y offset

  • z (int | float) – z offset

Return type:

None

original_elementObjects: Dict = {}

Dictionary containing all Element objects before changes are made

overwrite: bool | None = None

Flag to indicate whether existing files are to be overwritten #TODO deprecated?

password: str = ''

Password for remote execution

postProcess(files=None, startfile=None, endfile=None)[source]

Post-processes the tracking files and converts them to HDF5. See postProcess() and the same function in the child classes for specific codes.

Parameters:
  • files (list or None) – List of lattice names; if None, process all

  • startfile (str or None) – Starting lattice object; if None, process from the start

  • endfile (str or None) – End lattice object; if None, process to the end

Return type:

None

prepare_executables(location=None, ncpu=1)[source]
Parameters:
  • location (Optional[str])

  • ncpu (int)

progress: int | float = 0

Current progress of tracking

pushRunSettings()[source]

Updates the ‘Run Settings’ in each of the lattices

Return type:

None

read_Lattice(name, lattice)[source]

Create an instance of a <code>Lattice class; see frameworkLattice and its child classes. This instance is then added to the latticeObjects dictionary.

Parameters:
  • name (str) – The name of the lattice line

  • lattice (dict) – Dictionary containing settings for the lattice line

Return type:

None

runname: str = 'CLARA_240'

Name of the run for this setup #TODO deprecated?

saveParametersFile(file, parameters)[source]

Saves a list of parameters to a file

Parameters:
  • file (str)

  • parameters (dict | list | tuple)

Return type:

None

save_changes_file(filename=None, typ=None, elements=None, dictionary=False)[source]

Save a file, or returns a dictionary, of detected changes in the lattice from the loaded version.

Parameters:
  • filename (str or None) – Name of file containing changes; defaults to changes.yaml

  • typ (str or None) – Element types to check; if None, check all

  • elements (dict or None) – Dictionary containing elements and parameters to check; if None, check all

  • dictionary (bool) – Flag to return changes as dictionary; if False, save a YAML file

Returns:

If dictionary, return a dict; otherwise, save a file and return None

Return type:

dict or None

save_lattice(lattice=None, filename=None, directory='.')[source]

Save lattice to a file, or return a dictionary containing the lattice elements

Parameters:
  • lattice (str or None) – Name of lattice file; if None, sets to the name of the lattice

  • filename (str or None) – Name of the file to be saved; if None, sets to the name of the lattice + ‘_lattice.yaml’

  • directory (str) – Directory to which the file will be saved

Return type:

dict | None

save_settings(filename=None, directory='.', elements=None)[source]

Save Lattice Settings to a file.

Parameters:
  • filename (str or None) – Filename to which the settings will be saved; defaults to settings.def

  • directory (str) – Directory to which the settings will be saved

  • elements (dict or None) – Dictionary of Element objects to save

Return type:

None

save_summary_files(twiss=True, beams=True)[source]

Saves HDF5 summary files for the Twiss and/or Beam files using load_directory() and save_HDF5_summary_file()

Parameters:
  • twiss (bool) – If True, save Twiss_Summary.hdf5 in subdirectory

  • beams (bool) – If True, save Beam_Summary.hdf5 in subdirectory

Return type:

None

sddsindex: int = 0

Index for SDDS files

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

Define a parameter scan for a single parameter of a given machine element. See setElementScan

Parameters:
  • name (str) – Name of element to scan

  • item (str) – Parameter of that element to scan

  • scanrange (list) – List of values to set

  • multiplicative (bool) – Flag to indicate whether settings are multiplicative or additive with respect to the original value

Return type:

None

setElementType(typ, setting, values)[source]

Modifies the specified parameter of each element of a given type

Parameters:
  • typ (str) – All elements of a given type to set

  • setting (str) – Parameter in those elements to set

  • values (Any) – Values to set on those elements

Raises:

ValueError – If there is a mismatch between the length of values and the number of elements of that type

Return type:

None

setMasterLatticeLocation(master_lattice=None)[source]

Set the location of the LAURA package.

This then also sets the master_lattice in global_parameters.

Parameters:

master_lattice (str) – The full path to the LAURA master lattice folder

Return type:

None

setNRuns(nruns)[source]

Sets the number of simulation runs to a new value for all lattice objects. See setNRuns().

Parameters:

nruns (int) – Number of runs to set up

Return type:

None

setSeedValue(seed)[source]

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

See setSeedValue().

Parameters:

seed (int) – Random number seed

Return type:

None

setSimCodesLocation(simcodes=None)[source]

Set the location of the SimCodes package.

This then also sets the simcodes_location in global_parameters.

Parameters:

simcodes (str) – The full path to the SimCodes folder

Return type:

None

setSubDirectory(direc)[source]

Change the subdirectory and master_subdir in global_parameters to which lattice and beam files will be written.

If clean, then all existing files in the directory are removed.

Parameters:

direc (str) – Directory to which files will be written. If directory does not exist, create it.

Return type:

None

set_lattice_prefix(lattice, prefix)[source]

Sets the ‘prefix’ parameter for a lattice in latticeObjects, which determines where it looks for its starting beam distribution.

Parameters:
  • lattice (str) – Name of lattice

  • prefix (str) – Lattice prefix

Return type:

None

set_lattice_sample_interval(lattice, interval)[source]

Sets the ‘sample_interval’ parameter for a lattice, which determines the sampling of the distribution. See sample_interval.

Parameters:
  • lattice (str) – Name of lattice

  • interval (int) – Sampling interval in units of 2 ** (3 * interval)

Return type:

None

settings: FrameworkSettings | None = None

Settings for the lattice

settingsFilename: str | None = None

Filename containing lattice settings

setupGeneratorDefaults(generator_defaults)[source]
Parameters:

generator_defaults (str | None)

setupLAURA()[source]

Sets up the LAURA machine

Return type:

None

setup_remote_execution(lattice, code, server, ncpu=1, ngpu=1, exclude=None, username=None, password=None)[source]

Prepares the simulation of a given lattice line for remote execution on a server. This function modifies the remote_setup and executables attributes of the given lattice object, meaning that it can be run remotely using the run method of the lattice object.

The servers are defined in the hosts dictionary, each of which contain an address and the available codes.

Parameters:
  • lattice (str) – Name of the lattice line; if “All”, sets up all lattice lines in the same way.

  • code (str) – Code to be used for the remote execution. If the current lattice line is not set up for this code, then change_Lattice_Code() is called to change the code of the lattice line.

  • server (str) – Name of server on which to execute the simulation. The server must be defined in the hosts dictionary.

  • ncpu (int) – Number of CPUs to use for the remote execution. Default is 1.

  • ngpu (int) – Number of GPUs to use for the remote execution. Default is 1. Not currently implemented.

  • exclude (str | list | tuple | None (optional)) – Lattice line(s) to exclude from the remote execution setup.

  • username (str | None (optional)) – Username for SSH login to the server. Defaults to username of the Framework instance, if set.

  • password (str | None (optional)) – Password for SSH login to the server. Defaults to password of the Framework instance, if set.

Raises:
  • ValueError – If server is not found in the defined hosts.

  • ValueError – If code is not available on the specified server.

  • ValueError – If username or password is not provided and not set in the Framework instance.

Return type:

None

simcodes: str | None = None

Location of the simulation codes directory. If the package is installed, this will be configured autonatically

track(files=None, startfile=None, endfile=None, preprocess=True, write=True, track=True, postprocess=True, save_summary=True, frameworkDirec=False, check_lattice=True)[source]

Tracks the current machine, or a subset based on the ‘files’ list. The lattice is checked (check_lattice()) and saved (save_lattice()), the settings file is saved (save_settings()), and then each line in the lattice is tracked with the code specified.

Parameters:
  • files (list or None) – List of files (lattice names) to track; if None, track all

  • startfile (str or None) – Initial lattice name for tracking; if None, track all

  • endfile (str or None) – Final lattice name for tracking; if None, track all

  • preprocess (bool) – Call preProcess() before tracking each line

  • write (bool) – Write each lattice file

  • track (bool) – Track each lattice

  • postprocess (bool) – Call postProcess() after tracking each line

  • save_summary (bool) – Save beam and Twiss summary files

  • frameworkDirec (bool) – If True, return a frameworkDirectory object

  • check_lattice (bool) – Call check_lattice() before tracking

Returns:

Framework directory object if frameworkDirec is True

Return type:

frameworkDirectory or None

tracking: bool = False

Flag to indicate whether the Framework is tracking

updateGlobalParameters()[source]
username: str = ''

Username for remote execution

verbose: bool = True

Flag to indicate whether status updates should be printed during tracking

class NumpySafeDumper(stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True)[source]

Bases: SafeDumper

yaml_representers = {<class 'NoneType'>: <function SafeRepresenter.represent_none>, <class 'bool'>: <function SafeRepresenter.represent_bool>, <class 'bytes'>: <function SafeRepresenter.represent_binary>, <class 'datetime.date'>: <function SafeRepresenter.represent_date>, <class 'datetime.datetime'>: <function SafeRepresenter.represent_datetime>, <class 'dict'>: <function SafeRepresenter.represent_dict>, <class 'float'>: <function SafeRepresenter.represent_float>, <class 'int'>: <function SafeRepresenter.represent_int>, <class 'list'>: <function SafeRepresenter.represent_list>, <class 'munch.Munch'>: <function to_yaml_safe>, <class 'numpy.bool'>: <function numpy_scalar_representer>, <class 'numpy.float32'>: <function numpy_scalar_representer>, <class 'numpy.float64'>: <function numpy_scalar_representer>, <class 'numpy.generic'>: <function numpy_scalar_representer>, <class 'numpy.int32'>: <function numpy_scalar_representer>, <class 'numpy.int64'>: <function numpy_scalar_representer>, <class 'numpy.ndarray'>: <function numpy_array_representer>, <class 'set'>: <function SafeRepresenter.represent_set>, <class 'str'>: <function SafeRepresenter.represent_str>, <class 'tuple'>: <function SafeRepresenter.represent_list>, None: <function SafeRepresenter.represent_undefined>}
dict_constructor(loader, node)[source]
dict_representer(dumper, data)[source]
class frameworkDirectory(*args, **kwargs)[source]

Bases: BaseModel

Class to load a tracking run from a directory and read the Beam and Twiss files and make them available

beams: bool | beamGroup | None = False

Flag to indicate whether to load beam files

changes: str = 'changes.yaml'

Lattice changes filename

directory: str | None = None

Directory from which to load beam and Twiss files

element(element, field=None)[source]

Get an element definition from the framework object.

Parameters:
  • element (str) – Element to retrieve

  • field (str | None) – Field of that element to retrieve

Returns:

Get the field of element, or the entire Element if not field

Return type:

Any or Element

framework: Framework | None = None

Framework instance

general_plot(*args, **kwargs)[source]

Return a general_plot object; see general_plot().

getScreen(screen)[source]

Get a beam object for the given screen; see getScreen()

Parameters:

screen (str) – Name of screen

Returns:

The beam object from screen

Return type:

beam

Raises:

ValueError – If beams is not a beamGroup object

getScreenNames()[source]

Get beam objects from all screens

Returns:

The beam objects from the screen keyed by name

Return type:

Dict

Raises:

ValueError – If beams is not a beamGroup object

plot(*args, **kwargs)[source]

Return a plot object; see plot().

rest_mass: float | None = None

Particle rest mass

save_summary_files(twiss=True, beams=True)[source]

Save summary files in framework directory; see save_summary_files().

Parameters:
  • twiss (bool) – If True, save Twiss_Summary.hdf5 in directory

  • beams (bool) – If True, save Beam_Summary.hdf5 in directory

settings: str = 'settings.def'

Framework settings filename

twiss: bool | twiss = True

Flag to indicate whether to load Twiss files

verbose: bool = False

Flag to print status updates

load_directory(directory='.', twiss=True, beams=False, **kwargs)[source]

Load a directory from a SIMBA tracking run and return a frameworkDirectory object

Parameters:
  • directory (str)

  • twiss (bool)

  • beams (bool)

Return type:

frameworkDirectory

numpy_array_representer(dumper, data)[source]
numpy_scalar_representer(dumper, data)[source]

simba.FrameworkHelperFunctions module

checkValue(self, d, default=None)[source]
chop(expr, delta=1e-08)[source]

Performs a chop on small numbers

chunks(li, n)[source]

Yield successive n-sized chunks from l.

clean_directory(folder)[source]
compare_multiple_models(model_pairs)[source]

Given a list of (old_model, new_model) pairs, return a nested dictionary of all changes.

Parameters:

model_pairs (list[tuple[Element, Element]])

Return type:

dict

convert_numpy_types(v)[source]
createOptionalString(paramaterdict, parameter, n=None)[source]

Formats ASTRA strings for optional ASTRA parameters

deepdiff_to_nested(diff)[source]

Convert a DeepDiff result (values_changed only) into a nested dictionary structure.

Parameters:

diff (dict)

Return type:

dict

dot(a, b)[source]
Return type:

float

expand_substitution(self, param, subs={}, elements={}, absolute=False)[source]
findSetting(setting, value, dictionary={})[source]

Looks for a ‘value’ in ‘setting’ in dict ‘dictionary’

findSettingValue(setting, dictionary={})[source]

Finds the value of a setting in dict ‘dictionary’

flatten_changes_dict(d, parent_key='')[source]

Flattens nested dict keys into dotted paths. Returns a list of (dotted_path, value).

formatOptionalString(parameter, string, n=None)[source]

String for optional parameters

getParameter(dicts, param, default=0)[source]

Returns the values of ‘param’ in dict ‘dict’ if it exists, else returns default value. dict can be a list, the most important last.

isevaluable(self, s)[source]
lineReplaceFunction(line, findString, replaceString, i=None)[source]

Searches for, and replaces, the string ‘findString’ with ‘replaceString’ in ‘line’

list_add(list1, list2)[source]
normalize(obj)[source]
path_function(a, b)[source]
pydantic_basemodel_dump_computed_fields(self, *args, **kwargs)[source]
readFile(fname)[source]
replaceString(lines=[], findString=None, replaceString=None)[source]

Iterates over lines and replaces ‘findString’ with ‘replaceString’ which can be a list

rotationMatrix(theta)[source]

Simple 3D rotation matrix

saveFile(filename, lines=[], mode='w')[source]
set_deep_attr(obj, dotted_path, value)[source]

Set nested attribute using a dotted path like ‘a.b.c.d’.

sortByPositionFunction(element)[source]

Sort function for element positions

simba.Framework_Settings module

class FrameworkSettings(filename=None, new=False)[source]

Bases: Munch

add_element(name, type, length, position_start, position_end, **kwargs)[source]
add_element_file(filename)[source]
add_file(name, code, start, end, input={}, charge={})[source]
add_group(name, type, elements)[source]
copy() a shallow copy of D[source]
isthistheissue = {'element_list', 'elements', 'files', 'generator', 'global', 'groups', 'layout', 'section'}
loadSettings(filename)[source]
dict_constructor(loader, node)[source]
dict_representer(dumper, data)[source]

simba.Framework_lattices module

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.

Module contents