Reference manual

xtrack.Line class

The Xsuite Line class is the main class to build beam lines. Its interface is described in the following (more info on how to build and use beam lines for different purposes can be found in the Xsuite user’s guide).

class xtrack.Line(elements=(), element_names=None, particle_ref=None, energy_program=None)

Beam line object. Line.element_names contains the ordered list of beam elements, Line.element_dict is a dictionary associating to each name the corresponding beam element object.

Parameters:
  • elements (dict or list of beam elements) – If a dictionary, it must be a dictionary associating to each name the corresponding beam element object. If a list, it must be a list of beam elements having the same length as the provided element_names.

  • element_names (list of str) – Ordered list of beam element names. If not provided, elements must be a list, the names are automatically generated.

  • particle_ref (xpart.Particles) – Reference particle providing rest mass, charge and reference enegy used for building particles distributions, computing twiss parameters and matching.

  • energy_program (EnergyProgram) – (optional) Energy program used to update the reference energy during the tracking.

classmethod from_dict(dct, _context=None, _buffer=None, classes=())

Create a Line object from a dictionary.

Parameters:
  • dct (dict) – Dictionary containing the line data.

  • _context (xobjects.Context, optional) – Context used for allocating the element data. If not provided the default xobjects context is used.

  • _buffer (xobjects.Buffer, optional) – Buffer used for allocating the element data. If not provided, a new buffer is created.

  • classes (list of classes, optional) – List of classes to be used for deserializing the elements. If not provided, the default classes are used.

Returns:

line – Line object.

Return type:

Line

classmethod from_json(file, **kwargs)

Constructs a line from a json file.

Parameters:
  • file (str or file-like object) – Path to the json file or file-like object.

  • **kwargs (dict) – Additional keyword arguments passed to Line.from_dict.

Returns:

line – Line object.

Return type:

Line

classmethod from_sequence(nodes=None, length=None, elements=None, sequences=None, copy_elements=False, naming_scheme='{}{}', auto_reorder=False, refer: Literal['entry', 'centre', 'exit'] = 'entry', **kwargs)

Constructs a line from a sequence definition, inserting drift spaces as needed.

Parameters:
  • nodes (list of Node) – Sequence definition.

  • length (float) – Total length (in m) of line. Determines drift behind last element.

  • elements (dict) – Dictionary with named elements, which can be refered to in the sequence definion by name.

  • sequences (dict) – Dictionary with named sub-sequences, which can be refered to in the sequence definion by name.

  • copy_elements (bool, optional) – Whether to make copies of elements or not. By default, named elements are re-used which is memory efficient but does not allow to change parameters individually.

  • naming_scheme (str, optional) – Naming scheme to name sub-sequences. A format string accepting two names to be joined.

  • auto_reorder (bool, optional) – If false (default), nodes must be defined in order of increasing s coordinate, otherwise an exception is thrown. If true, nodes can be defined in any order and are re-ordered as necessary. Useful to place additional elements inside of sub-sequences.

  • refer (str, optional) – Specifies where in the node the s coordinate refers to. Can be ‘entry’, ‘centre’ or ‘exit’. By default given s specifies the entry point of the element. If ‘centre’ is given, the s coordinate marks the centre of the element. If ‘exit’ is given, the s coordinate marks the exit point of the element.

  • **kwargs (dict) – Arguments passed to constructor of the line

Returns:

line – Line object.

Return type:

Line

Examples

classmethod from_sixinput(sixinput, classes=())

Build a Line from a Sixtrack input object. N.B. This is a convenience function that calls sixinput.generate_xtrack_line(). It is used only for testing and will be removed in future versions.

Parameters:
  • sixinput (SixInput) – Sixtrack input object

  • classes (tuple) – Tuple of classes to be used for the elements. If empty, the default classes are used.

Returns:

line – Line object.

Return type:

Line

classmethod from_madx_sequence(sequence, deferred_expressions=False, install_apertures=False, apply_madx_errors=None, enable_field_errors=None, enable_align_errors=None, skip_markers=False, merge_drifts=False, merge_multipoles=False, expressions_for_element_types=None, replace_in_expr=None, classes=(), ignored_madtypes=(), allow_thick=None, use_compound_elements=True, name_prefix=None)

Build a line from a MAD-X sequence.

Parameters:
  • sequence (madx.Sequence) – MAD-X sequence object or name of the sequence

  • deferred_expressions (bool, optional) – If true, deferred expressions from MAD-X are imported and can be accessed in Line.vars and Line.element_refs.

  • install_apertures (bool, optional) – If true, aperture information is installed in the line.

  • apply_madx_errors (bool, optional) – If true, errors are applied to the line.

  • enable_field_errors (bool, optional) – If true, field errors are imported.

  • enable_align_errors (bool, optional) – If true, alignment errors are imported.

  • skip_markers (bool, optional) – If true, markers are skipped.

  • merge_drifts (bool, optional) – If true, consecutive drifts are merged.

  • merge_multipoles (bool, optional) – If true,consecutive multipoles are merged.

  • expressions_for_element_types (list, optional) – List of element types for which expressions are imported.

  • replace_in_expr (dict, optional) – Dictionary of replacements to be applied to expressions before they are imported.

  • classes (tuple, optional) – Tuple of classes to be used for the elements. If empty, the default classes are used.

  • ignored_madtypes (tuple, optional) – Tuple of MAD-X element types to be ignored.

  • allow_thick (bool, optional) – If true, thick elements are allowed. Otherwise, an error is raised if a thick element is encountered.

  • use_compound_elements (bool, optional) – If true, elements that are one element in madx but multiple elements in xtrack will be grouped together with a marker attached in front, and will be accessible through __getattr__. Otherwise, the line will be flattened.

Returns:

line – Line object.

Return type:

Line

to_dict(include_var_management=True)

Returns a dictionary representation of the line.

Parameters:

include_var_management (bool, optional) – If True (default) the dictionary will contain the information needed to restore the line with deferred expressions.

Returns:

out – Dictionary representation of the line.

Return type:

dict

to_json(file, **kwargs)

Save the line to a json file.

Parameters:
  • file (str or file-like object) – The file to save to. If a string is provided, a file is opened and closed. If a file-like object is provided, it is used directly.

  • **kwargs – Additional keyword arguments are passed to the Line.to_dict method.

to_pandas()

Return a pandas DataFrame with the elements of the line.

Returns:

line_df – DataFrame with the elements of the line.

Return type:

pandas.DataFrame

copy(_context=None, _buffer=None)

Return a copy of the line.

Parameters:
  • _context (xobjects.Context) – xobjects context to be used for the copy

  • _buffer (xobjects.Buffer) – xobjects buffer to be used for the copy

Returns:

line_copy – Copy of the line.

Return type:

Line

build_tracker(_context=None, _buffer=None, compile=True, io_buffer=None, use_prebuilt_kernels=True, enable_pipeline_hold=False, **kwargs)

Build the tracker associated to the line. This freezes the line (elements cannot be inserted or removed anymore). Use discard_tracker to unfreeze the line if needed.

Parameters:
  • _context (xobjects.Context, optional) – xobjects context to which the line data is moved and on which the tracking is performed. If not provided, the xobjects default context is used.

  • _buffer (xobjects.Buffer) – xobjects buffer to which the line data is moved. If not provided, the _buffer is creted from the _context.

  • compile (bool, optional) – If True (default) the tracker is compiled. If False, the tracker is not compiled until the first usage.

  • io_buffer (xobjects.Buffer, optional) – xobjects buffer to be used for the I/O. If not provided, a new buffer is created.

  • use_prebuilt_kernels (bool, optional) – If True (default) the prebuilt kernels are used if available. If False, the kernels are always compiled.

  • enable_pipeline_hold (bool, optional) – If True, the pipeline hold mechanism is enabled.

discard_tracker()

Discard the tracker associated to the line. This unfreezes the line (elements can be inserted or removed again).

track(particles, ele_start=0, ele_stop=None, num_elements=None, num_turns=None, turn_by_turn_monitor=None, freeze_longitudinal=False, time=False, with_progress=False, **kwargs)

Track particles through the line.

Parameters:
  • particles (xpart.Particles) – The particles to track

  • ele_start (int or str, optional) – The element to start tracking from (inclusive). If an integer is provided, it is interpreted as the index of the element in the line. If a string is provided, it is interpreted as the name of the element in the line.

  • ele_stop (int or str, optional) – The element to stop tracking at (exclusive). If an integer is provided, it is interpreted as the index of the element in the line. If a string is provided, it is interpreted as the name of the element in the line.

  • num_elements (int, optional) – The number of elements to track through. If ele_stop is not provided, this is the number of elements to track through from ele_start. If ele_stop is provided, num_elements should not be provided.

  • num_turns (int, optional) – The number of turns to track through. Defaults to 1.

  • backetrack (bool, optional) – If True, the particles are tracked backward from ele_stop to ele_start.

  • turn_by_turn_monitor (bool, str or xtrack.ParticlesMonitor, optional) – If True, a turn-by-turn monitor is created. If a monitor is provided, it is used directly. If the string ONE_TURN_EBE is provided, the particles coordinates are recorded at each element (one turn). The recorded data can be retrieved in line.record_last_track.

  • freeze_longitudinal (bool, optional) – If True, the longitudinal coordinates are frozen during tracking.

  • time (bool, optional) – If True, the time taken for tracking is recorded and can be retrieved in line.time_last_track.

  • with_progress (bool or int, optional) – If truthy, a progress bar is displayed during tracking. If an integer is provided, it is used as the number of turns between two updates of the progress bar. If True, 100 is taken by default. By default, equals to False and no progress bar is displayed.

slice_thick_elements(slicing_strategies)

Slice thick elements in the line. Slicing is done in place.

Parameters:

slicing_strategies (list) – List of slicing Strategy objects. In case multiple strategies apply to the same element, the last one takes precedence)

Examples

line.slice_thick_elements(
    slicing_strategies=[
        # Slicing with thin elements
        xt.Strategy(slicing=xt.Teapot(1)), # (1) Default applied to all elements
        xt.Strategy(slicing=xt.Uniform(2), element_type=xt.Bend), # (2) Selection by element type
        xt.Strategy(slicing=xt.Teapot(3), element_type=xt.Quadrupole),  # (4) Selection by element type
        xt.Strategy(slicing=xt.Teapot(4), name='mb1.*'), # (5) Selection by name pattern
        # Slicing with thick elements
        xt.Strategy(slicing=xt.Uniform(2, mode='thick'), name='mqf.*'), # (6) Selection by name pattern
        # Do not slice (leave untouched)
        xt.Strategy(slicing=None, name='mqd.1') # (7) Selection by name
])
build_particles(particle_ref=None, num_particles=None, x=None, px=None, y=None, py=None, zeta=None, delta=None, pzeta=None, x_norm=None, px_norm=None, y_norm=None, py_norm=None, zeta_norm=None, pzeta_norm=None, at_element=None, match_at_s=None, nemitt_x=None, nemitt_y=None, weight=None, particle_on_co=None, R_matrix=None, W_matrix=None, method=None, scale_with_transverse_norm_emitt=None, particles_class=None, _context=None, _buffer=None, _offset=None, _capacity=None, mode=None, **kwargs)

Create a Particles object from arrays containing physical or normalized coordinates.

Parameters:
  • particle_ref (Particle object) – Reference particle defining the reference quantities (mass0, q0, p0c, gamma0, etc.). Its coordinates (x, py, y, py, zeta, delta) are ignored unless `mode`=’shift’ is selected.

  • num_particles (int) – Number of particles to be generated (used if provided coordinates are all scalar).

  • x (float or array) – x coordinate of the particles in meters (default is 0).

  • px (float or array) – px coordinate of the particles (default is 0).

  • y (float or array) – y coordinate of the particles in meters (default is 0).

  • py (float or array) – py coordinate of the particles (default is 0).

  • zeta (float or array) – zeta coordinate of the particles in meters (default is 0).

  • delta (float or array) – delta coordinate of the particles (default is 0).

  • pzeta (float or array) – pzeta coordinate of the particles (default is 0).

  • x_norm (float or array) – transverse normalized coordinate x (in sigmas) used in combination with the one turn matrix and with the transverse emittances provided in the argument scale_with_transverse_norm_emitt to generate x, px, y, py (x, px, y, py cannot be provided if x_norm, px_norm, y_norm, py_norm are provided).

  • px_norm (float or array) – transverse normalized coordinate px (in sigmas) used in combination with the one turn matrix and with the transverse emittances (as above).

  • y_norm (float or array) – transverse normalized coordinate y (in sigmas) used in combination with the one turn matrix and with the transverse emittances (as above).

  • py_norm (float or array) – transverse normalized coordinate py (in sigmas) used in combination with the one turn matrix and with the transverse emittances (as above).

  • zeta_norm (float or array) – longitudinal normalized coordinate zeta (in sigmas) used in combination with the one turn matrix.

  • pzeta_norm (float or array) – longitudinal normalized coordinate pzeta (in sigmas) used in combination with the one turn matrix.

  • nemitt_x (float) – Transverse normalized emittance in the x plane.

  • nemitt_y (float) – Transverse normalized emittance in the y plane.

  • at_element (str or int) – Location within the line at which particles are generated. It can be an index or an element name.

  • match_at_s (float) – s location in meters within the line at which particles are generated. The value needs to be in the drift downstream of the element at at_element. The matched particles are backtracked to the element at at_element from which the tracking automatically starts when the generated particles are tracked.

  • weight (float or array) – weights to be assigned to the particles.

  • mode (str) –

    To be chosen between set, shift and normalized_transverse (the default mode is set. normalized_transverse is used if any if any of x_norm, px_norm, y_norm, py_norm is provided):

    • set: reference quantities including mass0, q0, p0c, gamma0,

      etc. are taken from the provided reference particle. Particles coordinates are set according to the provided input x, px, y, py, zeta, delta (zero is assumed as default for these variables).

    • shift: reference quantities including mass0, q0, p0c, gamma0,

      etc. are taken from the provided reference particle. Particles coordinates are set from the reference particles and shifted according to the provided input x, px, y, py, zeta, delta (zero is assumed as default for these variables).

    • normalized_transverse: reference quantities including mass0,

      q0, p0c, gamma0, etc. are taken from the provided reference particle. The longitudinal coordinates are set according to the provided input zeta, delta (zero is assumed as default for these variables). The transverse coordinates are set according to the provided input x_norm, px_norm, y_norm, py_norm (zero is assumed as default for these variables). The transverse coordinates are normalized according to the transverse emittance provided in nemitt_x and nemitt_y. The transverse coordinates are then transformed into physical space using the linearized one-turn matrix.

  • _capacity (int) – Capacity of the arrays to be created. If not provided, the capacity is set to the number of particles.

Returns:

particles – Particles object containing the generated particles.

Return type:

Particles object

twiss(particle_ref=None, method=None, particle_on_co=None, R_matrix=None, W_matrix=None, delta0=None, zeta0=None, r_sigma=None, nemitt_x=None, nemitt_y=None, delta_disp=None, delta_chrom=None, zeta_disp=None, co_guess=None, steps_r_matrix=None, co_search_settings=None, at_elements=None, at_s=None, continue_on_closed_orbit_error=None, freeze_longitudinal=None, freeze_energy=None, values_at_element_exit=None, radiation_method=None, eneloss_and_damping=None, start=None, end=None, init=None, num_turns=None, skip_global_quantities=None, matrix_responsiveness_tol=None, matrix_stability_tol=None, symplectify=None, reverse=None, use_full_inverse=None, strengths=None, hide_thin_groups=None, group_compound_elements=None, only_twiss_init=None, only_markers=None, only_orbit=None, compute_R_element_by_element=None, compute_lattice_functions=None, compute_chromatic_properties=None, init_at=None, x=None, px=None, y=None, py=None, zeta=None, delta=None, betx=None, alfx=None, bety=None, alfy=None, bets=None, dx=None, dpx=None, dy=None, dpy=None, dzeta=None, mux=None, muy=None, muzeta=None, ax_chrom=None, bx_chrom=None, ay_chrom=None, by_chrom=None, co_search_at=None, _continue_if_lost=None, _keep_tracking_data=None, _keep_initial_particles=None, _initial_particles=None, _ebe_monitor=None, ele_start='__discontinued__', ele_stop='__discontinued__', ele_init='__discontinued__', twiss_init='__discontinued__')

Compute the Twiss parameters of the beam line.

Parameters:
  • method ({'6d', '4d'}, optional) – Method to be used for the computation. If ‘6d’ the full 6D normal form is used. If ‘4d’ the 4D normal form is used.

  • start (int or str, optional) – Index of the element at which the computation starts. If not provided, the periodic sulution is computed. init must be provided if start is provided.

  • end (int or str, optional) – Index of the element at which the computation stops.

  • init (TwissInit object, optional) – Initial values for the Twiss parameters. If init=”periodic” is passed, the periodic solution for the selected range is computed.

  • delta0 (float, optional) – Initial value for the delta parameter.

  • zeta0 (float, optional) – Initial value for the zeta parameter.

  • freeze_longitudinal (bool, optional) – If True, the longitudinal motion is frozen.

  • only_markers (bool, optional) – If True, results are computed only at marker elements.

  • at_elements (list, optional) – List of elements at which the Twiss parameters are computed. If not provided, the Twiss parameters are computed at all elements.

  • at_s (list, optional) – List of positions in meters at which the Twiss parameters are computed. If not provided, the Twiss parameters are computed at all positions.

  • radiation_method ({'full', 'kick_as_co', 'scale_as_co'}, optional) – Method to be used for the computation of twiss parameters in the presence of radiation. If ‘full’ the method described in E. Forest, “From tracking code to analysis” is used. If ‘kick_as_co’ all particles receive the same radiation kicks as the closed orbit. If ‘scale_as_co’ all particles momenta are scaled by radiation as much as the closed orbit.

  • eneloss_and_damping (bool, optional) – If True, the energy loss and radiation damping constants are computed.

  • strengths (bool, optional) – If True, the strengths of the multipoles are added to the table.

  • hide_thin_groups (bool, optional) – If True, values associate to elements in thin groups are replacede with NaNs.

  • group_compound_elements (bool, optional) – If True, elements in compounds are grouped together.

  • values_at_element_exit (bool, optional (False)) – If True, the Twiss parameters are computed at the exit of the elements. If False (default), the Twiss parameters are computed at the entrance of the elements.

  • matrix_responsiveness_tol (float, optional) – Tolerance to be used tp check the responsiveness of the R matrix. If not provided, the default value is used.

  • matrix_stability_tol (float, optional) – Tolerance to be used tp check the stability of the R matrix. If not provided, the default value is used.

  • symplectify (bool, optional) – If True, the R matrix is symplectified before computing the linear normal form. Dafault is False.

Returns:

twiss

Twiss calculation results. The table contains the following element-by-element quantities:
  • s: position of the element in meters

  • name: name of the element

  • x: horizontal position in meters (closed orbit for periodic solution)

  • px: horizontal momentum (closed orbit for periodic solution)

  • y: vertical position in meters (closed orbit for periodic solution)

  • py: vertical momentum (closed orbit for periodic solution)

  • zeta: longitudinal position in meters (closed orbit for periodic solution)

  • delta: longitudinal momentum deviation (closed orbit for periodic solution)

  • ptau: longitudinal momentum deviation (closed orbit for periodic solution)

  • betx: horizontal beta function in meters

  • bety: vertical beta function in meters

  • alfx: horizontal alpha function

  • alfy: vertical alpha function

  • gamx: horizontal gamma function in 1/meters

  • gamy: vertical gamma function in 1/meters

  • mux: horizontal phase advance in tune units (angle/2/pi)

  • muy: vertical phase advance in tune units (angle/2/pi)

  • muzeta: longitudinal phase advance in tune units (angle/2/pi)

  • dx: horizontal dispersion (d x / d delta) in meters

  • dy: vertical dispersion (d y / d delta) in meters

  • dzeta: longitudinal dispersion (d zeta / d delta) in meters

  • dpx: horizontal dispersion (d px / d delta)

  • dpy: vertical dispersion (d y / d delta)

  • dx_zeta: horizontal crab dispersion (d x / d zeta)

  • dy_zeta: vertical crab dispersion (d y / d zeta)

  • dpx_zeta: horizontal crab dispersion (d px / d zeta)

  • dpy_zeta: vertical crab dispersion (d py / d zeta)

  • ax_chrom: chromatic function (d alfx / d delta - alfx / betx d betx / d delta)

  • ay_chrom: chromatic function (d alfy / d delta - alfy / bety d bety / d delta)

  • bx_chrom: chromatic function (d betx / d delta)

  • by_chrom: chromatic function (d bety / d delta)

  • wx_chrom: sqrt(ax_chrom**2 + bx_chrom**2)

  • wy_chrom: sqrt(ay_chrom**2 + by_chrom**2)

  • W_matrix: W matrix of the linear normal form

  • betx1: computed horizontal beta function (Mais-Ripken) in meters

  • bety1: computed vertical beta function (Mais-Ripken) in meters

  • betx2: computed horizontal beta function (Mais-Ripken) in meters

  • bety2: computed vertical beta function (Mais-Ripken) in meters

The table also contains the following global quantities:
  • qx: horizontal tune

  • qy: vertical tune

  • qs: synchrotron tune

  • dqx: horizontal chromaticity (d qx / d delta)

  • dqy: vertical chromaticity (d qy / d delta)

  • c_minus: closest tune approach coefficient

  • slip_factor: slip factor (-1 / f_ref * d f_ref / d delta) (positive above transition)

  • momentum_compaction_factor: momentum compaction factor (slip_factor + 1/gamma_0^2)

  • T_rev0: reference revolution period in seconds

  • circumference: reference trajectory length in meters

  • partice_on_co: particle on closed orbit

  • R_matrix: R matrix (if calculated or provided)

  • eneloss_turn, energy loss per turn in electron volts (if eneloss_and_damping is True)

  • damping_constants_turns, radiation damping constants per turn (if eneloss_and_damping is True)

  • damping_constants_s: radiation damping constants per second (if eneloss_and_damping is True)

  • partition_numbers: radiation partition numbers (if eneloss_and_damping is True)

Return type:

xtrack.TwissTable

Notes

The following additional parameters can also be provided:

  • particle_on_coxpart.Particles, optional

    Particle on the closed orbit. If not provided, the closed orbit is searched for.

  • R_matrixnp.ndarray, optional

    R matrix to be used for the computation. If not provided, the R matrix is computed using finite differences.

  • W_matrixnp.ndarray, optional

    W matrix to be used for the computation. If not provided, the W matrix is computed from the R matrix.

  • co_guessxpart.Particles or dict, optional

    Initial guess for the closed orbit. If not provided, zero is assumed.

  • co_search_settingsdict, optional

    Settings to be used for the closed orbit search. If not provided, the default values are used.

  • num_turns: int, optional

    If specified the periodic solution and the twiss table are computed on multiple turns.

  • continue_on_closed_orbit_errorbool, optional

    If True, the computation is continued even if the closed orbit search fails.

  • delta_dispfloat, optional

    Momentum deviation for the dispersion computation.

  • delta_chromfloat, optional

    Momentum deviation for the chromaticity computation.

  • skip_global_quantitiesbool, optional

    If True, the global quantities are not computed.

  • use_full_inversebool, optional

    If True, the full inverse of the W matrik is used. If False, the inverse is computed from the symplectic condition.

  • steps_r_matrixdict, optional

    Steps to be used for the finite difference computation of the R matrix. If not provided, the default values are used.

  • r_sigmafloat, optional

    Deviation in sigmas used for the propagation of the W matrix. Initial value for the r_sigma parameter.

  • nemitt_xfloat, optional

    Horizontal emittance assumed for the comutation of the deviation used for the propagation of the W matrix.

  • nemitt_yfloat, optional

    Vertical emittance assumed for the comutation of the deviation used for the propagation of the W matrix.

match(vary, targets, solve=True, assert_within_tol=True, compensate_radiation_energy_loss=False, solver_options={}, allow_twiss_failure=True, restore_if_fail=True, verbose=False, n_steps_max=20, default_tol=None, solver=None, **kwargs)

Change a set of knobs in the beamline in order to match assigned targets.

Parameters:
  • vary (list of str or list of Vary objects) – List of knobs to be varied. Each knob can be a string or a Vary object including the knob name and the step used for computing the Jacobian for the optimization.

  • targets (list of Target objects) – List of targets to be matched.

  • solve (bool) – If True (default), the matching is performed immediately. If not an Optimize object is returnd, which can be used for advanced matching.

  • assert_within_tol (bool) – If True (default), an exception is raised if the matching fails.

  • compensate_radiation_energy_loss (bool) – If True, the radiation energy loss is compensated at each step of the matching.

  • solver_options (dict) – Dictionary of options to be passed to the solver.

  • allow_twiss_failure (bool) – If True (default), the matching continues if the twiss computation computation fails at some of the steps.

  • restore_if_fail (bool) – If True (default), the beamline is restored to its initial state if the matching fails.

  • verbose (bool) – If True, the matching steps are printed.

  • n_steps_max (int) – Maximum number of steps for the matching before matching is stopped.

  • default_tol (float) – Default tolerances used on the target. A dictionary can be provided associating a tolerance to each target name. The tolerance provided for None is used for all targets for which a tolerance is not otherwise provided. Example: default_tol={‘betx’: 1e-4, None: 1e-6}.

  • solver (str) – Solver to be used for the matching. Available solvers are jacobian (default), and fsolve.

  • **kwargs (dict) – Additional arguments to be passed to the twiss.

Returns:

optimizer – xdeps optimizer object used for the optimization.

Return type:

xdeps.Optimize

Examples

# Match tunes and chromaticities to assigned values
line.match(
    vary=[
        xt.Vary('kqtf.b1', step=1e-8),
        xt.Vary('kqtd.b1', step=1e-8),
        xt.Vary('ksf.b1', step=1e-8),
        xt.Vary('ksd.b1', step=1e-8),
    ],
    targets = [
        xt.Target('qx', 62.315, tol=1e-4),
        xt.Target('qy', 60.325, tol=1e-4),
        xt.Target('dqx', 10.0, tol=0.05),
        xt.Target('dqy', 12.0, tol=0.05)]
)
# Match a local orbit bump
tw_before = line.twiss()

line.match(
    start='mq.33l8.b1',
    end='mq.23l8.b1',
    init=tw_before.get_twiss_init(at_element='mq.33l8.b1'),
    vary=[
        xt.Vary(name='acbv30.l8b1', step=1e-10),
        xt.Vary(name='acbv28.l8b1', step=1e-10),
        xt.Vary(name='acbv26.l8b1', step=1e-10),
        xt.Vary(name='acbv24.l8b1', step=1e-10),
    ],
    targets=[
        # I want the vertical orbit to be at 3 mm at mq.28l8.b1 with zero angle
        xt.Target('y', at='mb.b28l8.b1', value=3e-3, tol=1e-4, scale=1),
        xt.Target('py', at='mb.b28l8.b1', value=0, tol=1e-6, scale=1000),
        # I want the bump to be closed
        xt.Target('y', at='mq.23l8.b1', value=tw_before['y', 'mq.23l8.b1'],
                tol=1e-6, scale=1),
        xt.Target('py', at='mq.23l8.b1', value=tw_before['py', 'mq.23l8.b1'],
                tol=1e-7, scale=1000),
    ]
)
match_knob(knob_name, vary, targets, knob_value_start=0, knob_value_end=1, **kwargs)

Match a new knob in the beam line such that the specified targets are matched when the knob is set to the value knob_value_end and the state of the line before tha matching is recovered when the knob is set to the value knob_value_start.

Parameters:
  • knob_name (str) – Name of the knob to be matched.

  • vary (list of str or list of Vary objects) – List of existing knobs to be varied.

  • targets (list of Target objects) – List of targets to be matched.

  • knob_value_start (float) – Value of the knob before the matching. Defaults to 0.

  • knob_value_end (float) – Value of the knob after the matching. Defaults to 1.

survey(X0=0, Y0=0, Z0=0, theta0=0, phi0=0, psi0=0, element0=0, reverse=False)

Returns a survey of the beamline (based on MAD-X survey command).

Parameters:
  • X0 (float) – Initial X coordinate in meters.

  • Y0 (float) – Initial Y coordinate in meters.

  • Z0 (float) – Initial Z coordinate in meters.

  • theta0 (float) – Initial theta coordinate in radians.

  • phi0 (float) – Initial phi coordinate in radians.

  • psi0 (float) – Initial psi coordinate in radians.

  • element0 (int or str) – Element at which the given coordinates are defined.

Returns:

survey – Survey table.

Return type:

SurveyTable

correct_closed_orbit(reference, correction_config, solver=None, verbose=False, restore_if_fail=True)

Correct the closed orbit of the beamline through a set of local matches.

Parameters:
  • reference (Line) – Line on which the reference closed orbit is computed.

  • correction_config (dict) – Dictionary containing the configuration for the closed orbit correction. The dictionary must have the structure shown in the example below.

  • solver (str) – Solver to be used for the matching. Available solvers are “fsolve” and “bfgs”.

  • verbose (bool) – If True, the matching steps are printed.

  • restore_if_fail (bool) – If True, the beamline is restored to its initial state if the matching fails.

Examples

correction_config = {
    'IR1 left': dict(
        ref_with_knobs={'on_corr_co': 0, 'on_disp': 0},
        start='e.ds.r8.b1',
        end='e.ds.l1.b1',
        vary=(
            'corr_co_acbh14.l1b1',
            'corr_co_acbh12.l1b1',
            'corr_co_acbv15.l1b1',
            'corr_co_acbv13.l1b1',
            ),
        targets=('e.ds.l1.b1',),
    ),
    'IR1 right': dict(
        ref_with_knobs={'on_corr_co': 0, 'on_disp': 0},
        start='s.ds.r1.b1',
        end='s.ds.l2.b1',
        vary=(
            'corr_co_acbh13.r1b1',
            'corr_co_acbh15.r1b1',
            'corr_co_acbv12.r1b1',
            'corr_co_acbv14.r1b1',
            ),
        targets=('s.ds.l2.b1',),
    ),
    ...
}

line.correct_closed_orbit(
    reference=line_reference,
    correction_config=correction_config)
find_closed_orbit(co_guess=None, particle_ref=None, co_search_settings={}, delta_zeta=0, delta0=None, zeta0=None, continue_on_closed_orbit_error=False, freeze_longitudinal=False, start=None, end=None, num_turns=1, co_search_at=None)

Find the closed orbit of the beamline.

Parameters:
  • co_guess (Particles or dict) – Particle used as first guess to compute the closed orbit. If None, the reference particle is used.

  • particle_ref (Particle) – Particle used to compute the closed orbit. If None, the reference particle is used.

  • co_search_settings (dict) – Dictionary containing the settings for the closed orbit search (passed as keyword arguments to the scipy.fsolve function)

  • delta_zeta (float) – Initial delta_zeta coordinate.

  • delta0 (float) – Initial delta coordinate.

  • zeta0 (float) – Initial zeta coordinate in meters.

  • continue_on_closed_orbit_error (bool) – If True, the closed orbit at the last step is returned even if the closed orbit search fails.

  • freeze_longitudinal (bool) – If True, the longitudinal coordinates are frozen during the closed orbit search.

  • start (int or str) – Optional. It can be provided to find the periodic solution for a portion of the beamline.

  • end (int or str) – Optional. It can be provided to find the periodic solution for a portion of the beamline.

  • num_turns (int) – Number of turns to be used for the closed orbit search.

  • co_search_at (int or str) – Element at which the closed orbit search is performed. If None, the closed orbit search is performed at the start of the line.

Returns:

particle_on_co – Particle at the closed orbit.

Return type:

Particle

compute_T_matrix(start=None, end=None, particle_on_co=None, steps_t_matrix=None)

Compute the second order tensor of the beamline.

Parameters:
  • start (int or str) – Element at which the computation starts.

  • end (int or str) – Element at which the computation stops.

  • particle_on_co (Particle) – Particle at the closed orbit (optional).

  • steps_r_matrix (int) – Finite difference step for computing the second order tensor.

Returns:

T_matrix – Second order tensor of the beamline.

Return type:

ndarray

get_footprint(nemitt_x=None, nemitt_y=None, n_turns=256, n_fft=262144, mode='polar', r_range=None, theta_range=None, n_r=None, n_theta=None, x_norm_range=None, y_norm_range=None, n_x_norm=None, n_y_norm=None, linear_rescale_on_knobs=None, freeze_longitudinal=None, delta0=None, zeta0=None, keep_fft=True, keep_tracking_data=False)

Compute the tune footprint for a beam with given emittences using tracking.

Parameters:
  • nemitt_x (float) – Normalized emittance in the x-plane.

  • nemitt_y (float) – Normalized emittance in the y-plane.

  • n_turns (int) – Number of turns for tracking.

  • n_fft (int) – Number of points for FFT (tracking data is zero-padded to this length).

  • mode (str) – Mode for computing footprint. Options are ‘polar’ and ‘uniform_action_grid’. In ‘polar’ mode, the footprint is computed on a polar grid with r_range and theta_range specifying the range of r and theta values ( polar coordinates in the x_norm, y_norm plane). In ‘uniform_action_grid’ mode, the footprint is computed on a uniform grid in the action space (Jx, Jy).

  • r_range (tuple of floats) – Range of r values for footprint in polar mode. Default is (0.1, 6) sigmas.

  • theta_range (tuple of floats) – Range of theta values in radians for footprint in polar mode. Default is (0.05, pi / 2 - 0.05) radians.

  • n_r (int) – Number of r values for footprint in polar mode. Default is 10.

  • n_theta (int) – Number of theta values for footprint in polar mode. Default is 10.

  • x_norm_range (tuple of floats) – Range of x_norm values for footprint in uniform action grid mode. Default is (0.1, 6) sigmas.

  • y_norm_range (tuple of floats) – Range of y_norm values for footprint in uniform action grid mode. Default is (0.1, 6) sigmas.

  • n_x_norm (int) – Number of x_norm values for footprint in uniform action grid mode. Default is 10.

  • n_y_norm (int) – Number of y_norm values for footprint in uniform action grid mode. Default is 10.

  • linear_rescale_on_knobs (list of xt.LinearRescale) –

    Detuning from listed knobs is evaluated at a given value of the knob with the provided step and rescaled to the actual knob value. This is useful to avoid artefact from linear coupling or resonances. Example:

    ``line.get_footprint(…, linear_rescale_on_knobs=[

    xt.LinearRescale(knob_name=’beambeam_scale’, v0=0, dv-0.1)])``

  • freeze_longitudinal (bool) – If True, the longitudinal coordinates are frozen during the particles matching and the tracking.

  • delta0 (float) – Initial value of the delta coordinate.

  • zeta0 (float) – Initial value of the zeta coordinate in meters.

Returns:

fp – Footprint object containing footprint data (fp.qx, fp.qy).

Return type:

Footprint

get_amplitude_detuning_coefficients(nemitt_x=1e-06, nemitt_y=1e-06, num_turns=256, a0_sigmas=0.01, a1_sigmas=0.1, a2_sigmas=0.2)

Compute the amplitude detuning coefficients (det_xx = dQx / dJx, det_yy = dQy / dJy, det_xy = dQx / dJy, det_yx = dQy / dJx) using tracking.

Parameters:
  • nemitt_x (float) – Normalized emittance in the x-plane. Default is 1e-6.

  • nemitt_y (float) – Normalized emittance in the y-plane. Default is 1e-6.

  • num_turns (int) – Number of turns for tracking. Default is 256.

  • a0_sigmas (float) – Amplitude of the first particle (in sigmas). Default is 0.01.

  • a1_sigmas (float) – Amplitude of the second particle (in sigmas). Default is 0.1.

  • a2_sigmas (float) – Amplitude of the third particle (in sigmas). Default is 0.2.

Returns:

  • det_xx (float) – Amplitude detuning coefficient dQx / dJx.

  • det_yy (float) – Amplitude detuning coefficient dQy / dJy.

  • det_xy (float) – Amplitude detuning coefficient dQx / dJy.

  • det_yx (float) – Amplitude detuning coefficient dQy / dJx.

compute_one_turn_matrix_finite_differences(particle_on_co, steps_r_matrix=None, start=None, end=None, num_turns=1, element_by_element=False, only_markers=False)

Compute the one turn matrix using finite differences.

Parameters:
  • particle_on_co (Particle) – Particle at the closed orbit.

  • steps_r_matrix (float) – Step size for finite differences. In not given, default step sizes are used.

  • start (str) – Optional. It can be used to find the periodic solution for a portion of the line.

  • end (str) – Optional. It can be used to find the periodic solution for a portion of the line.

Returns:

one_turn_matrix – One turn matrix.

Return type:

np.ndarray

get_length()

Get total length of the line

get_s_elements(mode='upstream')

Get s position for all elements

Parameters:

mode (str) – “upstream” or “downstream” (default: “upstream”)

Returns:

s – s position for all elements

Return type:

list of float

get_s_position(at_elements=None, mode='upstream')

Get s position for given elements

Parameters:
  • at_elements (str or list of str) – Name of the element(s) to get s position for (default: all elements)

  • mode (str) – “upstream” or “downstream” (default: “upstream”)

Returns:

s – s position for given element(s)

Return type:

float or list of float

insert_element(name, element=None, index=None, at_s=None, s_tol=1e-06)

Insert an element in the line.

Parameters:
  • name (str) – Name of the element.

  • index (int, optional) – Index of the element in the line. If index is provided, at_s must be None.

  • element (xline.Element, optional) – Element to be inserted. If not given, the element of the given name already present in the line is used.

  • at_s (float, optional) – Position of the element in the line in meters. If at_s is provided, index must be None.

  • s_tol (float, optional) – Tolerance for the position of the element in the line in meters.

get_compound_by_name(name) Optional[Union[SlicedCompound, Compound]]

Get a compound object by its name.

get_compound_subsequence(name) List[str]

The sequence of element names corresponding to the compound name.

Equivalent to sorted(compound.elements, key=self.element_names.index) but should be faster due to the assumption that compounds are contiguous.

get_compound_for_element(name) Optional[str]

Get the compound name for an element name.

get_element_compound_names() List[Optional[str]]

Get the compound names for all elements.

get_compound_mask() List[bool]

The mask of elements that are entry to a compound, or not in one.

append_element(element, name)

Append element to the end of the lattice

Parameters:
  • element (object) – Element to append

  • name (str) – Name of the element to append

filter_elements(mask=None, exclude_types_starting_with=None)

Return a new line with only the elements satisfying a given condition. Other elements are replaced with Drifts.

Parameters:
  • mask (list of bool) – A list of booleans with the same length as the line. If True, the element is kept, otherwise it is replaced with a Drift.

  • exclude_types_starting_with (str) – If not None, all elements whose type starts with the given string are replaced with Drifts.

Returns:

new_line – A new line with only the elements satisfying the condition. Other elements are replaced with Drifts.

Return type:

Line

cycle(index_first_element=None, name_first_element=None, inplace=False)

Cycle the line to start from a given element.

Parameters:
  • index_first_element (int) – Index of the element to start from

  • name_first_element (str) – Name of the element to start from

  • inplace (bool) – If True, the line is modified in place. Otherwise, a new line is returned.

Returns:

new_line – A new line with the elements cycled.

Return type:

Line

freeze_energy(state=True, force=False)

Freeze energy in tracked Particles objects.

Parameters:

state (bool) – If True, energy is frozen. If False, it is unfrozen.

freeze_longitudinal(state=True)

Freeze longitudinal coordinates in tracked Particles objects.

Parameters:

state (bool) – If True, longitudinal coordinates are frozen. If False, they are unfrozen.

freeze_vars(variable_names)

Freeze variables in tracked Particles objects.

Parameters:

variable_names (list of str) – List of variable names to freeze.

unfreeze_vars(variable_names)

Unfreeze variables in tracked Particles objects.

Parameters:

variable_names (list of str) – List of variable names to unfreeze.

configure_bend_model(core=None, edge=None)

Configure the method used to track bends.

Parameters:
  • core (str) – Medel to be used for the thick bend cores. Can be ‘expanded’ or ‘ full’.

  • edge (str) – Model to be used for the bend edges. Can be ‘linear’, ‘full’ or ‘suppressed’.

configure_radiation(model=None, model_beamstrahlung=None, model_bhabha=None, mode='deprecated')

Configure radiation within the line.

Parameters:
  • model (str) – Radiation model to use. Can be ‘mean’, ‘quantum’ or None.

  • model_beamstrahlung (str) – Beamstrahlung model to use. Can be ‘mean’, ‘quantum’ or None.

  • model_bhabha (str) – Bhabha model to use. Can be ‘quantum’ or None.

compensate_radiation_energy_loss(delta0=0, rtol_eneloss=1e-10, max_iter=100, **kwargs)

Compensate beam energy loss from synchrotron radiation by configuring RF cavities and Multipole elements (tapering).

Parameters:
  • delta0 (float) – Initial energy deviation.

  • rtol_eneloss (float) – Relative tolerance on energy loss.

  • max_iter (int) – Maximum number of iterations.

  • kwargs (dict) – Additional keyword arguments passed to the twiss method.

optimize_for_tracking(compile=True, verbose=True, keep_markers=False)

Optimize the line for tracking by removing inactive elements and merging consecutive elements where possible. Deferred expressions are disabled.

Parameters:
  • compile (bool) – If True (default), the tracker is recompiled.

  • verbose (bool) – If True (default), print information about the optimization.

  • keep_markers (bool or list of str) – If True, all markers are kept.

start_internal_logging_for_elements_of_type(element_type, capacity)

Start internal logging for all elements of a given type.

Parameters:
  • element_type (str) – Type of the elements for which internal logging is started.

  • capacity (int) – Capacity of the internal record.

Returns:

record – Record object containing the elements internal logging.

Return type:

Record

stop_internal_logging_for_elements_of_type(element_type)

Stop internal logging for all elements of a given type.

Parameters:

element_type (str) – Type of the elements for which internal logging is stopped.

remove_markers(inplace=True, keep=None)

Remove markers from the line

Parameters:
  • inplace (bool) – If True, remove markers from the line (default: True)

  • keep (str or list of str) – Name of the markers to keep (default: None)

remove_inactive_multipoles(inplace=True, keep=None)

Remove inactive multipoles from the line

Parameters:
  • inplace (bool) – If True, remove inactive multipoles from the line (default: True), otherwise return a new line.

  • keep (str or list of str) – Name of the multipoles to keep (default: None)

Returns:

line – Line with inactive multipoles removed

Return type:

Line

remove_zero_length_drifts(inplace=True, keep=None)

Remove zero length drifts from the line

Parameters:
  • inplace (bool) – If True, remove zero length drifts from the line (default: True), otherwise return a new line.

  • keep (str or list of str) – Name of the drifts to keep (default: None)

Returns:

line – Line with zero length drifts removed

Return type:

Line

merge_consecutive_drifts(inplace=True, keep=None)

Merge consecutive drifts into a single drift

Parameters:
  • inplace (bool) – If True, merge consecutive drifts in the line (default: True), otherwise return a new line.

  • keep (str or list of str) – Name of the drifts to keep (default: None)

Returns:

line – Line with consecutive drifts merged

Return type:

Line

remove_redundant_apertures(inplace=True, keep=None, drifts_that_need_aperture=[])

Remove redundant apertures from the line

Parameters:
  • inplace (bool) – If True, remove redundant apertures from the line (default: True), otherwise return a new line.

  • keep (str or list of str) – Name of the apertures to keep (default: None)

  • drifts_that_need_aperture (list of str) – Names of drifts that need an aperture (default: [])

Returns:

line – Line with redundant apertures removed

Return type:

Line

use_simple_quadrupoles()

Replace multipoles having only the normal quadrupolar component with quadrupole elements. The element is not replaced when synchrotron radiation is active.

use_simple_bends()

Replace multipoles having only the horizontal dipolar component with dipole elements. The element is not replaced when synchrotron radiation is active.

get_elements_of_type(types)

Get all elements of given type(s)

Parameters:

types (type or list of types) – Type(s) of elements to get

Returns:

  • elements (list of elements) – List of elements of given type(s)

  • names (list of str) – List of names of elements of given type(s)

check_aperture(needs_aperture=[])

Check that all active elements have an associated aperture.

Parameters:

needs_aperture (list of str) – Names of inactive elements that also need an aperture.

Returns:

elements_df – DataFrame with information about the apertures associated with each active element.

Return type:

pandas.DataFrame

merge_consecutive_multipoles(inplace=True, keep=None)

Merge consecutive multipoles into one multipole.

Parameters:
  • inplace (bool, optional) – If True, the line is modified in place. If False, a new line is returned.

  • keep (str or list of str, optional) – Names of elements that should not be merged. If None, no elements are kept.

Returns:

line – The modified line.

Return type:

Line

get_line_with_second_order_maps(split_at)

Return a new lines with segments definded by the elements in split_at replaced by second order maps.

Parameters:

split_at (list of str) – Names of elements at which to split the line.

Returns:

line_maps – Line with segments replaced by second order maps.

Return type:

Line

property name

Name of the line (if it is part of a MultiLine)

Track

See also: Single particle tracking, Tracking with collective elements.

Line.track(particles, ele_start=0, ele_stop=None, num_elements=None, num_turns=None, turn_by_turn_monitor=None, freeze_longitudinal=False, time=False, with_progress=False, **kwargs)

Track particles through the line.

Parameters:
  • particles (xpart.Particles) – The particles to track

  • ele_start (int or str, optional) – The element to start tracking from (inclusive). If an integer is provided, it is interpreted as the index of the element in the line. If a string is provided, it is interpreted as the name of the element in the line.

  • ele_stop (int or str, optional) – The element to stop tracking at (exclusive). If an integer is provided, it is interpreted as the index of the element in the line. If a string is provided, it is interpreted as the name of the element in the line.

  • num_elements (int, optional) – The number of elements to track through. If ele_stop is not provided, this is the number of elements to track through from ele_start. If ele_stop is provided, num_elements should not be provided.

  • num_turns (int, optional) – The number of turns to track through. Defaults to 1.

  • backetrack (bool, optional) – If True, the particles are tracked backward from ele_stop to ele_start.

  • turn_by_turn_monitor (bool, str or xtrack.ParticlesMonitor, optional) – If True, a turn-by-turn monitor is created. If a monitor is provided, it is used directly. If the string ONE_TURN_EBE is provided, the particles coordinates are recorded at each element (one turn). The recorded data can be retrieved in line.record_last_track.

  • freeze_longitudinal (bool, optional) – If True, the longitudinal coordinates are frozen during tracking.

  • time (bool, optional) – If True, the time taken for tracking is recorded and can be retrieved in line.time_last_track.

  • with_progress (bool or int, optional) – If truthy, a progress bar is displayed during tracking. If an integer is provided, it is used as the number of turns between two updates of the progress bar. If True, 100 is taken by default. By default, equals to False and no progress bar is displayed.

Twiss

See also: Twiss.

Line.twiss(particle_ref=None, method=None, particle_on_co=None, R_matrix=None, W_matrix=None, delta0=None, zeta0=None, r_sigma=None, nemitt_x=None, nemitt_y=None, delta_disp=None, delta_chrom=None, zeta_disp=None, co_guess=None, steps_r_matrix=None, co_search_settings=None, at_elements=None, at_s=None, continue_on_closed_orbit_error=None, freeze_longitudinal=None, freeze_energy=None, values_at_element_exit=None, radiation_method=None, eneloss_and_damping=None, start=None, end=None, init=None, num_turns=None, skip_global_quantities=None, matrix_responsiveness_tol=None, matrix_stability_tol=None, symplectify=None, reverse=None, use_full_inverse=None, strengths=None, hide_thin_groups=None, group_compound_elements=None, only_twiss_init=None, only_markers=None, only_orbit=None, compute_R_element_by_element=None, compute_lattice_functions=None, compute_chromatic_properties=None, init_at=None, x=None, px=None, y=None, py=None, zeta=None, delta=None, betx=None, alfx=None, bety=None, alfy=None, bets=None, dx=None, dpx=None, dy=None, dpy=None, dzeta=None, mux=None, muy=None, muzeta=None, ax_chrom=None, bx_chrom=None, ay_chrom=None, by_chrom=None, co_search_at=None, _continue_if_lost=None, _keep_tracking_data=None, _keep_initial_particles=None, _initial_particles=None, _ebe_monitor=None, ele_start='__discontinued__', ele_stop='__discontinued__', ele_init='__discontinued__', twiss_init='__discontinued__')

Compute the Twiss parameters of the beam line.

Parameters:
  • method ({'6d', '4d'}, optional) – Method to be used for the computation. If ‘6d’ the full 6D normal form is used. If ‘4d’ the 4D normal form is used.

  • start (int or str, optional) – Index of the element at which the computation starts. If not provided, the periodic sulution is computed. init must be provided if start is provided.

  • end (int or str, optional) – Index of the element at which the computation stops.

  • init (TwissInit object, optional) – Initial values for the Twiss parameters. If init=”periodic” is passed, the periodic solution for the selected range is computed.

  • delta0 (float, optional) – Initial value for the delta parameter.

  • zeta0 (float, optional) – Initial value for the zeta parameter.

  • freeze_longitudinal (bool, optional) – If True, the longitudinal motion is frozen.

  • only_markers (bool, optional) – If True, results are computed only at marker elements.

  • at_elements (list, optional) – List of elements at which the Twiss parameters are computed. If not provided, the Twiss parameters are computed at all elements.

  • at_s (list, optional) – List of positions in meters at which the Twiss parameters are computed. If not provided, the Twiss parameters are computed at all positions.

  • radiation_method ({'full', 'kick_as_co', 'scale_as_co'}, optional) – Method to be used for the computation of twiss parameters in the presence of radiation. If ‘full’ the method described in E. Forest, “From tracking code to analysis” is used. If ‘kick_as_co’ all particles receive the same radiation kicks as the closed orbit. If ‘scale_as_co’ all particles momenta are scaled by radiation as much as the closed orbit.

  • eneloss_and_damping (bool, optional) – If True, the energy loss and radiation damping constants are computed.

  • strengths (bool, optional) – If True, the strengths of the multipoles are added to the table.

  • hide_thin_groups (bool, optional) – If True, values associate to elements in thin groups are replacede with NaNs.

  • group_compound_elements (bool, optional) – If True, elements in compounds are grouped together.

  • values_at_element_exit (bool, optional (False)) – If True, the Twiss parameters are computed at the exit of the elements. If False (default), the Twiss parameters are computed at the entrance of the elements.

  • matrix_responsiveness_tol (float, optional) – Tolerance to be used tp check the responsiveness of the R matrix. If not provided, the default value is used.

  • matrix_stability_tol (float, optional) – Tolerance to be used tp check the stability of the R matrix. If not provided, the default value is used.

  • symplectify (bool, optional) – If True, the R matrix is symplectified before computing the linear normal form. Dafault is False.

Returns:

twiss

Twiss calculation results. The table contains the following element-by-element quantities:
  • s: position of the element in meters

  • name: name of the element

  • x: horizontal position in meters (closed orbit for periodic solution)

  • px: horizontal momentum (closed orbit for periodic solution)

  • y: vertical position in meters (closed orbit for periodic solution)

  • py: vertical momentum (closed orbit for periodic solution)

  • zeta: longitudinal position in meters (closed orbit for periodic solution)

  • delta: longitudinal momentum deviation (closed orbit for periodic solution)

  • ptau: longitudinal momentum deviation (closed orbit for periodic solution)

  • betx: horizontal beta function in meters

  • bety: vertical beta function in meters

  • alfx: horizontal alpha function

  • alfy: vertical alpha function

  • gamx: horizontal gamma function in 1/meters

  • gamy: vertical gamma function in 1/meters

  • mux: horizontal phase advance in tune units (angle/2/pi)

  • muy: vertical phase advance in tune units (angle/2/pi)

  • muzeta: longitudinal phase advance in tune units (angle/2/pi)

  • dx: horizontal dispersion (d x / d delta) in meters

  • dy: vertical dispersion (d y / d delta) in meters

  • dzeta: longitudinal dispersion (d zeta / d delta) in meters

  • dpx: horizontal dispersion (d px / d delta)

  • dpy: vertical dispersion (d y / d delta)

  • dx_zeta: horizontal crab dispersion (d x / d zeta)

  • dy_zeta: vertical crab dispersion (d y / d zeta)

  • dpx_zeta: horizontal crab dispersion (d px / d zeta)

  • dpy_zeta: vertical crab dispersion (d py / d zeta)

  • ax_chrom: chromatic function (d alfx / d delta - alfx / betx d betx / d delta)

  • ay_chrom: chromatic function (d alfy / d delta - alfy / bety d bety / d delta)

  • bx_chrom: chromatic function (d betx / d delta)

  • by_chrom: chromatic function (d bety / d delta)

  • wx_chrom: sqrt(ax_chrom**2 + bx_chrom**2)

  • wy_chrom: sqrt(ay_chrom**2 + by_chrom**2)

  • W_matrix: W matrix of the linear normal form

  • betx1: computed horizontal beta function (Mais-Ripken) in meters

  • bety1: computed vertical beta function (Mais-Ripken) in meters

  • betx2: computed horizontal beta function (Mais-Ripken) in meters

  • bety2: computed vertical beta function (Mais-Ripken) in meters

The table also contains the following global quantities:
  • qx: horizontal tune

  • qy: vertical tune

  • qs: synchrotron tune

  • dqx: horizontal chromaticity (d qx / d delta)

  • dqy: vertical chromaticity (d qy / d delta)

  • c_minus: closest tune approach coefficient

  • slip_factor: slip factor (-1 / f_ref * d f_ref / d delta) (positive above transition)

  • momentum_compaction_factor: momentum compaction factor (slip_factor + 1/gamma_0^2)

  • T_rev0: reference revolution period in seconds

  • circumference: reference trajectory length in meters

  • partice_on_co: particle on closed orbit

  • R_matrix: R matrix (if calculated or provided)

  • eneloss_turn, energy loss per turn in electron volts (if eneloss_and_damping is True)

  • damping_constants_turns, radiation damping constants per turn (if eneloss_and_damping is True)

  • damping_constants_s: radiation damping constants per second (if eneloss_and_damping is True)

  • partition_numbers: radiation partition numbers (if eneloss_and_damping is True)

Return type:

xtrack.TwissTable

Notes

The following additional parameters can also be provided:

  • particle_on_coxpart.Particles, optional

    Particle on the closed orbit. If not provided, the closed orbit is searched for.

  • R_matrixnp.ndarray, optional

    R matrix to be used for the computation. If not provided, the R matrix is computed using finite differences.

  • W_matrixnp.ndarray, optional

    W matrix to be used for the computation. If not provided, the W matrix is computed from the R matrix.

  • co_guessxpart.Particles or dict, optional

    Initial guess for the closed orbit. If not provided, zero is assumed.

  • co_search_settingsdict, optional

    Settings to be used for the closed orbit search. If not provided, the default values are used.

  • num_turns: int, optional

    If specified the periodic solution and the twiss table are computed on multiple turns.

  • continue_on_closed_orbit_errorbool, optional

    If True, the computation is continued even if the closed orbit search fails.

  • delta_dispfloat, optional

    Momentum deviation for the dispersion computation.

  • delta_chromfloat, optional

    Momentum deviation for the chromaticity computation.

  • skip_global_quantitiesbool, optional

    If True, the global quantities are not computed.

  • use_full_inversebool, optional

    If True, the full inverse of the W matrik is used. If False, the inverse is computed from the symplectic condition.

  • steps_r_matrixdict, optional

    Steps to be used for the finite difference computation of the R matrix. If not provided, the default values are used.

  • r_sigmafloat, optional

    Deviation in sigmas used for the propagation of the W matrix. Initial value for the r_sigma parameter.

  • nemitt_xfloat, optional

    Horizontal emittance assumed for the comutation of the deviation used for the propagation of the W matrix.

  • nemitt_yfloat, optional

    Vertical emittance assumed for the comutation of the deviation used for the propagation of the W matrix.

Match

See also: Match.

Line.match(vary, targets, solve=True, assert_within_tol=True, compensate_radiation_energy_loss=False, solver_options={}, allow_twiss_failure=True, restore_if_fail=True, verbose=False, n_steps_max=20, default_tol=None, solver=None, **kwargs)

Change a set of knobs in the beamline in order to match assigned targets.

Parameters:
  • vary (list of str or list of Vary objects) – List of knobs to be varied. Each knob can be a string or a Vary object including the knob name and the step used for computing the Jacobian for the optimization.

  • targets (list of Target objects) – List of targets to be matched.

  • solve (bool) – If True (default), the matching is performed immediately. If not an Optimize object is returnd, which can be used for advanced matching.

  • assert_within_tol (bool) – If True (default), an exception is raised if the matching fails.

  • compensate_radiation_energy_loss (bool) – If True, the radiation energy loss is compensated at each step of the matching.

  • solver_options (dict) – Dictionary of options to be passed to the solver.

  • allow_twiss_failure (bool) – If True (default), the matching continues if the twiss computation computation fails at some of the steps.

  • restore_if_fail (bool) – If True (default), the beamline is restored to its initial state if the matching fails.

  • verbose (bool) – If True, the matching steps are printed.

  • n_steps_max (int) – Maximum number of steps for the matching before matching is stopped.

  • default_tol (float) – Default tolerances used on the target. A dictionary can be provided associating a tolerance to each target name. The tolerance provided for None is used for all targets for which a tolerance is not otherwise provided. Example: default_tol={‘betx’: 1e-4, None: 1e-6}.

  • solver (str) – Solver to be used for the matching. Available solvers are jacobian (default), and fsolve.

  • **kwargs (dict) – Additional arguments to be passed to the twiss.

Returns:

optimizer – xdeps optimizer object used for the optimization.

Return type:

xdeps.Optimize

Examples

# Match tunes and chromaticities to assigned values
line.match(
    vary=[
        xt.Vary('kqtf.b1', step=1e-8),
        xt.Vary('kqtd.b1', step=1e-8),
        xt.Vary('ksf.b1', step=1e-8),
        xt.Vary('ksd.b1', step=1e-8),
    ],
    targets = [
        xt.Target('qx', 62.315, tol=1e-4),
        xt.Target('qy', 60.325, tol=1e-4),
        xt.Target('dqx', 10.0, tol=0.05),
        xt.Target('dqy', 12.0, tol=0.05)]
)
# Match a local orbit bump
tw_before = line.twiss()

line.match(
    start='mq.33l8.b1',
    end='mq.23l8.b1',
    init=tw_before.get_twiss_init(at_element='mq.33l8.b1'),
    vary=[
        xt.Vary(name='acbv30.l8b1', step=1e-10),
        xt.Vary(name='acbv28.l8b1', step=1e-10),
        xt.Vary(name='acbv26.l8b1', step=1e-10),
        xt.Vary(name='acbv24.l8b1', step=1e-10),
    ],
    targets=[
        # I want the vertical orbit to be at 3 mm at mq.28l8.b1 with zero angle
        xt.Target('y', at='mb.b28l8.b1', value=3e-3, tol=1e-4, scale=1),
        xt.Target('py', at='mb.b28l8.b1', value=0, tol=1e-6, scale=1000),
        # I want the bump to be closed
        xt.Target('y', at='mq.23l8.b1', value=tw_before['y', 'mq.23l8.b1'],
                tol=1e-6, scale=1),
        xt.Target('py', at='mq.23l8.b1', value=tw_before['py', 'mq.23l8.b1'],
                tol=1e-7, scale=1000),
    ]
)
class xdeps.Optimize(vary, targets, restore_if_fail=True, solver=None, verbose=False, assert_within_tol=True, n_steps_max=20, solver_options={}, **kwargs)

Numerical optimizer for matching.

Parameters:
  • vary (list of Vary) – List of knobs to vary.

  • targets (list of Target) – List of targets to match.

  • restore_if_fail (bool, optional) – If True, restore the initial knob values if the optimization fails. Defaults to True.

  • solver (str, optional) – Solver to use. Can be ‘fsolve’, ‘bfgs’, or ‘jacobian’. Defaults to ‘jacobian’.

  • verbose (bool, optional) – If True, print information during the optimization. Defaults to False.

  • assert_within_tol (bool, optional) – If True, raise an error if the optimization fails. Defaults to True.

  • n_steps_max (int, optional) – Maximum number of steps to take. Defaults to 20.

  • solver_options (dict, optional) – Options to pass to the solver. Defaults to {}.

step(n_steps=1)

Perform one or more optimization steps.

Parameters:

n_steps (int, optional) – Number of steps to perform. Defaults to 1.

solve()

Perform the optimization, i.e. performs the required number of steps (up to n_steps_max) to find a point within tolerance. If assert_within_tol is True, raises an error if no point within tolerance is found. If restore_if_fail is True, restores the initial knob values if no point within tolerance is found.

vary_status(ret=False, max_col_width=40, iter_ref=0)

Display the status of the knobs.

Parameters:
  • ret (bool, optional) – If True, return the status as a Table. Defaults to False.

  • max_col_width (int, optional) – Maximum column width. Defaults to 40.

  • iter_ref (int, optional) – Iteration to use as reference. Defaults to 0.

target_status(ret=False, max_col_width=40)

Display the status of the targets.

Parameters:
  • ret (bool, optional) – If True, return the status as a Table. Defaults to False.

  • max_col_width (int, optional) – Maximum column width. Defaults to 40.

get_knob_values(iteration=None)

Get the knob values at a given iteration.

Parameters:

iteration (int, optional) – Iteration to use. Defaults to None, i.e. the last iteration.

Returns:

Dictionary of knob values.

Return type:

dict

show(vary=True, targets=True, maxwidth=1000, max_col_width=80)

Display the knobs and targets used in the optimization.

Parameters:
  • vary (bool, optional) – If True, display the knobs. Defaults to True.

  • targets (bool, optional) – If True, display the targets. Defaults to True.

  • maxwidth (int, optional) – Maximum width of the table. Defaults to 1000.

  • max_col_width (int, optional) – Maximum column width. Defaults to 80.

log()

Return the optimization log as a Table.

Returns:

Optimization log.

Return type:

Table

reload(iteration=None, tag=None)

Reload the knob values from a given iteration in the optimization log.

Parameters:

iteration (int) – Iteration to use.

clear_log()

Clear the optimization log.

add_point_to_log(tag='')

Add the current point to the optimization log.

Parameters:

tag (str, optional) – Tag to add to the point. Defaults to ‘’.

tag(tag='')

Tag the current point in the optimization log.

Parameters:

tag (str, optional) – Tag to add to the point. Defaults to ‘’.

enable_vary(id=None, tag=None)

Enable one or more knobs.

Parameters:
  • id (int or list of int, optional) – Index of the knobs to enable. Defaults to None.

  • tag (str or list of str, optional) – Tag of the knobs to enable. Defaults to None.

disable_vary(id=None, tag=None)

Disable one or more knobs.

Parameters:
  • id (int or list of int, optional) – Index of the knobs to disable. Defaults to None.

  • tag (str or list of str, optional) – Tag of the knobs to disable. Defaults to None.

enable_targets(id=None, tag=None)

Enable one or more targets.

Parameters:
  • id (int or list of int, optional) – Index of the targets to enable. Defaults to None.

  • tag (str or list of str, optional) – Tag of the targets to enable. Defaults to None.

disable_targets(id=None, tag=None)

Disable one or more targets.

Parameters:
  • id (int or list of int, optional) – Index of the targets to disable. Defaults to None.

  • tag (str or list of str, optional) – Tag of the targets to disable. Defaults to None.

disable_all_targets()

Disable all targets.

enable_all_targets()

Enable all targets.

disable_all_vary()

Disable all knobs.

enable_all_vary()

Enable all knobs.

Vary and Target

class xtrack.Vary(name, container=None, limits=None, step=None, weight=None, max_step=None, active=True, tag='')

Vary object for matching.

Parameters:
  • name (str) – Name of the variable to be varied.

  • container (dict, optional) – Container in which the variable is defined. If not specified, line.vars is used.

  • limits (tuple or None, optional) – Limits in which the variable is allowed to vary. Default is None.

  • step (float, optional) – Step size used to compute the derivative of the cost function with respect to the variable.

  • weight (float, optional) – Weight used for this vary in the cost function.

  • max_step (float, optional) – Maximum allowed change in the variable per iteration.

  • active (bool, optional) – Whether the variable is active in the optimization. Default is True.

  • tag (str, optional) – Tag associated to the variable. Default is ‘’.

class xtrack.VaryList(vars, container=None, limits=None, step=None, weight=None, max_step=None, active=True, tag='')

VaryList object for matching specifying a list of variables to be varied.

Parameters:
  • vars (list) – List of variables to be varied.

  • container (dict, optional) – Container in which the variables are defined. If not specified, line.vars is used.

  • limits (tuple or None, optional) – Limits in which the variables are allowed to vary. Default is None.

  • step (float, optional) – Step size used to compute the derivative of the cost function with respect to the variables.

  • weight (float, optional) – Weight used for these variables in the cost function.

  • max_step (float, optional) – Maximum allowed change in the variables per iteration.

  • active (bool, optional) – Whether the variables are active in the optimization. Default is True.

  • tag (str, optional) – Tag associated to the variables. Default is ‘’.

class xtrack.Target(tar=None, value=None, at=None, tol=None, weight=None, scale=None, line=None, action=None, tag='', optimize_log=False, **kwargs)

Target object for matching. Usage examples:

Target('betx', 0.15, at='ip1', tol=1e-3)
Target(betx=0.15, at='ip1', tol=1e-3)
Target('betx', LessThan(0.15), at='ip1', tol=1e-3)
Target('betx', GreaterThan(0.15), at='ip1', tol=1e-3)
Parameters:
  • tar (str or callable) – Name of the quantity to be matched or callable computing the quantity to be matched from the output of the action (by default the action is the Twiss action). Basic targets can also be specified using keyword arguments.

  • value (float or xdeps.GreaterThan or xdeps.LessThan or xtrack.TwissTable) – Value to be matched. Inequality constraints can also be specified. If a TwissTable is specified, the value is obtained from the table using the specified tar and at.

  • at (str, optional) – Element at which the quantity is evaluated. Needs to be specified if the quantity to be matched is not a scalar.

  • tol (float, optional) – Tolerance below which the target is considered to be met.

  • weight (float, optional) – Weight used for this target in the cost function.

  • line (Line, optional) – Line in which the quantity is defined. Needs to be specified if the match involves multiple lines.

  • action (Action, optional) – Action used to compute the quantity to be matched. By default the action is the Twiss action.

  • tag (str, optional) – Tag associated to the target. Default is ‘’.

  • optimize_log (bool, optional) – If True, the logarithm of the quantity is used in the cost function instead of the quantity itself. Default is False.

class xtrack.TargetSet(tars=None, value=None, at=None, tol=None, weight=None, scale=None, line=None, action=None, tag='', optimize_log=False, **kwargs)

TargetSet object for matching, specifying a set of targets to be matched.

Examples:

Parameters:
  • tars (list, optional) – List of quantities to be matched. Basic targets can also be specified using keyword arguments.

  • value (float or xdeps.GreaterThan or xdeps.LessThan) – Value to be matched. Inequality constraints can also be specified.

  • at (str, optional) – Element at which the quantity is evaluated. Needs to be specified if the quantity to be matched is not a scalar.

  • tol (float, optional) – Tolerance below which the target is considered to be met.

  • weight (float, optional) – Weight used for this target in the cost function.

  • line (Line, optional) – Line in which the quantity is defined. Needs to be specified if the match involves multiple lines.

  • action (Action, optional) – Action used to compute the quantity to be matched. By default the action is the Twiss action.

  • tag (str, optional) – Tag associated to the target. Default is ‘’.

  • optimize_log (bool, optional) – If True, the logarithm of the quantity is used in the cost function instead of the quantity itself. Default is False.

class xtrack.TargetRelPhaseAdvance(tar, value, end=None, start=None, tag='', **kwargs)

Target object for matching the relative phase advance between two elements in a line computed as mu(end) - mu(start).

Parameters:
  • tar (str) – Phase advance to be matched. Can be either ‘mux’ or ‘muy’.

  • value (float or GreaterThan or LessThan or TwissTable) – Value to be matched. Inequality constraints can also be specified. If a TwissTable is specified, the target obtained from the table using the specified tar and at.

  • end (str, optional) – Final element at which the phase advance is evaluated. Default is the last element of the line.

  • start (str, optional) – Initali wlement at which the phase advance is evaluated. Default is the first element of the line.

  • tol (float, optional) – Tolerance below which the target is considered to be met.

  • weight (float, optional) – Weight used for this target in the cost function.

  • line (Line, optional) – Line in which the phase advance is defined. Needs to be specified if the match involves multiple lines.

  • tag (str, optional) – Tag associated to the target. Default is ‘’.

Build particles

See also: Working with Particles objects.

Line.build_particles(particle_ref=None, num_particles=None, x=None, px=None, y=None, py=None, zeta=None, delta=None, pzeta=None, x_norm=None, px_norm=None, y_norm=None, py_norm=None, zeta_norm=None, pzeta_norm=None, at_element=None, match_at_s=None, nemitt_x=None, nemitt_y=None, weight=None, particle_on_co=None, R_matrix=None, W_matrix=None, method=None, scale_with_transverse_norm_emitt=None, particles_class=None, _context=None, _buffer=None, _offset=None, _capacity=None, mode=None, **kwargs)

Create a Particles object from arrays containing physical or normalized coordinates.

Parameters:
  • particle_ref (Particle object) – Reference particle defining the reference quantities (mass0, q0, p0c, gamma0, etc.). Its coordinates (x, py, y, py, zeta, delta) are ignored unless `mode`=’shift’ is selected.

  • num_particles (int) – Number of particles to be generated (used if provided coordinates are all scalar).

  • x (float or array) – x coordinate of the particles in meters (default is 0).

  • px (float or array) – px coordinate of the particles (default is 0).

  • y (float or array) – y coordinate of the particles in meters (default is 0).

  • py (float or array) – py coordinate of the particles (default is 0).

  • zeta (float or array) – zeta coordinate of the particles in meters (default is 0).

  • delta (float or array) – delta coordinate of the particles (default is 0).

  • pzeta (float or array) – pzeta coordinate of the particles (default is 0).

  • x_norm (float or array) – transverse normalized coordinate x (in sigmas) used in combination with the one turn matrix and with the transverse emittances provided in the argument scale_with_transverse_norm_emitt to generate x, px, y, py (x, px, y, py cannot be provided if x_norm, px_norm, y_norm, py_norm are provided).

  • px_norm (float or array) – transverse normalized coordinate px (in sigmas) used in combination with the one turn matrix and with the transverse emittances (as above).

  • y_norm (float or array) – transverse normalized coordinate y (in sigmas) used in combination with the one turn matrix and with the transverse emittances (as above).

  • py_norm (float or array) – transverse normalized coordinate py (in sigmas) used in combination with the one turn matrix and with the transverse emittances (as above).

  • zeta_norm (float or array) – longitudinal normalized coordinate zeta (in sigmas) used in combination with the one turn matrix.

  • pzeta_norm (float or array) – longitudinal normalized coordinate pzeta (in sigmas) used in combination with the one turn matrix.

  • nemitt_x (float) – Transverse normalized emittance in the x plane.

  • nemitt_y (float) – Transverse normalized emittance in the y plane.

  • at_element (str or int) – Location within the line at which particles are generated. It can be an index or an element name.

  • match_at_s (float) – s location in meters within the line at which particles are generated. The value needs to be in the drift downstream of the element at at_element. The matched particles are backtracked to the element at at_element from which the tracking automatically starts when the generated particles are tracked.

  • weight (float or array) – weights to be assigned to the particles.

  • mode (str) –

    To be chosen between set, shift and normalized_transverse (the default mode is set. normalized_transverse is used if any if any of x_norm, px_norm, y_norm, py_norm is provided):

    • set: reference quantities including mass0, q0, p0c, gamma0,

      etc. are taken from the provided reference particle. Particles coordinates are set according to the provided input x, px, y, py, zeta, delta (zero is assumed as default for these variables).

    • shift: reference quantities including mass0, q0, p0c, gamma0,

      etc. are taken from the provided reference particle. Particles coordinates are set from the reference particles and shifted according to the provided input x, px, y, py, zeta, delta (zero is assumed as default for these variables).

    • normalized_transverse: reference quantities including mass0,

      q0, p0c, gamma0, etc. are taken from the provided reference particle. The longitudinal coordinates are set according to the provided input zeta, delta (zero is assumed as default for these variables). The transverse coordinates are set according to the provided input x_norm, px_norm, y_norm, py_norm (zero is assumed as default for these variables). The transverse coordinates are normalized according to the transverse emittance provided in nemitt_x and nemitt_y. The transverse coordinates are then transformed into physical space using the linearized one-turn matrix.

  • _capacity (int) – Capacity of the arrays to be created. If not provided, the capacity is set to the number of particles.

Returns:

particles – Particles object containing the generated particles.

Return type:

Particles object

Particles class

Xsuite Particles classes, including the default xtrack.Particles class, expose the API described in the following (for more info on how to manipulate Particles objects, see the Particles section in the user’s guide).

class xtrack.Particles(_capacity=None, _no_reorganize=False, **kwargs)

The Particles class contains coordinates and other data associated to a set of particles. Parameters can be provided as arrays of the same length or as scalars. If arrays are provided, the length of the arrays must be equal to the number of particles. If scalars are provided, the same value is assigned to all particles. When parameters are not provided, they are initialized to default values, or inferred from the other parameters.

Parameters:
  • _capacity (int) – The maximum number of particles that can be stored in the object. If not provided, it is inferred from the size of the provided coordinates arrays.

  • s (array_like of float, optional) – Reference accumulated path length [m]

  • x (array_like of float, optional) – Horizontal position [m]

  • px (array_like of float, optional) – Px / (m/m0 * p0c) = beta_x gamma /(beta0 gamma0)

  • y (array_like of float, optional) – Vertical position [m]

  • py (array_like of float, optional) – Py / (m/m0 * p0c)

  • delta (array_like of float, optional) – (Pc m0/m - p0c) /p0c

  • ptau (array_like of float, optional) – (Energy m0/m - Energy0) / p0c

  • pzeta (array_like of float, optional) – ptau / beta0

  • rvv (array_like of float, optional) – beta / beta0

  • rpp (array_like of float, optional) – m/m0 P0c / Pc = 1/(1+delta)

  • zeta (array_like of float, optional) – (s - beta0 c t)

  • tau (array_like of float, optional) – (s / beta0 - ct)

  • mass0 (float, optional) – Reference rest mass [eV]

  • q0 (float, optional) – Reference charge [e]

  • p0c (array_like of float, optional) – Reference momentum [eV]

  • energy0 (array_like of float, optional) – Reference energy [eV]

  • gamma0 (array_like of float, optional) – Reference relativistic gamma

  • beta0 (array_like of float, optional) – Reference relativistic beta

  • mass_ratio (array_like of float, optional) – mass/mass0 (this is used to track particles of different species. Note that mass is the rest mass of the considered particle species and not the relativistic mass)

  • chi (array_like of float, optional) – q / q0 * m0 / m = qratio / mratio

  • charge_ratio (array_like of float, optional) – q / q0

  • particle_id (array_like of int, optional) – Identifier of the particle

  • at_turn (array_like of int, optional) – Number of tracked turns

  • state (array_like of int, optional) – It is <= 0 if the particle is lost, > 0 otherwise (different values are used to record information on how the particle is lost or generated)

  • pdg_id (array_like of float, optional) – PDG id of the particle under consideration (needed when tracking ions to distinguish different particle types). The default is 0 (undefined)

  • weight (array_like of float, optional) – Particle weight in number of particles (for collective simulations)

  • at_element (array_like of int, optional) – Identifier of the last element through which the particle has been

  • parent_particle_id (array_like of int, optional) – Identifier of the parent particle (secondary production processes)

add_particles(part, keep_lost=False)

Add particles to the particles object.

Parameters:
  • part (Particles) – The particles to add.

  • keep_lost (bool, optional) – If True, lost particles are also added. Default is False.

add_to_energy(delta_energy)

Add delta_energy to the energy of the particles object. delta, ‘ptau’, rvv and rpp are updated accordingly.

filter(mask)

Select a subset of particles satisfying a logical condition.

Parameters:

mask (array of bool) – The logical condition to apply to the particles.

Returns:

particles – The newly created Particles object.

Return type:

Particles

classmethod from_dict(dct, load_rng_state=True, **kwargs)

Create a new Particles object from a dictionary.

Parameters:
  • dct (dict) – The dictionary to load the Particles object from.

  • load_rng_state (bool, optional) – Whether to load the state of the random number generator from the dictionary. Defaults to True.

  • _context (Context, optional) – The context to load the Particles object into. If not provided, the xobjects default context will be used.

  • _buffer (Buffer, optional) – The buffer to load the Particles object into. If not provided, a new buffer will be allocated from the context.

Returns:

particles – The newly created Particles object.

Return type:

Particles

classmethod from_pandas(df, _context=None, _buffer=None, _offset=None)

Create a new Particles object from a pandas DataFrame.

Parameters:
  • df (pandas.DataFrame) – The DataFrame to load the Particles object from.

  • _context (Context, optional) – The context to load the Particles object into. If not provided, the xobjects default context will be used.

  • _buffer (Buffer, optional) – The buffer to load the Particles object into. If not provided, a new buffer will be allocated from the context.

Returns:

particles – The newly created Particles object.

Return type:

Particles

get_active_particle_id_range()

Get the range of particle ids of active particles.

get_classical_particle_radius0()

Get classical particle radius of the reference particle.

get_table()

Get a Table object with the Particles coordinates.

Returns:

table – The Table object containing the data from Particles object.

Return type:

Table

hide_first_n_particles(num_particles)

Hide first num_particles particles in the particles object.

hide_lost_particles(_assume_reorganized=False)

Hide lost particles in the particles object.

classmethod merge(lst, _context=None, _buffer=None, _offset=None)

Merge a list of Particles objects into a single one.

Parameters:
  • lst (list of Particles) – The list of Particles objects to merge.

  • _context (Context, optional) – The context to load the Particles object into. If not provided, the xobjects default context will be used.

  • _buffer (Buffer, optional) – The buffer to load the Particles object into. If not provided, a new buffer will be allocated from the context.

Returns:

particles – The newly created Particles object.

Return type:

Particles

remove_unused_space()

Return a new particles object with removed unused space in the particle arrays (when the number of particles is smaller than the capacity of the particles object).

reorganize()

Reorganize the particles object so that all active particles are at the beginning of the arrays.

Returns:

  • n_active (int) – The number of active particles.

  • n_lost (int) – The number of lost particles.

show()

Print particle properties.

sort(by='particle_id', interleave_lost_particles=False)

Sort the particles by a given variable.

Parameters:
  • by (str) – The name of the variable to sort by. Default is ‘particle_id’.

  • interleave_lost_particles (bool) – If True, lost particles are interleaved with active particles. If False, lost particles are moved to the end of the array.

Returns:

sorted_index – The index of the sorted particles.

Return type:

array of int

to_dict(copy_to_cpu=True, remove_underscored=None, remove_unused_space=None, remove_redundant_variables=None, keep_rng_state=None, compact=False)

Convert the Particles object to a dictionary.

Parameters:
  • copy_to_cpu (bool, optional) – Whether to copy the Particles object to the CPU before converting it to a dictionary. Defaults to True.

  • compact – Whether to minimize the size of the dictionary. Defaults to False.

  • remove_underscored (bool, optional) – Whether to remove underscored variables from the dictionary. Defaults to True.

  • remove_unused_space (bool, optional) – Whether to remove unused space from the arrays. Defaults to the value of compact.

  • remove_redundant_variables (bool, optional) – Whether to remove redundant variables from the dictionary. Defaults to the value of compact.

  • keep_rng_state (bool, optional) – Whether to keep the state of the random number generator in the dictionary. Defaults to true if compact is False.

Returns:

dct – The dictionary containing the data from Particles object.

Return type:

dict

to_pandas(remove_underscored=None, remove_unused_space=None, remove_redundant_variables=None, keep_rng_state=None, compact=False)

Convert the Particles object to a pandas DataFrame.

Parameters:
  • compact – Whether to minimize the size of the dictionary. Defaults to False.

  • remove_underscored (bool, optional) – Whether to remove underscored variables from the dictionary. Defaults to True.

  • remove_unused_space (bool, optional) – Whether to remove unused space from the arrays. Defaults to the value of compact.

  • remove_redundant_variables (bool, optional) – Whether to remove redundant variables from the dictionary. Defaults to the value of compact.

  • keep_rng_state (bool, optional) – Whether to keep the state of the random number generator in the dictionary. Defaults to true if compact is False.

Returns:

df – The DataFrame containing the data from Particles object.

Return type:

pandas.DataFrame

to_table()

Get a Table object with the Particles coordinates.

Returns:

table – The Table object containing the data from Particles object.

Return type:

Table

unhide_first_n_particles()

Unhide the particles in the particles object.

unhide_lost_particles()

Unhide lost particles in the particles object.

update_beta0(new_beta0)

Update the beta0 value of the particles object. p0c and gamma0 are updated accordingly. If new_beta0 contains nans, these values are not updated.

update_delta(new_delta_value)

Update the delta value of the particles object. ptau and rvv and rpp are updated accordingly. If new_delta_value contains nans, these values are not updated.

update_gamma0(new_gamma0)

Update the gamma0 value of the particles object. p0c and beta0 are updated accordingly. If new_gamma0 contains nans, these values are not updated.

update_p0c(new_p0c)

Update the p0c value of the particles object. gamma0 and beta0 are updated accordingly. If new_p0c contains nans, these values are not updated.

update_ptau(new_ptau)

Update the ptau value of the particles object. delta and rvv and rpp are updated accordingly. If new_ptau contains nans, these values are not updated.

Generation of particles distributions

See also Particles section in the user’s guide.

Gaussian bunch generation (6D)

xpart.generate_matched_gaussian_bunch(num_particles, nemitt_x, nemitt_y, sigma_z, total_intensity_particles=None, particle_on_co=None, R_matrix=None, circumference=None, momentum_compaction_factor=None, rf_harmonic=None, rf_voltage=None, rf_phase=None, p_increment=0.0, tracker=None, line=None, particle_ref=None, particles_class=None, engine=None, _context=None, _buffer=None, _offset=None, **kwargs)

Generate a matched Gaussian bunch.

Parameters:
  • line (xpart.Line) – Line for which the bunch is generated.

  • num_particles (int) – Number of particles to be generated.

  • nemitt_x (float) – Normalized emittance in the horizontal plane (in m rad).

  • nemitt_y (float) – Normalized emittance in the vertical plane (in m rad).

  • sigma_z (float) – RMS bunch length in meters.

  • total_intensity_particles (float) – Total intensity of the bunch in particles.

Returns:

part – Particles object containing the generated particles.

Return type:

xpart.Particles

Longitudinal coordinates generation

xpart.generate_longitudinal_coordinates(line=None, num_particles=None, distribution='gaussian', sigma_z=None, engine=None, return_matcher=False, particle_ref=None, mass0=None, q0=None, gamma0=None, circumference=None, momentum_compaction_factor=None, rf_harmonic=None, rf_voltage=None, rf_phase=None, p_increment=0.0, tracker=None, **kwargs)

Generate longitudinal coordinates matched to given RF parameters (non-linar bucket).

Parameters:
  • line (xline.Line) – Line for which the longitudinal coordinates are generated.

  • num_particles (int) – Number of particles to be generated.

  • distribution (str) – Distribution of the particles. Possible values are gaussian and parabolic.

  • sigma_z (float) – RMS bunch length in meters.

  • engine (str) – Engine to be used for the generation. Possible values are pyheadtail and single-rf-harmonic.

  • return_matcher (bool) – If True, the matcher object is returned.

Returns:

  • zeta (np.ndarray) – Longitudinal position of the generated particles.

  • delta (np.ndarray) – Longitudinal momentum deviation of the generated particles.

  • matcher (object) – Matcher object used for the generation. Returned only if return_matcher is True.

Normalized transverse coordinates generation

Gaussian

xpart.generate_2D_gaussian(num_particles)

Generate a 2D Gaussian distribution.

Parameters:

num_particles (int) – Number of particles to be generated.

Returns:

  • x1 (np.ndarray) – First normalized coordinate.

  • x2 (np.ndarray) – Second normalized coordinate.

Polar grid

xpart.generate_2D_polar_grid(r_range=None, r_grid=None, dr=None, nr=None, theta_range=None, theta_grid=None, dtheta=None, ntheta=None)

Generate a 2D polar grid.

Parameters:
  • r_range (tuple) – Range of the radial coordinate.

  • r_grid (np.ndarray) – Grid of the radial coordinate.

  • dr (float) – Step of the radial coordinate.

  • nr (int) – Number of points of the radial coordinate.

  • theta_range (tuple) – Range of the angular coordinate.

  • theta_grid (np.ndarray) – Grid of the angular coordinate.

  • dtheta (float) – Step of the angular coordinate.

  • ntheta (int) – Number of points of the angular coordinate.

Returns:

  • a1 (np.ndarray) – First normalized coordinate.

  • a2 (np.ndarray) – Second normalized coordinate.

  • r_all (np.ndarray) – Radial coordinate.

  • theta_all (np.ndarray) – Angular coordinate.

Uniform circular sector

xpart.generate_2D_uniform_circular_sector(num_particles, r_range=(0, 1), theta_range=(0, 6.283185307179586))

Generate a 2D uniform circular sector.

Parameters:
  • num_particles (int) – Number of particles to be generated.

  • r_range (tuple) – Range of the radial coordinate.

  • theta_range (tuple) – Range of the angular coordinate.

Returns:

  • a1 (np.ndarray) – First normalized coordinate.

  • a2 (np.ndarray) – Second normalized coordinate.

  • r_all (np.ndarray) – Radial coordinate.

  • theta_all (np.ndarray) – Angular coordinate.

Pencil

xpart.generate_2D_pencil(num_particles, pos_cut_sigmas, dr_sigmas, side='+')

Generate a 2D pencil beam distribution.

Parameters:
  • num_particles (int) – Number of particles to be generated.

  • pos_cut_sigmas (float) – Position cut in sigmas.

  • dr_sigmas (float) – Radius of the pencil beam in sigmas.

  • side (str) – Side of the pencil beam. Can be ‘+’, ‘-’ or ‘+-‘.

Returns:

  • x1 (np.ndarray) – First normalized coordinate.

  • x2 (np.ndarray) – Second normalized coordinate.

xpart.generate_2D_pencil_with_absolute_cut(num_particles, plane, absolute_cut, dr_sigmas, side='+', tracker=None, line=None, nemitt_x=None, nemitt_y=None, at_element=None, match_at_s=None, **kwargs)

Generate a 2D pencil beam distribution with an absolute cut.

Parameters:
  • line (xtrack.Line) – Line for which the coordinates are generated.

  • num_particles (int) – Number of particles to be generated.

  • plane (str) – Plane of the pencil beam. Can be ‘x’ or ‘y’.

  • absolute_cut (float) – Absolute cut in meters.

  • dr_sigmas (float) – Radius of the pencil beam in sigmas.

  • side (str) – Side of the pencil beam. Can be ‘+’ or ‘-‘.

Returns:

  • x1 (np.ndarray) – First normalized coordinate.

  • x2 (np.ndarray) – Second normalized coordinate.

CPU and GPU contexts

See also Getting Started Guide

Xsuite supports different plaforms allowing the exploitation of different kinds of hardware (CPUs and GPUs). A context is initialized by instanciating objects from one of the context classes available Xobjects, which is then passed to the other Xsuite components (see example in Getting Started Guide). Contexts are interchangeable as they expose the same API. Custom kernel functions can be added to the contexts. General source code with annotations can be provided to define the kernels, which is then automatically specialized for the chosen platform (see dedicated section).

Three contexts are presently available:

The corresponfig API is described in the following subsections.

Cupy context

class xobjects.ContextCupy(default_block_size=256, default_shared_mem_size_bytes=0, device=None)

Creates a Cupy Context object, that allows performing the computations on nVidia GPUs.

Parameters:
  • default_block_size (int) – CUDA thread size that is used by default for kernel execution in case a block size is not specified directly in the kernel object. The default value is 256.

  • device (int) – Identifier of the device to be used by the context.

Returns:

context object.

Return type:

ContextCupy

nparray_to_context_array(arr)

Copies a numpy array to the device memory.

Parameters:

arr (numpy.ndarray) – Array to be transferred

Returns:

The same array copied to the device.

Return type:

cupy.ndarray

nparray_from_context_array(dev_arr)

Copies an array to the device to a numpy array.

Parameters:

dev_arr (cupy.ndarray) – Array to be transferred.

Returns:

The same data copied to a numpy array.

Return type:

numpy.ndarray

property nplike_lib

Module containing all the numpy features supported by cupy.

property splike_lib

Module containing all the scipy features supported by cupy.

synchronize()

Ensures that all computations submitted to the context are completed. Equivalent to cupy.cuda.stream.get_current_stream().synchronize()

zeros(*args, **kwargs)

Allocates an array of zeros on the device. The function has the same interface of numpy.zeros

plan_FFT(data, axes)

Generates an FFT plan object to be executed on the context.

Parameters:
  • data (cupy.ndarray) – Array having type and shape for which the FFT needs to be planned.

  • axes (sequence of ints) – Axes along which the FFT needs to be performed.

Returns:

FFT plan for the required array shape, type and axes.

Return type:

FFTCupy

Example:

plan = context.plan_FFT(data, axes=(0,1))

data2 = 2*data

# Forward tranform (in place)
plan.transform(data2)

# Inverse tranform (in place)
plan.itransform(data2)
property kernels

Dictionary containing all the kernels that have been imported to the context. The syntax context.kernels.mykernel can also be used.

add_kernels(kernels: dict, sources: list = None, specialize: bool = True, apply_to_source: Sequence[callable] = (), save_source_as: str = None, extra_cdef: Optional[str] = '', extra_classes: Sequence[Type] = (), extra_headers: Sequence[Union[str, Path, io.TextIOBase, Source]] = (), compile: bool = True)

Adds user-defined kernels to the context. The kernel source code is provided as a string and/or in source files and must contain the kernel names defined in the kernel descriptions. :param sources: List of source codes that are concatenated before

compilation. The list can contain strings (raw source code), File objects and Path objects.

Parameters:
  • kernels (dict) – Dictionary with the kernel descriptions in the form given by the following examples. The descriptions define the kernel names, the type and name of the arguments and identify one input argument that defines the number of threads to be launched (only on cuda/opencl).

  • specialize (bool) – If True, the code is specialized using annotations in the source code. Default is True

  • apply_to_source (List[Callable]) – functions to be applied to source

  • save_source_as (str) – Filename for saving the specialized source code. Default is `None`.

  • extra_cdef – Extra C definitions to be passed to cffi.

  • extra_classes – Extra xobjects classes whose API is needed.

  • extra_headers – Extra headers to be added to the source code.

  • compile – If True, the source code is compiled. Default is True. Otherwise, a dummy kernel is returned, with the source code attached.

Example:

# A simple kernel
src_code = '''
/*gpukern*/
void my_mul(const int n,
    /*gpuglmem*/ const double* x1,
    /*gpuglmem*/ const double* x2,
    /*gpuglmem*/       double* y) {
    int tid = 0 //vectorize_over tid
    y[tid] = x1[tid] * x2[tid];
    //end_vectorize
    }
'''

# Prepare description
kernel_descriptions = {
    "my_mul": xo.Kernel(
        args=[
            xo.Arg(xo.Int32, name="n"),
            xo.Arg(xo.Float64, pointer=True, const=True, name="x1"),
            xo.Arg(xo.Float64, pointer=True, const=True, name="x2"),
            xo.Arg(xo.Float64, pointer=True, const=False, name="y"),
        ],
        n_threads="n",
        ),
}

# Import kernel in context
ctx.add_kernels(
    sources=[src_code],
    kernels=kernel_descriptions,
    save_source_as=None,
)

# With a1, a2, b being arrays on the context, the kernel
# can be called as follows:
ctx.kernels.my_mul(n=len(a1), x1=a1, x2=a2, y=b)

PyOpenCL context

class xobjects.ContextPyopencl(device=None, patch_pyopencl_array=True, minimum_alignment=None)

Creates a Pyopencl Context object, that allows performing the computations on GPUs and CPUs through PyOpenCL.

Parameters:
  • device (str or Device) – The device (CPU or GPU) for the simulation.

  • default_kernels (bool) – If True, the Xfields defult kernels are automatically imported.

  • patch_pyopencl_array (bool) – If True, the PyOpecCL class is patched to allow some operations with non-contiguous arrays.

  • specialize_code (bool) – If True, the code is specialized using annotations in the source code. Default is True

Returns:

context object.

Return type:

ContextPyopencl

nparray_to_context_array(arr)

Copies a numpy array to the device memory. :param arr: Array to be transferred :type arr: numpy.ndarray

Returns:

The same array copied to the device.

Return type:

pyopencl.array.Array

nparray_from_context_array(dev_arr)

Copies an array to the device to a numpy array.

Parameters:

dev_arr (pyopencl.array.Array) – Array to be transferred.

Returns:

The same data copied to a numpy array.

Return type:

numpy.ndarray

property nplike_lib

Module containing all the numpy features supported by PyOpenCL (optionally with patches to operate with non-contiguous arrays).

property splike_lib

Scipy features are not available through openCL

synchronize()

Ensures that all computations submitted to the context are completed. No action is performed by this function in the Pyopencl context. The method is provided so that the Pyopencl context has an identical API to the Cupy one.

zeros(*args, **kwargs)

Allocates an array of zeros on the device. The function has the same interface of numpy.zeros

plan_FFT(data, axes, wait_on_call=True)

Generates an FFT plan object to be executed on the context.

Parameters:
  • data (pyopencl.array.Array) – Array having type and shape for which the FFT needs to be planned.

  • axes (sequence of ints) – Axes along which the FFT needs to be performed.

Returns:

FFT plan for the required array shape, type and axes.

Return type:

FFTPyopencl

Example:

plan = context.plan_FFT(data, axes=(0,1))

data2 = 2*data

# Forward tranform (in place)
plan.transform(data2)

# Inverse tranform (in place)
plan.itransform(data2)
property kernels

Dictionary containing all the kernels that have been imported to the context. The syntax context.kernels.mykernel can also be used.

add_kernels(kernels: dict, sources: list = None, specialize: bool = True, apply_to_source: Sequence[callable] = (), save_source_as: str = None, extra_cdef: Optional[str] = '', extra_classes: Sequence[Type] = (), extra_headers: Sequence[Union[str, Path, io.TextIOBase, Source]] = (), compile: bool = True)

Adds user-defined kernels to the context. The kernel source code is provided as a string and/or in source files and must contain the kernel names defined in the kernel descriptions. :param sources: List of source codes that are concatenated before

compilation. The list can contain strings (raw source code), File objects and Path objects.

Parameters:
  • kernels (dict) – Dictionary with the kernel descriptions in the form given by the following examples. The descriptions define the kernel names, the type and name of the arguments and identify one input argument that defines the number of threads to be launched (only on cuda/opencl).

  • specialize (bool) – If True, the code is specialized using annotations in the source code. Default is True

  • apply_to_source (List[Callable]) – functions to be applied to source

  • save_source_as (str) – Filename for saving the specialized source code. Default is `None`.

  • extra_cdef – Extra C definitions to be passed to cffi.

  • extra_classes – Extra xobjects classes whose API is needed.

  • extra_headers – Extra headers to be added to the source code.

  • compile – If True, the source code is compiled. Default is True. Otherwise, a dummy kernel is returned, with the source code attached.

Example:

# A simple kernel
src_code = '''
/*gpukern*/
void my_mul(const int n,
    /*gpuglmem*/ const double* x1,
    /*gpuglmem*/ const double* x2,
    /*gpuglmem*/       double* y) {
    int tid = 0 //vectorize_over tid
    y[tid] = x1[tid] * x2[tid];
    //end_vectorize
    }
'''

# Prepare description
kernel_descriptions = {
    "my_mul": xo.Kernel(
        args=[
            xo.Arg(xo.Int32, name="n"),
            xo.Arg(xo.Float64, pointer=True, const=True, name="x1"),
            xo.Arg(xo.Float64, pointer=True, const=True, name="x2"),
            xo.Arg(xo.Float64, pointer=True, const=False, name="y"),
        ],
        n_threads="n",
        ),
}

# Import kernel in context
ctx.add_kernels(
    sources=[src_code],
    kernels=kernel_descriptions,
    save_source_as=None,
)

# With a1, a2, b being arrays on the context, the kernel
# can be called as follows:
ctx.kernels.my_mul(n=len(a1), x1=a1, x2=a2, y=b)

CPU context

class xobjects.ContextCpu(omp_num_threads=0)

Creates a CPU Platform object, that allows performing the computations on conventional CPUs.

Returns:

platform object.

Return type:

ContextCpu

Create a new CPU context, serial or with parallelization using OpenMP. :param omp_num_threads: Number of threads to be :type omp_num_threads: int | Literal[‘auto’] :param used by OpenMP. If 0: :param no parallelization is used. If ‘auto’: :param the: :param number of threads is selected automatically by OpenMP.:

add_kernels(sources=None, kernels=None, specialize=True, apply_to_source=(), save_source_as=None, extra_compile_args: Sequence[str] = ('-O3', '-Wno-unused-function'), extra_link_args: Sequence[str] = ('-O3',), extra_cdef='', extra_classes=(), extra_headers=(), compile=True)

Adds user-defined kernels to the context. The kernel source code is provided as a string and/or in source files and must contain the kernel names defined in the kernel descriptions. :param sources: List of source codes that are concatenated before

compilation. The list can contain strings (raw source code), File objects and Path objects.

Parameters:
  • kernels (dict) – Dictionary with the kernel descriptions in the form given by the following examples. The descriptions define the kernel names, the type and name of the arguments and identify one input argument that defines the number of threads to be launched (only on cuda/opencl).

  • specialize (bool) – If True, the code is specialized using annotations in the source code. Default is True

  • apply_to_source (List[Callable]) – functions to be applied to source

  • save_source_as (str) – Filename for saving the specialized source code. Default is `None`.

  • extra_compile_args – Extra arguments to be passed to the compiler.

  • extra_link_args – Extra arguments to be passed to the linker.

  • extra_cdef – Extra C definitions to be passed to cffi.

  • extra_classes – Extra xobjects classes whose API is needed.

  • extra_headers – Extra headers to be added to the source code.

  • compile – If True, the source code is compiled. Default is True. Otherwise, a dummy kernel is returned, with the source code attached.

Example:

# A simple kernel
src_code = '''
/*gpukern*/
void my_mul(const int n,
    /*gpuglmem*/ const double* x1,
    /*gpuglmem*/ const double* x2,
    /*gpuglmem*/       double* y) {
    int tid = 0 //vectorize_over tid
    y[tid] = x1[tid] * x2[tid];
    //end_vectorize
    }
'''

# Prepare description
kernel_descriptions = {
    "my_mul": xo.Kernel(
        args=[
            xo.Arg(xo.Int32, name="n"),
            xo.Arg(xo.Float64, pointer=True, const=True, name="x1"),
            xo.Arg(xo.Float64, pointer=True, const=True, name="x2"),
            xo.Arg(xo.Float64, pointer=True, const=False, name="y"),
        ],
        n_threads="n",
        ),
}

# Import kernel in context
ctx.add_kernels(
    sources=[src_code],
    kernels=kernel_descriptions,
    save_source_as=None,
)

# With a1, a2, b being arrays on the context, the kernel
# can be called as follows:
ctx.kernels.my_mul(n=len(a1), x1=a1, x2=a2, y=b)
kernels_from_file(module_name: str, kernel_descriptions: Dict[str, Kernel], containing_dir='.') Dict[Tuple[str, tuple], KernelCpu]

Import a compiled module module_name located in containing_dir (by default it is the current working directory), and add the kernels from the module, as defined in kernel_descriptions, to the context. Returns the path to the loaded so file.

nparray_to_context_array(arr)

Moves a numpy array to the device memory. No action is performed by this function in the CPU context. The method is provided so that the CPU context has an identical API to the GPU ones.

Parameters:

arr (numpy.ndarray) – Array to be transferred

Returns:

The same array (no copy!).

Return type:

numpy.ndarray

nparray_from_context_array(dev_arr)

Moves an array to the device to a numpy array. No action is performed by this function in the CPU context. The method is provided so that the CPU context has an identical API to the GPU ones.

Parameters:

dev_arr (numpy.ndarray) – Array to be transferred

Returns:

The same array (no copy!)

Return type:

numpy.ndarray

property nplike_lib

Module containing all the numpy features. Numpy members should be accessed through nplike_lib to keep compatibility with the other contexts.

property splike_lib

Module containing all the scipy features. Numpy members should be accessed through splike_lib to keep compatibility with the other contexts.

synchronize()

Ensures that all computations submitted to the context are completed. No action is performed by this function in the CPU context. The method is provided so that the CPU context has an identical API to the GPU ones.

zeros(*args, **kwargs)

Allocates an array of zeros on the device. The function has the same interface of numpy.zeros

plan_FFT(data, axes)

Generate an FFT plan object to be executed on the context.

Parameters:
  • data (numpy.ndarray) – Array having type and shape for which the FFT needs to be planned.

  • axes (sequence of ints) – Axes along which the FFT needs to be performed.

Returns:

FFT plan for the required array shape, type and axes.

Return type:

FFTCpu

Example:

plan = context.plan_FFT(data, axes=(0,1))

data2 = 2*data

# Forward tranform (in place)
plan.transform(data2)

# Inverse tranform (in place)
plan.itransform(data2)
property kernels

Dictionary containing all the kernels that have been imported to the context. The syntax context.kernels.mykernel can also be used.

Configuration tools

xtrack.Multiline class

class xtrack.Multiline(lines: dict, link_vars=True)

Class to manage multiple beam lines (they can optionally share the xdeps vars).

Parameters:
  • lines (dict) – Dictionary with the lines objects

  • link_vars (bool) – If True, the variables are linked between the lines.

to_dict(include_var_management=True)

Save the multiline to a dictionary.

Parameters:

include_var_management (bool) – If True, the variable management data is included in the dictionary.

Returns:

dct – The dictionary with the multiline data.

Return type:

dict

classmethod from_dict(dct)

Load a multiline from a dictionary.

Parameters:

dct (dict) – The dictionary with the multiline data.

Returns:

new_multiline – The multiline object.

Return type:

Multiline

to_json(file, **kwargs)

Save the multiline to a json file.

Parameters:
  • file (str or file-like object) – The file to save to. If a string is provided, a file is opened and closed. If a file-like object is provided, it is used directly.

  • **kwargs (dict) – Additional keyword arguments are passed to the Line.to_dict method.

classmethod from_json(file, **kwargs)

Load a multiline from a json file.

Parameters:
  • file (str or file-like object) – The file to load from. If a string is provided, a file is opened and closed. If a file-like object is provided, it is used directly.

  • **kwargs (dict) –

Returns:

new_multiline – The multiline object.

Return type:

Multiline

copy()

Returns a deep copy of the multiline.

build_trackers(_context=None, _buffer=None, **kwargs)

Build the trackers for the lines.

Parameters:
  • _context (xobjects.Context) – The context in which the trackers are built.

  • _buffer (xobjects.Buffer) – The buffer in which the trackers are built.

  • **kwargs (dict) – Additional keyword arguments are passed to the Line.build_tracker method.

discard_trackers()

Discard the trackers associated to the lines.

twiss(lines=None, **kwargs)

Compute the twiss parameters for the lines.

Parameters:
  • lines (list of str) – The lines for which the twiss parameters are computed. If None, the twiss parameters are computed for all lines.

  • **kwargs (dict) – Additional keyword arguments are passed to the Line.twiss method.

Returns:

out – A MultiTwiss object containing the twiss parameters for the lines.

Return type:

MultiTwiss

match(vary, targets, restore_if_fail=True, solver=None, verbose=False, **kwargs)

Change a set of knobs in the beam lines in order to match assigned targets.

Parameters:
  • vary (list of str or list of Vary objects) – List of knobs to be varied. Each knob can be a string or a Vary object including the knob name and the step used for computing the Jacobian for the optimization.

  • targets (list of Target objects) – List of targets to be matched.

  • restore_if_fail (bool) – If True, the beamline is restored to its initial state if the matching fails.

  • solver (str) – Solver to be used for the matching. Available solvers are “fsolve” and “bfgs”.

  • verbose (bool) – If True, the matching steps are printed.

  • **kwargs (dict) – Additional arguments to be passed to the twiss.

Returns:

result_info – Dictionary containing information about the matching result.

Return type:

dict

match_knob(knob_name, vary, targets, knob_value_start=0, knob_value_end=1, **kwargs)

Match a new knob in the beam line such that the specified targets are matched when the knob is set to the value knob_value_end and the state of the line before tha matching is recovered when the knob is set to the value knob_value_start.

Parameters:
  • knob_name (str) – Name of the knob to be matched.

  • vary (list of str or list of Vary objects) – List of existing knobs to be varied.

  • targets (list of Target objects) – List of targets to be matched.

  • knob_value_start (float) – Value of the knob before the matching. Defaults to 0.

  • knob_value_end (float) – Value of the knob after the matching. Defaults to 1.

install_beambeam_interactions(clockwise_line, anticlockwise_line, ip_names, num_long_range_encounters_per_side, num_slices_head_on, harmonic_number, bunch_spacing_buckets, sigmaz, delay_at_ips_slots=None)

Install beam-beam elements in the lines. Elements are inserted in the lines in the appropriate positions. They are not configured and are kept inactive.

Parameters:
  • clockwise_line (str) – Name of the line in which the beam-beam elements for the clockwise beam are installed.

  • anticlockwise_line (xt.Line) – Name of the line in which the beam-beam elements for the anticlockwise beam are installed.

  • ip_names (list) – The names of the IPs in the lines around which the beam-beam elements need to be installed.

  • num_long_range_encounters_per_side (dict) – The number of long range encounters per side for each IP.

  • num_slices_head_on (int) – The number of slices to be used for the head-on beam-beam interaction.

  • harmonic_number (int) – The harmonic number of the machine.

  • bunch_spacing_buckets (float) – The bunch spacing in buckets.

  • sigmaz (float) – The longitudinal size of the beam.

  • delay_at_ips_slots (list) – Delay between the two beams in bunch slots for each IP. It specifies which bunch of the anticlockwise beam interacts with bunch zero of the clockwise beam.

configure_beambeam_interactions(num_particles, nemitt_x, nemitt_y, crab_strong_beam=True, use_antisymmetry=False, separation_bumps=None)

Configure the beam-beam elements in the lines.

Parameters:
  • num_particles (float) – The number of particles per bunch.

  • nemitt_x (float) – The normalized emittance in the horizontal plane.

  • nemitt_y (float) – The normalized emittance in the vertical plane.

  • crab_strong_beam (bool) – If True, crabbing of the strong beam is taken into account.

  • use_antisymmetry (bool) – If True, the antisymmetry of the optics and orbit is used to compute the momenta of the beam-beam interaction (in the absence of the counter-rotating beam)

  • separation_bumps (dict) – Dictionary previding the plane of the separation bump in the IPs where separation is present. The keys are the IP names and the values are the plane (“x” or “y”). This information needs to be provided only when use_antisymmetry is True.

apply_filling_pattern(filling_pattern_cw, filling_pattern_acw, i_bunch_cw, i_bunch_acw)

Enable only he beam-beam elements corresponding to actual encounters for the given filling pattern and the selected bunches.

Parameters:
  • filling_pattern_cw (list or array) – The filling pattern for the clockwise beam.

  • filling_pattern_acw (list or array) – The filling pattern for the anticlockwise beam.

  • i_bunch_cw (int) – The index of the bunch to be simulated for the clockwise beam.

  • i_bunch_acw (int) – The index of the bunch to be simulated for the anticlockwise beam.

xtrack.Multisetter class

See also: Fast lattice changes

class xtrack.MultiSetter(line, elements, field, index=None)

Create object to efficiently set and get values of a specific field of several elements of a line.

Parameters:
  • line (xtrack.Line) – Line in which the elements are mutated

  • elements (list of int or strings) – List of indeces or names of the elements to be mutated.

  • field (str) – Name of the field to be mutated.

  • index (int or None) – If the field is an array, the index of the array to be mutated.

get_values()

Get the values of the multisetter fields.

set_values(values)

Set the values of the multisetter fields.

Parameters:

values (np.ndarray) – Array of values to be set.

Space charge configuration

See also: Space charge

xfields.install_spacecharge_frozen(line=None, _buffer=None, particle_ref=None, longitudinal_profile=None, nemitt_x=None, nemitt_y=None, sigma_z=None, num_spacecharge_interactions=None, tol_spacecharge_position=None, s_spacecharge=None)

Install spacecharge elements (frozen modeling) in a xtrack.Line object.

Parameters:
  • line (xtrack.Line) – Line in which the spacecharge elements are installed.

  • particle_ref (xpart.Particles (optional)) – Reference particle for the spacecharge elements.

  • longitudinal_profile (str) – Longitudinal profile for the spacecharge elements.

  • nemitt_x (float) – Normalized emittance in the horizontal plane (in m rad).

  • nemitt_y (float) – Normalized emittance in the vertical plane (in m rad).

  • sigma_z (float) – RMS bunch length in meters.

  • num_spacecharge_interactions (int) – Number of spacecharge interactions to be installed.

  • tol_spacecharge_position (float) – Tolerance for the spacecharge position.

  • s_spacecharge (np.ndarray (optional)) – Position of the spacecharge elements.

Returns:

spacecharge_elements – List of spacecharge elements.

Return type:

list

xfields.replace_spacecharge_with_quasi_frozen(line, _buffer=None, update_mean_x_on_track=True, update_mean_y_on_track=True, update_sigma_x_on_track=True, update_sigma_y_on_track=True)

Replace spacecharge elements with quasi-frozen spacecharge elements.

Parameters:
  • line (xtrack.Line) – Line in which the spacecharge elements are replaced.

  • _buffer (xtrack.Buffer) – Buffer used allocate the spacecharge elements.

  • update_mean_x_on_track (bool (optional)) – Update the mean x position on track.

  • update_mean_y_on_track (bool (optional)) – Update the mean y position on track.

  • update_sigma_x_on_track (bool (optional)) – Update the sigma x position on track.

  • update_sigma_y_on_track (bool (optional)) – Update the sigma y position on track.

Returns:

spacecharge_elements – List of spacecharge elements.

Return type:

list

xfields.replace_spacecharge_with_PIC(line, n_sigmas_range_pic_x, n_sigmas_range_pic_y, nx_grid, ny_grid, nz_grid, n_lims_x, n_lims_y, z_range, solver='FFTSolver2p5D', _context=None, _buffer=None)

Replace spacecharge elements with Particle In Cell (PIC) elements.

Parameters:
  • line (xtrack.Line) – Line in which the spacecharge elements are replaced.

  • n_sigmas_range_pic_x (float) – Extent of the PIC grid in the horizontal direction in units beam sigmas.

  • n_sigmas_range_pic_y (float) – Extent of the PIC grid in the vertical direction in units beam sigmas.

  • nx_grid (int) – Number of grid points in the horizontal direction.

  • ny_grid (int) – Number of grid points in the vertical direction.

  • nz_grid (int) – Number of grid points in the longitudinal direction.

  • n_lims_x (int) – Number different limits in x for which PIC need to be generated.

  • n_lims_y (int) – Number different limits in y for which PIC need to be generated.

  • z_range (float) – Range of the longitudinal grid.

  • _context (xtrack.Context (optional)) – Context in which the PIC elements are created.

  • _buffer (xtrack.Buffer (optional)) – Buffer in which the PIC elements are created.

Returns:

  • pic_collection (xfields.PICCollection) – Collection of PIC elements.

  • all_pics (list) – List of all PIC elements.

Loss location refinement

See also: Loss location refinement

class xtrack.LossLocationRefinement(line, backtrack_line=None, n_theta=None, r_max=None, dr=None, ds=None, save_refine_lines=False, allowed_backtrack_types=[])

Class to refine the location of the lost particles within a line.

Parameters:
  • line (xtrack.Line) – Line for which the loss location refinement is performed.

  • backtrack_line (xtrack.Line (optional)) – Line used to backtrack the lost particles. If None, the backtracking line is automatically generated from the line.

  • n_theta (int) – Number of angles used to generate the interpolating aperture model. If None, the number of angles is automatically determined.

  • r_max (float) – Radius larger than the largest aperture radius.

  • dr (float) – Radius step used to generate the interpolating aperture model.

  • ds (float) – Step in the s direction used to generate the interpolating aperture model.

  • save_refine_lines (bool) – If True, the lines used to refine the loss location are saved.

  • allowed_backtrack_types (list) – List of element types through which the backtracking is allowed. Elements exposing the attribute allow_backtrack are automatically added to the list.

refine_loss_location(particles, i_apertures=None)

Refine the location of the lost particles within the line.

Parameters:
  • particles (xpart.Particles) – Particles for which the loss location is refined.

  • i_apertures (list (optional)) – List of indices of the apertures for which the loss location is refined. If None, the loss location is refined for all apertures.

Beam elements (xtrack)

Marker

class xtrack.Marker(*args, **kwargs)

A marker beam element with no effect on the particles.

Drift

class xtrack.Drift(*args, **kwargs)

Beam element modeling a drift section.

Parameters:

length (float) – Length of the drift section in meters. Default is 0.

Bend

class xtrack.Bend(**kwargs)

Bending magnet element.

Parameters:
  • k0 (float) – Strength of the dipole component in m^-1.

  • h (float) – Curvature of the reference trajectory in m^-1.

  • length (float) – Length of the element in m.

  • knl (array_like, optional) – Integrated strength of the high-order normal multipolar components (knl[0] and knl[1] should not be used).

  • ksl (array_like, optional) – Integrated strength of the high-order skew multipolar components (ksl[0] and ksl[1] should not be used).

  • model (str, optional) – Model used for the computation. It can be ‘expanded’ or ‘full’. Default is ‘expanded’.

  • num_multipole_kicks (int) – Number of multipole kicks used to model high order multipolar components.

Quadrupole

class xtrack.Quadrupole(**kwargs)

Quadrupole element.

Parameters:
  • k1 (float) – Strength of the quadrupole component in m^-2.

  • length (float) – Length of the element in meters.

  • knl (array_like, optional) – Integrated strength of the high-order normal multipolar components (knl[0] and knl[1] should not be used).

  • ksl (array_like, optional) – Integrated strength of the high-order skew multipolar components (ksl[0] and ksl[1] should not be used).

  • num_multipole_kicks (int, optional) – Number of multipole kicks used to model high order multipolar components.

CombinedFunctionMagnet

class xtrack.CombinedFunctionMagnet(**kwargs)

Implementation of combined function magnet (i.e. a bending magnet with a quadrupole component).

Parameters:
  • k0 (float) – Strength of the horizontal dipolar component in units of m^-1.

  • k1 (float) – Strength of the horizontal quadrupolar component in units of m^-2.

  • h (float) – Curvature of the reference trajectory in units of m^-1.

  • length (float) – Length of the element in units of m.

  • knl (array) – Integrated strength of the high-order normal multipolar components (knl[0] and knl[1] should not be used).

  • ksl (array) – Integrated strength of the high-order skew multipolar components (ksl[0] and ksl[1] should not be used).

  • num_multipole_kicks (int) – Number of multipole kicks used to model high order multipolar components.

DipoleEdge

class xtrack.DipoleEdge(k=None, e1=None, e1_fd=None, hgap=None, fint=None, model=None, side=None, **kwargs)

Beam element modeling a dipole edge (see MAD-X manual for detaild description).

Parameters:
  • k (float) – Strength in 1/m.

  • e1 (float) – Face angle in rad.

  • hgap (float) – Equivalent gap in m.

  • fint (float) – Fringe integral.

  • e1_fd (float) – Term added to e1 only for the linear mode and only in the vertical plane to acconut for non zero angle in the closed orbit when entering the fringe field (feed down effect).

  • model (str) – Model to be used for the edge. It can be ‘linear’, ‘full’ or ‘suppress’. Default is ‘linear’.

  • side (str) – Side of the bend on which the edge is located. It can be ‘entry’ or ‘exit’. Default is ‘entry’.

Sextupole

class xtrack.Sextupole(*args, **kwargs)

Sextupole element.

Parameters:
  • k2 (float) – Strength of the sextupole component in m^-3.

  • k2s (float) – Strength of the skew sextupole component in m^-3.

  • length (float) – Length of the element in meters.

Multipole

class xtrack.Multipole(order=None, knl=None, ksl=None, **kwargs)

Beam element modeling a thin magnetic multipole.

Parameters:
  • knl (array) – Normalized integrated strength of the normal components in units of m^-n.

  • ksl (array) – Normalized integrated strength of the skew components in units of m^-n.

  • order (int) – Order of the multipole. Default is 0.

  • hxl (float) – Rotation angle of the reference trajectory in the horizontal plane in radians. Default is 0.

  • hyl (float) – Rotation angle of the reference trajectory in the vertical plane in radians. Default is 0.

  • length (float) – Length of the originating thick multipole. Default is 0.

Solenoid

class xtrack.Solenoid(length=0, ks=0, ksi=0, **kwargs)

Solenoid element.

Parameters:
  • length (float) – Length of the element in meters.

  • ks (float) – Strength of the solenoid component in rad / m. Only to be specified when the element is thin, i.e. when length is 0.

  • ksi (float) – Integrated strength of the solenoid component in rad.

NonLinearLens

class xtrack.NonLinearLens(*args, **kwargs)

Beam element modeling a non-linear lens with elliptic potential. See the corresponding element in MAD-X documentation.

Parameters:
  • knll (float) – Integrated strength of lens (m). The strength is parametrized so that the quadrupole term of the multipole expansion is k1=2*knll/cnll^2.

  • cnll (float) – Focusing strength (m). The dimensional parameter of lens (m). The singularities of the potential are located at x=-cnll, +cnll and y=0.

Cavity

class xtrack.Cavity(*args, **kwargs)

Beam element modeling an RF cavity.

Parameters:
  • voltage (float) – Voltage of the RF cavity in Volts. Default is 0.

  • frequency (float) – Frequency of the RF cavity in Hertz. Default is 0.

  • lag (float) – Phase seen by the reference particle in degrees. Default is 0.

RFMultipole

class xtrack.RFMultipole(order=None, knl=None, ksl=None, pn=None, ps=None, **kwargs)

Beam element modeling a thin modulated multipole, with strengths dependent on the z coordinate:

Parameters:
  • order (int) – Order of the multipole. Default is 0.

  • knl (array) – Normalized integrated strength of the normal components in units of m^-n. Must be of length order+1.

  • ksl (array) – Normalized integrated strength of the skew components in units of m^-n. Must be of length order+1.

  • pn (array) – Phase of the normal components in degrees. Must be of length order+1.

  • ps (array) – Phase of the skew components in degrees. Must be of length order+1.

  • voltage (float) – Longitudinal voltage. Default is 0.

  • lag (float) – Longitudinal phase seen by the reference particle. Default is 0.

  • frequency (float) – Frequency in Hertz. Default is 0.

ReferenceEnergyIncrease

class xtrack.ReferenceEnergyIncrease(*args, **kwargs)

Beam element modeling a change of reference energy (acceleration, deceleration).

Parameters:

Delta_p0c (float) – Change in reference energy in eV. Default is 0.

Elens

class xtrack.Elens(inner_radius=1.0, outer_radius=1.0, current=0.0, elens_length=0.0, voltage=0.0, residual_kick_x=0, residual_kick_y=0, coefficients_polynomial=[0], _xobject=None, **kwargs)

Beam element modeling a hollow electron lens.

Parameters:
  • inner_radius (float) – Inner radius of the electron lens in meters. Default is 0.

  • outer_radius (float) – Outer radius of the electron lens in meters. Default is 0.

  • current (float) – Current of the electron lens in Ampere. Default is 0.

  • elens_length (float) – Length of the electron lens in meters. Default is 0.

  • voltage (float) – Voltage of the electron lens in Volts. Default is 0.

  • residual_kick_x (float) – Residual kick in the horizontal plane in radians. Default is 0.

  • residual_kick_y (float) – Residual kick in the vertical plane in radians. Default is 0.

  • coefficients_polynomial (array) – Array of coefficients of the polynomial. Default is [0].

  • polynomial_order (int) – Order of the polynomial. Default is 0.

Exciter

class xtrack.Exciter(*, samples=None, nsamples=None, sampling_frequency=0, frev=0, knl=[1], ksl=[], start_turn=0, duration=None, _xobject=None, **kwargs)

Beam element modeling a transverse exciter as a time-dependent thin multipole.

The given multipole components (knl and ksl) are scaled according to a custom waveform, allowing for arbitrary time dependence. The waveform is specified by an array of samples:

knl(t) = knl * samples[i]

It is not assumed that the variations are slow compared to the revolution frequency and the particle arrival time is taken into account when determining the sample index:

i = sampling_frequency * ( ( at_turn - start_turn ) / f_rev - zeta / beta0 / c0 )

where zeta=(s-beta0*c0*t) is the longitudinal coordinate of the particle, beta0 the relativistic beta factor of the particle, c0 is the speed of light, at_turn is the current turn number, f_rev is the revolution frequency, and sampling_frequency is the sampling frequency. The excitation starts with the first sample when the reference particle arrives at the element in start_turn.

For example, to compute samples for a sinusoidal excitation with frequency f_ex one would calculate the waveform as: samples[i] = np.sin(2*np.pi*f_ex*i/sampling_frequency)

Notes

  • This is not to be confused with an RFMultipole, which inherits the characteristics of an RFCavity and whose oscillation is therefore with respect to the reference particle. While the frequency of the RFMultipole is therefore restricted to harmonics of the revolution frequency, the exciter allows for arbitrary frequencies.

  • This is also not to be confused with an ACDipole, for which the oscillation is assumed to be slow compared to the revolution frequency and the kick is the same for all particles independent of their longitudinal coordinate.

Parameters:
  • knl (-) – Normalized integrated strength of the normal components. Unit: m^-n (n=0,1,2,…).

  • ksl (-) – Normalized integrated strength of the skew components. Unit: m^-n (n=0,1,2,…).

  • order (-) – Multipole order (readonly), i.e. largest n with non-zero knl or ksl.

  • samples (-) – Samples of excitation strength to scale knl and ksl as function of time.

  • nsamples (-) – Number of samples. Pass this instead of samples to reserve memory for later initialisation.

  • sampling_frequency (-) – Sampling frequency in Hz.

  • frev (-) – Revolution frequency in Hz of circulating beam (used to relate turn number to sample index).

  • start_turn (-) – Turn of the reference particle when to start excitation.

  • duration (-) – Duration of excitation in s (defaults to nsamples/sampling_frequency). Repeats the waveform to fill the duration.

Example

>>> fs = 10e6 # sampling frequency in Hz
>>>
>>> # load waveform into memory
>>> signal = np.copy(np.memmap("signal.10MHz.float32", np.float32))
>>>
>>> # alternatively compute samples on the fly, for example a simple sine at 500 kHz ...
>>> t = np.arange(1000)/fs
>>> f_ex = 5e5 # excitation frequency in Hz
>>> signal = np.sin(2*np.pi*f_ex*t)
>>>
>>> # ... or a sweep from 500 to 800 kHz
>>> f_ex_1 = 8e5
>>> signal = scipy.signal.chirp(t, f_ex, t[-1], f_ex_1)
>>>
>>> # create the exciter
>>> frev = 1e6 # revolution frequency in Hz
>>> k0l = 0.1 # this is scaled by the waveform
>>> exciter = Exciter(samples=signal, sampling_frequency=fs, frev=frev, start_turn=0, knl=[k0l])
>>>
>>> # add it to the line
>>> line.insert_element(index=..., name=..., element=exciter)

Wire

class xtrack.Wire(L_phy=0, L_int=0, current=0, xma=0, yma=0, post_subtract_px=0, post_subtract_py=0, _xobject=None, **kwargs)

Beam element modeling a wire (used for long range beam-beam compensation).

Parameters:
  • L_phy (float) – Physical length of the wire in meters. Default is 0.

  • L_int (float) – Interaction length of the wire in meters. Default is 0.

  • current (float) – Current of the wire in Ampere. Default is 0.

  • xma (float) – Horizontal position of the wire in meters. Default is 0.

  • yma (float) – Vertical position of the wire in meters. Default is 0.

  • post_subtract_px (float) – Horizontal post-subtraction kick in radians. Default is 0.

  • post_subtract_py (float) – Vertical post-subtraction kick in radians. Default is 0.

FirstOrderTaylorMap

class xtrack.FirstOrderTaylorMap(length=0.0, m0=None, m1=None, radiation_flag=0, **nargs)

First order Taylor map.

Parameters:
  • length (float) – length of the element in meters.

  • m0 (array_like) – 6x1 array of the zero order Taylor map coefficients.

  • m1 (array_like) – 6x6 array of the first order Taylor map coefficients.

  • radiation_flag (int) – Flag for synchrotron radiation. 0 - no radiation, 1 - radiation on.

SecondOrderTaylorMap

class xtrack.SecondOrderTaylorMap(*args, **kwargs)

Implements the second order Taylor map:

z_out[i] = k[i] + sum_j (R[i,j]*z_in[j]) + sum_jk (T[i,j,k]*z_in[j]*z_in[k])

where z = (x, px, y, py, zeta, pzeta)

Parameters:
  • length (float) – length of the element in meters.

  • k (array_like) – 6x1 array of the zero order Taylor map coefficients.

  • R (array_like) – 6x6 array of the first order Taylor map coefficients.

  • T (array_like) – 6x6x6 array of the second order Taylor map coefficients.

classmethod from_line(line, start, end, twiss_table=None, **kwargs)

Generate a SecondOrderTaylorMap from a Line object. The coefficients are computed with finite differences around the closed orbit.

Parameters:
  • line (Line) – A Line object.

  • start (str) – Name of the element where the map starts.

  • end (str) – Name of the element where the map stops.

  • twiss_table (TwissTable, optional) – A TwissTable object. If not given, it will be computed.

Returns:

A SecondOrderTaylorMap object.

Return type:

SecondOrderTaylorMap

scale_coordinates(scale_x=1, scale_px=1, scale_y=1, scale_py=1, scale_zeta=1, scale_pzeta=1)

Generate a new SecondOrderTaylorMap with scaled coordinates.

Parameters:
  • scale_x (float) – Scaling factor for x.

  • scale_px (float) – Scaling factor for px.

  • scale_y (float) – Scaling factor for y.

  • scale_py (float) – Scaling factor for py.

  • scale_zeta (float) – Scaling factor for zeta.

  • scale_pzeta (float) – Scaling factor for pzeta.

Returns:

A new SecondOrderTaylorMap with scaled coordinates.

Return type:

SecondOrderTaylorMap

LineSegmentMap

class xtrack.LineSegmentMap(length=None, qx=0, qy=0, betx=1.0, bety=1.0, alfx=0.0, alfy=0.0, dx=0.0, dpx=0.0, dy=0.0, dpy=0.0, x_ref=0.0, px_ref=0.0, y_ref=0.0, py_ref=0.0, longitudinal_mode=None, qs=None, bets=None, momentum_compaction_factor=None, slippage_length=None, voltage_rf=None, frequency_rf=None, lag_rf=None, dqx=0.0, dqy=0.0, det_xx=0.0, det_xy=0.0, det_yy=0.0, det_yx=0.0, energy_increment=0.0, energy_ref_increment=0.0, damping_rate_x=0.0, damping_rate_y=0.0, damping_rate_s=0.0, equ_emit_x=0.0, equ_emit_y=0.0, equ_emit_s=0.0, gauss_noise_ampl_x=0.0, gauss_noise_ampl_px=0.0, gauss_noise_ampl_y=0.0, gauss_noise_ampl_py=0.0, gauss_noise_ampl_zeta=0.0, gauss_noise_ampl_delta=0.0, **nargs)

Map representing a simplified segment of a beamline.

Parameters:
  • length (float) – Length of the segment in meters.

  • qx (float) – Horizontal tune or phase advance of the segment.

  • qy (float) – Vertical tune or phase advance of the segment.

  • betx (tuple of length 2 or float) – Horizontal beta function at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • bety (tuple of length 2 or float) – Vertical beta function at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • alfx (tuple of length 2 or float) – Horizontal alpha function at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • alfy (tuple of length 2 or float) – Vertical alpha function at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • dx (tuple of length 2 or float) – Horizontal dispersion at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • dpx (tuple of length 2 or float) – Px dispersion at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • dy (tuple of length 2 or float) – Vertical dispersion at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • dpy (tuple of length 2 or float) – Py dispersion at the entrance and exit of the segment. If a float is given, the same value is used for both entrance and exit.

  • x_ref (tuple of length 2 or float) – Horizontal position of the reference position at the entrance and exit of the segment (it is the closed orbit no other effects are present that perturb the closed orbit). If a float is given, the same value is used for both entrance and exit.

  • px_ref (tuple of length 2 or float) – Px coordinate of the reference position at the entrance and exit of the segment (it is the closed orbit no other effects are present that perturb the closed orbit). If a float is given, the same value is used for both entrance and exit.

  • y_ref (tuple of length 2 or float) – Vertical position of the reference position at the entrance and exit of the segment (it is the closed orbit no other effects are present that perturb the closed orbit). If a float is given, the same value is used for both entrance and exit.

  • py_ref (tuple of length 2 or float) – Py coordinate of the reference position at the entrance and exit of the segment (it is the closed orbit no other effects are present that perturb the closed orbit). If a float is given, the same value is used for both entrance and exit.

  • longitudinal_mode (str) – Longitudinal mode of the segment. Can be one of 'linear_fixed_qs', 'nonlinear', 'linear_fixed_rf' or 'frozen'.

  • qs (float) – Synchrotron tune of the segment. Only used if longitudinal_mode is 'linear_fixed_qs'.

  • bets (float) – Synchrotron beta function of the segment (positive above transition, negative below transition). Only used if longitudinal_mode is 'linear_fixed_qs'.

  • momentum_compaction_factor (float) – Momentum compaction factor of the segment. Only used if longitudinal_mode is 'nonlinear' or 'linear_fixed_rf'.

  • slippage_length (float) – Slippage length of the segment. Only used if longitudinal_mode is 'nonlinear' or 'linear_fixed_rf'. If not given, the length of the segment is used.

  • voltage_rf (list of float) – List of voltages of the RF kicks in the segment. Only used if longitudinal_mode is 'nonlinear' or 'linear_fixed_rf'.

  • frequency_rf (list of float) – List of frequencies of the RF kicks in the segment. Only used if longitudinal_mode is 'nonlinear' or 'linear_fixed_rf'.

  • lag_rf (list of float) – List of lag of the RF kicks in the segment. Only used if longitudinal_mode is 'nonlinear' or 'linear_fixed_rf'.

  • dqx (float) – Horizontal chromaticity of the segment.

  • dqy (float) – Vertical chromaticity of the segment.

  • det_xx (float) – Anharmonicity xx coefficient (i.e. dqx / dJx, where Jx is the horizontal action). Optional, default is 0.

  • det_xy (float) – Anharmonicity xy coefficient (i.e. dqx / dJy, where Jy is the vertical action). Optional, default is 0.

  • det_yx (float) – Anharmonicity yx coefficient (i.e. dqy / dJx, where Jx is the horizontal action). Optional, default is 0.

  • det_yy (float) – Anharmonicity yy coefficient (i.e. dqy / dJy, where Jy is the vertical action). Optional, default is 0.

  • energy_increment (float) – Energy increment of the segment in eV.

  • energy_ref_increment (float) – Increment of the reference energy in eV.

  • damping_rate_x (float) – Horizontal damping rate on the particles motion defined such that emit_x = emit_x(n=0) * exp(-damping_rate_x * n) where n is the turn number. Optional, default is 0.

  • damping_rate_y (float) – Vertical damping rate on the particles motion defined such that emit_y = emit_y(n=0) * exp(-damping_rate_y * n) where n is the turn number. Optional, default is 0.

  • damping_rate_s (float) – Longitudinal damping rate on the particles motion defined such that emit_s = emit_s(n=0) * exp(-damping_rate_s * n) where n is the turn number. Optional, default is 0.

  • equ_emit_x (float) – Horizontal equilibrium emittance (geometric). Optional.

  • equ_emit_y (float) – Vertical equilibrium emittance (geometric). Optional.

  • equ_emit_s (float) – Longitudinal equilibrium emittance (geometric). Optional.

  • gauss_noise_ampl_x (float) – Amplitude of Gaussian noise on the horizontal position. Optional, default is 0.

  • gauss_noise_ampl_px (float) – Amplitude of Gaussian noise on the horizontal momentum. Optional, default is 0.

  • gauss_noise_ampl_y (float) – Amplitude of Gaussian noise on the vertical position. Optional, default is 0.

  • gauss_noise_ampl_py (float) – Amplitude of Gaussian noise on the vertical momentum. Optional, default is 0.

  • gauss_noise_ampl_zeta (float) – Amplitude of Gaussian noise on the longitudinal position. Optional, default is 0.

  • gauss_noise_ampl_delta (float) – Amplitude of Gaussian noise on the longitudinal momentum. Optional, default is 0.

LinearTransferMatrix

N.B. This element is deprecated. Use LineSegmentMap instead.

class xtrack.LinearTransferMatrix(Q_x=0, Q_y=0, beta_x_0=1.0, beta_x_1=1.0, beta_y_0=1.0, beta_y_1=1.0, alpha_x_0=0.0, alpha_x_1=0.0, alpha_y_0=0.0, alpha_y_1=0.0, disp_x_0=0.0, disp_x_1=0.0, disp_y_0=0.0, disp_y_1=0.0, Q_s=0.0, beta_s=1.0, chroma_x=0.0, chroma_y=0.0, det_xx=0.0, det_xy=0.0, det_yy=0.0, det_yx=0.0, energy_increment=0.0, energy_ref_increment=0.0, x_ref_0=0.0, px_ref_0=0.0, x_ref_1=0.0, px_ref_1=0.0, y_ref_0=0.0, py_ref_0=0.0, y_ref_1=0.0, py_ref_1=0.0, damping_rate_x=0.0, damping_rate_y=0.0, damping_rate_s=0.0, equ_emit_x=0.0, equ_emit_y=0.0, equ_emit_s=0.0, gauss_noise_ampl_x=0.0, gauss_noise_ampl_px=0.0, gauss_noise_ampl_y=0.0, gauss_noise_ampl_py=0.0, gauss_noise_ampl_zeta=0.0, gauss_noise_ampl_delta=0.0, **nargs)

LongitudinalLimitRect

class xtrack.LongitudinalLimitRect(min_zeta=-10000000000.0, max_zeta=10000000000.0, min_pzeta=-10000000000.0, max_pzeta=10000000000.0, **kwargs)

Beam element introducing a limit on the longitudinal coordinates.

Parameters:
  • min_zeta (float) – Lower limit on zeta coordinate in meters.

  • max_zeta (float) – Upper limit on zeta coordinate in meters.

  • min_pzeta (float) – Lower limit on pzeta coordinate.

  • max_pzeta (float) – Upper limit on pzeta coordinate.

XYShift

class xtrack.XYShift(*args, **kwargs)

Beam element modeling an transverse shift of the reference system.

Parameters:
  • dx (float) – Horizontal shift in meters. Default is 0.

  • dy (float) – Vertical shift in meters. Default is 0.

SRotation

class xtrack.SRotation(angle=None, cos_z=None, sin_z=None, **kwargs)

Beam element modeling an rotation of the reference system around the s axis.

Parameters:

angle (float) – Rotation angle in degrees. Default is 0.

If either angle or a sufficient number of trig values are given, calculate the missing values from the others. If more than necessary parameters are given, their consistency will be checked.

XRotation

class xtrack.XRotation(angle=None, cos_angle=None, sin_angle=None, tan_angle=None, **kwargs)

Beam element modeling an rotation of the reference system around the x axis.

Parameters:

angle (float) – Rotation angle in degrees. Default is 0.

If either angle or a sufficient number of trig values are given, calculate the missing values from the others. If more than necessary parameters are given, their consistency will be checked.

YRotation

class xtrack.YRotation(angle=None, cos_angle=None, sin_angle=None, tan_angle=None, **kwargs)

Beam element modeling an rotation of the reference system around the y axis.

Parameters:

angle (float) – Rotation angle in degrees. Default is 0.

If either angle or a sufficient number of trig values are given, calculate the missing values from the others. If more than necessary parameters are given, their consistency will be checked.

ZetaShift

class xtrack.ZetaShift(dzeta=0, **nargs)

Beam element modeling a time delay.

Parameters:

dzeta (float) – Time shift dzeta in meters. Default is 0.

LimitEllipse

class xtrack.LimitEllipse(a=None, b=None, a_squ=None, b_squ=None, **kwargs)

Beam element modeling an elliptical aperture limit.

Parameters:
  • a (float) – Horizontal semi-axis in meters.

  • b (float) – Vertical semi-axis in meters.

LimitRect

class xtrack.LimitRect(min_x=-10000000000.0, max_x=10000000000.0, min_y=-10000000000.0, max_y=10000000000.0, **kwargs)

Beam element modeling a rectangular aperture limit.

Parameters:
  • min_x (float) – Lower x limit in meters.

  • max_x (float) – Upper x limit in meters.

  • min_y (float) – Lower y limit in meters.

  • max_y (float) – Upper y limit in meters.

LimitRectEllipse

class xtrack.LimitRectEllipse(max_x=10000000000.0, max_y=10000000000.0, a_squ=None, b_squ=None, a=None, b=None, **kwargs)

Element modeling an aperture limit given by the intersection of a symmetric LimitRect and a LimitEllipse.

The particles are lost if they exceed either the rect or ellipse aperture.

Parameters:
  • max_x (float) – Horizontal semi-axis of rect in meters.

  • max_y (float) – Vertical semi-axis of rect in meters.

  • a (float) – Horizontal semi-axis of ellipse in meters.

  • b (float) – Vertical semi-axis of ellipse in meters.

LimitRacetrack

class xtrack.LimitRacetrack(min_x=-10000000000.0, max_x=10000000000.0, min_y=-10000000000.0, max_y=10000000000.0, a=0, b=0, **kwargs)

Beam element modeling a racetrack aperture limit.

Parameters:
  • min_x (float) – Lower x limit in meters.

  • max_x (float) – Upper x limit in meters.

  • min_y (float) – Lower y limit in meters.

  • max_y (float) – Upper y limit in meters.

  • a (float) – Horizontal semi-axis in meters of ellipse used for the rounding of the corners.

  • b (float) – Vertical semi-axis in meters of ellipse used for the rounding of the corners.

LimitPolygon

class xtrack.LimitPolygon(x_vertices=None, y_vertices=None, **kwargs)

Beam element modeling a polygonal aperture limit.

Parameters:
  • x_vertices (array_like) – x coordinates of the vertices of the polygon in meters.

  • y_vertices (array_like) – y coordinates of the vertices of the polygon in meters.

Notes

The polygon is closed automatically by connecting the last and first vertex.

ParticlesMonitor

class xtrack.ParticlesMonitor(_context=None, _buffer=None, _offset=None, _xobject=None, start_at_turn=None, stop_at_turn=None, n_repetitions=None, repetition_period=None, num_particles=None, particle_id_range=None, auto_to_numpy=True)

Beam element logging the coordinates of the particles passing through it.

Parameters:
  • start_at_turn (int) – Turn at which the monitor starts logging the particles coordinates.

  • stop_at_turn (int) – Turn at which the monitor stops logging the particles coordinates.

  • n_repetitions (int) – Number of times the monitor repeats the logging of the particles.

  • repetition_period (int) – Period in number of turns for the repetition of the logging of the particles.

  • num_particles (int) – Number of particles to be logged.

  • particle_id_range (tuple of int) – Range of particle ids to be logged.

  • auto_to_numpy (bool) – If True, the data is automatically converted to numpy arrays when accessed.

LastTurnsMonitor

class xtrack.LastTurnsMonitor(*, n_last_turns=None, num_particles=None, particle_id_range=None, every_n_turns=1, _xobject=None, **kwargs)

Monitor to save particle data in last turns before respective particle loss

The monitor provides the following data as 2D array of shape (num_particles, n_last_turns), where the first index corresponds to the particle_id in particle_id_range and the second index corresponds to the turn (or every_n_turns) before the respective particle is lost: particle_id, at_turn, x, px, y, py, delta, zeta

Parameters:
  • n_last_turns (int) – Amount of turns to store before particle loss.

  • particle_id_range (tuple) – Range of particle ids to monitor (start, stop).

  • num_particles (int, optional) – Number of particles. Equal to passing particle_id_range=(0, num_particles).

  • every_n_turns (int, optional) – Save only every n-th turn, i.e. turn numbers which are a multiples of this. Because n_last_turns defines the amount of turns to store (and not the range), the data will cover turn numbers up to n_last_turns*every_n_turns turns before particle loss.

Example

monitor = LastTurnsMonitor(n_last_turns=5, particle_id_range=(1, 5)) monitor.at_turn[:,-1] # last turn before loss of each particle, respectively monitor.x[3,-2] # x coordinate in one but last turn of particle with id 4

Beam elements (xfields)

Beam-beam Bi-Gaussian 2D

class xfields.BeamBeamBiGaussian2D(scale_strength=1.0, other_beam_q0=None, other_beam_beta0=None, other_beam_num_particles=None, other_beam_Sigma_11=None, other_beam_Sigma_13=None, other_beam_Sigma_33=None, ref_shift_x=0, ref_shift_y=0, other_beam_shift_x=0, other_beam_shift_y=0, post_subtract_px=0, post_subtract_py=0, min_sigma_diff=1e-10, config_for_update=None, **kwargs)

Beam-beam Bi-Gaussian 3D

class xfields.BeamBeamBiGaussian3D(phi=None, alpha=None, other_beam_q0=None, scale_strength=1.0, slices_other_beam_num_particles=None, slices_other_beam_x_center=0.0, slices_other_beam_px_center=0.0, slices_other_beam_y_center=0.0, slices_other_beam_py_center=0.0, slices_other_beam_zeta_center=None, slices_other_beam_pzeta_center=0.0, flag_beamstrahlung=0, slices_other_beam_zeta_bin_width_beamstrahlung=None, slices_other_beam_zeta_bin_width_star_beamstrahlung=None, slices_other_beam_sqrtSigma_11_beamstrahlung=None, slices_other_beam_sqrtSigma_33_beamstrahlung=None, slices_other_beam_sqrtSigma_55_beamstrahlung=None, flag_bhabha=0, compt_x_min=0.0001, flag_beamsize_effect=1, flag_luminosity=0, slices_other_beam_x_center_star=None, slices_other_beam_px_center_star=None, slices_other_beam_y_center_star=None, slices_other_beam_py_center_star=None, slices_other_beam_zeta_center_star=None, slices_other_beam_pzeta_center_star=None, slices_other_beam_Sigma_11=None, slices_other_beam_Sigma_12=None, slices_other_beam_Sigma_13=None, slices_other_beam_Sigma_14=None, slices_other_beam_Sigma_22=None, slices_other_beam_Sigma_23=None, slices_other_beam_Sigma_24=None, slices_other_beam_Sigma_33=None, slices_other_beam_Sigma_34=None, slices_other_beam_Sigma_44=None, slices_other_beam_Sigma_11_star=None, slices_other_beam_Sigma_12_star=None, slices_other_beam_Sigma_13_star=None, slices_other_beam_Sigma_14_star=None, slices_other_beam_Sigma_22_star=None, slices_other_beam_Sigma_23_star=None, slices_other_beam_Sigma_24_star=None, slices_other_beam_Sigma_33_star=None, slices_other_beam_Sigma_34_star=None, slices_other_beam_Sigma_44_star=None, ref_shift_x=0, ref_shift_px=0, ref_shift_y=0, ref_shift_py=0, ref_shift_zeta=0, ref_shift_pzeta=0, other_beam_shift_x=0, other_beam_shift_px=0, other_beam_shift_y=0, other_beam_shift_py=0, other_beam_shift_zeta=0, other_beam_shift_pzeta=0, post_subtract_x=0, post_subtract_px=0, post_subtract_y=0, post_subtract_py=0, post_subtract_zeta=0, post_subtract_pzeta=0, min_sigma_diff=1e-10, threshold_singular=1e-28, old_interface=None, config_for_update=None, _sin_phi=None, _cos_phi=None, _tan_phi=None, _sin_alpha=None, _cos_alpha=None, **kwargs)

Space Charge Bi-Gaussian

class xfields.SpaceChargeBiGaussian(_context=None, _buffer=None, _offset=None, _xobject=None, update_on_track=False, length=None, apply_z_kick=False, longitudinal_profile=None, mean_x=0.0, mean_y=0.0, sigma_x=None, sigma_y=None, fieldmap=None, min_sigma_diff=1e-10, **kwargs)

Space Charge 3D

class xfields.SpaceCharge3D(_context=None, _buffer=None, _offset=None, update_on_track=True, length=None, apply_z_kick=True, fieldmap=None, x_range=None, y_range=None, z_range=None, nx=None, ny=None, nz=None, dx=None, dy=None, dz=None, x_grid=None, y_grid=None, z_grid=None, rho=None, phi=None, solver=None, gamma0=None, fftplan=None)

Simulates the effect of space charge on a bunch.

Parameters:
  • context (XfContext) – identifies the context on which the computation is executed.

  • update_on_track (bool) – If True the beam field map is update at each interaction. If False the initial field map is used at each interaction (frozen model). The default is True.

  • length (float) – the length of the space-charge interaction in meters.

  • apply_z_kick (bool) – If True, the longitudinal kick on the particles is applied.

  • x_range (tuple) – Horizontal extent (in meters) of the computing grid.

  • y_range (tuple) – Vertical extent (in meters) of the computing grid.

  • z_range (tuple) – Longitudina extent (in meters) of the computing grid.

  • nx (int) – Number of cells in the horizontal direction.

  • ny (int) – Number of cells in the vertical direction.

  • nz (int) – Number of cells in the vertical direction.

  • dx (float) – Horizontal cell size in meters. It can be provided alternatively to nx.

  • dy (float) – Vertical cell size in meters. It can be provided alternatively to ny.

  • dz (float) – Longitudinal cell size in meters.It can be provided alternatively to nz.

  • x_grid (np.ndarray) – Equispaced array with the horizontal grid points (cell centers). It can be provided alternatively to x_range, dx/nx.

  • y_grid (np.ndarray) – Equispaced array with the horizontal grid points (cell centers). It can be provided alternatively to y_range, dy/ny.

  • z_grid (np.ndarray) – Equispaced array with the horizontal grid points (cell centers). It can be provided alternatively to z_range, dz/nz.

  • rho (np.ndarray) – initial charge density at the grid points in Coulomb/m^3.

  • phi (np.ndarray) – initial electric potential at the grid points in Volts. If not provided the phi is calculated from rho using the Poisson solver (if available).

  • solver (str or solver object) – Defines the Poisson solver to be used to compute phi from rho. Accepted values are FFTSolver3D and FFTSolver2p5D. A Xfields solver object can also be provided. In case update_on_track``is ``False and phi is provided by the user, this argument can be omitted.

  • gamma0 (float) – Relativistic gamma factor of the beam. This is required only if the solver is FFTSolver3D.

Returns:

A space-charge 3D beam element.

Return type:

(SpaceCharge3D)

track(particles)

Computes and applies the space-charge forces for the provided set of particles.

Parameters:

particles (Particles Object) – Particles to be tracked.