at.lattice.lattice_object#

Lattice object

The methods implemented in this module are internal to the ‘lattice’ package. This is necessary to ensure that the ‘lattice’ package is independent of other AT packages.

Other Lattice methods are implemented in other AT packages and are available as soon as the package is imported. The ‘tracking’ and ‘physics’ packages are automatically imported.

As an example, see the at.physics.orbit module

Functions

type_filter(params, elems)

Run through all elements and check element validity.

params_filter(params, elem_filter, *args)

Run through all elements, looking for energy and periodicity.

lattice_filter(params, lattice)

Copy lattice parameters and run through all lattice elements

elem_generator(params, elems)

Run through all elements without any check

no_filter(params, elems)

Run through all elements without any check

Classes

Lattice()

Lattice object.

Filter

alias of Callable[[...], Iterable[Element]]

Filter#

alias of Callable[[…], Iterable[Element]]

class Lattice(elements, **params)[source]#
class Lattice(filter, [filter, ..., ]iterator=iter, **params)

Bases: list

Lattice object.

An AT lattice is a sequence of AT elements. In addition to list methods, Lattice supports extended indexing as a numpy ndarray.

Parameters:
  • elements – iterable of Element objects

  • iter – function called as iter(params, *args). It must return an iterable of Element objects for building the lattice. It must also fill the params dictionary providing the Lattice attributes.

  • params – dictionary of lattice parameters. A custom iterator may add, remove or modify parameters. Finally, the remaining parameters will be set as Lattice attributes.

Keyword Arguments:
  • name='' – Name of the lattice

  • energy – Energy of the lattice

  • periodicity=1 – Number of periods

  • particle='relativistic' – circulating particle. May be ‘relativistic’, ‘electron’, ‘positron’, ‘proton’ or a Particle object

  • iterator=None – custom iterator (see below)

  • * – all other keywords will be set as attributes of the Lattice object

  • beam_current – Total current in the beam, used for collective effects

An iterator it is called as it(params, *args) where args and params are the arguments of the Lattice constructor. It must yield the AT Elements for building the lattice. It must also fill its params dictionary argument, which will be used to set the Lattice attributes. An iterator can be:

  • a “generator” which yields elements from scratch. Examples: a list, or a file iterator,

  • a “filter” which runs through an input iterator, processes each element, possibly adds parameters to the params dictionary and yields the processed elements.

Note

To reduce the inter-package dependencies, some methods of the lattice object are defined in other AT packages, in the module where the underlying function is implemented.

Note

It is possible to define a filling pattern for the beam using the function ring.set_fillingpattern(). The default configuration (no arguments) is for single bunch and is the one loaded at lattice initialization. See function help for details. Changing Lattice.harmonic_number will reset the filling pattern to its default configuration. The beam current can be changed with Lattice.beam_current=current The filling pattern and beam current are used by collective effects passmethods.

Examples

Chaining iterators (taken from load_mat):

Lattice(ringparam_filter, matfile_generator, filename
        iterator=params_filter, **params)
matfile_generator(params, filename)

opens filename and generates AT elements for each cell of the Matlab cell array representing the lattice,

ringparam_filter(params, matfile_generator, *args)

runs through matfile_generator(params, *args), looks for RingParam elements, fills params with their information and discards them,

params_filter(params, ringparam_filter, *args)

runs through ringparam_filter(params, *args), looks for energy and periodicity if not yet defined.

append(elem, copy_elements=False)[source]#

This method overwrites the inherited method list.append(), its behavior is changed, it accepts only AT lattice elements Element as input argument.

Equivalent syntaxes:

>>> ring.append(elem)
>>> ring += [elem]
Parameters:
  • elem (Element) – AT element to be appended to the lattice

  • copy_elements (bool) – Default True. If True a deep copy of elem is used

attrs_filter(params, elem_filter, *args)[source]#

Filter function which duplicates the lattice attributes

Parameters:
  • params (dict) – Dictionary of Lattice attributes

  • elem_filter (Callable[[...], Iterable[Element]]) – Element filter

  • *args – Arguments provided to elem_filter

avlinopt(dp=0.0, refpts=None, **kwargs)#

Linear analysis of a lattice with average values

avlinopt() returns average beta, mu, dispersion over the lattice elements.

avlinopt() returns average beta, mu, dispersion over the lattice elements. avlinopt() acts on a single cell (periodicity is not taken into account).

Parameters:
  • ring (Lattice) – Lattice description.

  • dp (float) – Momentum deviation.

  • refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) –

    Elements at which data is returned. It can be:

    1. an integer in the range [-len(ring), len(ring)-1] selecting the element according to python indexing rules. As a special case, len(ring) is allowed and refers to the end of the last element,

    2. an ordered list of such integers without duplicates,

    3. a numpy array of booleans of maximum length len(ring)+1, where selected elements are True.

Keyword Arguments:
  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation of RF frequency. Defaults to None

  • orbit (Orbit) – Avoids looking for the closed orbit if it is already known ((6,) array)

  • get_chrom (bool) – Compute chromaticities. Needs computing the tune at 2 different momentum deviations around the central one.

  • get_w (bool) – Computes chromatic amplitude functions (W) [4]. Needs to compute the optics at 2 different momentum deviations around the central one.

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

  • twiss_in

    Initial conditions for transfer line optics. Record array as output by linopt6(), or dictionary. Keys:

    R or alpha, beta

    mandatory (2,) arrays

    closed_orbit

    Optional (6,) array, default 0

    dispersion

    Optional (6,) array, default 0

    If present, the attribute R will be used, otherwise the attributes alpha and beta will be used. All other attributes are ignored.

Returns:
  • elemdata – Linear optics at the points referred to by refpts, if refpts is None an empty lindata structure is returned.

  • avebeta – Average beta functions [\(\hat{\beta_x},\hat{\beta_y}\)] at refpts

  • avemu – Average phase advances [\(\hat{\mu_x},\hat{\mu_y}\)] at refpts

  • avedisp – Average dispersion [\(\hat{\eta_x}, \hat{\eta'_x}, \hat{\eta_y}, \hat{\eta'_y}\)] at refpts

  • avespos – Average s position at refpts

  • tune – [\(\nu_1,\nu_2\)], linear tunes for the two normal modes of linear motion [1]

  • chrom – [\(\xi_1,\xi_2\)], chromaticities

bool_refpts(refpts, endpoint=True, regex=False)#

Returns a bool array of element indices, selecting ring elements.

Parameters:
Returns:

bool_refs (BoolRefpts) – A bool numpy array used for indexing Elements in a lattice.

Examples

>>> refpts = get_bool_index(ring, at.Quadrupole)

Returns a numpy array of booleans where all Quadrupole are True

>>> refpts = get_bool_index(ring, "Q[FD]*")

Returns a numpy array of booleans where all elements whose FamName matches “Q[FD]*” are True

>>> refpts = get_bool_index(ring, at.checkattr('K', 0.0))

Returns a numpy array of booleans where all elements whose K attribute is 0.0 are True

>>> refpts = get_bool_index(ring, None)

Returns a numpy array of len(ring)+1 False values

concatenate(*lattices, copy_elements=False, copy=False)[source]#

Concatenate several Iterable[Element] with the lattice

Equivalent syntaxes:

>>> newring = ring.concatenate(r1, r2, r3, copy=True)
>>> newring = ring + r1 + r2 + r3
>>> ring.concatenate(r1, copy=False)
>>> ring += r1
Parameters:
  • lattices (Iterable[Element]) – Iterables[Element] to be concatenanted to the Lattice, several lattices are allowed (see example)

  • copy_elements (bool) – Default False. If True deepcopies of the elements of lattices are used

  • copy (bool) – Default False. If True the lattice is modified in place. Oterwise a new Lattice object is returned

Returns:

lattice (Lattice) – concatenated Lattice, if copy==True the new lattice object is returned otherwise None

copy()[source]#

Returns a shallow copy of the lattice

deepcopy()[source]#

Returns a deep copy of the lattice

develop(copy_elements=True)[source]#

Develop a periodical lattice by repeating its elements self.periodicity times

Parameters:

copy_elements (bool) – If True, deep copies of the elements are used for the repetition. Otherwise, the original elements are repeated in the developed lattice.

Returns:

newlattice – The developed lattice

disable_6d(elem_class[, elem_class]... , copy=False)[source]#
disable_6d(cavity_pass='auto'[, dipole_pass='auto']..., copy=False) None

Turn longitudinal motion off. By default, remove all longitudinal motion.

Modify the lattice in-place or creates a new lattice, depending on the copy keyword argument.

Syntax using positional arguments:

Parameters:

elem_class

LongtMotion subclass. Longitudinal motion is turned off for elements which are instances of any given elem_class.

In adition to single element classes, a few grouping classes are available:

The default PassMethod conversion is used, as with the 'auto' keyword value.

No keyword except copy is allowed in this syntax.

Syntax using keyword arguments:

Keyword Arguments:
  • all_pass – PassMethod overloading the default values for all elements (None or ‘auto’)

  • cavity_pass='auto' – PassMethod set on cavities

  • dipole_pass='auto' – PassMethod set on dipoles

  • quadrupole_pass=auto – PassMethod set on quadrupoles

  • wiggler_pass='auto' – PassMethod set on wigglers

  • sextupole_pass='auto' – PassMethod set on sextupoles

  • octupole_pass='auto' – PassMethod set on octupoles

  • multipole_pass='auto' – PassMethod set on higher order multipoles

  • collective_pass='auto' – PassMethod set on collective effect elements (WakeElement,…)

  • diffusion_pass='auto' – PassMethod set on QuantumDiffusion

  • copy=False

    If False, the modification is done in-place, If True, return a shallow copy of the lattice. Only the radiating elements are copied with PassMethod modified.

    Caution

    a shallow copy means that all non-modified elements are shared with the original lattice. Any further modification will affect both lattices.

For PassMethod names, the convention is:

  • None: no change

  • ‘auto’: Use the default conversion (replace *RadPass by *Pass)

  • anything else: set as the new PassMethod

Examples

>>> ring.disable_6d()

Modify ring in-place, turn OFF everything affecting the longitudinal momentum.

>>> ring.disable_6d(at.RFCavity)

Turn cavities OFF (nothing else modified).

>>> ring.disable_6d(all_pass=None, cavity_pass='auto')

Same as the previous example, but using the keyword syntax.

>>> newring = ring.disable_6d(cavity_pass=None, copy=True)

Return a new Lattice (shallow copy of ring) with everything turned OFF except RF cavities.

>>> newring = ring.disable_6d(all_pass=None,
... sextupole_pass='DriftPass', copy=True)

Return a new Lattice (shallow copy of ring) with sextupoles turned into Drifts (turned off) and everything else unchangedd.

See also

enable_6d(), is_6d.

enable_6d(elem_class[, elem_class]..., copy=False)[source]#
enable_6d(cavity_pass='auto'[, dipole_pass='auto']..., copy=False) None

Turn longitudinal motion on. By default, turn on radiation in dipoles and quadrupoles, turn on RF cavities, activates collective effects and other elements acting on momentum.

Modify the lattice in-place or creates a new lattice, depending on the copy keyword argument.

Syntax using positional arguments:

Parameters:

elem_class

LongtMotion subclass. Longitudinal motion is turned on for elements which are instances of any given elem_class.

In adition to single element classes, a few grouping classes are available:

The default PassMethod conversion is used, as with the 'auto' keyword value..

No keyword except copy is allowed in this syntax.

Syntax using keyword arguments:

Keyword Arguments:
  • all_pass – PassMethod overloading the default values for all elements (None or ‘auto’)

  • cavity_pass='auto' – PassMethod set on cavities

  • dipole_pass='auto' – PassMethod set on dipoles

  • quadrupole_pass='auto' – PassMethod set on quadrupoles

  • wiggler_pass='auto' – PassMethod set on wigglers

  • sextupole_pass=None – PassMethod set on sextupoles

  • octupole_pass=None – PassMethod set on octupoles

  • multipole_pass=None – PassMethod set on higher order multipoles

  • collective_pass='auto' – PassMethod set on collective effect elements (WakeElement,…)

  • diffusion_pass='auto' – PassMethod set on QuantumDiffusion

  • copy=False

    If False, the modification is done in-place, If True, return a shallow copy of the lattice. Only the radiating elements are copied with PassMethod modified.

    Caution

    a shallow copy means that all non-modified elements are shared with the original lattice. Any further modification will affect both lattices.

For PassMethod names, the convention is:

  • None: No change

  • ‘auto’: Use the default conversion (replace *Pass by *RadPass)

  • anything else: set as the new PassMethod

Examples

>>> ring.enable_6d()

Modify ring in-place, turn cavities ON, turn synchrotron radiation ON in Dipoles and Quadrupoles, turn collective effects ON.

>>> ring.enable_6d(at.RFCavity, at.Radiative)

Modify ring in-place, turn cavities ON, turn synchrotron radiation ON in dipoles and quadupoles.

>>> newring = ring.enable_6d(at.Collective, copy=True)

Returns a new lattice with collective effects turned ON and nothing else changed

>>> newring = ring.enable_6d(all_pass=None, collective_pass='auto',
... copy=True)

Same as the previous example, using the keyword syntax.

See also

disable_6d(), is_6d.

envelope_parameters(params=None, orbit=None, keep_lattice=False)#

Compute ring parameters from ohmi_envelope

Parameters:
  • ring (Lattice) – Lattice description.

  • params (RingParameters | None) – RingParameters object to be updated. Default: create a new one

  • orbit (ndarray | None) – Avoids looking for the closed orbit if it is already known ((6,) array)

  • keep_lattice (bool) – Assume no lattice change since the previous tracking.

Returns:

paramsRingParameters object.

params is a RingParameters object with the following attributes:

tunes6

(3,) fractional (H, V, Long.) tunes (6D motion)

emittances

(3,) Mode emittances

J

(3,) Damping partition numbers

Tau

(3,) Damping times [s]

sigma_e

Energy spread

sigma_l

Bunch length [m]

voltage

Total accelerating voltage [V]

phi_s

Synchrotron phase [rad]

f_s

Synchrotron frequency [Hz]

extend(elems, copy_elements=False)[source]#

This method adds all the elements of elems to the end of the lattice. The behavior is the same as for a list

Equivalent syntaxes:

>>> ring.extend(elems)
>>> ring += elems
Parameters:
  • elems (Iterable[Element]) – Sequence of AT elements to be appended to the lattice

  • copy_elements (bool) – Default True. If True deep copies of each element of elems are used

find_m44(dp=None, refpts=None, dct=None, df=None, orbit=None, keep_lattice=False, **kwargs)#

One turn 4x4 transfer matrix

find_m44() finds the 4x4 transfer matrix of an accelerator lattice by differentiation of trajectories near the closed orbit.

Important

find_m44() assumes constant momentum deviation. The PassMethod used for any element SHOULD NOT:

  1. change the longitudinal momentum dP (cavities , magnets with radiation, …)

  2. have any time dependence (localized impedance, fast kickers, …)

Unless an input orbit is introduced, find_m44() assumes that the lattice is a ring and first finds the closed orbit.

Parameters:
  • ring (Lattice) – Lattice description (radiation must be OFF)

  • dp (float | None) – Momentum deviation.

  • refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – Observation points

  • dct (float | None) – Path lengthening.

  • df (float | None) – Deviation of RF frequency.

  • orbit (ndarray | None) – Avoids looking for initial the closed orbit if it is already known ((6,) array).

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Default: False

Keyword Arguments:
  • full (bool) – If True, matrices are full 1-turn matrices at the entrance of each element indexed by refpts. If False (Default), matrices are between the entrance of the first element and the entrance of the selected element

  • XYStep (float) – Step size. Default: DConstant.XYStep

Returns:
  • m44 – full one-turn matrix at the entrance of the first element

  • ms – 4x4 transfer matrices between the entrance of the first element and each element indexed by refpts: (Nrefs, 4, 4) array

find_m66(refpts=None, orbit=None, keep_lattice=False, **kwargs)#

One-turn 6x6 transfer matrix

find_m66() finds the 6x6 transfer matrix of an accelerator lattice by differentiation of trajectories near the closed orbit.

find_m66() uses find_orbit6() to search for the closed orbit in 6-D. In order for this to work the ring MUST have a Cavity element

Parameters:
Keyword Arguments:
Returns:
  • m66 – full one-turn matrix at the entrance of the first element

  • ms – 6x6 transfer matrices between the entrance of the first element and each element indexed by refpts: (Nrefs, 6, 6) array

find_orbit(refpts=None, **kwargs)#

Gets the closed orbit in the general case

Depending on the lattice, find_orbit() will:

Parameters:
Keyword Arguments:
  • orbit (Orbit) – Avoids looking for initial the closed orbit if it is already known. find_orbit() propagates it to the specified refpts.

  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation from the nominal RF frequency. Defaults to None

  • guess (Orbit) – (6,) initial value for the closed orbit. It may help convergence. Default: (0, 0, 0, 0, 0, 0)

  • convergence (float) – Convergence criterion. Default: DConstant.OrbConvergence

  • max_iterations (int) – Maximum number of iterations. Default: DConstant.OrbMaxIter

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

For other keywords, refer to the underlying methods

Returns:
  • orbit0 – (6,) closed orbit vector at the entrance of the 1-st element (x,px,y,py,dp,0)

  • orbit – (Nrefs, 6) closed orbit vector at each location specified in refpts

find_orbit4(dp=None, refpts=None, *, dct=None, df=None, orbit=None, keep_lattice=False, **kwargs)#

Gets the 4D closed orbit for a given dp

Finds the closed orbit in the 4-d transverse phase space by numerically solving for a fixed point of the one turn map M calculated with internal_lpass().

\[\begin{split}\begin{pmatrix}x \\ p_x \\ y \\ p_y \\ dp \\ c\tau_2\end{pmatrix} =\mathbf{M} \cdot \begin{pmatrix}x \\ p_x \\ y \\ p_y \\ dp \\ c\tau_1\end{pmatrix}\end{split}\]

under the CONSTANT MOMENTUM constraint dp and with NO constraint on the 6-th coordinate \(c\tau\)

Important

find_orbit4() imposes a constraint on dp and relaxes the constraint on the revolution frequency. A physical storage ring does exactly the opposite: the momentum deviation of a particle on the closed orbit settles at the value such that the revolution is synchronous with the RF cavity: \(f_{RF} = h*f_{rev}\)

To impose this artificial constraint in find_orbit4(), the PassMethod used for any element SHOULD NOT:

  1. Change the longitudinal momentum dp (cavities , magnets with radiation)

  2. Have any time dependence (localized impedance, fast kickers etc)

Parameters:
  • ring (Lattice) – Lattice description (is_6d must be False)

  • dp (float | None) – Momentum deviation. Defaults to 0

  • refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – Observation points. See “Selecting elements in a lattice

  • dct (float | None) – Path lengthening. If specified, dp is ignored and the off-momentum is deduced from the path lengthening.

  • df (float | None) – Deviation from the nominal RF frequency. If specified, dp is ignored and the off-momentum is deduced from the frequency deviation.

  • orbit (ndarray | None) – Avoids looking for initial the closed orbit if it is already known ((6,) array). find_orbit4() propagates it to the specified refpts.

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Default: False

Keyword Arguments:
Returns:
  • orbit0 – (6,) closed orbit vector at the entrance of the 1-st element (x,px,y,py,dp,0)

  • orbit – (Nrefs, 6) closed orbit vector at each location specified in refpts

find_orbit6(refpts=None, *, orbit=None, keep_lattice=False, **kwargs)#

Gets the closed orbit in the full 6-D phase space

Finds the closed orbit in the full 6-D phase space by numerically solving for a fixed point of the one turn map M calculated with internal_lpass()

\[\begin{split}\begin{pmatrix}x \\ p_x \\ y \\ p_y \\ dp \\ c\tau_2\end{pmatrix} =\mathbf{M} \cdot \begin{pmatrix}x \\ p_x \\ y \\ p_y \\ dp \\ c\tau_1\end{pmatrix}\end{split}\]

with constraint \(c\tau_2 - c\tau_1 = c.h (1/f_{RF} - 1/f_{RF_0})\)

Important

find_orbit6() is a realistic simulation:

  1. The requency in the RF cavities \(f_{RF}\) (may be different from \(f_{RF_0}\)) imposes the synchronous condition \(c\tau_2 - c\tau_1 = c.h (1/f_{RF} - 1/f_{RF_0})\),

  2. The algorithm numerically calculates the 6-by-6 Jacobian matrix J6. In order for (J-E) matrix to be non-singular it is NECESSARY to use a realistic PassMethod for cavities with non-zero momentum kick (such as RFCavityPass).

  3. find_orbit6() can find orbits with radiation. In order for the solution to exist the cavity must supply an adequate energy compensation. In the simplest case of a single cavity, it must have Voltage set so that \(V > E_{loss}\), the energy loss per turn

  4. There is a family of solutions that correspond to different RF buckets They differ in the 6-th coordinate by \(c*Nb/f_{RF}\), Nb = 0:h-1

  5. The value of the 6-th coordinate found at the cavity gives the equilibrium RF phase. If there is no radiation it is 0.

  6. dp, dct and df arguments are applied with respect to the NOMINAL on-momentum frequency. They overwrite exisiting frequency offsets

Parameters:
Keyword Arguments:
Returns:
  • orbit0 – (6,) closed orbit vector at the entrance of the 1-st element (x,px,y,py,dp,0)

  • orbit – (Nrefs, 6) closed orbit vector at each location specified in refpts

find_sync_orbit(dct=None, refpts=None, *, dp=None, df=None, orbit=None, keep_lattice=False, **kwargs)#

Gets the 4D closed orbit for a given dct

Finds the closed orbit, synchronous with the RF cavity (first 5 components of the phase space vector) by numerically solving for a fixed point of the one turn map M calculated with internal_lpass()

\[\begin{split}\begin{pmatrix}x \\ p_x \\ y \\ p_y \\ dp \\ c\tau_1+ dc\tau\end{pmatrix} =\mathbf{M} \cdot \begin{pmatrix}x \\ p_x \\ y \\ p_y \\ dp \\ c\tau_1\end{pmatrix}\end{split}\]

under the constraint \(dc\tau = c\tau_2 - c\tau_1 = c/f_{rev} - c/f_{rev_0}\), where \(f_{rev_0} = f_{RF_0}/h\) is the design revolution frequency and \(f_{rev} = (f_{RF_0} + df_{RF})/h\) is the imposed revolution frequency.

Important

find_sync_orbit() imposes a constraint \(c\tau_2 - c\tau_1\) and \(dp_2 = dp_1\) but no constraint on the value of \(dp_2\) or \(dp_1\). The algorithm assumes time-independent fixed-momentum ring to reduce the dimensionality of the problem.

To impose this artificial constraint in find_sync_orbit(), the PassMethod used for any element SHOULD NOT:

  1. Change the longitudinal momentum dp (cavities , magnets with radiation)

  2. Have any time dependence (localized impedance, fast kickers etc)

Parameters:
Keyword Arguments:
Returns:
  • orbit0 – (6,) closed orbit vector at the entrance of the 1-st element (x,px,y,py,dp,0)

  • orbit – (Nrefs, 6) closed orbit vector at each location specified in refpts

get_acceptance(planes, npoints, amplitudes, nturns=1024, refpts=None, dp=None, offset=None, bounds=None, grid_mode=GridMode.RADIAL, use_mp=False, verbose=True, divider=2, shift_zero=1e-06, start_method=None)#

Computes the acceptance at repfts observation points

Parameters:
  • ring (Lattice) – Lattice definition

  • planes – max. dimension 2, Plane(s) to scan for the acceptance. Allowed values are: 'x', 'xp', 'y', 'yp', 'dp', 'ct'

  • npoints – (len(planes),) array: number of points in each dimension

  • amplitudes

    (len(planes),) array: set the search range:

  • nturns (int | None) – Number of turns for the tracking

  • refpts (Refpts | None) – Observation points. Default: start of the machine

  • dp (float | None) – static momentum offset

  • offset (Sequence[float]) – initial orbit. Default: closed orbit

  • bounds

    defines the tracked range: range=bounds*amplitude. It can be used to select quadrants. For example, default values are:

  • grid_mode (GridMode | None) –

    defines the evaluation grid:

  • use_mp (bool | None) – Use python multiprocessing (patpass(), default use lattice_pass()).

  • verbose (bool | None) – Print out some information

  • divider (int | None) – Value of the divider used in GridMode.RECURSIVE boundary search

  • shift_zero (float | None) – Epsilon offset applied on all 6 coordinates

  • start_method (str | None) – Python multiprocessing start method. The default None uses the python default that is considered safe. Available parameters: 'fork', 'spawn', 'forkserver'. The default for linux is 'fork', the default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation or to solve runtime errors, however it is considered unsafe.

Returns:
  • boundary – (2,n) array: 2D acceptance

  • survived – (2,n) array: Coordinates of surviving particles

  • tracked – (2,n) array: Coordinates of tracked particles

In case of multiple refpts, return values are lists of arrays, with one array per ref. point.

Examples

>>> bf, sf, gf = ring.get_acceptance(planes, npoints, amplitudes)
>>> plt.plot(*gf, ".")
>>> plt.plot(*sf, ".")
>>> plt.plot(*bf)
>>> plt.show()

Note

  • When``use_mp=True`` all the available CPUs will be used. This behavior can be changed by setting at.DConstant.patpass_poolsize to the desired value

  • When multiple refpts are provided particles are first projected to the beginning of the ring with tracking. Then, all particles are tracked up to nturns. This allows to do most of the work in a single function call and allows for full parallelization.

get_beam_current()[source]#
get_bool_index(refpts, endpoint=True, regex=False)#

Returns a bool array of element indices, selecting ring elements.

Parameters:
Returns:

bool_refs (BoolRefpts) – A bool numpy array used for indexing Elements in a lattice.

Examples

>>> refpts = get_bool_index(ring, at.Quadrupole)

Returns a numpy array of booleans where all Quadrupole are True

>>> refpts = get_bool_index(ring, "Q[FD]*")

Returns a numpy array of booleans where all elements whose FamName matches “Q[FD]*” are True

>>> refpts = get_bool_index(ring, at.checkattr('K', 0.0))

Returns a numpy array of booleans where all elements whose K attribute is 0.0 are True

>>> refpts = get_bool_index(ring, None)

Returns a numpy array of len(ring)+1 False values

get_bunch_length_espread(zn=None, bunch_curr=None, espread=None)#

Haissinski equation solver

Solves the Haissinski formula and returns the bunch length and energy spread for given bunch current and \(Z/n\). If both zn and bunch_curr are None, zero current case, otherwise both are needed for the calculation

Parameters:

ring – ring use for tracking

Keyword Arguments:
  • zn=None\(Z/n\) for the full ring

  • bunch_curr=None – Bunch current

  • espread=None – Energy spread, if None use lattice parameter

Returns:

Bunch length, energy spread

get_cells(ring, filtfunc) BoolRefpts#
get_cells(ring, element_type) BoolRefpts
get_cells(ring, attrname) BoolRefpts
get_cells(ring, attrname, attrvalue) BoolRefpts

Returns a bool array of element indices, selecting ring elements.

Deprecated: get_cells(ring, refpts) is ring.bool_refpts(refpts) except for str arguments: get_cells(ring, attrname [, attrvalue]) is ring.bool_refpts(checkattr(strkey [, attrvalue]))

Parameters:
  • ring (Sequence[Element]) – Lattice description

  • filtfunc (ElementFilter) – Filter function. Selects Elements satisfying the filter function

  • element_type (Type[Element]) – Element type

  • attrname (str) – Attribute name

  • attrvalue (Any) – Attribute value. If absent, select the presence of an attrname attribute. If present, select Elements with attrname == attrvalue.

  • regex – Use regular expression for refpts string matching; Default: False (Unix shell-style wildcards)

Returns:

bool_refs (BoolRefpts) – numpy Array of bool with length len(ring)+1

Examples

>>> refpts = get_cells(ring, 'Frequency')

Returns a numpy array of booleans where all elements having a Frequency attribute are True

>>> refpts = get_cells(ring, 'K', 0.0)

Returns a numpy array of booleans where all elements having a K attribute equal to 0.0 are True

get_chrom(*, method='linopt', dp=None, dct=None, df=None, cavpts=None, **kwargs)#

Computes the chromaticities using several available methods

get_tune() may use several methods depending on a method keyword.

Parameters:
  • ring (Lattice) – Lattice description.

  • method (str) –

    'linopt' returns the tunes from the linopt6() function,

    'fft' tracks a single particle and computes the tunes with fft(),

    'interp_fft' tracks a single particle and computes the tunes with interpolated FFT.

  • dp (float) – Momentum deviation.

  • dct (float) – Path lengthening.

  • df (float) – Deviation of RF frequency.

  • cavpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – If None, look for ring.cavpts, or otherwise take all cavities.

Keyword Arguments:

DPStep (float) – Momentum step for differentiation Default: DConstant.DPStep

for the 'fft' and 'interp_fft' methods only:

Keyword Arguments:
  • nturns (int) – Number of turns. Default: 512

  • amplitude (float) – Amplitude of oscillation. Default: 1.E-6

  • remove_dc (bool) – Remove the mean of oscillation data. Default: True

  • num_harmonics (int) – Number of harmonic components to compute (before mask applied, default: 20)

  • fmin (float) – Lower tune bound. Default: 0

  • fmax (float) – Upper tune bound. Default: 1

  • hann (bool) – Turn on Hanning window. Default: False, Work only for 'fft'

Returns:

chromaticities (ndarray) – array([\(\xi_x,\xi_y\)])

get_elements(refpts, regex=False)#

Returns a list of elements selected by key.

Deprecated: get_elements(ring, refpts) is ring[refpts]

Parameters:
Returns:

elem_list (list) – list of Elements matching key

get_energy_loss(method=ELossMethod.INTEGRAL)#

Computes the energy loss per turn

Parameters:
  • ring (Lattice) – Lattice description

  • method (ELossMethod | None) – Method for energy loss computation. See ELossMethod.

Returns:

eloss (float) – Energy loss per turn [eV]

get_geometry(refpts=RefptsCode.All, start_coordinates=(0, 0, 0), centered=False, regex=False)#

Compute the 2D ring geometry in cartesian coordinates

Parameters:
Returns:
  • geomdata – recarray containing, x, y, angle.

  • radius – machine radius at the beginning of the lattice.

    Attention

    This radius is different from the radius usually defined as \(C/2\pi\)

Example

>>> geomdata, radius = get_geometry(ring)
get_horizontal_acceptance(resolution, amplitude, *args, **kwargs)#

Computes the 1D horizontal acceptance at refpts observation points

See get_acceptance()

Parameters:
Keyword Arguments:
  • nturns – Number of turns for the tracking

  • refpts – Observation points. Default: start of the machine

  • dp – static momentum offset

  • offset – initial orbit. Default: closed orbit

  • grid_mode

    defines the evaluation grid:

  • use_mp – Use python multiprocessing (patpass(), default use lattice_pass()). In case multiprocessing is not enabled, grid_mode is forced to GridMode.RECURSIVE (most efficient in single core)

  • verbose – Print out some information

  • divider – Value of the divider used in GridMode.RECURSIVE boundary search

  • shift_zero – Epsilon offset applied on all 6 coordinates

  • start_method – Python multiprocessing start method. The default None uses the python default that is considered safe. Available parameters: 'fork', 'spawn', 'forkserver'. The default for linux is 'fork', the default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation or to solve runtime errors, however it is considered unsafe.

Returns:
  • boundary – (len(refpts),2) array: 1D acceptance

  • survived – (n,) array: Coordinates of surviving particles

  • tracked – (n,) array: Coordinates of tracked particles

In case of multiple tracked and survived are lists of arrays, with one array per ref. point.

Note

  • When``use_mp=True`` all the available CPUs will be used. This behavior can be changed by setting at.DConstant.patpass_poolsize to the desired value

  • When multiple refpts are provided particles are first projected to the beginning of the ring with tracking. Then, all particles are tracked up to nturns. This allows to do most of the work in a single function call and allows for full parallelization.

get_lifetime(emity, bunch_curr, emitx=None, sigs=None, sigp=None, zn=None, momap=None, refpts=None, offset=None, **kwargs)#

Touschek lifetime calculation

Computes the touschek lifetime using the Piwinski formula

Parameters:
  • ring – ring use for tracking

  • emity – verticla emittance

  • bunch_curr – bunch current

Keyword Arguments:
  • emitx=None – horizontal emittance

  • sigs=None – rms bunch length

  • sigp=None – energy spread

  • zn=None – full ring \(Z/n\)

  • momap=None – momentum aperture, has to be consistent with refpts if provided the momentum aperture is not calculated

  • refpts=Nonerefpts where the momentum aperture is calculated, the default is to compute it for all elements in the ring, len(refpts)>2 is required

  • resolution – minimum distance between 2 grid points, default=1.0e-3

  • amplitude – max. amplitude for RADIAL and CARTESIAN or initial step in RECURSIVE default = 0.1

  • nturns=1024 – Number of turns for the tracking

  • dp=None – static momentum offset

  • offset – initial orbit. Default: closed orbit

  • grid_modeat.GridMode.CARTESIAN/RADIAL track full vector (default). at.GridMode.RECURSIVE: recursive search

  • use_mp=False – Use python multiprocessing (patpass, default use lattice_pass). In case multi-processing is not enabled GridMode is forced to RECURSIVE (most efficient in single core)

  • verbose=False – Print out some inform

  • epsrel (epsabs,) – integral absolute and relative tolerances

Returns:
  • tl – touschek lifetime, double expressed in seconds

  • ma – momentum aperture (len(refpts), 2) array

  • refpts – refpts used for momentum aperture calculation (len(refpts), ) array

Note

  • When``use_mp=True`` all the available CPUs will be used. This behavior can be changed by setting at.DConstant.patpass_poolsize to the desired value

  • When multiple refpts are provided particles are first projected to the beginning of the ring with tracking. Then, all particles are tracked up to nturns. This allows to do most of the work in a single function call and allows for full parallelization.

get_mcf(dp=0.0, keep_lattice=False, fit_order=1, n_step=2, **kwargs)#

Compute the momentum compaction factor \(\alpha\)

Parameters:
  • ring (Lattice) – Lattice description (ring.is_6d must be False)

  • dp (float | None) – Momentum deviation. Defaults to None

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Default: False

  • fit_order (int | None) – Maximum momentum compaction factor order to be fitted. Default to 1, corresponding to the first-order momentum compaction factor.

  • n_step (int | None) – Number of different calculated momentum deviations to be fitted with a polynomial. Default to 2.

Keyword Arguments:

DPStep (Optional[float]) – Momentum step size. Default: DConstant.DPStep

Returns:

mcf (float/array) – Momentum compaction factor \(\alpha\) up to the order fit_order. Returns a float if fit_order=1 otherwise returns an array.

get_momentum_acceptance(resolution, amplitude, *args, **kwargs)#

Computes the 1D momentum acceptance at refpts observation points

See get_acceptance()

Parameters:
Keyword Arguments:
  • nturns – Number of turns for the tracking

  • refpts – Observation points. Default: start of the machine

  • dp – static momentum offset

  • offset – initial orbit. Default: closed orbit

  • grid_mode

    defines the evaluation grid:

  • use_mp – Use python multiprocessing (patpass(), default use lattice_pass()). In case multiprocessing is not enabled, grid_mode is forced to GridMode.RECURSIVE (most efficient in single core)

  • verbose – Print out some information

  • divider – Value of the divider used in GridMode.RECURSIVE boundary search

  • shift_zero – Epsilon offset applied on all 6 coordinates

  • start_method – Python multiprocessing start method. The default None uses the python default that is considered safe. Available parameters: 'fork', 'spawn', 'forkserver'. The default for linux is 'fork', the default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation or to solve runtime errors, however it is considered unsafe.

Returns:
  • boundary – (len(refpts),2) array: 1D acceptance

  • survived – (n,) array: Coordinates of surviving particles

  • tracked – (n,) array: Coordinates of tracked particles

In case of multiple tracked and survived are lists of arrays, with one array per ref. point.

Note

  • When``use_mp=True`` all the available CPUs will be used. This behavior can be changed by setting at.DConstant.patpass_poolsize to the desired value

  • When multiple refpts are provided particles are first projected to the beginning of the ring with tracking. Then, all particles are tracked up to nturns. This allows to do most of the work in a single function call and allows for full parallelization.

get_optics(refpts=None, dp=None, method=<function linopt6>, **kwargs)#

Linear analysis of a fully coupled lattice

get_optics() computes the linear optics parameters on a single cell (periodicity is not taken into account).

Parameters:
  • ring (Lattice) – Lattice description.

  • refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) –

    Elements at which data is returned. It can be:

    1. an integer in the range [-len(ring), len(ring)-1] selecting the element according to python indexing rules. As a special case, len(ring) is allowed and refers to the end of the last element,

    2. an ordered list of such integers without duplicates,

    3. a numpy array of booleans of maximum length len(ring)+1, where selected elements are True.

  • dp (float | None) – Momentum deviation.

  • method (Callable) –

    Method for linear optics:

    linopt2: no longitudinal motion, no H/V coupling,

    linopt4: no longitudinal motion, Sagan/Rubin 4D-analysis of coupled motion,

    linopt6 (default): with or without longitudinal motion, normal mode analysis

Keyword Arguments:
  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation of RF frequency. Defaults to None

  • orbit (Orbit) – Avoids looking for the closed orbit if it is already known ((6,) array)

  • get_chrom (bool) – Compute chromaticities. Needs computing the tune at 2 different momentum deviations around the central one.

  • get_w (bool) – Computes chromatic amplitude functions (W) [4]. Needs to compute the optics at 2 different momentum deviations around the central one.

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

  • twiss_in

    Initial conditions for transfer line optics. Record array as output by linopt6(), or dictionary. Keys:

    R or alpha, beta

    mandatory (2,) arrays

    closed_orbit

    Optional (6,) array, default 0

    dispersion

    Optional (6,) array, default 0

    If present, the attribute R will be used, otherwise the attributes alpha and beta will be used. All other attributes are ignored.

Returns:
  • elemdata0 – Linear optics data at the entrance of the ring

  • ringdata – Lattice properties

  • elemdata – Linear optics at the points refered to by refpts, if refpts is None an empty lindata structure is returned.

elemdata is a record array, Its fields depend on the selected method. See linopt6, linopt4, linopt2

ringdata is a record array with fields:

tune

Fractional tunes

chromaticity

Chromaticities, only computed if get_chrom is True

damping_time

Damping times [s] (only if radiation is ON)

Warning

The format of output record arrays depends on the selected method. See linopt2(), linopt4(), linopt6().

get_radiation_integrals(dp=None, twiss=None, **kwargs)#

Computes the 5 radiation integrals for uncoupled lattices.

Parameters:
  • ring – Lattice description

  • twiss – Linear optics at all points (from linopt6()). If None, it will be computed.

Keyword Arguments:
  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation of RF frequency. Defaults to

  • method (Callable) –

    Method for linear optics:

    linopt2: no longitudinal motion, no H/V coupling,

    linopt6 (default): with or without longitudinal motion, normal mode analysis

Returns:
  • i1 (float) – Radiation integrals - \(I_1 \quad [m]\)

  • i2 (float) – \(I_2 \quad [m^{-1}]\)

  • i3 (float) – \(I_3 \quad [m^{-2}]\)

  • i4 (float) – \(I_4 \quad [m^{-1}]\)

  • i5 (float) – \(I_5 \quad [m^{-1}]\)

get_refpts(refpts, regex=False)#

Return a uint32 array of element indices selecting ring elements.

Deprecated: get_elements(ring, refpts) is ring.uint32_refpts(refpts)

Parameters:
Returns:

uint32_refs (Uint32Refs) – uint32 numpy array as long as the number of refpts

get_revolution_frequency(dp=None, dct=None, df=None)#

Compute the revolution frequency of the full ring [Hz]

Parameters:
  • ring (Lattice) – Lattice description

  • dp (float | None) – Momentum deviation. Defaults to None

  • dct (float | None) – Path lengthening. Defaults to None

  • df (float | None) – Deviation of RF frequency. Defaults to None

Returns:

frev – Revolution frequency [Hz]

get_rf_frequency(**kwargs)#

Return the RF frequency

Parameters:

ring (Lattice) – Lattice description

Keyword Arguments:
  • cavpts=None – Cavity location. If None, look for ring.cavpts, otherwise take all cavities.

  • array=False

    If False, return the frequency of the selected cavities with the lowest frequency.

    If True, return the frequency of all selected cavities

Returns:

rf_freq – RF frequency

get_rf_timelag(**kwargs)#

Return the RF time lag

Parameters:

ring (Lattice) – Lattice description

Keyword Arguments:
  • cavpts=None – Cavity location. If None, look for ring.cavpts, otherwise take all cavities.

  • array=False

    If False, return the frequency of the selected cavities with the lowest frequency.

    If True, return the frequency of all selected cavities

Returns:

rf_timelag – RF time lag

get_rf_voltage(**kwargs)#

Return the total RF voltage (full ring)

Parameters:

ring (Lattice) – Lattice description

Keyword Arguments:
  • cavpts=None – Cavity location. If None, look for ring.cavpts, otherwise take all cavities.

  • array=False

    If False, return the frequency of the selected cavities with the lowest frequency.

    If True, return the frequency of all selected cavities

Returns:

rf_v – Total RF voltage (full ring)

get_s_pos(refpts=RefptsCode.All, regex=False)#

Returns the locations of selected elements

Parameters:
Returns:

s_pos – Array of locations of the elements selected by refpts

Example

>>> get_s_pos(ring, at.End)
array([26.37428795])

Position at the end of the last element: length of the lattice

get_scattering_rate(emity, bunch_curr, emitx=None, sigs=None, sigp=None, zn=None, momap=None, refpts=None, offset=None, **kwargs)#

Touschek scattering rate calculation

Computes the touschek scattering using the Piwinski formula

Parameters:
  • ring – ring use for tracking

  • emity – verticla emittance

  • bunch_curr – bunch current

Keyword Arguments:
  • emitx=None – horizontal emittance

  • sigs=None – rms bunch length

  • sigp=None – energy spread

  • zn=None – full ring \(Z/n\)

  • momap=None – momentum aperture, has to be consistent with refpts if provided the momentum aperture is not calculated

  • refpts=Nonerefpts where the momentum aperture is calculated, the default is to compute it for all elements in the ring, len(refpts)>2 is required

  • resolution – minimum distance between 2 grid points, default=1.0e-3

  • amplitude – max. amplitude for RADIAL and CARTESIAN or initial step in RECURSIVE default = 0.1

  • nturns=1024 – Number of turns for the tracking

  • dp=None – static momentum offset

  • grid_modeat.GridMode.CARTESIAN/RADIAL track full vector (default). at.GridMode.RECURSIVE: recursive search

  • use_mp=False – Use python multiprocessing (patpass, default use lattice_pass). In case multi-processing is not enabled GridMode is forced to RECURSIVE (most efficient in single core)

  • verbose=False – Print out some inform

  • epsrel (epsabs,) – integral absolute and relative tolerances

Returns:
  • scattering_rate – scattering rate double array (len(refpts), ) expressed in event/seconds

  • ma – momentum aperture (len(refpts), 2) array

  • refpts – refpts used for momentum aperture calculation (len(refpts), ) array

get_slip_factor(**kwargs)#

Compute the slip factor \(\eta\)

Parameters:

ring (Lattice) – Lattice description (ring.is_6d must be False)

Keyword Arguments:
Returns:

eta (float) – Slip factor \(\eta\)

get_tune(*, method='linopt', dp=None, dct=None, df=None, orbit=None, **kwargs)#

Computes the tunes using several available methods

get_tune() may use several methods depending on a method keyword.

Parameters:
  • ring (Lattice) – Lattice description

  • method (str) –

    'linopt' returns the tunes from the linopt6() function,

    'fft' tracks a single particle and computes the tunes with fft,

    'interp_fft' tracks a single particle and computes the tunes with interpolated FFT.

  • dp (float) – Momentum deviation.

  • dct (float) – Path lengthening.

  • df (float) – Deviation of RF frequency.

  • orbit (Orbit) – Avoids looking for the closed orbit if it is already known ((6,) array)

for the 'fft' and 'interp_fft' methods only:

Keyword Arguments:
  • nturns (int) – Number of turns. Default: 512

  • amplitude (float) – Amplitude of oscillation. Default: 1.E-6

  • remove_dc (bool) – Remove the mean of oscillation data. Default: True

  • num_harmonics (int) – Number of harmonic components to compute (before mask applied, default: 20)

  • fmin (float) – Lower tune bound. Default: 0

  • fmax (float) – Upper tune bound. Default: 1

  • hann (bool) – Turn on Hanning window. Default: False. Work only for 'fft'

  • get_integer (bool) – Turn on integer tune (slower)

Returns:

tunes (ndarray) – array([\(\nu_x,\nu_y\)])

get_uint32_index(refpts, endpoint=True, regex=False)#

Returns an integer array of element indices, selecting ring elements.

Parameters:
Returns:

uint32_ref (Uint32Refpts) – uint32 numpy array used for indexing Elements in a lattice.

Examples

>>> get_uint32_index(ring, at.Sextupole)
array([ 21,  27,  35,  89,  97, 103], dtype=uint32)

numpy array of indices of all Sextupoles

>>> get_uint32_index(ring, at.End)
array([121], dtype=uint32)

numpy array([len(ring)+1])

>>> get_uint32_index(ring, at.checkattr('Frequency'))
array([0], dtype=uint32)

numpy array of indices of all elements having a ‘Frequency’ attribute

get_value_refpts(refpts, attrname, index=None, regex=False)#
Extracts attribute values from selected

lattice Elements.

Parameters:
Returns:

attrvalues – numpy Array of attribute values.

get_vertical_acceptance(resolution, amplitude, *args, **kwargs)#

Computes the 1D vertical acceptance at refpts observation points

See get_acceptance()

Parameters:
Keyword Arguments:
  • nturns – Number of turns for the tracking

  • refpts – Observation points. Default: start of the machine

  • dp – static momentum offset

  • offset – initial orbit. Default: closed orbit

  • grid_mode

    defines the evaluation grid:

  • use_mp – Use python multiprocessing (patpass(), default use lattice_pass()). In case multiprocessing is not enabled, grid_mode is forced to GridMode.RECURSIVE (most efficient in single core)

  • verbose – Print out some information

  • divider – Value of the divider used in GridMode.RECURSIVE boundary search

  • shift_zero – Epsilon offset applied on all 6 coordinates

  • start_method – Python multiprocessing start method. The default None uses the python default that is considered safe. Available parameters: 'fork', 'spawn', 'forkserver'. The default for linux is 'fork', the default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation or to solve runtime errors, however it is considered unsafe.

Returns:
  • boundary – (len(refpts),2) array: 1D acceptance

  • survived – (n,) array: Coordinates of surviving particles

  • tracked – (n,) array: Coordinates of tracked particles

In case of multiple tracked and survived are lists of arrays, with one array per ref. point.

Note

  • When``use_mp=True`` all the available CPUs will be used. This behavior can be changed by setting at.DConstant.patpass_poolsize to the desired value

  • When multiple refpts are provided particles are first projected to the beginning of the ring with tracking. Then, all particles are tracked up to nturns. This allows to do most of the work in a single function call and allows for full parallelization.

insert(idx, elem, copy_elements=False)[source]#

This method allow to insert an AT element in the lattice.

Parameters:
  • idx (SupportsIndex) – index at which the lement is inserted

  • elem (Element) – AT element to be inserted in the lattice

  • copy_elements (bool) – Default True. If True a deep copy of elem is used.

lattice_pass(r_in, nturns=1, refpts=RefptsCode.End, **kwargs)#

lattice_pass() tracks particles through each element of a lattice calling the element-specific tracking function specified in the Element’s PassMethod field.

Parameters:
Keyword Arguments:
  • keep_lattice (bool) – Use elements persisted from a previous call. If True, assume that the lattice has not changed since the previous call.

  • keep_counter (bool) – Keep the turn number from the previous call.

  • turn (int) – Starting turn number. Ignored if keep_counter is True. The turn number is necessary to compute the absolute path length used in RFCavityPass.

  • losses (bool) – Boolean to activate loss maps output

  • omp_num_threads (int) – Number of OpenMP threads (default: automatic)

The following keyword arguments overload the Lattice values

Keyword Arguments:
  • particle (Optional[Particle]) – circulating particle. Default: lattice.particle if existing, otherwise Particle('relativistic')

  • energy (Optiona[float]) – lattice energy. Default 0.

  • unfold_beam (bool) – Internal beam folding activate, this assumes the input particles are in bucket 0, works only if all bucket see the same RF Voltage. Default: True

If energy is not available, relativistic tracking if forced, rest_energy is ignored.

Returns:
  • r_out – (6, N, R, T) array containing output coordinates of N particles at R reference points for T turns.

  • loss_map – If losses is True: dictionary with the following key:

    islost

    (npart,) bool array indicating lost particles

    turn

    (npart,) int array indicating the turn at which the particle is lost

    element

    ((npart,) int array indicating the element at which the particle is lost

    coord

    (6, npart) float array giving the coordinates at which the particle is lost (zero for surviving particles)

Note

  • lattice_pass(lattice, r_in, refpts=len(line)) is the same as lattice_pass(lattice, r_in) since the reference point len(line) is the exit of the last element.

  • lattice_pass(lattice, r_in, refpts=0) is a copy of r_in since the reference point 0 is the entrance of the first element.

  • To resume an interrupted tracking (for instance to get intermediate results), one must use one of the turn or keep_counter keywords to ensure the continuity of the turn number.

  • For multiparticle tracking with large number of turn the size of r_out may increase excessively. To avoid memory issues lattice_pass(lattice, r_in, refpts=None) can be used. An empty list is returned and the tracking results of the last turn are stored in r_in.

  • To model buckets with different RF voltage unfold_beam=False has to be used. The beam can be unfolded using the function unfold_beam(). This function takes into account the true voltage in each bucket and distributes the particles in the bunches defined by ring.fillpattern using a 6D orbit search.

linopt2(*args, **kwargs)#

Linear analysis of an uncoupled lattice

linopt2() computes the linear optics parameters on a single cell (periodicity is not taken into account).

Parameters:

ring (Lattice) – Lattice description.

Keyword Arguments:
  • refpts (Refpts) –

    Elements at which data is returned. It can be:

    1. an integer in the range [-len(ring), len(ring)-1] selecting the element according to python indexing rules. As a special case, len(ring) is allowed and refers to the end of the last element,

    2. an ordered list of such integers without duplicates,

    3. a numpy array of booleans of maximum length len(ring)+1, where selected elements are True.

  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation of RF frequency. Defaults to None

  • orbit (Orbit) – Avoids looking for the closed orbit if it is already known ((6,) array)

  • get_chrom (bool) – Compute chromaticities. Needs computing the tune at 2 different momentum deviations around the central one.

  • get_w (bool) – Computes chromatic amplitude functions (W, WP) [4], and derivatives of the dispersion and twiss parameters versus dp. Needs to compute the optics at 2 different momentum deviations around the central one.

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

  • twiss_in

    Initial conditions for transfer line optics. Record array as output by linopt6(), or dictionary. Keys:

    R or alpha, beta

    mandatory (2,) arrays

    closed_orbit

    Optional (6,) array, default 0

    dispersion

    Optional (6,) array, default 0

    If present, the attribute R will be used, otherwise the attributes alpha and beta will be used. All other attributes are ignored.

Returns:
  • elemdata0 – Linear optics data at the entrance of the ring

  • ringdata – Lattice properties

  • elemdata – Linear optics at the points referred to by refpts, if refpts is None an empty lindata structure is returned.

elemdata is a record array with fields:

s_pos

longitudinal position [m]

M

(4, 4) transfer matrix M from the beginning of ring to the entrance of the element [2]

closed_orbit

(6,) closed orbit vector

dispersion

(4,) dispersion vector

beta

\(\left[ \beta_x,\beta_y \right]\) vector

alpha

\(\left[ \alpha_x,\alpha_y \right]\) vector

mu

\(\left[ \mu_x,\mu_y \right]\), betatron phase (modulo \(2\pi\))

W

\(\left[ W_x,W_y \right]\) only if get_w is True: chromatic amplitude function

Wp

\(\left[ Wp_x,Wp_y \right]\) only if get_w is True: chromatic phase function

dalpha

(2,) alpha derivative vector (\(\Delta \alpha/ \delta_p\))

dbeta

(2,) beta derivative vector (\(\Delta \beta/ \delta_p\))

dmu

(2,) mu derivative vector (\(\Delta \mu/ \delta_p\))

ddispersion

(4,) dispersion derivative vector (\(\Delta D/ \delta_p\))

All values given at the entrance of each element specified in refpts. Field values can be obtained with either lindata[‘idx’] or lindata.idx

ringdata is a record array with fields:

tune

Fractional tunes

chromaticity

Chromaticities, only computed if get_chrom is True

References

[1] D.Edwards,L.Teng IEEE Trans.Nucl.Sci. NS-20, No.3, p.885-888 , 1973

[3] D.Sagan, D.Rubin Phys.Rev.Spec.Top.-Accelerators and beams, vol.2 (1999)

linopt4(*args, **kwargs)#

Linear analysis of a H/V coupled lattice

4D-analysis of coupled motion following Sagan/Rubin [7]

linopt4() computes the linear optics parameters on a single cell (periodicity is not taken into account).

Parameters:

ring (Lattice) – Lattice description.

Keyword Arguments:
  • refpts (Refpts) –

    Elements at which data is returned. It can be:

    1. an integer in the range [-len(ring), len(ring)-1] selecting the element according to python indexing rules. As a special case, len(ring) is allowed and refers to the end of the last element,

    2. an ordered list of such integers without duplicates,

    3. a numpy array of booleans of maximum length len(ring)+1, where selected elements are True.

  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation of RF frequency. Defaults to None

  • orbit (Orbit) – Avoids looking for the closed orbit if it is already known ((6,) array)

  • get_chrom (bool) – Compute chromaticities. Needs computing the tune at 2 different momentum deviations around the central one.

  • get_w (bool) – Computes chromatic amplitude functions (W) [8]. Needs to compute the optics at 2 different momentum deviations around the central one.

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

  • twiss_in

    Initial conditions for transfer line optics. Record array as output by linopt6(), or dictionary. Keys:

    R or alpha, beta

    mandatory (2,) arrays

    closed_orbit

    Optional (6,) array, default 0

    dispersion

    Optional (6,) array, default 0

    If present, the attribute R will be used, otherwise the attributes alpha and beta will be used. All other attributes are ignored.

Returns:
  • elemdata0 – Linear optics data at the entrance of the ring

  • ringdata – Lattice properties

  • elemdata – Linear optics at the points refered to by refpts, if refpts is None an empty lindata structure is returned.

elemdata is a record array with fields:

s_pos

longitudinal position [m]

M

(4, 4) transfer matrix M from the beginning of ring to the entrance of the element [6]

closed_orbit

(6,) closed orbit vector

dispersion

(4,) dispersion vector

beta

\(\left[ \beta_x,\beta_y \right]\) vector

alpha

\(\left[ \alpha_x,\alpha_y \right]\) vector

mu

\(\left[ \mu_x,\mu_y \right]\), betatron phase (modulo \(2\pi\))

gamma

gamma parameter of the transformation to eigenmodes [7]

W

\(\left[ W_x,W_y \right]\) only if get_w is True: chromatic amplitude function

Wp

\(\left[ Wp_x,Wp_y \right]\) only if get_w is True: chromatic phase function

dalpha

(2,) alpha derivative vector (\(\Delta \alpha/ \delta_p\))

dbeta

(2,) beta derivative vector (\(\Delta \beta/ \delta_p\))

dmu

(2,) mu derivative vector (\(\Delta \mu/ \delta_p\))

ddispersion

(4,) dispersion derivative vector (\(\Delta D/ \delta_p\))

All values given at the entrance of each element specified in refpts. Field values can be obtained with either lindata[‘idx’] or lindata.idx

ringdata is a record array with fields:

tune

Fractional tunes

chromaticity

Chromaticities, only computed if get_chrom is True

References

[5] D.Edwards,L.Teng IEEE Trans.Nucl.Sci. NS-20, No.3, p.885-888 , 1973

linopt6(*args, **kwargs)#

Linear analysis of a fully coupled lattice using normal modes

For circular machines, linopt6() analyses

  • the 4x4 1-turn transfer matrix if ring is 4D, or

  • the 6x6 1-turn transfer matrix if ring is 6D.

For a transfer line, The “twiss_in” intput must contain either:

  • a field R, as provided by ATLINOPT6, or

  • the fields beta and alpha, as provided by linopt and linopt6

linopt6() computes the linear optics parameters on a single cell (periodicity is not taken into account).

Parameters:

ring (Lattice) – Lattice description.

Keyword Arguments:
  • refpts (Refpts) –

    Elements at which data is returned. It can be:

    1. an integer in the range [-len(ring), len(ring)-1] selecting the element according to python indexing rules. As a special case, len(ring) is allowed and refers to the end of the last element,

    2. an ordered list of such integers without duplicates,

    3. a numpy array of booleans of maximum length len(ring)+1, where selected elements are True.

  • dp (float) – Momentum deviation. Defaults to None

  • dct (float) – Path lengthening. Defaults to None

  • df (float) – Deviation of RF frequency. Defaults to None

  • orbit (Orbit) – Avoids looking for the closed orbit if it is already known ((6,) array)

  • get_chrom (bool) – Compute chromaticities. Needs computing the tune at 2 different momentum deviations around the central one.

  • get_w (bool) – Computes chromatic amplitude functions (W) [11]. Needs to compute the optics at 2 different momentum deviations around the central one.

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

  • twiss_in

    Initial conditions for transfer line optics. Record array as output by linopt6(), or dictionary. Keys:

    R or alpha, beta

    mandatory (2,) arrays

    closed_orbit

    Optional (6,) array, default 0

    dispersion

    Optional (6,) array, default 0

    If present, the attribute R will be used, otherwise the attributes alpha and beta will be used. All other attributes are ignored.

  • cavpts (Refpts) – Cavity location for off-momentum tuning

Returns:
  • elemdata0 – Linear optics data at the entrance of the ring

  • ringdata – Lattice properties

  • elemdata – Linear optics at the points refered to by refpts, if refpts is None an empty lindata structure is returned.

elemdata is a record array with fields:

s_pos

longitudinal position [m]

M

(6, 6) transfer matrix M from the beginning of ring to the entrance of the element

closed_orbit

(6,) closed orbit vector

dispersion

(4,) dispersion vector

A

(6,6) A-matrix

R

(3, 6, 6) R-matrices

beta

\(\left[ \beta_x,\beta_y \right]\) vector

alpha

\(\left[ \alpha_x,\alpha_y \right]\) vector

mu

\(\left[ \mu_x,\mu_y \right]\), betatron phase (modulo \(2\pi\))

W

\(\left[ W_x,W_y \right]\) only if get_w is True: chromatic amplitude function

Wp

\(\left[ Wp_x,Wp_y \right]\) only if get_w is True: chromatic phase function

dalpha

(2,) alpha derivative vector (\(\Delta \alpha/ \delta_p\))

dbeta

(2,) beta derivative vector (\(\Delta \beta/ \delta_p\))

dmu

(2,) mu derivative vector (\(\Delta \mu/ \delta_p\))

ddispersion

(4,) dispersion derivative vector (\(\Delta D/ \delta_p\))

dR

(3, 6, 6) R derivative vector (\(\Delta R/ \delta_p\))

All values given at the entrance of each element specified in refpts. Field values can be obtained with either lindata[‘idx’] or lindata.idx

ringdata is a record array with fields:

tune

Fractional tunes

chromaticity

Chromaticities, only computed if get_chrom is True

damping_time

Damping times [s] (only if radiation is ON)

References

[9] Etienne Forest, Phys. Rev. E 58, 2481 – Published 1 August 1998

[10] Andrzej Wolski, Phys. Rev. ST Accel. Beams 9, 024001 – Published 3 February 2006

static load(filepath, **kwargs)#

Load a Lattice object from a file

The file format is indicated by the filepath extension. The file name is stored in the in_file Lattice attribute. The selected variable, if relevant, is stored in the use Lattice attribute.

Parameters:

filepath (str) – Name of the file

Keyword Arguments:
  • use (str) – Name of the variable containing the desired lattice. Default: if there is a single variable, use it, otherwise select "RING"

  • name (str) – Name of the lattice. Default: taken from the file, or ""

  • energy (float) – Energy of the lattice (default: taken from the file)

  • periodicity (int) – Number of periods (default: taken from the file, or 1)

  • * – All other keywords will be set as Lattice attributes

Returns:

lattice (Lattice) – New Lattice object

Check the format-specific function for specific keyword arguments:

Known extensions are:

.mat

Matlab binary mat-file. See load_mat().

.m

Matlab text m-file. See load_m().

.repr

Text representation of a python AT Lattice. See load_repr().

.lat

Tracy format. See load_tracy().

.lte

Elegant format. See load_elegant().

.json

JSON representation of a python AT Lattice. See load_json().

.seq

MAD-X lattice description. See load_madx().

modify_elements(elem_modify, copy=True, **kwargs)[source]#

Modify selected elements, in-place or in a lattice copy

Parameters:
  • elem_modify (Callable) – element selection function. If elem_modify(elem) returns None, the element is unchanged. Otherwise, elem_modify(elem) must return a dictionary of attribute name and values, to be set to elem.

  • copy (bool | None) – If True, return a shallow copy of the lattice. Only the modified elements are copied. If False, the modification is done in-place

Returns:

newring – New lattice if copy is True, None if copy is False

Keyword Arguments:

ohmi_envelope(refpts=None, orbit=None, keep_lattice=False)#

Calculates the equilibrium beam envelope

Computation based on Ohmi’s beam envelope formalism [1]

Parameters:
Returns:
  • emit0 (np.recarray) – Emittance data at the start/end of the ring

  • beamdata (np.recarray) – Beam parameters at the start of the ring

  • emit (np.recarray) – Emittance data at the points selected to by refpts

emit is a record array with the following fields:

r66

(6, 6) equilibrium envelope matrix R

r44

(4, 4) betatron emittance matrix (dpp = 0)

m66

(6, 6) transfer matrix from the start of the ring

orbit6

(6,) closed orbit

emitXY

(2,) betatron emittance projected on xxp and yyp

emitXYZ

(3,) 6x6 emittance projected on xxp, yyp, ldp

Values given at the entrance of each element specified in refpts.

Field values can be obtained with either emit['r66'] or emit.r66

beamdata is a record array with the following fields:

tunes

tunes of the 3 normal modes

damping_rates

damping rates of the 3 normal modes

mode_matrices

R-matrices of the 3 normal modes

mode_emittances

equilibrium emittances of the 3 normal modes

References

plot_RF_bucket_hamiltonian(ct_range=None, dp_range=None, num_points=400, num_levels=41, plot_separatrix=True, **kwargs)#

Plot the resulting longitudinal Hamiltonian of a ring (defining the RF bucket). The Hamiltonian is calculated by summing all the cavities in the ring. Harmonic cavities are supported by the function.

A perfectly tuned lattice is assumed, the cavities’ frequency is nominal and the TimeLag is set in a way ensuring ct=0 for the synchronous phase by using set_cavity_phase().

Parameters:
  • ring – Lattice description

  • ct_range (tuple) – Forced lower and upper ct values for the plot. Default to \(\pm 1.1 \times C / (2h)\)

  • dp_range (tuple) – Forced lower and upper dp values for the plot. Default to twice the RF acceptance of the bucket.

  • num_points (int) – Number of points for 1D grid (ct/dp) Default to 400.

  • num_levels (int) – Number of levels for contour plot. Odd number of levels allow to center the colorbar around 0. Default to 41.

  • plot_separatrix (bool) – Flag to plot the separatrix contour (\(\mathcal{H}=0\)).

Returns:
  • CT – (num_points,num_points) array: ct grid

  • DP – (num_points,num_points) array: dp grid

  • hamiltonian – (num_points,num_points) array: Hamiltonian values

  • along (CT,DP)

plot_acceptance(planes, *args, **kwargs)#

Plots the acceptance

Computes the acceptance at repfts observation points using get_acceptance() and plots the tracked and survived particles, and the acceptance boundary.

Parameters:
  • ring (Lattice) – Lattice definition

  • planes – max. dimension 2, Plane(s) to scan for the acceptance. Allowed values are: ‘x’, ‘xp’, ‘y’, ‘yp’, ‘dp’, ‘ct’

Keyword Arguments:
  • acceptance (tuple[ndarray, ndarray, ndarray]) – tuple containing pre-computed acceptance (boundary, survived, grid)

  • npoints – (len(planes),) array: number of points in each dimension

  • amplitudes

    (len(planes),) array: set the search range:

  • nturns (int) – Number of turns for the tracking

  • obspt (Refpts) – Observation points. Default: start of the machine

  • dp (float) – Static momentum offset

  • offset – Initial orbit. Default: closed orbit

  • bounds

    Defines the tracked range: range=bounds*amplitude. It can be used to select quadrants. For example, default values are:

  • grid_mode (GridMode) –

    Defines the evaluation grid:

  • use_mp (bool) – Use python multiprocessing (patpass(), default use lattice_pass()). In case multiprocessing is not enabled, grid_mode is forced to GridMode.RECURSIVE (most efficient in single core)

  • verbose (bool) – Print out some information

  • divider (int) – Value of the divider used in GridMode.RECURSIVE boundary search

  • shift_zero

  • start_method (str) – Python multiprocessing start method. The default None uses the python default that is considered safe. Available parameters: ‘fork’, ‘spawn’, ‘forkserver’. The default for linux is ‘fork’, the default for macOS and Windows is ‘spawn’. ‘fork’ may be used for macOS to speed up the calculation or to solve runtime errors, however it is considered unsafe.

Returns:
  • boundary – (2,n) array: 2D acceptance

  • tracked – (2,n) array: Coordinates of tracked particles

  • survived – (2,n) array: Coordinates of surviving particles

Example

>>> ring.plot_acceptance(planes, npoints, amplitudes)
>>> plt.show()
plot_beta(**kwargs)#

Plot beta functions and dispersion

Parameters:

ring (Lattice) – Lattice description.

Keyword Arguments:
  • dp (float) – Momentum deviation.

  • dct (float) – Path lengthening. If specified, dp is ignored and the off-momentum is deduced from the path lengthening.

  • orbit (Orbit) – Avoids looking for the closed orbit if is already known ((6,) array)

  • method (Callable) –

    Method for linear optics (see get_optics()):

    linopt2: no longitudinal motion, no H/V coupling,

    linopt4: no longitudinal motion, Sagan/Rubin 4D-analysis of coupled motion,

    linopt6 (default): with or without longitudinal motion, normal mode analysis

  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

  • twiss_in – Initial conditions for transfer line optics. Record array as output by linopt2(), linopt6(), or dictionary.

  • s_range – Lattice range of interest, default: unchanged, initially set to the full cell.

  • axes (tuple[Axes, Optional[Axes]) – Axes for plotting as (primary_axes, secondary_axes). Default: create new axes

  • slices (int) – Number of slices. Default: 400

  • legend (bool) – Show a legend on the plot

  • labels (Refpts) – display the name of selected elements. Default: None

  • block (bool) – If True, block until the figure is closed. Default: False

  • dipole (dict) – Dictionary of properties overloading the default properties of dipole representation. See plot_synopt() for details

  • quadrupole (dict) – Same definition as for dipole

  • sextupole (dict) – Same definition as for dipole

  • multipole (dict) – Same definition as for dipole

  • monitor (dict) – Same definition as for dipole

plot_geometry(start_coordinates=(0, 0, 0), centered=False, ax=None, **kwargs)#

Compute and plot the 2D ring geometry in cartesian coordinates.

Parameters:
  • ring (Lattice) – Lattice description

  • start_coordinates (tuple[float, float, float]) – x,y,angle at starting point

  • centered (bool) – it True the coordinates origin is the center of the ring

  • ax (Axes | None) – axes for the plot. If not given, new axes are created

Keyword arguments are forwarded to the underlying plot() function

Returns:
  • geomdata – recarray containing, x, y, angle

  • radius – machine radius

  • ax – plot axis

Example

>>> ring.plot_geometry()
plot_trajectory(r_in, nturns=1, **kwargs)#

Plot a particle’s trajectory

Parameters:
  • ring (Lattice) – Lattice object

  • r_in – (6,n) array: input coordinates of n particles

  • nturns (int) – Number of turns

Keyword Arguments:
  • keep_lattice (bool) – Assume no lattice change since the previous tracking. Defaults to False

  • s_range – Lattice range of interest, default: unchanged, initially set to the full cell.

  • axes (tuple[Axes, Optional[Axes]) – Axes for plotting as (primary_axes, secondary_axes). Default: create new axes

  • slices (int) – Number of slices. Default: 400

  • legend (bool) – Show a legend on the plot

  • block (bool) – If True, block until the figure is closed. Default: False

  • dipole (dict) – Dictionary of properties overloading the default properties of dipole representation. See plot_synopt() for details

  • quadrupole (dict) – Same definition as for dipole

  • sextupole (dict) – Same definition as for dipole

  • multipole (dict) – Same definition as for dipole

  • monitor (dict) – Same definition as for dipole

radiation_off(*args, **kwargs)[source]#

Obsolete. Turn longitudinal motion off

The function name is misleading, since the function deals with longitudinal motion in general.

For this reason the method is obsolete and replaced by disable_6d()

See also

disable_6d()

radiation_on(*args, **kwargs)[source]#

Obsolete. Turn longitudinal motion on

The function name is misleading, since the function deals with longitudinal motion in general.

For this reason the method is obsolete and replaced by enable_6d()

See also

enable_6d()

radiation_parameters(dp=None, params=None, **kwargs)#

Compute ring parameters from the radiation integrals

Valid for uncoupled lattices with no RF cavity or radiating element.

Parameters:
Keyword Arguments:
  • dct (float) – Path lengthening. If specified, dp is ignored and the off-momentum is deduced from the path lengthening.

  • method (Callable) –

    Method for linear optics:

    linopt2: no longitudinal motion, no H/V coupling,

    linopt6 (default): with or without longitudinal motion, normal mode analysis

  • orbit (Orbit) – Avoids looking for the closed orbit if is already known ((6,) array)

  • XYStep (float) – Step size. Default: DConstant.XYStep

  • DPStep (float) – Momentum step size. Default: DConstant.DPStep

Returns:

paramsRingParameters object.

params is a RingParameters object with the following attributes:

tunes

(3,) fractional (H, V, Long.) tunes

fulltunes

(3,) full tunes

chromaticities

(2,) H, V Chromaticities

alphac

Momentum compaction factor

etac

Frequency slip factor

E0

Energy [eV]

U0

Energy loss / turn [eV]

i1

Radiation integrals - \(I_1 \quad [m]\)

i2

\(I_2 \quad [m^{-1}]\)

i3

\(I_3 \quad [m^{-2}]\)

i4

\(I_4 \quad [m^{-1}]\)

i5

\(I_5 \quad [m^{-1}]\)

emittances

(3,) Mode emittances

J

(3,) Damping partition numbers

Tau

(3,) Damping times [s]

sigma_e

Energy spread

sigma_l

Bunch length [m]

voltage

Total accelerating voltage [V]

phi_s

Synchrotron phase [rad]

f_s

Synchrotron frequency [Hz]

reduce(**kwargs)[source]#

Removes all elements with an IdentityPass PassMethod and merges compatible consecutive elements.

The “reduced” lattice has the same optics as the original one, but fewer elements. Compatible elements must have the same PolynomA, PolynomB and bending radius, so that the optics is preserved. But magnet misalignments are not preserved, so this method should be applied to lattices without errors.

Keyword Arguments:

keep (Refpts) – Keep the selected elements, even with IdentityPass PassMethod. Default: keep Monitor and RFCavity elements

refcount(refpts, endpoint=True, regex=False)#

Returns the number of reference points

Parameters:
Returns:

nrefs (int) – The number of reference points

Examples

>>> refpts = ring.refcount(at.Sextupole)
6

Returns the number of Sextupoles in the lattice

>>> refpts = ring.refcount(at.All)
122

Returns len(ring)+1

>>> refpts = ring.refcount(at.All, endpoint=False)
121

Returns len(ring)

repeat(n, copy_elements=True)[source]#

This method allows to repeat the lattice n times. If n does not divide ring.periodicity, the new ring periodicity is set to 1, otherwise it is set to ring.periodicity /= n.

Equivalent syntaxes:

>>> newring = ring.repeat(n)
>>> newring = ring * n
Parameters:
  • n (int) – number of repetitions

  • copy_elements (bool) – If True, deep copies of the lattice are used for the repetition. Otherwise, the original elements are repeated in the developed lattice.

Returns:

newring (Lattice) – the new repeated lattice

replace(refpts, **kwargs)[source]#

Return a shallow copy of the lattice replacing the selected elements by a deep copy

Parameters:

refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – element selector

reverse(copy=False)[source]#

Reverse the order of the lattice and swapt the faces of elements. Alignment errors are not swapped

Parameters:

copy (bool) – Default False. If True the lattice is modified in place. Oterwise a new Lattice object is returned

Returns:

lattice (Lattice) – reversed Lattice, if copy==True the new lattice object is returned otherwise None

Example

>>> newring = ring.reverse(copy=True)
rotate(n)[source]#

Return a new lattice rotated left by n elements

save(filepath, **kwargs)#

Save a Lattice object

The file format is indicated by the filepath extension.

Parameters:
  • ring (Lattice) – Lattice description

  • filepath (str) – Name of the file

Check the format-specific function for specific keyword arguments:

Known extensions are:

.mat

Matlab binary mat-file. See load_mat().

.m

Matlab text m-file. See load_m().

.repr

Text representation of a python AT Lattice. See load_repr().

.json

JSON representation of a python AT Lattice. See load_json().

sbreak(break_s, break_elems=None, **kwargs)[source]#

Insert elements at selected locations in the lattice

Parameters:
  • break_s – location or array of locations of breakpoints

  • break_elems – elements to be inserted at breakpoints (array of elements as long as break_s or single element duplicated as necessary). Default: Marker(‘sbreak’)

Returns:

newring – A new lattice with new elements inserted at breakpoints

select(refpts, regex=False)#

Return an iterator over selected elements in a lattice

Parameters:
Returns:

elem_iter (Iterator[Element]) – Iterator over the elements in ring selected by refpts.

set_beam_current(value, clear_history=True)[source]#
set_cavity(Voltage=None, Frequency=None, TimeLag=None, cavpts=None, copy=False, array=False)#

Set the parameters of the RF cavities

Parameters:
  • ring (Lattice) – lattice description

  • Frequency (float | None) – RF frequency [Hz]

  • Voltage (float | None) – RF voltage [V]

  • TimeLag (float | None) – RF time shift [-ct]

  • cavpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – Cavity location. If None, look for ring.cavpts, or otherwise take all cavities

  • array (bool | None) – If False, the value is applied as described for set_rf_voltage, set_rf_timelag and set_rf_frequency If True, directly apply the value to the selected cavities. The value must be broadcastable to the number of cavities.

  • copy (bool | None) – If True, returns a shallow copy of ring with new cavity elements. Otherwise, modify ring in-place

set_cavity_phase(method=ELossMethod.TRACKING, refpts=None, cavpts=None, copy=False)#

Adjust the TimeLag attribute of RF cavities based on frequency, voltage and energy loss per turn, so that the synchronous phase is zero. An error occurs if all cavities do not have the same frequency.

Warning

This function changes the time reference, this should be avoided

Parameters:
set_fillpattern(bunches=1)[source]#

Function to generate the filling pattern lof the ring. The filling pattern is computed as:

bunches/numpy.sum(bunches)

This function also generates the bunch spatial distribution accessible with Lattice.bunch_spos

Keyword Arguments:

bunches – integer or array of positive double or bool to define the bunch distribution. For scalar input, equidistant bunches are assumed. ring.harmonic_number has to be a multiple of bunches. For array input the condition len(bunches)==ring.harmonic_number is required. (default=1, single bunch configuration).

set_rf_frequency(frequency=None, dp=None, dct=None, df=None, **kwargs)#

Set the RF frequency

Parameters:
  • ring (Lattice) – Lattice description

  • frequency (float | None) – RF frequency [Hz]. Default: nominal frequency.

  • dp (float | None) – Momentum deviation. Defaults to None

  • dct (float | None) – Path lengthening. Defaults to None

  • df (float | None) – Deviation of RF frequency. Defaults to None

Keyword Arguments:
  • cavpts (Optional[Refpts]) – If None, look for ring.cavpts, or otherwise take all cavities.

  • array (Optional[bool]) –

    If False (default), frequency is applied to the selected cavities with the lowest frequency. The frequency of all the other selected cavities is scaled by the same ratio.

    If True, directly apply frequency to the selected cavities. The value must be broadcastable to the number of cavities.

  • copy (Optional[bool]) – If True, returns a shallow copy of ring with new cavity elements. Otherwise (default), modify ring in-place

set_rf_timelag(timelag, **kwargs)#

Set the RF time lag

Parameters:
  • ring (Lattice) – Lattice description

  • timelag (float) – RF time lag

Keyword Arguments:
  • cavpts=None – Cavity location. If None, look for ring.cavpts, otherwise take all cavities.

  • array=False

    If False, return the frequency of the selected cavities with the lowest frequency.

    If True, return the frequency of all selected cavities

  • copy=False – If True, returns a shallow copy of ring with new cavity elements. Otherwise, modify ring in-place.

set_rf_voltage(voltage, **kwargs)#

Set the RF voltage for the full ring

Parameters:
  • ring (Lattice) – Lattice description

  • voltage (float) – Total RF voltage (full ring)

Keyword Arguments:
  • cavpts=None – Cavity location. If None, look for ring.cavpts, otherwise take all cavities.

  • array=False

    If False, return the frequency of the selected cavities with the lowest frequency.

    If True, return the frequency of all selected cavities

  • copy=False – If True, returns a shallow copy of ring with new cavity elements. Otherwise, modify ring in-place.

set_shift(dxs, dzs, relative=False)#

Sets the translations of a list of elements.

Parameters:
  • ring (Sequence[Element]) – Lattice description

  • dxs – Sequence of horizontal displacements values as long as ring or scalar value applied to all elements [m]

  • dzs – Sequence of vertical displacements values as long as ring or scalar value applied to all elements [m]

  • relative – If True, the displacement is added to the existing one

set_tilt(tilts, relative=False)#

Sets the tilts of a list of elements.

Parameters:
  • ring (Sequence[Element]) – Lattice description

  • tilts – Sequence of tilt values as long as ring or scalar tilt value applied to all elements

  • relative – If True, the rotation is added to the existing one

set_value_refpts(refpts, attrname, attrvalues, index=None, increment=False, copy=False, regex=False)#

Set the values of an attribute of an array of elements based on their refpts

Parameters:
  • ring (Sequence[Element]) – Lattice description

  • refpts (Type[Element] | Element | Callable[[Element], bool] | str | None | int | Sequence[int] | bool | Sequence[bool] | RefptsCode) – Element selection key. See “Selecting elements in a lattice

  • attrname (str) – Attribute name

  • attrvalues – Attribute values

  • index (int | None) – index of the value to set if attrname is an array. if None, the full array is replaced by attrvalue

  • increment (bool) – If True, attrvalues are added to the initial values.

  • regex (bool) – Use regular expression for refpts string matching instead of Unix shell-style wildcards.

  • copy (bool) –

    If False, the modification is done in-place,

    If True, return a shallow copy of the lattice. Only the modified elements are copied.

    Caution

    a shallow copy means that all non-modified elements are shared with the original lattice. Any further modification will affect both lattices.

set_wake_turnhistory()[source]#

Function to reset the shape of the turn history in collective elements based on the number of slices, turns and bunches

slice(size=None, slices=1)[source]#

Create a new lattice by slicing the range of interest into small elements

Keyword Arguments:
  • size=None – Length of a slice. Default: computed from the range and number of points: size = (s_max-s_min)/slices.

  • slices=1 – Number of slices in the specified range. Ignored if size is specified. Default: no slicing

Returns:

newring – New Lattice object

slice_elements(refpts, slices=1)[source]#

Create a new lattice by slicing the elements at refpts

Parameters:
Returns:

newring – New Lattice object

tapering(multipoles=True, niter=1, **kwargs)#

Scales magnet strengths

Scales magnet strengths with local energy to cancel the closed orbit and optics errors due to synchrotron radiations. The dipole bending angle is changed by changing the reference momentum. This is the ideal tapering scheme where magnets and multipoles components (PolynomB and PolynomA) are scaled individually.

Warning

This method works only for lattices without errors and corrections: if not all corrections and field errors will also be scaled !!!

Parameters:
  • ring (Lattice) – Lattice description

  • multipoles (bool) – Scales all multipoles

  • niter (int) – Number of iteration

Keyword Arguments:
track(r_in, nturns=1, refpts=RefptsCode.End, in_place=False, **kwargs)#

track_function() tracks particles through each element of a lattice or throught a single Element calling the element-specific tracking function specified in the Element’s PassMethod field.

Usage:
>>> lattice_track(lattice, r_in)
>>> lattice.track(r_in)
Parameters:
  • lattice (Iterable[Element]) – list of elements

  • r_in – (6, N) array: input coordinates of N particles. r_in is modified in-place only if in_place is True and reports the coordinates at the end of the element. For the best efficiency, r_in should be given as F_CONTIGUOUS numpy array.

Keyword Arguments:
  • nturns – number of turns to be tracked

  • refpts – Selects the location of coordinates output. See “Selecting elements in a lattice

  • in_place (bool) – If True r_in is modified in-place and reports the coordinates at the end of the element. (default: False)

  • keep_lattice (bool) – Use elements persisted from a previous call. If True, assume that the lattice has not changed since the previous call.

  • keep_counter (bool) – Keep the turn number from the previous call.

  • turn (int) – Starting turn number. Ignored if keep_counter is True. The turn number is necessary to compute the absolute path length used in RFCavityPass.

  • losses (bool) – Boolean to activate loss maps output

  • omp_num_threads (int) – Number of OpenMP threads (default: automatic)

  • use_mp (bool) – Flag to activate multiprocessing (default: False)

  • pool_size – number of processes used when use_mp is True. If None, min(npart,nproc) is used. It can be globally set using the variable at.lattice.DConstant.patpass_poolsize

  • start_method – python multiprocessing start method. None uses the python default that is considered safe. Available values: 'fork', 'spawn', 'forkserver'. Default for linux is 'fork', default for macOS and Windows is 'spawn'. 'fork' may be used on macOS to speed up the calculation or to solve Runtime Errors, however it is considered unsafe. Used only when use_mp is True. It can be globally set using the variable at.lattice.DConstant.patpass_startmethod

The following keyword arguments overload the lattice values

Keyword Arguments:
  • particle (Optional[Particle]) – circulating particle. Default: lattice.particle if existing, otherwise Particle('relativistic')

  • energy (Optiona[float]) – lattice energy. Default 0.

  • unfold_beam (bool) – Internal beam folding activate, this assumes the input particles are in bucket 0, works only if all bucket see the same RF Voltage. Default: True

If energy is not available, relativistic tracking if forced, rest_energy is ignored.

Returns:
  • r_out – (6, N, R, T) array containing output coordinates of N particles at R reference points for T turns

  • trackparam – A dictionary containing tracking input parameters with the following keys:

    npart

    number of particles

    rout

    final particle coordinates

    turn

    starting turn

    refpts

    array of index where particle coordinate are saved (only for lattice tracking)

    nturns

    number of turn

  • trackdata – A dictionary containing tracking data with the following keys:

    loss_map:

    recarray containing the loss_map (only for lattice tracking)

    The loss_map is filled only if losses is True, it contains the following keys:

    islost

    (npart,) bool array indicating lost particles

    turn

    (npart,) int array indicating the turn at which the particle is lost

    element

    (npart,) int array indicating the element at which the particle is lost

    coord

    (npart, 6) float array giving the coordinates at which the particle is lost (zero for surviving particles)

Note

  • track_function(lattice, r_in, refpts=len(line)) is the same as track_function(lattice, r_in) since the reference point len(line) is the exit of the last element.

  • track_function(lattice, r_in, refpts=0) is a copy of r_in since the reference point 0 is the entrance of the first element.

  • To resume an interrupted tracking (for instance to get intermediate results), one must use one of the turn or keep_counter keywords to ensure the continuity of the turn number.

  • For multiparticle tracking with large number of turn the size of r_out may increase excessively. To avoid memory issues track_function(lattice, r_in, refpts=None, in_place=True) can be used. An empty list is returned and the tracking results of the last turn are stored in r_in.

  • To model buckets with different RF voltage unfold_beam=False has to be used. The beam can be unfolded using the function unfold_beam(). This function takes into account the true voltage in each bucket and distributes the particles in the bunches defined by ring.fillpattern using a 6D orbit search.

uint32_refpts(refpts, endpoint=True, regex=False)#

Returns an integer array of element indices, selecting ring elements.

Parameters:
Returns:

uint32_ref (Uint32Refpts) – uint32 numpy array used for indexing Elements in a lattice.

Examples

>>> get_uint32_index(ring, at.Sextupole)
array([ 21,  27,  35,  89,  97, 103], dtype=uint32)

numpy array of indices of all Sextupoles

>>> get_uint32_index(ring, at.End)
array([121], dtype=uint32)

numpy array([len(ring)+1])

>>> get_uint32_index(ring, at.checkattr('Frequency'))
array([0], dtype=uint32)

numpy array of indices of all elements having a ‘Frequency’ attribute

update(**kwargs)[source]#
update(mapping, **kwargs) None
update(iterable, **kwargs) None

Update the lattice attributes with the given values

property BRho: float#

Magnetic rigidity [T.m]

property attrs: dict#

Dictionary of lattice attributes

property beam_current#
property beta: float#

Relativistic \(\beta\) of the particles

property bunch_currents: ndarray#

Bunch currents [A]

property bunch_list: ndarray#

Indices of filled bunches

property bunch_spos: ndarray#

Bunch position around the ring [m]

property cell_harmnumber: float#

Harmonic number per cell

See also

harmonic_number().

property cell_length: float#

Cell length (1 cell) [m]

See also

circumference().

property cell_revolution_frequency: float#

Revolution frequency for 1 cell [Hz]

property circumference: float#

Ring circumference (full ring) [m]

See also

cell_length().

property energy: float#

Lattice energy

property energy_loss: float#

Computes the energy loss per turn

Parameters:
  • ring – Lattice description

  • method – Method for energy loss computation. See ELossMethod.

Returns:

eloss (float) – Energy loss per turn [eV]

property fillpattern: ndarray#

Filling pattern describing the bunch relative amplitudes such that sum(fillpattern)=1

property gamma: float#

Relativistic \(\gamma\) of the particles

property harmonic_number: int#

Ring harmonic number (full ring)

See also

cell_harmnumber().

property has_cavity: bool#

True if the lattice contains an active RFCavity

property i_range: ndarray#

Range of elements inside the range of interest

property is_6d: bool#

True if at least one element modifies the beam momentum

property is_collective: bool#

True if any element involves collective effects

property mat_file#

.mat input file. Deprecated, use in_file instead.

property mat_key#

selected Matlab variable. Deprecated, use use instead.

property mcf: float#

Momentum compaction factor

property nbunch: int#

Number of bunches

property particle: Particle#

Circulating particle

property revolution_frequency: float#

Revolution frequency (full ring) [Hz]

property rf_frequency: float#

Fundamental RF frequency [Hz]. The special value Frf.NOMINAL means nominal frequency.

property rf_timelag: float#

Time lag of the fundamental mode [m]

property rf_voltage: float#

RF voltage of the full ring [V]

property s_range: None | tuple[float, float]#

(s_min, s_max). None means the full cell.

Type:

Range of interest

property slip_factor: float#

Slip factor

elem_generator(params, elems)[source]#

Run through all elements without any check

Parameters:
  • params – Dictionary of Lattice attributes

  • elems (Iterable[Element]) – Iterable of lattice Elements

Yields:

lattice Elements

lattice_filter(params, lattice)[source]#

Copy lattice parameters and run through all lattice elements

Parameters:
  • params – Dictionary of Lattice attributes

  • lattice – Input Lattice

Yields:

lattice Elements

no_filter(params, elems)#

Run through all elements without any check

Parameters:
  • params – Dictionary of Lattice attributes

  • elems (Iterable[Element]) – Iterable of lattice Elements

Yields:

lattice Elements

params_filter(params, elem_filter, *args)[source]#

Run through all elements, looking for energy and periodicity. Remove the Energy attribute of non-radiating elements

Parameters:
  • params – Dictionary of Lattice attributes

  • elem_filter (Callable[[...], Iterable[Element]]) – Next Elements filter

  • args – Arguments forwarded to elem_filter

Yields:

lattice Elements

The following keys in params are set:

  • _length

  • periodicity

  • energy (optional)

  • _frequency (optional)

  • harmonic_number (optional)

energy is taken from:
  1. The params dictionary

  2. Cavity elements

  3. Any other element

periodicity is taken from:
  1. The params dictionary

  2. Sum of the bending angles of magnets

type_filter(params, elems)[source]#

Run through all elements and check element validity. Analyse elements for radiation state

Parameters:
  • params – Dictionary of Lattice attributes

  • elems (Iterable[Element]) – Iterable of lattice Elements

Yields:

lattice Elements