Values: False (default), True
Keeps the intermediate files generated by CFFI. Used primarily for
debugging and testing.
cuda_backend — XSUITE_CUDA_BACKEND
Values: nvrtc (default), clang
Selects the compiler backend used for CUDA kernels.
cuda_fast_compile — XSUITE_CUDA_FAST_COMPILE
Values: True (default), False
Enables faster NVRTC compilation when supported.
cuda_compiler — XSUITE_CUDA_COMPILER
Values: None (default), executable path
Selects the clang++ executable used by the CUDA clang backend.
Notes
The same object is exposed as xobjects.settings and
xtrack.settings. Environment variables provide its initial values when
Xobjects is imported. Later Python assignments take precedence and can be
applied temporarily with override().
Boolean environment variables accept 1/0, true/false,
yes/no, and on/off, case-insensitively.
force_kernel_compilation=True skips prebuilt-kernel lookup and takes
precedence over allow_kernel_compilation. When forcing is disabled,
allow_kernel_compilation=True permits compilation only if a compatible
prebuilt kernel is unavailable. Compilation can also be enabled for one
context or element class by setting its allow_kernel_compilation
attribute to True. The legacy class attribute
allow_no_prebuilt_kernel is temporarily recognized for compatibility
with packages that have not migrated yet.
Examples
Allow Xsuite to compile a kernel when no compatible prebuilt kernel is
available:
length (float) – Length of the element in meters along the reference trajectory.
angle (float) – Angle of the bend in radians. This is the angle by which the reference
trajectory is bent in the horizontal plane.
k0 (float, optional) – Strength of the horizontal dipolar component in units of m^-1.
It can be set to the string value ‘from_h’, in which case k0 is
computed from the curvature defined by angle and length
(i.e. k0 = h = angle/length) and k0_from_h is set to True.
k1 (float, optional) – Strength of the quadrupolar component in units of m^-2.
k2 (float, optional) – Strength of the sextupolar component in units of m^-3.
k0_from_h (bool, optional) – If True, k0 is computed from the curvature defined by angle and
length (i.e. k0 = h = angle/length). Default is True. The flag
becomes false when k0 is set directly to a numeric value.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
knl_rel (array, optional) – Relative integrated strength of the normal components with respect to the
main component k0. The effect of knl_rel is added to the one of knl.
ksl_rel (array, optional) – Relative integrated strength of the skew components with respect to the
main component k0. The effect of ksl_rel is added to the one of ksl.
model (str) – Model used for the element. Available models are: “adaptive”,
“bend-kick-bend”, “rot-kick-rot”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”.
Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Edge effects at the entrance edge are active if True. Default is True.
edge_exit_active (bool) – Edge effects at the exit edge are active if True. Default is True.
edge_entry_model (str) – Model used for the entrance edge. Available models are: “suppressed”,
“linear”, “full”, “dipole-only”. Default is “linear”.
edge_exit_model (str) – Model used for the exit edge. Available models are: “suppressed”,
“linear”, “full”, “dipole-only”. Default is “linear”.
edge_entry_angle (float) – Entrance edge angle in radians. Default is 0.
edge_exit_angle (float) – Exit edge angle in radians. Default is 0.
edge_entry_angle_fdown (float) – Angle of the reference trajectory at the entrance edge. Used only
when edge_entry_model is “linear”. Default is 0.
edge_exit_angle_fdown (float) – Angle of the reference trajectory at the exit edge. Used only
when edge_exit_model is “linear”. Default is 0.
edge_entry_fint (float) – Fringe field integral at the entrance edge. Used only when
edge_entry_model is “full”. Default is 0.
edge_exit_fint (float) – Fringe field integral at the exit edge. Used only when
edge_exit_model is “full”. Default is 0.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Integrated strength of the main dipole component k0*length.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
length_strait (float) – Length of the element in meters along the axis of the magnet (straight line
between entry and exit points). This is different from the length of the
reference trajectory, i.e. the increase of the s coordinate through the
element, which is computed internally and can be inspected via the
length property.
angle (float) – Angle of the bend in radians. This is the angle by which the reference
trajectory is bent in the horizontal plane.
k0 (float) – Strength of the horizontal dipolar component in units of m^-1.
It can be set to the string value ‘from_h’, in which case k0 is
computed from the curvature defined by angle and length
(i.e. k0 = h = angle/length) and k0_from_h is set to True.
k1 (float) – Strength of the quadrupolar component in units of m^-2.
k2 (float) – Strength of the sextupolar component in units of m^-3.
k0_from_h (bool) – If True, k0 is computed from the curvature defined by angle and
length (i.e. k0 = h = angle/length). Default is True. The flag
becomes false when k0 is set directly to a numeric value.
rbend_model (str) – Model used for the rectangular bend. Possible values are:
“adaptive’, “curved-body”, “straight-body”. Default is “adaptive’,
which falls back to “curved-body”.
rbend_angle_diff (float) – Difference in radians between the angle of the reference trajectory
with respect to the magnet axis at the entrance and exit of the magnet.
See drawing on Xsuite Physics Guide. Default is 0.0.
rbend_shift (float) – Shift of the magnet body, in meters, defined as the displacement
of the reference trajectory with respect to the magnet axis at the center
of the magnet. This parameter has effect only when rbend_model is
“straight-body”. Default is 0.0.
rbend_compensate_sagitta (bool) – If True, the magnet body is shifted by half of the trajectory sagitta,
defined as (1 / h) * (1 - cos(angle / 2)). The shift is added to rbend_shift.
This parameter has effect only when rbend_model is “straight-body”.
Default is True.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
knl_rel (array) – Relative integrated strength of the normal components with respect to the
main component k0. The effect of knl_rel is added to the one of knl.
ksl_rel (array) – Relative integrated strength of the skew components with respect to the
main component k0. The effect of ksl_rel is added to the one of ksl.
model (str) – Model used for the element. Available models are: “adaptive”,
“bend-kick-bend”, “rot-kick-rot”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”.
Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Edge effects at the entrance edge are active if True. Default is True.
edge_exit_active (bool) – Edge effects at the exit edge are active if True. Default is True.
edge_entry_model (str) – Model used for the entrance edge. Available models are: “suppressed”,
“linear”, “full”, “dipole-only”. Default is “linear”.
edge_exit_model (str) – Model used for the exit edge. Available models are: “suppressed”,
“linear”, “full”, “dipole-only”. Default is “linear”.
edge_entry_angle (float) – Entrance edge angle in radians. Default is 0.
edge_exit_angle (float) – Exit edge angle in radians. Default is 0.
edge_entry_angle_fdown (float) – Angle of the reference trajectory at the entrance edge. Used only
when edge_entry_model is “linear”. Default is 0.
edge_exit_angle_fdown (float) – Angle of the reference trajectory at the exit edge. Used only
when edge_exit_model is “linear”. Default is 0.
edge_entry_fint (float) – Fringe field integral at the entrance edge. Used only when
edge_entry_model is “full”. Default is 0.
edge_exit_fint (float) – Fringe field integral at the exit edge. Used only when
edge_exit_model is “full”. Default is 0.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Integrated strength of the main dipole component k0*length.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
Rectangular with arbitrary face angles and arbitrary placement with respect to
the reference trajectory.
k1 (float) – Strength of the quadrupole component in m^-2.
k1s (float) – Strength of the skew quadrupole component in m^-2.
length (float) – Length of the element in meters.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
knl_rel (array, optional) – Relative integrated strength of the normal components with respect to the
main component k1 or k1s, depending whether main_is_skew is False or True, respectively.
The effect of knl_rel is added to the one of knl.
ksl_rel (array, optional) – Relative integrated strength of the skew components with respect to the
main component k1 or k1s, depending whether main_is_skew is False or True, respectively.
The effect of ksl_rel is added to the one of ksl.
main_is_skew (bool, optional) – If True, the main component is the skew one (k1s), otherwise it is the normal one (k1).
Default is False.
model (str) – Model used for the element. Available models are: “adaptive”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”. Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Fringe field at the entrance edge is active if True. Default is False.
edge_exit_active (bool) – Fringe field at the exit edge is active if True. Default is False.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Returns the integrated strength of the main component, i.e. k1*length
if the main component is the normal one, or k1s*length if the main component
is the skew one.
It is True if the main component is the skew one, i.e. k1s,
or False if the main component is the normal one, i.e. k1.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
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.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
knl_rel (array, optional) – Relative integrated strength of the normal components with respect to the
main component k2 or k2s, depending on whether main_is_skew is False or True, respectively.
The effect of knl_rel is added to the one of knl.
ksl_rel (array, optional) – Relative integrated strength of the skew components with respect to the
main component k2 or k2s, depending on whether main_is_skew is False or True, respectively.
The effect of ksl_rel is added to the one of ksl.
main_is_skew (bool, optional) – If False (default), the main component is the normal sextupole k2,
while if True the main component is the skew sextupole k2s.
model (str) – Model used for the element. Available models are: “adaptive”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”. Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Fringe field at the entrance edge is active if True. Default is False.
edge_exit_active (bool) – Fringe field at the exit edge is active if True. Default is False.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Returns the integrated strength of the main component, i.e. k2*length
if the main component is the normal one, or k2s*length if the main component
is the skew one.
It is True if the main component is the skew one, i.e. k2s,
or False if the main component is the normal one, i.e. k2.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
k3 (float) – Strength of the octupole component in m^-4.
k3s (float) – Strength of the skew octupole component in m^-4.
length (float) – Length of the element in meters.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
knl_rel (array, optional) – Relative integrated strength of the normal components with respect to the
main component k3 or k3s, depending on whether main_is_skew is False or True, respectively.
The effect of knl_rel is added to the one of knl.
ksl_rel (array, optional) – Relative integrated strength of the skew components with respect to the
main component k3 or k3s, depending on whether main_is_skew is False or True, respectively.
The effect of ksl_rel is added to the one of ksl.
main_is_skew (bool, optional) – If False (default), the main component is the normal octupole k3,
while if True the main component is the skew octupole k3s.
model (str) – Model used for the element. Available models are: “adaptive”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”. Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Fringe field at the entrance edge is active if True. Default is False.
edge_exit_active (bool) – Fringe field at the exit edge is active if True. Default is False.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Returns the integrated strength of the main component, i.e. k3*length
if the main component is the normal one, or k3s*length if the main component
is the skew one.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
knl (array) – Integrated strength of the normal components in units of m^-n.
ksl (array) – Integrated strength of the skew components in units of m^-n.
order (int) – Order of the multipole. By default it is inferred from the length of
knl and ksl.
hxl (float) – Rotation angle in radians applied to the reference trajectory in the
horizontal plane. Default is 0.
length (float) – Length of the originating thick multipole. Default is 0.
isthick (bool) – Whether the multipole is to be treated as thick (True) or thin (False).
Default is False.
knl_rel (array) – Relative integrated strength of the normal components with respect to the main
component defined by main_order and main_is_skew. The effect of
knl_rel is added to the one of knl.
ksl_rel (array) – Relative integrated strength of the skew components with respect to the main
component defined by main_order and main_is_skew. The effect of
ksl_rel is added to the one of ksl.
main_order (int) – Order of the main multipole component used for defining the relative strengths
knl_rel and ksl_rel. Default is 0.
main_is_skew (bool) – Whether the main multipole component used for defining the relative strengths
knl_rel and ksl_rel is skew (True) or normal (False). Default is False.
model (str) – Model used for the element. Available models are: “adaptive”,
“bend-kick-bend”, “rot-kick-rot”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”.
Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Fringe field at the entrance edge is active if True. Default is False.
edge_exit_active (bool) – Fringe field at the exit edge is active if True. Default is False.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
Uniform solenoid element with hard-edge fringe field. The axis of the
solenoid is assumed parallel to the s axis. Radiation and spin
precession are take place only in the solenoid body (no radiation and
precession in the fringe field).
Parameters:
ks (float) – Strength of the solenoid component (defined as B_s / reference_rigidity)
length (float) – Length of the element in meters.
x0 (float, optional) – Horizontal offset of the solenoid center in meters. Defaults to 0.
y0 (float, optional) – Vertical offset of the solenoid center in meters. Defaults to 0.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
edge_entry_active (bool) – Fringe field at the entrance edge is active if True. Default is False.
edge_exit_active (bool) – Fringe field at the exit edge is active if True. Default is False.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Get list of available integrators for this element.
Returns:
List of available integrators.
Return type:
List[str]
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
Solenoid with linearly varying lingitudinal field. The transverse fields
arising form the derivative of the longitudinal fields are taken into account
in particle dynamics, radiation, spin precession.
Parameters:
ks_profile (array-like of 2 floats) – Solenoid strength at entry and exit of the element (defined as
B_s / reference_rigidity).
length (float) – Length of the element in meters along the reference trajectory.
x0 (float, optional) – Horizontal offset of the solenoid center in meters. Defaults to 0.
y0 (float, optional) – Vertical offset of the solenoid center in meters. Defaults to 0.
knl (array-like) – Integrated strengths of additional normal multipole components in m^(-order).
ksl (array-like) – Integrated strengths of additional skew multipole components in m^(-order).
order (int) – Maximum order of additional multipole components. Default is 5.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_multipole_kicks (int) – Number of multipole kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
Get list of available integrators for this element.
Returns:
List of available integrators.
Return type:
List[str]
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
Thick element integrating the Lorentz force with a Boris stepper in a
magnetic field represented by piecewise polynomials in the longitudinal
coordinate.
The field is expressed in a local longitudinal coordinate
s_local\in[0,length]; any global s bookkeeping is handled at the
lattice level.
Parameters:
bs (Spline4, optional) – Longitudinal field component as Hermite boundary data.
bx (Spline4 or tuple/list of (Spline4 or None), optional) – Hermite data for the skew multipole components (Bx channel). A single
Spline4 corresponds to derivative order 0. A tuple/list item index
gives the transverse derivative order with respect to x;
None entries are treated as zero.
by (Spline4 or tuple/list of (Spline4 or None), optional) – Hermite data for the normal multipole components (By channel), with
the same indexing semantics as bx.
length (float) – Physical length of the element in meters.
n_steps (int) – Number of Boris substeps (must be >=1).
shift_x (float, optional) – Horizontal offset of the field map in meters. Default is 0.
shift_y (float, optional) – Vertical offset of the field map in meters. Default is 0.
scale_b (float, optional) – Multiplicative scale factor applied to the magnetic field. Default is 1.
radiation_flag (int, optional) – Radiation model flag. 0 disables radiation, non-zero values select
synchrotron radiation models as for other thick elements.
knl (array-like, optional) – Integrated strengths of additional normal multipole components in
m**(-order). The corresponding kick is split over the Boris steps.
ksl (array-like, optional) – Integrated strengths of additional skew multipole components in
m**(-order). The corresponding kick is split over the Boris steps.
Examples
Build a one-meter element with a normal dipole field plus a normal
quadrupole-gradient term and track particles through it:
importxtrackasxtbs0=xt.Spline4(val_start=0.02,der_start=0.0,val_end=0.02,der_end=0.0,mean=0.02,)bx0=xt.Spline4(val_start=0.03,der_start=0.0,val_end=0.03,der_end=0.0,mean=0.03,)by0=xt.Spline4(val_start=0.1,der_start=0.0,val_end=0.1,der_end=0.0,mean=0.1,)by1=xt.Spline4(val_start=20.0,der_start=0.0,val_end=20.0,der_end=0.0,mean=20.0,)element=xt.SplineBoris(bs=bs0,by=(by0,by1),# By = by0(s) + by1(s) * x + ...bx=(bx0,),# Bx skew dipole componentlength=1.0,n_steps=100,)line=xt.Line(elements=[element])line.particle_ref=xt.Particles("electron",p0c=1e9)particles=line.particle_ref.copy()particles.x=1e-3line.track(particles)
Higher-order normal or skew components can be supplied by adding entries to
by or bx. The tuple index is the transverse derivative order with
respect to x: by=(by0,by1,by2) defines normal dipole,
quadrupole-gradient and sextupole-like terms.
Build the element from Spline4 data and store Hermite boundary data in the xobject.
Evaluate B in the element’s local longitudinal coordinate.
Parameters:
x (float or array-like) – Transverse positions [m].
y (float or array-like) – Transverse positions [m].
s_local (float or array-like) – Local longitudinal coordinate(s) in the range [0,length].
If array-like, it is broadcast together with x and y.
The reconstruction of the three-dimensional field from the on-axis field data
is described in the Fieldexpansionfors-dependentmagneticfield chapter
of the Physics Guide.
Data defining a fourth-order longitudinal polynomial.
The five values constrain a quantity f(s) over one longitudinal
interval: its value and derivative at both boundaries, and its mean over
the interval. Together they uniquely define the fourth-order polynomial
used by SplineBoris.
Parameters:
val_start (float) – Value of f at the entrance of the interval.
der_start (float) – Longitudinal derivative df/ds at the entrance of the interval.
val_end (float) – Value of f at the exit of the interval.
der_end (float) – Longitudinal derivative df/ds at the exit of the interval.
mean (float) – Mean value of f over the interval.
Notes
The units depend on the quantity represented. For a magnetic-field
component, val_start, val_end, and mean are in tesla, while
der_start and der_end are in tesla per meter. For transverse field
derivatives, the corresponding additional inverse-meter powers apply.
Track particles through a magnetic field map with a spatial Boris stepper.
The element advances particles from s_start to s_end using
n_steps fixed longitudinal steps. The magnetic field is supplied by a
Python callable evaluated at each step midpoint. Only magnetic fields are
supported; no electric-field kick is applied.
Parameters:
fieldmap_callable (callable) – Function called as fieldmap_callable(x,y,z). It must accept arrays
of particle coordinates in meters and return (Bx,By,Bz) arrays in
tesla.
s_start (float) – Initial longitudinal coordinate, in meters, used when evaluating the
field map.
s_end (float) – Final longitudinal coordinate, in meters, used when evaluating the
field map.
n_steps (int) – Number of fixed spatial Boris steps between s_start and s_end.
verbose (bool, optional) – If True, print a progress line while tracking.
Track an xtrack.Particles object through the configured field map.
Only particles with state>0 are advanced. Lost particles are left
unchanged. When log_trajectories is True, the coordinates after
each Boris step are stored in x_log, y_log and z_log.
length (float) – Length of the RF cavity in meters. Default is 0.
voltage (float) – Voltage of the RF cavity in Volts. Default is 0.
frequency (float) – Frequency of the RF cavity in Hertz. It can be set only if harmonic is zero.
Default is 0.
harmonic (float) – Harmonic number of the RF cavity. It can be set only if frequency is zero.
If harmonic is non-zero, the frequency is computed from the length of the
beam_line and the speed of the reference particle (beta0 * clight).
When harmonic is set, the cavity can only be used within a Line and not
in standalone tracking (i.e. Cavity.track(…) will raise an error).
Default is 0.
phase (float) – Phase in radians seen at the arrival time of the reference particle (zeta = 0).
When absolute_time is True, phase is the phase at time zero. Default is 0.
lag (float) – Deprecated phase shift in degrees, added to phase. Default is 0.
absolute_time (bool) – If True, the cavity phase is computed from the absolute time of the
simulation, otherwise the cavity is synchronized with the arrival time of
the reference particle (zeta=0). Default is False.
model (str) – Model used for the element. Available models are: “adaptive”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”. Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_kicks (int) – Number of kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
length (float) – Length of the RF cavity in meters. Default is 0.
crab_voltage (float) – Voltage associated to the horizontal RF deflection in Volts. Default is 0.
frequency (float) – Frequency of the cavity in Hertz. It can be set only if harmonic is zero.
Default is 0.
phase (float) – Phase in radians seen at the arrival time of the reference particle (zeta = 0).
Default is 0.
lag (float) – Deprecated phase shift in degrees, added to phase. Default is 0.
model (str) – Model used for the element. Available models are: “adaptive”, “mat-kick-mat”,
“drift-kick-drift-exact”, “drift-kick-drift-expanded”. Default is “adaptive”.
integrator (str) – Integrator used for the element. Available integrators are: “adaptive”,
“teapot”, “yoshida4”, “uniform”. Default is “adaptive”.
num_kicks (int) – Number of kicks to be used. For the yoshida integrator, this
is rounded up to the nearest number compatible with the integrator scheme.
Default is 0, for which the number of kicks is chosen automatically
based on the element length and strength.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
Beam element modeling a thin modulated multipole, with strengths
dependent on the z coordinate:
Parameters:
frequency (float) – Frequency in Hertz. Default is 0.
knl (array) – Integrated strength of the normal rf-multipole components in units of m^-n.
ksl (array) – Integrated strength of the skew rf-multipole components in units of m^-n.
order (int) – Order of the multipole. If not provided, it will be inferred from knl and/or ksl.
phase_n (array) – Phase of the normal components in radians.
phase_s (array) – Phase of the skew components in radians.
pn (array) – Deprecated. Phase of the normal components in degrees.
ps (array) – Deprecated. Phase of the skew components in degrees.
voltage (float) – Longitudinal voltage. Default is 0.
phase (float) – Longitudinal phase in radians seen by the reference particle. Default is 0.
lag (float) – Deprecated longitudinal phase in degrees, added to phase. Default is 0.
shift_x (float) – Horizontal shift of the element in meters. Default is 0.
shift_y (float) – Vertical shift of the element in meters. Default is 0.
shift_s (float) – Longitudinal shift of the element in meters. Default is 0.
rot_s_rad (float) – Rotation around the longitudinal axis in radians. Default is 0.
rot_x_rad (float) – Rotation around the horizontal axis in radians. Default is 0.
rot_y_rad (float) – Rotation around the vertical axis in radians. Default is 0.
rot_s_rad_no_frame (float) – Additional rotation around the longitudinal axis in radians. In this case
the element field is rotated, but the reference frame at the interfaces
is not changed. Default is 0.
rot_shift_anchor (float) – Position along the element length where the rotations and shifts are applied.
Given in meters from the element entrance. Default is 0.
The definition of the misalignment parameters (rot_s_rad,
rot_s_rad_no_frame, rot_x_rad, rot_y_rad, shift_x, shift_y, shift_s)
can be found in the element misalignment section.
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:
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)
ACDipole is a thin element that applies an oscillating kick to the beam in the x or y direction.
It is used for beam excitations in circular machines for optics measurements. The kick is
a sinusoidal function defined by a voltage amplitude (with ramped up and down), a fixed frequency
(small compared to the revolution frequency) and fixed phase lag.
If the dipole is not in twiss mode (typically used for tracking simulations):
The kick is applied as a function of the turn number, and it can be ramped up and down
to avoid emittance growth. The transverse momentum in the vertical plane is changed by
(0.3 * volt/p0c) * sin(2π * freq * turn + lag).
If the dipole is in twiss mode:
It approximates the effect of an AC dipole, simulating it as a thin gradient error
see (Miyamoto, R., Kopp, S., Jansson, A., & Syphers, M. (2008). Parametrization of
the driven betatron oscillation. Phys. Rev. ST Accel. Beams, 11, 084002) for more details.
It applies a beta and tune shift to the beam in the horizontal plane,
depending on the natural and driven tunes.
If any of the parameters natural_q or beta_at_acdipole are not provided,
the effective gradient (eff_grad) during twiss mode is set to zero, meaning
it will have no effect on the twiss computation.
Parameters:
volt (float | None) – The voltages applied to control the peak of the kick in tracking mode.
If None, no kick is applied.
freq (float | None) – The driven frequency of the AC dipole, in units of 2π per turn. This is
equivalent to the fractional driven tune. If None, freq is set to zero.
Note that freq must be small compared to the revolution frequency.
_This is the only parameter that is used in _both_ tracking and twiss modes._
lag (float | None) – The phase lag of the AC dipole, in units of radians. This is only used in
tracking mode and shifts the phase of the sinusoidal kick.
If None, lag is set to zero.
ramp (list of int) – The ramp settings for the AC dipole, defining the turns for ramping up and
down the kick in tracking mode.
The list should contain four integers: [ramp1, ramp2, ramp3, ramp4].
- ramp1: Starting turn of amplitude ramp-up.
- ramp2: Last turn of amplitude ramp-up.
- ramp3: Starting turn of amplitude ramp-down.
- ramp4: Last turn of amplitude ramp-down.
If not provided, no kick is applied in tracking mode.
plane (str | None) – The plane in which the AC dipole acts, either ‘h’ or ‘v’ (lowercase).
If None, the ACDipole is turned off and has no effect in twiss or
tracking simulations.
twiss_mode (bool | None) – If True, the element is in twiss mode, and the effective gradient is computed
from freq, natural_q and beta_at_acdipole. If None or False, the element is in
tracking mode and applies kicks based on volt, freq, lag, and ramp.
beta_at_acdipole (float | None) – The beta function at the location of the AC dipole, in meters. This is only
required if the element is in twiss mode. If not provided, the effective
gradient is set to zero.
natural_q (float | None) – The natural tune of the machine in the specified plane.
This is only required if the element is in twiss mode.
If not provided, the effective gradient is set
to zero.
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.
Beam element modeling an electron cooler. In particular, this beam element uses the Parkhomchuk model for electron cooling.
Every turn each particle receives transverse and longitudinal kicks based on the cooling force provided by the Parkhomchuk model.
Parameters
currentfloat, optional
The current in the electron beam, in amperes.
lengthfloat, optional
The length of the electron cooler, in meters.
radius_e_beamfloat, optional
The radius of the electron beam, in meters.
temp_perpfloat, optional
The transverse temperature of the electron beam, in electron volts.
temp_longfloat, optional
The longitudinal temperature of the electron beam, in electron volts.
magnetic_fieldfloat, optional
The magnetic field strength, in tesla.
offset_xfloat, optional
The horizontal offset of the electron cooler, in meters.
offset_pxfloat, optional
The horizontal angle of the electron cooler, in rad.
offset_yfloat, optional
The horizontal offset of the electron cooler, in meters.
offset_pyfloat, optional
The vertical angle of the electron cooler, in rad.
offset_energyfloat, optional
The energy offset of the electrons, in eV.
magnetic_field_ratiofloat, optional
The ratio of perpendicular component of magnetic field with the
longitudinal component of the magnetic field. This is a measure
of the magnetic field quality. With the ideal magnetic field quality
being 0.
space_chargefloat, optional
Whether space charge of electron beam is enabled. 0 is off and 1 is on.
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'.
bucket_length (float) – The linear RF force becomes a sawtooth with a fixed point every
bucket_length [full length in seconds]. 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 lags in degrees of the RF kicks in the segment. Only used if
longitudinal_mode is 'nonlinear' or 'linear_fixed_rf'.
dqx (float or list of float) – Horizontal linear chromaticity of the segment.
dqy (float or list of float) – Vertical linear chromaticity of the segment.
ddqx (float) – Horizontal second order chromaticity of the segment
ddqy (float) – Vertical second order chromaticity of the segment
dnqx (list of float) – List of horizontal chromaticities up to any order. The first element
of the list is the horizontal tune, the second element is the
horizontal linear chromaticity, the third element the horizontal
second order chromaticity and so on. It can be specified only if the
horizontal tune, and chromaticities are not specified.
dnqy (list of float) – List of vertical chromaticities up to any order. The first element
of the list is the vertical tune, the second element is the
vertical linear chromaticity, the third element the vertical
second order chromaticity and so on. It can be specified only if the
vertical tune, and chromaticities are not specified.
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) – Damping rate of the horizontal position
x_n+1 = (1-damping_rate_x)*x_n. Optional, default is 0.
damping_rate_px (float) – Damping rate of the horizontal momentum
px_n+1 = (1-damping_rate_px)*px_n. Optional, default is 0.
damping_rate_y (float) – Damping rate of the vertical position
y_n+1 = (1-damping_rate_y)*y_n. Optional, default is 0.
damping_rate_py (float) – Damping rate of the vertical momentum
px_n+1 = (1-damping_rate_x)*py_n. Optional, default is 0.
damping_rate_z (float) – Damping rate of the longitudinal position
z_n+1 = (1-damping_rate_z)*z_n. Optional, default is 0.
damping_rate_pzeta (float) – Damping rate on the momentum
pzeta_n+1 = (1-damping_rate_pzeta)*pzeta_n. Optional, default is 0.
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_pzeta (float) – Amplitude of Gaussian noise on the longitudinal momentum. Optional, default is 0.
damping_matrix (float[6,6]) – Matrix of damping: Each paticles coordinate vector (x,px,y,py,zeta,pzeta) is multiplied
by the identity + the damping matrix. Incompatible with inputs damping_rate_*.
Optional, default is None
gauss_noise_matrix (float[6,6]) – Covariance matrix of the Gaussian noise applied in (x,px,y,py,zeta,pzeta).
Incompatible with inputs gauss_noise_ampl_*. Optional, default is None
rot_s_rad (float) – Rotation around the longitudinal axis applied to the element [rad].
rot_x_rad (float) – Rotation around the horizontal axis applied to the element [rad].
rot_y_rad (float) – Rotation around the vertical axis applied to the element [rad].
seq (str) – Sequence of rotations, as a permutation of ‘x’, ‘y’, ‘s’.
Default is ‘yxs’, which means that the first rotation applied to
the element is around y, then around x, and finally around s.
Beam element modeling a rotation of the reference system around the s-axis.
Warning
SRotation is deprecated and will be removed in a future version. Please use Rotation(rot_s_rad=…) instead.
The sign convention is such that:
px_out = px_in * cos(angle) - py_in * sin(angle)
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.
Beam element modeling a rotation of the reference system around the x-axis.
Warning
XRotation is deprecated and will be removed in a future version. Please use Rotation(rot_x_rad=…) instead.
The sign convention is such that:
py_out = py_in * cos(angle) + pz_in * sin(angle)
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.
Beam element modeling a rotation of the reference system around the y-axis.
Warning
YRotation is deprecated and will be removed in a future version. Please use Rotation(rot_y_rad=…) instead.
The sign convention is such that:
px_out = px_in * cos(angle) - pz_in * sin(angle)
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.
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.
svg (dict containing) – “path” : string describing an svg path
“scale” : scale from svg unit to meters default= 0.001
“curved_steps” : steps for curved segments default=10
“line_steps” : steps for linear segments default=2}
Notes
The polygon is closed automatically by connecting the last and first vertex.
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
Monitor to save the transversal centroid of the tracked particles
The monitor allows for arbitrary sampling rate and can thus not only be used to monitor
bunch positions, but also to record schottky spectra. Internally, the particle arrival time
is used when determining the record index:
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.
Note that the index is rounded, i.e. the result array represents data of particles
equally distributed around the reference particle. For example, if the sampling_frequency
is twice the revolution frequency, the first item contains data from particles in the
range zeta/circumference = -0.25 .. 0.25, the second item in the range 0.25 .. 0.75 and
so on.
The monitor provides the following data:
count, x_sum, x_mean, y_sum, y_mean,
each as an array of size:
num_particles (int, optional) – Number of particles to monitor. Defaults to -1 which means ALL.
particle_id_start (int, optional) – First particle id to monitor. Defaults to 0.
particle_id_range (tuple, optional) – Range of particle ids to monitor (start, stop). Stop is exclusive.
Defaults to (particle_id_start, particle_id_start+num_particles).
start_at_turn (int) – First turn of reference particle (inclusive) at which to monitor.
stop_at_turn (int) – Last turn of reference particle (exclusiv) at which to monitor.
frev (float) – Revolution frequency in Hz of circulating beam (used to relate turn number to sample index).
sampling_frequency (float) – Sampling frequency in Hz.
Monitor to save the transverse profile of the tracked particles
The monitor allows for arbitrary sampling rate and can thus not only be used to monitor
bunch profiles, but also for coasting beams. Internally, the particle arrival time
is used when determining the record index:
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.
Note that the index is rounded, i.e. the result array represents data of particles
equally distributed around the reference particle. For example, if the sampling_frequency
is twice the revolution frequency, the first item contains data from particles in the
range zeta/circumference = -0.25 .. 0.25, the second item in the range 0.25 .. 0.75 and
so on.
The monitor provides the following data:
- x_intensity, y_intensity: the profile intensity (particle count per bin) as 2D array of shape (size, n)
x_edges, y_edges: the profile edges (position) in m as 1D array of shape (n+1)
x_grid, y_grid: the profile position (midpoints) in m as 1D array of shape (n)
Parameters:
num_particles (int, optional) – Number of particles to monitor. Defaults to -1 which means ALL.
particle_id_start (int, optional) – First particle id to monitor. Defaults to 0.
particle_id_range (tuple, optional) – Range of particle ids to monitor (start, stop). Stop is exclusive.
Defaults to (particle_id_start, particle_id_start+num_particles).
start_at_turn (int) – First turn of reference particle (inclusive) at which to monitor.
stop_at_turn (int) – Last turn of reference particle (exclusiv) at which to monitor.
frev (float) – Revolution frequency in Hz of circulating beam (used to relate turn number to sample index).
sampling_frequency (float) – Sampling frequency in Hz.
nx (int, optional) – Number of raster points of the horizontal profile. Defaults to 128.
x_range (float or tuple) – Extend of raster points of the profile in m. Either a tuple of (min_x, max_x)
or a scalar width in which case a range of (-width/2, width/2) is used.
ny (int, optional) – Number of raster points of the vertical profile. Defaults to 128.
y_range (float or tuple) – Extend of raster points of the profile in m. Either a tuple of (min_y, max_y)
or a scalar width in which case a range of (-width/2, width/2) is used.
n – Default value for nx and ny if these are not set.
range – Default value for x_range and y_range if these are not set.
Monitor to save the transverse beam size (standard deviation of the tracked particle positions)
The monitor allows for arbitrary sampling rate and can thus not only be used to monitor
bunch emittance, but also to record coasting beams. Internally, the particle arrival time
is used when determining the record index:
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.
Note that the index is rounded, i.e. the result array represents data of particles
equally distributed around the reference particle. For example, if the sampling_frequency
is twice the revolution frequency, the first item contains data from particles in the
range zeta/circumference = -0.25 .. 0.25, the second item in the range 0.25 .. 0.75 and
so on.
The monitor provides the following data:
- count Number of particles
- x_mean, y_mean Beam position in m (centroid, i.e. mean of particle x, y)
- x_std, y_std Beam size in m (standard deviation of particle x, y)
- x_var, y_var Variance of particle x, y in m² (= std**2)
- x_sum, y_sum Sum of particle x, y in m (= mean * count)
- x2_sum, y2_sum Sum of particle x, y squared in m² (= (std**2 + mean**2) * count)
each as an array of size:
num_particles (int, optional) – Number of particles to monitor. Defaults to -1 which means ALL.
particle_id_start (int, optional) – First particle id to monitor. Defaults to 0.
particle_id_range (tuple, optional) – Range of particle ids to monitor (start, stop). Stop is exclusive.
Defaults to (particle_id_start, particle_id_start+num_particles).
start_at_turn (int) – First turn of reference particle (inclusive) at which to monitor.
stop_at_turn (int) – Last turn of reference particle (exclusiv) at which to monitor.
frev (float) – Revolution frequency in Hz of circulating beam (used to relate turn number to sample index).
sampling_frequency (float) – Sampling frequency in Hz.
The monitor records beam statistics over selected turns. It operates in
one of four modes selected from the constructor inputs:
beam mode: no bunch or slice inputs are provided. One value is recorded
per logged turn for the whole beam.
bunch mode: bunch inputs are provided without slice inputs. One value is
recorded per logged turn and selected physical slot. Whole-beam
statistics are also available.
slice mode: zeta_range and num_slices are provided. One value is
recorded per logged turn, selected physical slot, and longitudinal slice.
Per-bunch and whole-beam statistics are also available.
coasting mode: coasting=True and num_slices are provided. One value
is recorded per logged turn and full-turn slice. Whole-beam statistics
are also available.
In this monitor, “slot” means a bunch position on the bunch pattern grid,
where adjacent slots are separated in zeta by bunch_spacing_zeta.
Note that bunch_spacing_zeta is distinct from an RF bucket, which can be
finer than the bunch spacing.
The bunch pattern to be monitored can be specified using either
filling_scheme or filled_slots. For example,
filling_scheme=[1, 0, 1, 1] is equivalent to
filled_slots=[0, 2, 3]. The selected_slots argument can be used to
record only a subset of the filled slots. A “slice” is a longitudinal
subdivision inside a bunch, or a full-turn subdivision in coasting mode.
All statistics are weighted by particles.weight. The public
num_particles quantity is therefore the sum of particle weights in each
bin, not the number of macroparticles.
Particle species diagnostics can be requested with sum_charge_ratio,
mean_charge_ratio, sum_mass_ratio, and mean_mass_ratio; these
quantities use the same particles.weight weighting.
The optional particle_id_range=(start,stop) argument restricts
recording to particles with particle_id in the inclusive-lower,
exclusive-upper range [start,stop).
Whole-beam statistics, obtained with level="beam", are computed from
all accepted particles for the same effective turn. In bunched and sliced
modes, this means summing the recorded weighted sums over the selected
slots and slices; unselected filled slots do not contribute.
Requested statistics are available as attributes at the most detailed
recorded level, for example monitor.mean_x. The get() method
gives access to a specific aggregation level and accepts physical
selectors:
monitor.get("mean_x")# Default level, with shape depending on the monitor mode.monitor.get("mean_x",level="beam")# Shape: (n_logged_turns,)monitor.get("mean_x",level="bunch")# Shape: (n_logged_turns, n_selected_slots)monitor.get("mean_x",level="bunch",slot=3)# Shape: (n_logged_turns,)monitor.get("mean_x",level="slice")# Shape: (n_logged_turns, n_selected_slots, n_slices)monitor.get("mean_x",level="slice",slot=3,slice_index=12)# Shape: (n_logged_turns,)
Scalar selectors such as turn=10, slot=3, or slice_index=12
remove the selected axis by default. Use keepdims=True to preserve
length-one axes.
Parameters:
start_at_turn (int, optional) – First turn to record, inclusive.
stop_at_turn (int, optional) – Last turn to record, exclusive. If omitted, record only
start_at_turn.
every_n_turns (int, optional) – Record turns separated by this stride.
zeta_range (tuple[float, float], optional) – Longitudinal range for slice mode. Must be provided together with
num_slices.
num_slices (int, optional) – Number of longitudinal slices per selected bunch.
bunch_spacing_zeta (float, optional) – Longitudinal spacing between adjacent bunch slots.
num_bunches (int, optional) – Number of consecutive filled slots. Mutually exclusive with
filled_slots and filling_scheme.
filling_scheme (array_like, optional) – Slot-indexed boolean/integer filling scheme identifying filled slots.
Mutually exclusive with num_bunches and filled_slots.
filled_slots (array_like, optional) – Explicit slot numbers which are filled. Mutually exclusive
with num_bunches and filling_scheme.
selected_slots (array_like, optional) – Filled slots to record. Output follows this order.
coasting (bool, optional) – If True, slice the full turn periodically for a coasting beam.
Requires num_slices and rejects bunched-beam filling inputs.
particle_id_range (tuple[int, int], optional) – Inclusive-lower, exclusive-upper particle-id range to record. By
default all particles are recorded.
stats (sequence of str, optional) – Requested public statistics.
output_file (str or path-like, optional) – HDF5 file where save_to_file() appends the current frame.
profiles (dict, optional) – Optional weighted profile histograms, keyed by coordinate. Each value
must define range=(min,max) and num_bins.
Initialize the monitor configuration and primitive moment storage.
Return covariance-derived optics diagnostics for one selected bin.
The monitor must have stored the full 6D covariance moment set, for
example by requesting a coupled-emittance or covariance-optics
statistic. The returned dictionary contains the selected covariance
matrix, emittances, W matrix, Twiss parameters, dispersion, and status
metadata. The internal dummy map used to define the normal form is not
exposed.
Append newly available records to an HDF5 output file.
If output_file is provided, it becomes the monitor output file. The
file is created if missing, or validated and appended to if it already
exists. Only newly touched records are appended. Use
start_new_frame() to clear the in-memory frame and retarget the
monitor to later turns.
2D beam-beam element in the soft-Gaussian approximation.
Parameters:
scale_strength (float) – Used to scale beam-beam force strength. Scales other_beam_q0.
other_beam_q0 (float) – Charge sign of opposing beam. -1 for electrons, +1 for protons or positrons.
other_beam_beta0 (float) – Relativistic beta of the opposing beam.
other_beam_num_particles (float) – Number of real charges in the opposing bunch.
other_beam_Sigma_{13}{13} (float) – Statistical moments (variances and covariance of x (=1) and y (=3)) of the opposing bunch, in the unboosted accelerator frame.
ref_shift_{xy} (float) – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
other_beam_shift_{x (float) – Closed orbit shift of the opposing beam. Subtracted and from the opposing slice centroids before collision and added back after.
y} (float) – Closed orbit shift of the opposing beam. Subtracted and from the opposing slice centroids before collision and added back after.
post_subtract_{px (float) – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
py} (float) – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
min_sigma_diff (float) – Round beam kick (~2x faster) is used instead of elliptical kick, if fabs(sigma_x-sigma_y) < min_sigma_diff.
config_for_update (xfields.ConfigForUpdateBeamBeamBiGaussian3D) – Used for (quasi-)strong-strong beam-beam and None for weak-strong. See documentation of xfields.ConfigForUpdateBeamBeamBiGaussian3D.
3D beam-beam element in the soft-Gaussian approximation.
Parameters:
phi (float) – Half crossing angle in [rad].
alpha (float) – Crossing plane. E.g. CMS (y-z crossing) has alpha=pi/2 and ATLAS (x-z crossing) has alpha=0.
other_beam_q0 (float) – Charge sign of opposing beam. -1 for electrons, +1 for protons or positrons.
scale_strength (float) – Used to scale beam-beam force strength. Scales other_beam_q0.
slices_other_beam_num_particles (float array) – Number of real charges per slice in the opposing bunch. Length of the array is the number of longitudinal slices.
slices_other_beam_{x (float array) – Array storing the per-slice centroid variables of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
px (float) – Array storing the per-slice centroid variables of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
y (float) – Array storing the per-slice centroid variables of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
py (float) – Array storing the per-slice centroid variables of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
zeta (float) – Array storing the per-slice centroid variables of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
pzeta}_center (float array) – Array storing the per-slice centroid variables of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
flag_beamstrahlung (int) – Flag to simulate beamstrahlung. 0: OFF, 1: ON (mean, only for testing), 2: ON (quantum, use this for simulations)
slices_other_beam_zeta_bin_width_beamstrahlung (float array) – Array storing the longitudinal bin width in the unboosted accelerator frame. Length of the array is the number of longitudinal slices. Used for beamstrahlung only.
slices_other_beam_zeta_bin_width_star_beamstrahlung (float array) – Array storing the longitudinal bin width in the boosted accelerator frame. Length of the array is the number of longitudinal slices. Used for beamstrahlung only. Obtained as slices_other_beam_zeta_bin_width_beamstrahlung/cos(phi).
slices_other_beam_sqrtSigma_{135}{135}_beamstrahlung (float array) – Array storing the per-slice standard deviations of x (=1), y (=3) and zeta (=5) of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices. Used for beamstrahlung only.
flag_bhabha (int) – Flag to simulate small angle radiative Bhabha scattering. 1: ON (quantum), 0: OFF
compt_x_min (float) – Low energy cut on virtual photon spectrum, used for Bhabha, in units of [gamma^-2] where gamma is the rel. Lorentz factor.
compt_scale (float) – Scaling factor to scale up photon generation, used for Bhabha.
flag_beamsize_effect (int) – Flag to simulate beamsize effect, used for Bhabha. 1: ON, 0: OFF. Results in ~factor 2 reduction in cross section.
flag_luminosity (int) – Flag to record soft-Gaussian luminosity per bunch crossing in a buffer. Luminosity will be in units of [m^-2].
slices_other_beam_{x – Array storing the per-slice centroid variables of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
px – Array storing the per-slice centroid variables of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
y – Array storing the per-slice centroid variables of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
py – Array storing the per-slice centroid variables of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
zeta – Array storing the per-slice centroid variables of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
pzeta}_center_star (float array) – Array storing the per-slice centroid variables of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
slices_other_beam_Sigma_{1234}{1234} (float array) – Array storing the per-slice statistical moments (variances and covariances of x (=1), px (=2), y (=3), py (=4)) of the opposing bunch, in the unboosted accelerator frame. Length of the array is the number of longitudinal slices.
slices_other_beam_Sigma_{1234}{1234}_star (float array) – Array storing the per-slice statistical moments (variances and covariances of x (=1), px (=2), y (=3), py (=4)) of the opposing bunch, in the boosted accelerator frame. Length of the array is the number of longitudinal slices.
ref_shift_{x (float) – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
px – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
y – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
py – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
zeta – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
pzeta} (float) – Closed orbit shift, subtracted from each macroparticle before collision and added back after.
other_beam_shift_{x (float) – Closed orbit shift of the opposing beam (used in weak-strong mode). Subtracted and from the opposing slice centroids before collision and added back after.
px – Closed orbit shift of the opposing beam (used in weak-strong mode). Subtracted and from the opposing slice centroids before collision and added back after.
y – Closed orbit shift of the opposing beam (used in weak-strong mode). Subtracted and from the opposing slice centroids before collision and added back after.
py – Closed orbit shift of the opposing beam (used in weak-strong mode). Subtracted and from the opposing slice centroids before collision and added back after.
zeta – Closed orbit shift of the opposing beam (used in weak-strong mode). Subtracted and from the opposing slice centroids before collision and added back after.
pzeta} – Closed orbit shift of the opposing beam (used in weak-strong mode). Subtracted and from the opposing slice centroids before collision and added back after.
post_subtract_{x (float) – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
px – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
y – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
py – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
zeta – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
pzeta} – Additional quantity that is subtracted after the beam-beam collision. Used e.g. for dipole kick.
min_sigma_diff (float) – Round beam kick (~2x faster) is used instead of elliptical kick, if fabs(sigma_x-sigma_y) < min_sigma_diff.
threshold_singular (float) – Small number used to handle singularities when transporting slice moments from interaction point (IP) to collision point (CP).
old_interface (dict) – Dictionary containing parameters with the old interface. (obsolete)
config_for_update (xfields.ConfigForUpdateBeamBeamBiGaussian3D) – Used for (quasi-)strong-strong beam-beam and None for weak-strong. See documentation of xfields.ConfigForUpdateBeamBeamBiGaussian3D.
_sin_phi (float) – Sine of half crossing angle.
_cos_phi (float) – Cosine of half crossing angle.
_tan_phi (float) – Tangent of half crossing angle.
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
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 True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
Beam element to apply IBS effects to particles during tracking according to
the formalism introduced in :cite:`NuclInstr:Zenkevich:Kinetic_IBS`. It provides
momenta kicks based on analytical growth rates, weighted by the longitudinal
line density of the particles and including a random component.
The element starts off by default (will not affect particles) and has to be
configured through the line.configure_intrabeam_scattering method.
The frequency at which to recompute the kick coefficients, in
number of turns. They will be computed at the first turn of
tracking, and then every update_every turns afterwards.
The computed diffusion coefficients, from the kinetic theory.
This attribute self-updates when they are computed with the
.compute_kinetic_coefficients method.
The computed friction coefficients, from the kinetic theory.
This attribute self-updates when they are computed with the
.compute_kinetic_coefficients method.
Type:
FrictionCoefficients
Initialize the Simple IBS kick element. It is off
by default and will have to be configured (see the
line.configure_intrabeam_scattering method).
Parameters:
num_slices (int) – The number of slices used for the computation of
the bunch’s longitudinal line density.
Computes the IBS friction coefficients (named \(D_x, D_y\)
and \(D_z\) in this code base) and friction coefficients (named
\(F_x, F_y\) and \(F_z\)) from the kinetic theory introduced
in :cite:`NuclInstr:Zenkevich:Kinetic_IBS`. These are computed from
terms of Nagaitsev’s theory for faster evaluation, according to the
derivations done in :cite:arXiv:`Zampetakis:Interplay_SC_IBS_LHC`.
Notes
The calculation is done according to the following steps, which are related
to the derivations found in :cite:arXiv:`Zampetakis:Interplay_SC_IBS_LHC`
(in which the generalized diffusion and friction coefficients are used):
Computes various terms from the Nagaitsev formalism
Computes the intermediate \(D_{xx}, D_{xz}, D_{yy}\) and \(D_{zz}\) terms from Eq (39-41, 44)
Computes the intermediate \(K_x, K_y\) and \(K_z\) terms from Eq (42-44)
Computes the diffusion coefficients \(D_{x,y,z}\) from Eq (45-47)
Computes the friction coefficients \(F_{x,y,z}\) from Eq (48-50)
Parameters:
particles (xtrack.Particles) – The particles to apply the IBS kicks to and compute it from.
Returns:
A tuple with the computed kinetic coefficients slotted into a
DiffusionCoefficients and a FrictionCoefficients objects.
Method to determine and apply IBS momenta kicks based on the provided
xtrack.Particles. The kicks are implemented according to Eq (19) of
:cite:arXiv:`Zampetakis:Interplay_SC_IBS_LHC`.
Parameters:
particles (xtrack.Particles) – The particles to apply the IBS kicks to and compute it from.
Beam element that performs a Monte Carlo Touschek scattering simulation
at a single location in a lattice.
Each element represents one scattering center along the lattice. When
scatter() is called it draws macro-particle pairs from the local
6D phase-space (Gaussian) distribution, applies the Møller cross-section,
boosts scattered pairs back to the lab frame, and returns the subset of
macro-particles whose momentum deviation exceeds the local momentum
acceptance (LMA).
The element is passive during normal tracking (track is a no-op);
all physics happens inside scatter().
The Monte Carlo kernel is implemented in C99 and follows the ELEGANT
algorithm of Xiao & Borland (PRSTAB 13, 074201, 2010).
Parameters:
s (float, optional) – Longitudinal position of the element in the lattice [m]. Default 0.
n_scattering_events (int, optional) – Number of Touschek scattering events to generate in the Monte Carlo
loop. Larger values reduce statistical noise but increase CPU time.
nx (float, optional) – Truncation of the Gaussian distribution in the transverse and
longitudinal planes. nz may be reduced automatically by
TouschekStudy to prevent particles being drawn outside the
LMA before scattering.
ny (float, optional) – Truncation of the Gaussian distribution in the transverse and
longitudinal planes. nz may be reduced automatically by
TouschekStudy to prevent particles being drawn outside the
LMA before scattering.
nz (float, optional) – Truncation of the Gaussian distribution in the transverse and
longitudinal planes. nz may be reduced automatically by
TouschekStudy to prevent particles being drawn outside the
LMA before scattering.
theta_min (float, optional) – Lower and upper limits of the centre-of-mass scattering angle
theta [rad]. In practice set to 0.00005*pi and
0.99995*pi to avoid the forward/backward divergence of the
Møller cross-section.
theta_max (float, optional) – Lower and upper limits of the centre-of-mass scattering angle
theta [rad]. In practice set to 0.00005*pi and
0.99995*pi to avoid the forward/backward divergence of the
Møller cross-section.
piwinski_rate (float, optional) – Local Piwinski scattering rate [Hz] evaluated at this element.
Stored for diagnostics; not used in the Monte Carlo kernel.
weight_retention_fraction (float, optional) – Fraction of the generated scattering weight to retain in the returned
particle sample. The highest-weight particles are retained until their
cumulative weight reaches approximately this fraction of the total
generated weight. The default value of 1.0 keeps all generated
particles. Values smaller than one reduce tracking cost by discarding
the lowest-weight tail, at the price of a controlled downward
truncation of the represented rate.
integrated_piwinski_rate (float, optional) – Piwinski rate integrated (trapezoidal rule) over the lattice section
preceding this element and divided by the line length to give the
section contribution to the ring-averaged per-bunch rate [1/s].
Set by TouschekStudy.initialise_touschek(); used to weight
the scattered macro-particles.
Scattering rate [Hz] associated with the low-weight particles
discarded by pickPart in the last call to scatter(),
i.e. approximately (1-weight_retention_fraction) times
total_mc_rate.
Mapping {particle_id:theta} of centre-of-mass scattering
angles [rad] for the particles returned by the last call to
scatter().
Type:
dict
Notes
Physics summary
The Monte Carlo loop follows Xiao & Borland (PRSTAB 13, 074201, 2010):
Two particles are drawn from the local 6-D Gaussian distribution
using selectPartGauss with a truncated range of
nx, ny, and nz.
The pair is boosted to the centre-of-mass (CM) frame
(bunch2cm).
A scattering angle theta is drawn uniformly between
theta_min and theta_max, and a random azimuthal angle phi
is drawn uniformly between 0 and pi.
The Møller cross-section moeller is evaluated at
theta.
Scattered momenta are rotated (eulertrans) and boosted back to
the lab frame (cm2bunch).
A particle is selected for tracking only if its resulting
delta falls outside the LMA:
delta<delta_neg or delta>delta_pos.
pickPart retains only the highest-weight particles whose
cumulative weight reaches approximately
weight_retention_fraction of the total simulated weight.
The remaining low-weight events are discarded.
Macro-particle weights are normalised so that
the sum of weight equals the per-turn loss rate in the corresponding
lattice section (in particles/turn).
References
Create a Touschek scattering element.
Most local optics and beam parameters are normally supplied later by
xfields.TouschekStudy; direct construction is mainly used to
place scattering markers in a line before configuring a study.
Parameters:
s (float, optional) – Longitudinal position of the element in the lattice.
piwinski_rate (float, optional) – Local Piwinski scattering rate.
weight_retention_fraction (float, optional) – Fraction of generated scattering weight retained in the returned
particle sample.
ignored_portion (float, optional) – Deprecated alias for 1-weight_retention_fraction.
integrated_piwinski_rate (float, optional) – Piwinski rate integrated over the lattice section represented by
this element.
rng ({'elegant', 'xtrack'}, optional) – Random-number generator used by scatter(). 'elegant'
reproduces the Elegant/SDDS generator sequence; 'xtrack' uses
the xtrack accurate uniform generator.
**kwargs – Keyword arguments forwarded to xtrack.BeamElement.
_rng_state (TouschekRNGState or None, optional) – Explicit Elegant-compatible RNG state. Used only when
rng='elegant'. If None, a temporary state is created from a
seed drawn with numpy.random.
_rng_particle (xtrack.Particles or None, optional) – Carrier particle holding the xtrack RNG state. Used only when
rng='xtrack'. If None, a temporary carrier is created and
seeded from numpy.random.
Returns:
particles – Particles selected by the local momentum-acceptance criterion and
weighted so that their total weight represents the retained
section scattering rate.
Build a Touschek study and validate the supplied line, optics, beam
parameters, and local momentum acceptance table.
The configured study computes the local Piwinski scattering rate at
each TouschekScattering element, integrates those rates over
the lattice sections represented by the elements, and configures the
elements with the local optics and beam parameters needed to generate
weighted Monte Carlo particles.
In user code, the TouschekStudy instance for a line is
typically obtained with line.xfields.touschek_configure(...).
After construction, call run() to obtain a
TouschekResult. With tracking disabled, run() returns
the integrated scattering rate, the corresponding Touschek lifetime,
and a per-element diagnostics table. With tracking enabled, it also
returns the tracked loss rate and the corresponding lifetime. The
generated and lost particle samples are returned only when
keep_particles=True is passed to run().
Parameters:
line (xtrack.Line) – Line containing the TouschekScattering elements to
configure.
elements (str, sequence of str, or None, optional) – Touschek scattering elements included in the study. If None,
all TouschekScattering elements in the line are used.
twiss (xtrack.TwissTable or None, optional) – Twiss table used for optics-dependent rates. If None, it is
computed when initialise_touschek() is called.
local_momentum_acceptance (xtrack.Table) – Table with name, s, delta_neg, and delta_pos
columns.
nemitt_x (float, optional) – Normalized horizontal and vertical emittances. Mutually exclusive
with gemitt_x and gemitt_y.
nemitt_y (float, optional) – Normalized horizontal and vertical emittances. Mutually exclusive
with gemitt_x and gemitt_y.
bunch_intensity (float) – Number of real particles in the bunch.
n_scattering_events (int) – Number of Monte Carlo scattering events generated at each
scattering element.
n_simulated (int, optional) – Deprecated alias for n_scattering_events.
gemitt_x (float, optional) – Geometric horizontal and vertical emittances. Mutually exclusive
with nemitt_x and nemitt_y.
gemitt_y (float, optional) – Geometric horizontal and vertical emittances. Mutually exclusive
with nemitt_x and nemitt_y.
local_momentum_acceptance_scale (float, optional) – Multiplicative factor applied to delta_neg and delta_pos.
weight_retention_fraction (float, optional) – Fraction of the generated scattering weight retained in the
generated particle sample.
ignored_portion (float, optional) – Deprecated alias for 1-weight_retention_fraction.
seed (int or None, optional) – Seed for the random-number generator. If provided, a reproducible
Touschek Monte Carlo sequence is used. If None (default), a
seed is drawn with numpy.random when particles are
generated.
rng ({'elegant', 'xtrack'}, optional) – Random-number generator used for Monte Carlo particle generation.
'elegant' reproduces the Elegant/SDDS generator sequence;
'xtrack' uses the xtrack accurate uniform generator.
nx (float, optional) – Gaussian sampling cutoffs in the horizontal, vertical, and
longitudinal planes.
ny (float, optional) – Gaussian sampling cutoffs in the horizontal, vertical, and
longitudinal planes.
nz (float, optional) – Gaussian sampling cutoffs in the horizontal, vertical, and
longitudinal planes.
**kwargs – Additional keyword arguments forwarded to line.twiss() when a
Twiss table is computed internally.
The scattering rate reported in the result is the integrated Piwinski
rate configured on the Touschek elements. If track is true,
particles are generated and tracked from each scattering element back
to itself to estimate the tracking-derived loss rate.
Parameters:
track (bool, optional) – If True, track generated particles and compute the loss rate
from particles lost during tracking. If False, only the
configured scattering rate is reported.
n_turns (int or None, optional) – Number of turns to track. Required when track is True.
generate_particles (bool or None, optional) – If True, generate weighted scattered particles even when
tracking is disabled. If None, particles are generated only
when track is True.
keep_particles (bool, optional) – If True, store the generated particle samples in the returned
TouschekResult. If False (default), particles are
generated and tracked as needed but are not retained in the result.
When tracking is disabled, setting keep_particles=True also
requests particle generation.
with_progress (bool, optional) – Forwarded to xtrack.Line.track() when tracking is enabled.
Returns:
result – Study result containing local rates, scattering rate and lifetime,
optional tracking-derived rate and lifetime, and optionally the
generated and lost particle samples.
1. Evaluates the local Piwinski scattering rate using the Twiss
parameters, beam emittances, and the local momentum acceptance.
2. Integrates the rate over the preceding lattice section using the
trapezoidal rule to obtain the per-bunch, per-turn loss probability.
3. Stores the integrated rate and all local optics parameters on the
element via TouschekScattering._configure() so that
TouschekScattering.scatter() can weight the Monte Carlo
macro-particles correctly.
Parameters:
element (str or None, optional) – If None (default), all TouschekScattering elements in
the line are initialised in one pass. If a string, only the named
element is (re-)initialised; the Piwinski rate is integrated only
over the lattice section between that element and the preceding
scattering centre.
Return an xt.Table with per-scattering-element diagnostics.
Parameters:
particles_by_element (dict or None, optional) – Mapping from element name to the particles generated at that
element. If provided, Monte Carlo particle counts and weight sums
are included in the table.
include_tracking (bool, optional) – If True, include loss-count and lost-weight columns computed
from tracked particle states. This option is meaningful only when
particles_by_element is provided.
Returns:
table – Per-element diagnostics table. It always contains name, s,
delta_neg, delta_pos, piwinski_rate, and
integrated_piwinski_rate. If particles are provided, it also
contains total_mc_rate, ignored_rate, num_particles,
and sum_weight. If include_tracking is True, it
additionally contains num_lost_particles and
sum_lost_weight.
The result separates quantities inferred from the scattering model from
quantities obtained after tracking the generated particles. The particle
samples are optional and are stored only when TouschekStudy.run() is
called with keep_particles=True.
Parameters:
element_names (list) – Names of the Touschek scattering elements included in the result.
local_momentum_acceptance (xtrack.Table) – Local momentum acceptance table used by the study.
local_rates (xtrack.Table) – Per-element diagnostics table. It always contains name, s,
delta_neg, delta_pos, piwinski_rate, and
integrated_piwinski_rate. When particles are generated it also
contains total_mc_rate, ignored_rate, num_particles, and
sum_weight. When tracking is enabled it additionally contains
num_lost_particles and sum_lost_weight.
rate_scattering (float) – Total Touschek scattering rate represented by the result [1/s].
lifetime_scattering (float) – Touschek lifetime inferred from rate_scattering [s].
rate_tracking (float or None) – Weighted loss rate after tracking generated particles [1/s]. None
when tracking is disabled.
lifetime_tracking (float or None) – Touschek lifetime inferred from rate_tracking [s]. None when
tracking is disabled.
particles_by_element (dict or None) – Mapping {element_name:xtrack.Particles} with the generated
particles for each scattering element. None unless
keep_particles=True.
where \(\bar{x}(z)\) and \(\bar{y}(z)\) are the transverse centroids,
and \(\lambda(z)\) is the line density. The exponents \((i,j)\) belong
to the source moments, while \((k,l)\) apply to the test particle offsets.
Longitudinal kicks are defined so that the energy momentum deviation change is:
with the sign convention that a positive wake causes energy loss.
Each predefined kind maps to a plane and to a set of source exponents
\((i,j)\) and test exponents \((k,l)\), following \(W^{i,j,k,l}\) in
the formulas above. The available kinds are listed below:
kind
plane
source_exponents
test_exponents
meaning
longitudinal
z
(0, 0)
(0, 0)
longitudinal
constant_x
x
(0, 0)
(0, 0)
constant x
constant_y
y
(0, 0)
(0, 0)
constant y
dipolar_x
x
(1, 0)
(0, 0)
dipolar / driving x
dipolar_y
y
(0, 1)
(0, 0)
dipolar / driving y
dipolar_xy
x
(0, 1)
(0, 0)
dipolar / driving xy
dipolar_yx
y
(1, 0)
(0, 0)
dipolar / driving yx
quadrupolar_x
x
(0, 0)
(1, 0)
quadrupolar / detuning x
quadrupolar_y
y
(0, 0)
(0, 1)
quadrupolar / detuning y
quadrupolar_xy
x
(0, 0)
(0, 1)
quadrupolar / detuning xy
quadrupolar_yx
y
(0, 0)
(1, 0)
quadrupolar / detuning yx
Wakefield objects can be initialized in different ways, as illustrated by the following
examples.
# Horizontal + vertical dipolar with same r/q/f_rw2=xw.WakeResonator(kind=['dipolar_x','dipolar_y'],r=1e8,q=1e5,f_r=1e9)
Weighted components (dict)
# Scale horizontal twice as strong as verticalw3=xw.WakeResonator(kind={'dipolar_x':2.0,'dipolar_y':1.0},r=1e8,q=1e5,f_r=1e9)
Using Yokoya factors
# Flat chamber (horizontal) yokoya factors expanded into the right componentsw4=xw.WakeResonator(kind=xw.Yokoya('flat_horizontal'),r=1e8,q=1e5,f_r=1e9)
Custom polynomial term
# Custom plane/exponents without a predefined kind entryw5=xw.WakeResonator(plane='y',source_exponents=(1,0),# x_source^1 y_source^0test_exponents=(0,2),# x_test^0 y_test^2r=1e8,q=1e5,f_r=1e9)
Combine and configure
w=w1+w2+w3.components[0]# mix whole wakes and single componentsw.configure_for_tracking(zeta_range=(-0.1,0.1),num_slices=200)
kind (str | list[str] | tuple[str] | dict[str, float] | xwakes.Yokoya, optional) – Predefined wake kind(s). A dict scales each kind by its value. If
None, a custom polynomial term must be provided via plane and
exponent arguments.
plane ({'x','y','z'}, optional) – Plane used only when kind is None to define a the plane in which the
wake acts.
source_exponents (tuple[int, int], optional) – Exponents (x^a y^b) on the source coordinates when kind is None.
test_exponents (tuple[int, int], optional) – Exponents (x^c y^d) on the test coordinates when kind is None.
r (float) – Shunt impedance (units depend on kind, e.g. Ohm/m for dipolar).
q (float) – Quality factor.
f_r (float) – Resonant frequency [Hz].
f_roi_level (float, default 0.5) – Fractional cutoff used to build ROI meshes for impedance/wake sampling.
Additional information on the definition of element properties and the
implemented physics and models can be found in the “Wakefields and
impedances” section of the Xsuite physics guide:
https://xsuite.readthedocs.io/en/latest/physicsguide.html
Generic wake object handling multiple wake components.
Parameters:
components (list[xwakes.wit.Component]) – List of wake components.
kind (str | list[str] | tuple[str] | dict[str, float], optional) – Predefined wake kind(s). A dict scales each kind by its value. If
None, a custom term must be defined via plane and exponent arguments.
plane ({'x','y','z'}, optional) – Plane used only when kind is None to define a the plane in which the
wake acts.
source_exponents (tuple[int, int], optional) – Exponents (x^a y^b) on the source coordinates when kind is None.
test_exponents (tuple[int, int], optional) – Exponents (x^c y^d) on the test coordinates when kind is None.
radius (float) – Beam pipe radius [m].
length (float, default 1.0) – Effective length of the wall segment [m].
resistivity (float) – Material resistivity [Ohm*m].
Additional information on the definition of element properties and the
implemented physics and models can be found in the “Wakefields and
impedances” section of the Xsuite physics guide:
https://xsuite.readthedocs.io/en/latest/physicsguide.html
Generic wake object handling multiple wake components.
Parameters:
components (list[xwakes.wit.Component]) – List of wake components.
Build wake components from sampled tables (e.g. HEADTAIL format).
Parameters:
table (pandas.DataFrame | dict) – Must contain a 'time' column plus one or more wake columns matching
KIND_DEFINITIONS keys (e.g. 'longitudinal', 'dipolar_x').
Dict input is converted to a DataFrame.
columns (iterable[str], optional) – Subset of columns to use. Defaults to all columns except 'time'.
Examples
importpandasaspdimportnumpyasnpimportxwakesasxw# Minimal example table: time plus dipolar and quadrupolar componentstable=pd.DataFrame({'time':np.linspace(0,1e-9,5),'dipolar_x':[0.0,1.0,0.5,-0.2,0.0],'quadrupolar_x':[0.0,-0.5,-0.25,0.1,0.0],})wf=xw.WakeFromTable(table,columns=['dipolar_x','quadrupolar_x'])wf.configure_for_tracking(zeta_range=(-0.4,0.4),num_slices=100)
You can also read legacy HEADTAIL/PyHEADTAIL tables directly:
Additional information on the definition of element properties and the
implemented physics and models can be found in the “Wakefields and
impedances” section of the Xsuite physics guide:
https://xsuite.readthedocs.io/en/latest/physicsguide.html
Generic wake object handling multiple wake components.
Parameters:
components (list[xwakes.wit.Component]) – List of wake components.
Read legacy HEADTAIL/PyHEADTAIL wake tables into a pandas DataFrame.
Parameters:
wake_file (str | path-like) – Path to the ASCII wake table file.
wake_file_columns (list[str]) – Ordered list of column names in the file. Must include 'time' and
can contain any of the valid wake components (e.g. 'longitudinal',
'dipolar_x', 'quadrupolar_y'). Length must match the number of
columns in the file.
Returns:
Columns are converted to SI units (time in seconds, wakes scaled to
V/C/m^n according to component).
The Xsuite environment manages variables and elements that can be shared by
different lines and can be used to create elements and line objects. See
Xsuite environment in the User’s guide for
tutorial examples.
Associate a particle type to a name. The particle is stored in Environment.particles, its properties can be controlled with deferred expressions and it can be used as reference particle for lines.
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.
importxtrackasxtenv=xt.Environment()env['kq']=0.2env.new('qf','Quadrupole',length=1.0,k1='kq')element=env.get('qf')value=env.get('kq')# element is the Quadrupole object; value is 0.2
importxtrackasxtenv=xt.Environment()env['a']=2.0env['b']='3*a'expr=env.get_expr('b')# expr is the expression controlling b.# env.get_expr('a') returns None because a is a constant.
line (xtrack.Line) – Line to import. Its elements, variables, particle reference,
configuration, and metadata are copied into this environment.
suffix_for_common_elements (str, optional) – Suffix to be added to the names of the elements that are common to
the imported line and the line in this environment. If None,
'/{line_name}' is used.
rename_elements (dict, optional) – Dictionary with the elements to be renamed. The keys are the names
of the elements in line, and the values are the new names.
line_name (str, optional) – Name of the new line. If None, the name of the imported line is used.
overwrite_vars (bool, optional) – If True, the variables in the imported line will overwrite the
variables with the same name in this environment. Default is False.
prototype (str or class) – Prototype class or name of the prototype element
parent (str or class, optional) – Deprecated alias for prototype.
mode (str, optional) –
clone: clone the prototype element or line.
The prototype element or line is copied, together with the associated
expressions.
replica: replicate the prototype elements or lines are made.
import: clone from a different environment. import_from must be
provided.
at (float or str, optional) – Position of the created object.
from (str, optional) – Name of the element from which the position is calculated (its center
is used as reference).
mirror (bool, optional) – Can only be used when cloning lines. If True, the order of the elements
is reversed.
import_from (Environment, optional. Only to be used when mode is 'import'.) –
Notes
Environment.new can instantiate only the built-in element classes
supported by the line builder. For user-defined element classes, or
other element types that are not supported by Environment.new,
instantiate the element explicitly, store it in env.elements, and
attach deferred expressions through the environment view.
Returns:
Name of the created element or line or a Place object if at or from_ is
provided.
components (list, optional) – List of components to be added to the line. It can include strings,
place objects, and lines.
name (str, optional) – Name of the new line.
refer (str, optional) – Specifies which part of the component the at position will refer
to. Allowed values are start, center (default; also allowed
is centre), and end.
length (float | str, optional) – Length of the line to be built by the composer. Can be an expression.
If not specified, the length will be the minimum length that can
fit all the components.
mirror (bool, optional) – Whether the line should be mirrored after creation.
compose (bool, optional) – Whether to instantiate the line in compose mode, which allows
the components to be added to the line after creation.
s_tol (float, optional) – Difference between two s positions below which they should be
treated as the same location.
diagnostics (bool, optional) – If true, analyze unresolved placement dependencies when immediate
line assembly fails. In compose mode, pass this option to
xtrack.Line.end_compose() when finalizing the line.
Returns:
The new line.
Return type:
line
Examples
importxtrackasxtenv=xt.Environment()env['a']=3# Define a variableenv.new('mq1','Quadrupole',length=0.3,k1='a')env.new('mq2','Quadrupole',length=0.3,k1='-a')ln=env.new_line(name='myline',components=['mq1',env.new('mymark','Marker',at=10.0),env.new('mq1_clone','mq1',k1='2*a'),env.place('mq2',at=20.0,from_='mymark'),])
Container of named beam elements stored in the environment.
Use this container to inspect, add, replace, or remove elements by
name. Element names share the environment namespace with variables,
particles, and lines.
Returns:
elements – Dictionary-like container of elements. When expression management
is enabled, item access returns reference-aware views.
importxtrackasxtenv=xt.Environment()env['kq']=0.2env.new('qf','Quadrupole',length=1.0)env.ref['qf'].k1=2*env.ref['kq']env.ref['qf'].k1.xdeps.info()# Info for element_refs['qf'].k1## value: 0.4## controlled by expr:# element_refs['qf'].k1 = (2 * vars['kq'])
importxtrackasxtenv=xt.Environment()env.vars['a']=2.0env.vars['b']='3*a'env.vars.get_table().show()# name value expr# t_turn_s 0 None# a 2 None# b 6 (3.0 * a)
Associate a particle type to a name. The particle is stored in
Environment.particles, its properties can be controlled with deferred
expressions and it can be used as reference particle for lines.
Note that this method is not meant to create particles distributions for
tracking. For that purpose use xt.Particles(…), Line.build_particles(…)
or the generation functions for particles distributions available in xpart.
See https://xsuite.readthedocs.io/en/latest/particlesmanip.html for more
details.
Parameters:
name (str) – Name of the new particle type
parent (str or class) – Parent class or name of the parent particle type
pdg_id_0 (int or str, optional, define reference mass and charge from) – PDG id or particle name.
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
rigidity0 (array_like of float, optional) – Reference magnetic rigidity [T.m]
kinetic_energy0 (array_like of float, optional) – Reference kinetic energy [eV]
Examples
Create a positron particle type with gamma0 controlled by a deferred
expression:
>>> env=xt.Environment()>>> env['a']=5>>> env.new_particle('my_particle_type',pdg_id_0='positron',gamma0='3*a')'my_particle_type'>>> env['my_particle_type'].gamma0View of LinkedArrayCpu([15.])>>> env['a']=10>>> env['my_particle_type'].gamma0View of LinkedArrayCpu([30.])
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.
check_limits (bool) – If True (default), the limits of the knobs are checked before the
optimization. If False, if the knobs are out of limits, the optimization
knobs are set to the limits on the first iteration.
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.
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.
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.
indent (int, optional) – Indentation level used for the JSON output. Default is 1.
**kwargs – Additional keyword arguments passed to Environment.to_dict.
Returns:
This method writes the serialized environment to file.
This function is deprecated and will be removed in a future
version. Please use xtrack.load(…), which uses the xsuite native MAD-X
parser, without requiring Cpymad. In case you need to use cpymad for
specific features, please load the individual lines using
Line.from_madx_sequence(…) and add them to the environment
using Environment.import_line(…).
Parameters:
filename (str, optional) – The MAD-X file to load from.
madx (cpymad.madx.Madx, optional) – Existing MAD-X instance to load from.
stdout (object, optional) – Stream used by the legacy MAD-X loader.
return_lines (bool, optional) – Whether to return individual lines instead of an environment.
**kwargs – Additional keyword arguments are passed to the Line.from_madx_sequence
method.
Deprecated: set multipolar errors for specified elements of the environment.
Warning
This function is deprecated and will be removed in a future
version. Please use the attributes knl_rel and ksl_rel of the elements
to set relative multipolar errors directly on the elements.
Parameters:
errors (dict) –
Dictionary with the errors to be set. The keys are the names of the
elements, and the values are dictionaries with the following keys:
rel_knl: list of relative errors for the normal multipolar strengths.
rel_ksl: list of relative errors for the skew multipolar strengths.
refer: name of the strength to be used as reference, which is
multiplied by the length. If None, the default reference strength
is used (k0 for bends, k1 for quadrupoles, k2 for sextupoles,
and k3 for octupoles).
with_progress (bool, optional) – Whether to show progress while applying errors. Defaults to
True.
Instances are available as env.vars and provide dictionary-like access
to environment variables, expressions, variable values, and variable table
generation.
Instances are available as env.elements. The container provides
dictionary-like access to named elements and returns reference-aware views
when the environment has variable management enabled.
Container for named particle references stored in an environment.
Instances are available as env.particles. The container provides
dictionary-like access to particle objects and returns reference-aware views
when the environment has variable management enabled.
Instances are used internally by xtrack.Environment to expose the
current reference particle while allowing the reference particle to be stored
either directly or by name.
Table returned by environment variable table methods.
VarsTable stores one row per environment variable. The main columns are
the variable name, its current value, and the expression that defines it,
when present. It is returned by methods such as env.vars.get_table().
Create a variable table.
Parameters:
data (mapping) – Mapping containing variable-table columns. Typical columns are
name, value, and expr.
*args – Additional positional arguments passed to xtrack.Table.
**kwargs – Additional keyword arguments passed to xtrack.Table.
The returned view is used to select multiple columns while preserving
the table type. Columns can be selected from a whitespace-separated
string or from an iterable of column names. String selectors can also
contain simple expressions involving table columns, for example
"dx/sqrt(betx)".
Returns:
Accessor exposing column selection and column utilities.
The returned view is used to select rows while preserving the table
type. Rows can be selected by name, by regular expression, by a list of
names, by a range of row names, by a range on a chosen column, or by
offsets relative to named rows. It also provides methods such as
match() and
match_not() to select rows using regular
expressions on any column.
Returns:
Accessor exposing row selection, iteration, and row utilities.
rows (str, slice, list, or None, optional) – Rows to show. If None, show all rows. See table.rows for
accepted row selectors.
cols (str, list, or None, optional) – Columns to show. If None, show all columns. See table.cols
for accepted column selectors.
maxrows (int or None, optional) – Maximum number of rows to show. If None, show all rows.
maxwidth (int, "auto", "full", or None, optional) – Maximum width of the output. If "auto", use the terminal width.
If "full" or None, use the full width.
max_col_width (int or None, optional) – Maximum width of a column. If None, do not truncate column
values.
output (None, str, file-like object, or path-like, optional) – If None, print the output. If str, return the output as a
string. If a file-like object, write the output to the file. Other
values are interpreted as output paths.
digits (int, optional) – Number of digits to use for floats.
fixed ({"g", "f"}, optional) – If "g", use general floating-point format. If "f", use
fixed-point format.
header (bool, optional) – If True, show the header.
Returns:
String representation when outputisstr. Otherwise None.
default_column_width (int, optional) – Minimum column width to enforce for headers and data cells.
float_precision (int, optional) – Significant digits used when writing floating-point values.
numeric_column_width (int, optional) – If provided, enforces this uniform width for all numeric columns.
When omitted, numeric columns still share a common width derived
from the widest numeric entry.
column_formats (Mapping[str, str], optional) – Per-column Python/C-style format specifiers (e.g. ‘.3f’, ‘10.4g’).
Applied to data cells while falling back to float_precision
defaults when unspecified.
column_widths (Mapping[str, int], optional) – Per-column minimum widths overriding the defaults. Non-numeric
columns stay left-aligned; numeric ones keep right alignment.
Define a line by arranging components along its length.
A composer is created automatically for a line in compose mode. Users should
normally create such a line with env.new_line(compose=True) and add
components through the line, rather than instantiate a composer directly. The
underlying composer remains available as line.composer for inspection and
validation.
Components can be element names, placements, lines, other composers, or nested
sequences of these objects. They can be placed at an absolute longitudinal
position, relative to another component, or sequentially after the previous
component.
Parameters:
env (xtrack.Environment) – Environment containing the elements, variables, and lines used by the
composer.
components (list, optional) – Components defining the line. Entries can be element names,
xtrack.Place objects, lines, composers, or nested sequences of
these objects.
length (float, str, or xdeps reference, optional) – Requested total length of the line. Strings and references are evaluated
using env when the line is built. If omitted, the line is made just
long enough to contain all its components.
refer ({'start', 'center', 'centre', 'end'}, optional) – Default anchor used when a placement does not specify one. The default is
'center'.
s_tol (float, optional) – Longitudinal tolerance used when filling gaps and checking overlaps and
line-length constraints. The default is 1e-6.
mirror (bool, optional) – If true, reverse the component sequence after assembling the line.
The default is false.
Notes
When the components are sorted, the following ordering rules are applied:
Components are sorted by increasing s_center. Only thin elements can
form a group at the same s; for these elements s_start, s_center,
and s_end are identical. This is why s_center is used as the common
sorting coordinate.
For thin elements at the same s (within the sorting tolerance):
- input order is preserved unless placement dependencies establish an order;
- an element whose from_ names an upstream element moves toward the
beginning of the group;
an element whose from_ names a downstream element moves toward the end
of the group;
when from_ names an element inside the group:
- an explicit from_anchor of 'start', 'center', or 'centre'
places the element before the element named by from_;
an explicit from_anchor of 'end' places it after the element named
by from_;
an omitted from_anchor imposes no tie-break;
sequential elements depend on the end of the previous occurrence.
Calling resolve_s_positions() with sort=False skips these rules and
preserves the expanded input order.
Examples
Create a line in compose mode. Its composer is available as
line.composer and can resolve component positions before the line is
assembled:
importxtrackasxtenv=xt.Environment()env.new('q1',xt.Quadrupole,length=1)env.new('q2',xt.Quadrupole,length=1)env.new('ip',xt.Marker)line=env.new_line(compose=True)line.place('q1',at=1,anchor='start')line.place('ip',at=2,from_='q1',from_anchor='end')line.place('q2')positions=line.composer.resolve_s_positions()positions.cols['name s_start s_center s_end'].show()# name s_start s_center s_end# q1 1 1.5 2# ip 4 4 4# q2 4 4.5 5line.end_compose()
prototype (str or type) – Element type or existing element used as the prototype.
at (float, str, or xdeps reference, optional) – Longitudinal position of the element. If from_ is omitted, the
position is measured from the beginning of the line.
from (str, optional) – Component relative to which at is measured.
extra (dict, optional) – Additional metadata associated with the new element.
force (bool, optional) – If true, replace an existing element with the same name. The default
is false.
cls (str or type, optional) – Deprecated alias for prototype.
parent (str or type, optional) – Deprecated alias for prototype.
**kwargs – Attributes used to initialize or customize the element.
Returns:
The name of the created element when neither at nor from_ is
provided; otherwise, an xtrack.Place object describing where the
element is positioned. The returned value is also appended to
composer.components.
When neither at nor from_ is provided, the component is placed
sequentially after the preceding component.
Parameters:
name (str, xtrack.Line, or sequence of str) – Element or line to place. A sequence of element names is first combined
into a line.
obj (object, optional) – Object to register in the environment under name before placing it.
at (float, str, or xdeps reference, optional) – Position of the selected component anchor. If from_ is omitted, the
position is measured from the beginning of the line.
from (str, optional) – Component relative to which at is measured.
anchor ({'start', 'center', 'centre', 'end'}, optional) – Anchor of the placed component positioned at at. If omitted, the
composer’s default reference anchor is used.
from_anchor ({'start', 'center', 'centre', 'end'}, optional) – Anchor of the reference component from which at is measured. If
omitted, the composer’s default reference anchor is used.
Returns:
The xtrack.Place object describing the component placement. It is
also appended to composer.components.
Build a line from the current component definitions.
Component positions are resolved and positive gaps are filled with drifts.
A new line is created unless an existing line is supplied through line.
Parameters:
s_tol (float, optional) – Longitudinal tolerance used when filling gaps and checking overlaps and
line-length constraints. If omitted, the composer’s configured
tolerance is used.
line (xtrack.Line, optional) – Existing line whose element sequence is replaced with the assembled
sequence. The line must belong to the composer’s environment. If
omitted, a new line is created.
diagnostics (bool, optional) – If true, analyze unresolved placement dependencies and distinguish
missing references from dependency cycles. The default is false.
Returns:
The assembled line. If line was provided, the same line object is
returned.
Resolve the longitudinal positions of the composer components.
The components are expanded and their start, center, and end positions are
computed. This method neither assembles the final line nor fills gaps with
drifts. Overlaps are not checked at this stage: overlapping components are
included in the returned table with their resolved positions and do not
raise an error.
Parameters:
sort (bool, optional) – If true, sort the returned rows by longitudinal position and order
components sharing the same position according to their placement
dependencies. If false, preserve the input component order. The default
is true.
diagnostics (bool, optional) – If true, analyze unresolved placement dependencies and distinguish
missing references from dependency cycles. The default is false.
Returns:
Table containing one row per expanded component, including its
s_start, s_center, and s_end positions.
Component positions and dependencies are resolved with detailed
diagnostics. The resolved components are then checked for overlaps and
against the requested line length. Gap-filling drifts are not created.
Parameters:
s_tol (float, optional) – Longitudinal tolerance used when checking overlaps and the requested
line length. If omitted, the composer’s configured tolerance is used.
check_overlaps (bool, optional) – If true, raise an error when components overlap. If false, skip the
overlap check. The default is true.
Returns:
Returns normally when the component definitions are valid.
Return type:
None
Raises:
ValueError – If a placement reference is missing, the placement dependencies contain
a cycle, enabled overlap checking finds overlapping components, or the
components exceed the requested line length.
Serialize the composer definition to a dictionary.
The dictionary contains the component placements and composer configuration,
but not the elements, variables, or lines stored in the environment. It can
be restored with from_dict() using a compatible environment.
Returns:
Dictionary representation of the composer.
Return type:
dict
Raises:
NotImplementedError – If a component is neither an element name nor an xtrack.Place
object.
Create a composer from a dictionary representation.
The environment must contain the elements, variables, and named lines
referenced by the serialized component definitions. The input dictionary is
not modified.
Define how a component is positioned within a line.
A Place object can position a component at an absolute longitudinal
coordinate, relative to another component, or sequentially after the preceding
component. Place objects are normally created with env.place(...) and passed
to env.new_line(...) or added to a line in compose mode.
Reference anchors can be written compactly by appending @anchor to the
component name. For example, from_='q1@end' is equivalent to
from_='q1',from_anchor='end'. Similarly, at='q1@end' places a component
with zero offset from the end of q1.
Parameters:
name (str or xtrack.Line) – Element or line to place.
at (float, str, or xdeps reference, optional) – Position of the selected component anchor. If from_ is provided, this is
an offset from the selected anchor of the reference component. A string of
the form 'name@anchor' places the component directly at that anchor. If
omitted together with from_, the component is placed sequentially.
from (str, optional) – Component relative to which at is measured. The reference anchor can be
included using the 'name@anchor' form.
anchor ({'start', 'center', 'centre', 'end'}, optional) – Anchor of the placed component positioned at at. If omitted, the
composer’s default reference anchor is used.
from_anchor ({'start', 'center', 'centre', 'end'}, optional) – Anchor of the reference component from which at is measured. If omitted,
the composer’s default reference anchor is used.
env (xtrack.Environment, optional) – Associated environment. This is normally supplied automatically by
env.place(...).
Examples
Place q1 at an absolute position, place q2 relative to the end of
q1, and place ip sequentially after q2:
The Xsuite Line class represents an ordered sequence of beam elements used
for tracking, optics calculations, matching, and lattice manipulation. A line
stores the sequence of element names and resolves them in its associated
environment, available as line.env. The environment owns the named elements,
variables, particles, and other lines that can be shared across lattice
descriptions.
A line can be in normal mode or in compose mode, as indicated by line.mode.
In compose mode, elements are placed with line.place(...) and
line.new(...) by their longitudinal position and/or relative to each other;
the line is resolved later with line.end_compose().
For most new lattices it is convenient to create an
xtrack.Environment and build lines with env.new_line(...). The
Line constructor can also be used directly when the element objects and
their order are already available. See Lines in the
User’s guide for tutorial examples on building and inspecting lines.
Compute the local momentum acceptance (LMA) along the line by tracking a grid of momentum offsets (δ) from the entrance of selected elements and reporting the surviving negative and positive δ limits.
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.
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.
Replace multipoles having only the horizontal dipolar component with dipole elements. The element is not replaced when synchrotron radiation is active.
Replace multipoles having only the normal quadrupolar component with quadrupole elements. The element is not replaced when synchrotron radiation is active.
Return a table with the horizontal and vertical aperture estimated at all elements of the line. The aperture is estimated by tracking a particle through the line and measuring the maximum and minumum horizontal and vertical position at which particles survive. For elements at which no lost particles are detected, the aperture is estimated by interpolating the values of the neighbouring elements.
what (str, Line or Iterable) – Element(s) to be appended. Can be a list of Place objects specifying
the location of each insertion.
obj (object (optional)) – Object to be appended (if not already present in the environment).
It can be specified only when what is a string.
Examples
## Appending elements from the environment# Create a set of new elements to be placedenv.new('s1',xt.Sextupole,length=0.1,k2=0.2)env.new('s2',xt.Sextupole,length=0.1,k2=-0.2)env.new('m1',xt.Marker)env.new('m2',xt.Marker)env.new('m3',xt.Marker)# Insert the new elements in the lineline.append(['m1','s1','m2','s2','m3'])
## Appending elements instantiated by the user using the class## constructormyoct=xt.Octupole(length=0.1,k3=0.3)line.append('o1',myoct)
shallow (bool, optional) – If False (default), a deep copy is returned.
If True, a shallow copy is returned, i.e. the line is placed in the
same environment and shares variables and elements with the original.
_context (xobjects.Context) – xobjects context to be used for the copy
_buffer (xobjects.Buffer) – xobjects buffer to be used for the copy
If there are multiple valid options for the insertion (which is sometimes the
case for thin elements), the first suitable place will usually be chosen.
Parameters:
what (str, Line or Iterable) – Element(s) to be inserted. Can be a list of Place objects specifying
the location of each insertion.
obj (object (optional)) – Object to be inserted (if not already present in the environment).
It can be specified only when what is a string.
at (str or float (optional)) – Location of the insertion. If a string is given, it will first be interpreted
as a name of the element in the line: if one exits the behaviour will be the
same as with at=0,from_=at. Otherwise, at will be treated as an expression
evaluating to the s position. The s positions can be absolute or relative to
another element (specified by from_).
from (str (optional)) – Element with respect to which at is defined.
anchor (str (optional)) – Location within the inserted element for which at is defined.
It can be ‘start’, ‘end’ or ‘center’. Default is ‘center’.
from_anchor (str (optional)) – Location within the element specified by from_ for which at is defined.
It can be ‘start’, ‘end’ or ‘center’. Default is ‘center’.
with_progress (bool, optional) – Whether to show progress while slicing at insertion boundaries.
Defaults to True.
Example
importxtrackasxtenv=xt.Environment()line=env.new_line(components=[env.new('q0',xt.Quadrupole,length=1.0,at=2.0),env.new('m0',xt.Marker,at=5.0),env.new('q1',xt.Quadrupole,length=1.0,at=8.0),env.new('end',xt.Marker,at=10.0),])# Create a set of new elements to be placedenv.new('s1',xt.Sextupole,length=0.1,k2=0.2)env.new('s2',xt.Sextupole,length=0.1,k2=-0.2)env.new('m1',xt.Marker)env.new('m2',xt.Marker)env.new('m3',xt.Marker)# Insert the new elements in the lineline.insert([env.place('s1',at=1.0),env.place('s2',anchor='end',at=-0.5,from_='q1@start'),env.place(['m1','m2'],at='m0@start'),env.place('m3',at='m0@end'),])# Elements can also be instantiated directly by the usermysext=xt.Sextupole(length=0.1,k2=0.2)myaperture=xt.LimitEllipse(a=0.01,b=0.02)# Insert the element in the line and, contextually, define its name:line.insert('s3',mysext,at=0.75,from_='q1@end')# Alternatively, add the element to the environment and then do the insertion:env.elements['ap1']=myapertureline.insert('ap1',at='q0@start')
Replace an element in the line with another element having the same length.
Parameters:
name (str) – Name of the element to be replaced.
new_name (str) – Name of the element to be installed to replace the removed one.
s_tol (float (optional)) – Tolerance for the length of the elements. If the difference in length
is larger than s_tol, the replacement is not performed and an
error is raised. Default is 1e-10.
Replace repeated element occurrences with newly named elements.
Parameters:
separator (str, optional) – Separator inserted between the original element name and the
generated index in the new element names. Default is ‘.’.
mode (str, optional) – Creation mode passed to env.new(...) when generating each new
element from the repeated source element.
replace_generated_drifts (bool, optional) – If False, elements whose names start with '||drift_' are
skipped. If True, repeated generated drifts are also replaced.
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)
with_progress (bool, optional) – Whether to show progress while slicing. Defaults to True.
Examples
line.slice_thick_elements(slicing_strategies=[# Slicing with thin elementsxt.Strategy(slicing=xt.Teapot(1)),# (1) Default applied to all elementsxt.Strategy(slicing=xt.Uniform(2),element_type=xt.Bend),# (2) Selection by element typext.Strategy(slicing=xt.Teapot(3),element_type=xt.Quadrupole),# (4) Selection by element typext.Strategy(slicing=xt.Teapot(4),name='mb1.*'),# (5) Selection by name pattern# Slicing with thick elementsxt.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])
reverse (bool, optional) – If True, return strengths in reverse reference frame. If
None, the value is taken from line.twiss_default['reverse']
(default False).
Returns:
strengths – Table with one row per element plus '_end_point', including
integrated strengths (for example k0l, k1l, k2l,
k3l) and other twiss strength fields.
importxtrackasxtenv=xt.Environment()line=env.new_line()line.vars['a']=2.0line.vars['b']='3*a'line.vars.get_table().show()# name value expr# t_turn_s 0 None# a 2 None# b 6 (3.0 * a)
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. If this is None (default), the
reference particle associated with this line is used.
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.
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.
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:
Return a new line with segments defined 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. These elements are
kept as they are in the new line and are excluded from the maps:
each map spans from the exit of one split element to the
entrance of the next. Hence also thick and/or nonlinear elements
can be preserved exactly by splitting at them (e.g. octupoles,
to retain their amplitude detuning). Repeated elements are
referred to by their disambiguated name ‘name::N’ (as shown in
the line table and in the twiss table); the same names are used
in the returned line.
Returns:
line_maps – Line with segments replaced by second order maps.
Compute the local momentum acceptance (LMA) along the line by tracking a
grid of momentum offsets (δ) from the entrance of selected
elements and reporting the surviving negative and positive δ limits.
The δ grid is centered on the local closed orbit at each element, and offsets
can be applied (either physical x/y or normalized x/y in σ units).
Parameters:
elements (list of str or array-like of str, optional) – Names of the elements at whose entrance the LMA is evaluated.
If None (default), all elements in the line are used.
If multiple elements share the same s, only the first encountered
is used.
twiss (xt.TwissTable, optional) – Twiss table to define the closed orbit and optics. By default,
a 6D solution is computed with self.twiss(method=’6d’). You can
override the method with method=… in **kwargs.
scattering (str, optional) – Wheter scattering has been enabled or not (‘on’ or ‘off’).
x_offset (float, default 0.0) – Horizontal physical offset in meters. Mutually exclusive with
x_norm_offset.
y_offset (float, default 0.0) – Vertical physical offset in meters. Mutually exclusive with
y_norm_offset.
x_norm_offset (float, default 0.0) – Horizontal normalized offset in units of σx (rms). Mutually exclusive
with x_offset.
y_norm_offset (float, default 0.0) – Vertical normalized offset in units of σy (rms). Mutually exclusive
with y_offset.
delta_negative_limit (float, default -0.10) – Lower bound of the δ scan (inclusive). Must be < 0.
delta_positive_limit (float, default +0.10) – Upper bound of the δ scan (inclusive). Must be > 0.
delta_step_size (float, default 0.01) – Step for the δ grid. Must be > 0. The positive end is included
with a half-step guard to reduce floating-point exclusion.
n_turns (int, default 512) – Number of turns to track.
with_progress (bool | int, default False) – If truthy, shows a per-element progress bar.
verbose (bool, default False) – If True, enables tracker progress for each element scan.
**kwargs – Passed through to self.twiss and build_particles.
semantics (Selection) –
------------------- –
element. (- LMA is evaluated at the entrance of each) –
s (- If multiple elements share the same) –
used. (only the first encountered is) –
element) (Algorithm (per selected) –
-------------------------------- –
offsets. (1. Build particles on closed orbit with the requested (normalized or physical)) –
delta_co. (2. Apply the δ grid by shifting the initial δ around) –
itself. (3. Track for n_turns turns from the element to) –
particles (4. Among surviving) –
report –
survivors (- delta_neg = min of the initial δ of) –
:param :
:param - delta_pos = max of the initial δ of survivors.:
:param If none survive:
:param delta_neg = delta_pos = 0.0:
Returns:
Table indexed by ‘name’ with columns:
- name (str): Element name.
- s (float): Element entrance position (m).
- delta_neg (float): Surviving negative δ limit (may be 0).
- delta_pos (float): Surviving positive δ limit (may be 0).
The output survey table contains the following columns:
name: element name (with occurrence counts for repeated names).
element_type: type of the element (e.g. Drift, Marker, Bend).
prototype: name of the element prototype, when present.
s: longitudinal coordinate at the element entrance [m].
X, Y, Z: position of the element entrance in the global frame [m].
theta, phi, psi: orientation angles of the local frame
(azimuth, elevation, roll) unwrapped along the line [rad].
ex, ey, ez: unit vectors of the local frame expressed in
the global frame (they are the columns of E_matrix).
E_matrix: 3x3 rotation matrices describing the local frame at each
element entrance.
XYZ: position vectors stacked as [X,Y,Z].
isthick: True for thick elements, False for markers.
drift_length: length used while advancing the survey (zero for
thin elements) [m].
length: physical length of the element [m].
Examples
importxtrackasxt# Create a simple lineenv=xt.Environment(particle_ref=xt.Particles(p0c=1e9))line=env.new_line(length=6,components=[env.new('b1',xt.Bend,length=0.2,angle=0.1,at=1),env.new('q1',xt.Quadrupole,length=0.1,k1=0.5,at=2),env.new('b2',xt.Bend,length=0.2,angle=-0.1,at=3),env.new('q2',xt.Quadrupole,length=0.1,k1=-0.5,at=4),])# Compute the surveysv=line.survey()# sv.X, sv.Y, sv.Z contain the coordinates of the reference# trajectory in the global frame# Compute the trajectory of a particle entering with x=1 mm and y=2 mmtw=line.twiss4d(betx=1,bety=1,x=1e-3,y=2e-3)# tw.x, tw.y contain the coordinates of the particle in the local frame# Compute the trajectory of the particle in the global framep_global=tw.x[:,None]*sv.ex+tw.y[:,None]*sv.ey+sv.XYZX_trajectory=p_global[:,0]Y_trajectory=p_global[:,1]Z_trajectory=p_global[:,2]
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.
multi_element_monitor_at (list of str, optional) – If provided, a multi-element monitor is created and coordinates of the
trcked particles are recorded at the elements whose names are in the list.
The recorded data can be retrieved in line.record_multi_element_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.
Compute the Twiss parameters of the beam line. If no initial conditions
are provided, the periodic solution is computed.
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.
particle_ref (xpart.Particles, optional) – Reference particle used to search for the closed orbit. If not provided,
line.particle_ref is used.
chi (float, optional) – Relative charge-to-mass ratio q/q0*mass0/mass. The particle
used for the Twiss calculation is a copy; particle_ref is not
modified. If provided alone, its charge_ratio is preserved and
mass_ratio is adjusted consistently.
charge_ratio (float, optional) – Relative charge q/q0. If provided alone, the mass_ratio of
particle_ref is preserved and chi is adjusted consistently.
mass_ratio (float, optional) – Relative rest mass mass/mass0. If provided alone, the
charge_ratio of particle_ref is preserved and chi is
adjusted consistently.
with_progress (bool, optional) – Whether to show progress when temporary slicing is needed for at_s.
Defaults to True.
start (str, optional) – Name of the element at which the computation starts. If not provided,
the periodic solution is computed. Initial conditions must be provided if
start is provided.
end (str, optional) – Name 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.
Instead of passing init, initial conditions can be provided directly
as keyword arguments, e.g. line.twiss(betx=1,bety=2,x=1e-3).
Accepted fields: x, px, y, py, zeta, delta, betx,
alfx, bety, alfy, bets, dx, dpx, dy, dpy,
dzeta, mux, muy, muzeta, ax_chrom, bx_chrom,
ay_chrom, by_chrom, ddx, ddpx, ddy, ddpy, spin_x,
spin_y, spin_z.
init_at (str, optional) – Element name at which the initial conditions are defined. If not provided,
the initial conditions are defined at start.
delta0 (float, optional) – Closed-orbit delta at the start of the beam line, used when solving
the closed orbit in method='4d'. Mutually exclusive with zeta0.
Cannot be used in 6d mode.
zeta0 (float, optional) – Closed-orbit zeta at the start of the beam line, used when solving
the closed orbit in method='4d'. Mutually exclusive with delta0.
Cannot be used in 6d mode.
zeta_shift (float, optional) – Offset applied to zeta during closed-orbit search (closed orbit is
found for zeta[out]=zeta[in]-zeta_shift). Default is 0.
co_guess (xpart.Particles or dict, optional) – Initial guess for the closed orbit. If not provided, zero is assumed.
co_search_at (str, optional) – Element name at which the closed orbit is searched. If not provided,
the closed orbit is searched at the start of the line.
strengths (bool, optional) – If True, the strengths of the magnetic elements are added to the table.
include_collective (bool, optional) – If True, keep collective elements active during the twiss computation.
Default is False.
disable_apertures (bool, optional) – If True (default), aperture checks on tracked particles are disabled
while computing twiss.
reverse (bool, optional) – If True, the output is computed in the reversed reference frame, i.e.
s = -s, x = -x, y = y, zeta = -zeta, px=px, py=-py, delta=delta.
Default is False.
chrom (bool, optional) – If True, compute chromatic properties. Default is None, which means
chromatic properties are computed only for the periodic solution, but
not for open twiss.
radiation_analysis (bool, optional) – If True, the energy loss, radiation damping constants, and equilibrium
emittances are computed. Default is False.
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.
radiation_integrals (bool, optional) – If True, the radiation integrals are computed.
spin (bool, optional) – If True, for periodic twiss compute spin closed solution (n0);
for open twiss, propagate spin components.
polarization_analysis (bool, optional) – If True, compute quantititis related to spin polarization.
delta_chrom (float, optional) – Momentum deviation for the chromaticity computation.
steps_R_matrix (dict, optional) – Steps to be used for the finite difference computation of the R matrix.
If not provided, the default values are used.
matrix_responsiveness_tol (float, optional) – Tolerance to be used to check the responsiveness of the R matrix.
If not provided, the default value is used.
matrix_stability_tol (float, optional) – Tolerance to be used to check the stability of the R matrix.
If not provided, the default value is used.
step_W_sigma (float, optional.) – Deviation in sigmas used for the propagation of the W matrix.
nemitt_x (float, optional) – Horizontal emittance assumed for the computation of the deviation
used for the propagation of the W matrix.
nemitt_y (float, optional) – Vertical emittance assumed for the computation of the deviation
used for the propagation of the W matrix.
coupling_edw_teng (bool, optional) – If True, Edwards-Teng coupling quantities are computed. Default is
False.
zero_at (str, optional) – Element name at which the s coordinate and the phase advances are set to
zero.
compute_R_element_by_element (bool, optional) – If True, the element-by-element R matrices are computed and stored in
the output table. Default is False.
num_turns (int, optional) – If specified the periodic solution and the twiss table are computed
on multiple turns.
search_for_t_rev (bool, optional) – If True, the revolution period is searched for, otherwise the revolution
period computed from the line length is assumed.
num_turns_search_t_rev (int, optional) – Number of turns used for the search of the revolution period. Used only
if search_for_t_rev is True.
symplectify (bool, optional) – If True, the R matrix is symplectified before computing the linear normal
form. Default is False.
particle_on_co (xpart.Particles, optional) – Particle on the closed orbit. If not provided, the closed orbit is searched for.
co_search_settings (dict, optional) – Settings to be used by the optimizer for the closed orbit search. If not
provided, the default values are used.
R_matrix (np.ndarray, optional) – R matrix to be used for the computation. If not provided, the R matrix is
computed using finite differences.
W_matrix (np.ndarray, optional) – W matrix to be used for the computation. If not provided, the W matrix is
computed from the R matrix.
use_full_inverse (bool, optional) – If True, the full inverse of the W matrix is used. If False, the inverse is
computed from the symplectic condition.
Output fields depending on selected options (for detailed definitions and
explanations refer to the Xsuite Physics Guide (https://xsuite.readthedocs.io/en/latest/physicsguide.html):
Fields marked as “ebe” are element-by-element quantities.
Default output fields:
name: element name, when repeated elements are present “::1”, “::2”, …
suffixes are added to make the names unique. (ebe)
env_name: environment name of the element, i.e. name without suffix
for repeated elements. (ebe)
s: element position [m] (ebe)
x, px, y, py, zeta, delta, ptau: coordinates
of the closed orbit for the periodic twiss and of the beam trajectory
for the open twiss. (ebe)
betx, bety, alfx, alfy, gamx, gamy: Twiss parameters.
In the presence of linear coupling, these are respectively betx1,
bety2, alfx1, alfy2, gamx1, gamy2 in the Mais-Ripken sense. (ebe)
Correct the beam trajectory using linearized response matrix from optics
table.
Parameters:
run (bool) – If True (default), the correction is performed immediately. If False,
a TrajectoryCorrection object is returned, which can be used for
advanced correction.
n_iter (int) – Number of iterations for the correction. If ‘auto’ (default), the
iterations are performed for as long as the correction is improving.
start (str) – Start of the line range in which the correction is performed.
If start is provided end must also be provided.
If start is None, the correction is performed on the periodic
solution (closed orbit).
end (str) – End of the line range in which the correction is performed.
If end is provided start must also be provided.
If start is None, the correction is performed on the periodic
solution (closed orbit).
twiss_table (TwissTable) – Twiss table used to compute the response matrix for the correction.
If None, the twiss table is computed from the line.
planes (str) – Planes for which the correction is performed. It can be ‘x’, ‘y’ or
‘xy’. If None, the correction is performed for both planes.
monitor_names_x (list of str) – List of elements used as monitors in the horizontal plane.
corrector_names_x (list of str) – List of elements used as correctors in the horizontal plane. They
must have knl and ksl attributes.
monitor_names_y (list of str) – List of elements used as monitors in the vertical plane.
corrector_names_y (list of str) – List of elements used as correctors in the vertical plane. They
must have knl and ksl attributes.
n_micado (int) – If n_micado is not None, the MICADO algorithm is used for the
correction. In that case, the number of correctors to be used is
given by n_micado.
n_singular_values (int) – Number of singular values used for the correction.
rcond (float) – Cutoff for small singular values (relative to the largest singular
value). Singular values smaller than rcond are considered zero.
corrector_limits_x (tuple of array-like or None) – Limits for the horizontal corrector strengths. If not None, it should be a tuple
of two arrays (lower_limits, upper_limits) with the same length as
the number of horizontal correctors. If None, no limits are applied.
corrector_limits_y (tuple of array-like or None) – Limits for the vertical corrector strengths. If not None, it should be a tuple
of two arrays (lower_limits, upper_limits) with the same length as
the number of vertical correctors. If None, no limits are applied.
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 returned, 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.
check_limits (bool) – If True (default), the limits of the knobs are checked before the
optimization. If False, if the knobs are out of limits, the optimization
knobs are set to the limits on the first iteration.
**kwargs (dict) – Additional arguments to be passed to the twiss.
Returns:
optimizer – xdeps optimizer object used for the optimization.
# Match tunes and chromaticities to assigned valuesline.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 bumptw_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 anglext.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 closedxt.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 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.
Returns:
Returned xtrack.match.KnobOptimizer used to match and
generate the knob. It exposes the underlying
xdeps.Optimize methods, and provides
generate_knob() to install the matched knob expression.
See documentation of xt.Bend for more details on the values of the
models and schemes used below.
Parameters:
core (str) – Model to be used for the thick bend cores. Can be ‘adaptive’,
‘full’, ‘bend-kick-bend’, ‘rot-kick-rot’, ‘mat-kick-mat’,
‘drift-kick-drift-exact’, or ‘drift-kick-drift-expanded’.
edge (str) – Model to be used for the bend edges. Can be ‘linear’, ‘full’,
‘dipole-only’ or ‘suppressed’.
num_multipole_kicks (int) – Number of multipole kicks to consider.
integrator (str) – Integration scheme to be used. Can be ‘adaptive’, ‘teapot’,
‘yoshida4’, or ‘uniform’.
Compensate beam energy loss from synchrotron radiation by configuring
RF cavities and Multipole elements (tapering).
Parameters:
delta0 (float) – Initial energy deviation. If delta0=’zero_mean’ is specified, the
compensation is done such that the mean energy deviation along the
ring is zero.
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.
model (str) – Radiation model to use. Can be ‘mean’, ‘quantum’, ‘quantum-kick’
or None. 'mean' applies the average radiation energy loss.
'quantum' samples individual emitted photons, which can be
captured through internal radiation logging. 'quantum-kick'
samples the equivalent stochastic total radiation kick without
generating individual photon records.
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.
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.
Examples
## Choose a contextcontext=xo.ContextCpu()# For CPU (single thread)# context = xo.ContextCpu(omp_num_threads=4) # For CPU (4 thread)# context = xo.ContextCpu(omp_num_threads='auto') # For CPU (max. thread)# context = xo.ContextCupy() # For CUDA GPUs# context = xo.ContextPyopencl() # For OpenCL GPUsline.build_tracker(_context=context)
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
include_var_management (bool, optional) – If True (default) the dictionary will contain the information
needed to restore the line with deferred expressions.
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.
Replace multipoles having only the horizontal dipolar component
with dipole elements. The element is not replaced when synchrotron
radiation is active.
Replace multipoles having only the normal quadrupolar component
with quadrupole elements. The element is not replaced when synchrotron
radiation is active.
Deprecated alias for line.xfields.ibs_configure(...).
Warning
This method is deprecated and will be removed in a future version.
Use line.xfields.ibs_configure(...) instead. This deprecation
is part of the interface cleanup in view of the 1.0 release.
Notes
This should be one of the last steps taken before tracking.
At the very least, if steps are taken that change the lattice’s
optics after this configuration, then this function should be
called once again.
Parameters:
element (IBSKick, optional) – If provided, the element is first inserted in the line,
before proceeding to configuration. In this case the keyword
arguments are passed on to the line.insert_element method.
update_every (int) – The frequency at which to recompute the kick coefficients, in
number of turns. They will be computed at the first turn of
tracking, and then every update_every turns afterwards.
**kwargs (dict, optional) – Required if an element is provided. Keyword arguments are
passed to the line.insert() method according to
line.insert(obj=element, **kwargs).
Raises:
ImportError – If the xfields package is not installed, with a sufficiently
recent version.
AssertionError – If the provided update_every is not a positive integer.
AssertionError – If more than one IBS kick element is found in the line.
AssertionError – If the element is an IBSSimpleKick and the line is operating
below transition energy.
This method is deprecated and will be removed in a future version.
Use tt=line.get_table() and then tt.s to get all s positions
or tt['s','myelem'] for one specific s position.
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”)
This property is deprecated and will be removed in a future version.
Use line.xcoll.collimators instead. This deprecation is part of
the interface cleanup in view of the 1.0 release.
Returns:
collimators – Xcoll collimator API bound to this line.
This property is deprecated and will be removed in a future version.
Use line.xcoll.scattering instead. This deprecation is part of
the interface cleanup in view of the 1.0 release.
Returns:
scattering – Xcoll scattering API bound to this line.
what (Line or list of str) – If a line, append its sequence of element names. The source line
must belong to the same environment as this line. If a list, append
the provided element names directly.
Returns:
This method modifies the line in place.
Return type:
None
Notes
This method only extends the sequence of names; it does not import or
copy elements from another environment.
Return a table with the horizontal and vertical aperture estimated at all
elements of the line.
The aperture is estimated by tracking a particle through the line and
measuring the maximum and minumum horizontal and vertical position
at which particles survive. For elements at which no lost particles are
detected, the aperture is estimated by interpolating the values
of the neighbouring elements.
Parameters:
dx (float, optional) – Required horizontal resolution (in m) for the aperture measurement.
Default is 1e-3.
dy (float, optional) – Required vertical resolution (in m) for the aperture measurement.
Default is 1e-3.
x_range (tuple, optional) – Horizontal range (in m) for the aperture measurement.
Default is (-0.1, 0.1).
y_range (tuple, optional) – Vertical range (in m) for the aperture measurement.
Default is (-0.1, 0.1).
Returns:
aperture_table – Table with the horizontal and vertical aperture at all elements
of the line.
Line-bound access to Xpart particle generation helpers.
This API is exposed as line.xpart. Methods delegate to the
corresponding xpart functions. When the underlying function accepts a
line argument, this line is used by default unless line or
tracker is provided explicitly.
This is the line.xpart container form of xpart.build_particles.
Defaults to the line owning this xpart container.
Explicit line or tracker arguments override the container. See
xtrack.Line.build_particles for the full parameter list.
The transverse coordinates are generated from independent Gaussian
distributions in normalized phase space and converted to physical
coordinates using build_particles. The longitudinal coordinates are
matched to the RF bucket using generate_longitudinal_coordinates with
distribution=’gaussian’.
Parameters:
num_particles (int) – Number of macroparticles to generate.
nemitt_x (float) – Normalized horizontal emittance in m rad.
nemitt_y (float) – Normalized vertical emittance in m rad.
sigma_z (float) – RMS bunch length in m.
total_intensity_particles (float, optional) – Total bunch intensity in physical particles. If not provided, the
particle weights are set to one.
particle_on_co (xpart.Particles, optional) – Particle on the closed orbit used as reference for the generated bunch.
Cannot be provided together with particle_ref.
R_matrix (array_like, optional) – Linear transfer matrix passed to build_particles.
circumference (float, optional) – Ring circumference in m. Required when no line is provided.
momentum_compaction_factor (float, optional) – Momentum compaction factor. Required when no line is provided.
rf_harmonic (float or array_like, optional) – RF harmonic number or numbers. Required when no line is provided.
rf_voltage (float or array_like, optional) – RF voltage or voltages in V. Required when no line is provided.
rf_phase (float or array_like, optional) – RF phase or phases in rad. Required when no line is provided.
energy_ref_increment (float, optional) – Reference energy increment used for the longitudinal matching.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line, optional) – Line for which the bunch is generated. If provided, missing RF and
lattice parameters are inferred from the line.
Defaults to the line owning this xpart container.
particle_ref (xpart.Particles, optional) – Reference particle. If not provided, line.particle_ref is used when
available. Cannot be provided together with particle_on_co.
engine (str, optional) – Longitudinal matching engine passed to
generate_longitudinal_coordinates.
return_matcher (bool, optional) – If True, also return the longitudinal matcher object.
_context (xobjects.Context, optional) – Context on which to allocate the returned particles.
_buffer (xobjects.Buffer, optional) – Buffer on which to allocate the returned particles.
_offset (int, optional) – Offset in _buffer at which to allocate the returned particles.
**kwargs – Additional keyword arguments passed to generate_longitudinal_coordinates
and build_particles.
Each selected bunch is generated with generate_matched_gaussian_bunch and
then shifted in zeta according to the filled bucket positions in
filling_scheme. The returned object contains the selected bunches
concatenated in bunch-selection order.
Parameters:
filling_scheme (array_like) – One-dimensional array indicating which RF buckets are filled. Non-zero
entries are treated as filled buckets.
bunch_num_particles (int) – Number of macroparticles to generate per bunch.
nemitt_x (float) – Normalized horizontal emittance in m rad.
nemitt_y (float) – Normalized vertical emittance in m rad.
sigma_z (float) – RMS bunch length of each bunch in m.
bunch_intensity_particles (float, optional) – Intensity of each bunch in physical particles.
particle_on_co (xpart.Particles, optional) – Particle on the closed orbit used as reference for the generated
bunches. Cannot be provided together with particle_ref.
R_matrix (array_like, optional) – Linear transfer matrix passed to build_particles.
circumference (float, optional) – Ring circumference in m. If not provided, it is taken from line.
momentum_compaction_factor (float, optional) – Momentum compaction factor passed to the longitudinal matching.
rf_harmonic (float or array_like, optional) – RF harmonic number or numbers. Used to infer the bucket length when
bucket_length is not provided.
rf_voltage (float or array_like, optional) – RF voltage or voltages in V. Used together with rf_harmonic for the
longitudinal matching and to infer the main harmonic.
rf_phase (float or array_like, optional) – RF phase or phases in rad.
bucket_length (float, optional) – Bucket spacing in m. If provided, rf_harmonic and rf_voltage must
not be provided.
energy_ref_increment (float, optional) – Reference energy increment used for the longitudinal matching.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line, optional) – Line for which the beam is generated. If provided, missing RF and
lattice parameters are inferred from the line.
Defaults to the line owning this xpart container.
particle_ref (xpart.Particles, optional) – Reference particle. If not provided, line.particle_ref is used when
available.
engine (str, optional) – Longitudinal matching engine passed to
generate_longitudinal_coordinates.
_context (xobjects.Context, optional) – Context on which to allocate the returned particles.
_buffer (xobjects.Buffer, optional) – Buffer on which to allocate the returned particles.
_offset (int, optional) – Offset in _buffer at which to allocate the returned particles.
bunch_selection (iterable of int, optional) – Indices, within the list of filled buckets, of the bunches to generate.
If not provided, all filled bunches are generated, unless MPI wake
preparation is enabled.
bunch_spacing_buckets (int, optional) – Spacing between consecutive entries of filling_scheme, expressed in
RF buckets. The physical spacing is
bunch_spacing_buckets * bucket_length.
prepare_line_and_particles_for_mpi_wake_sim (bool, optional) – If True, split the filled bunches over MPI ranks when bunch_selection
is not provided and configure the line and particles for wakefield
simulations.
communicator (mpi4py communicator, optional) – MPI communicator used when
prepare_line_and_particles_for_mpi_wake_sim is True. If not provided,
mpi4py.MPI.COMM_WORLD is used.
**kwargs – Additional keyword arguments passed to
generate_matched_gaussian_bunch.
Returns:
particles – Particles object containing the generated selected bunches.
Generate a 2D pencil distribution with a cut in physical coordinates.
The requested absolute_cut is converted to normalized coordinates at the
selected location using the line optics and the provided normalized
emittances. A normalized pencil distribution is then generated with
generate_2D_pencil and converted back to physical coordinates.
Parameters:
num_particles (int) – Number of points to generate.
plane ({'x', 'y'}) – Plane in which to generate the pencil distribution.
absolute_cut (float) – Position cut in m.
dr_sigmas (float) – Radial thickness of the pencil distribution in units of sigma.
side ({'+', '-'}, optional) – Side on which to generate the pencil distribution.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line) – Line used to compute the optics and physical coordinates.
Defaults to the line owning this xpart container.
nemitt_x (float) – Normalized horizontal emittance in m rad.
nemitt_y (float) – Normalized vertical emittance in m rad.
at_element (int or str, optional) – Element at which the cut is defined. If not provided, the start of the
line is used.
match_at_s (float, optional) – Longitudinal position in m at which the cut is defined, downstream of
at_element. If provided, at_element must also be provided.
twiss (xtrack.TwissTable or table row, optional) – Twiss data at the selected location. If not provided, it is computed
from line.
**kwargs – Additional keyword arguments passed to line.twiss and
line.build_particles.
Returns:
v (np.ndarray) – Physical coordinate in the selected plane, x for plane=’x’ or y
for plane=’y’, in m.
pv (np.ndarray) – Conjugate physical coordinate in the selected plane, px for
plane=’x’ or py for plane=’y’.
Generate longitudinal coordinates matched to an RF bucket.
The RF and optics parameters can be inferred from line, or provided
explicitly. With the default engine, linear longitudinal elements use a
linear Gaussian match, while nonlinear RF buckets use the PyHEADTAIL-style
RF bucket matcher.
Parameters:
line (xtrack.Line, optional) – Line for which the longitudinal coordinates are generated.
Defaults to the line owning this xpart container.
num_particles (int) – Number of particles to generate.
distribution ({'gaussian', 'parabolic', 'binomial', 'qgaussian'}, optional) – Longitudinal distribution to generate. Non-Gaussian distributions
require engine=’single-rf-harmonic’.
sigma_z (float) – RMS bunch length in m.
engine ({'linear', 'pyheadtail', 'single-rf-harmonic'}, optional) – Matching engine. If not provided, it is selected from the line.
return_matcher (bool, optional) – If True, also return the matcher object.
particle_ref (xpart.Particles, optional) – Reference particle. If not provided, line.particle_ref is used.
mass0 (float, optional) – Reference-particle properties used when they cannot be inferred from
particle_ref.
q0 (float, optional) – Reference-particle properties used when they cannot be inferred from
particle_ref.
gamma0 (float, optional) – Reference-particle properties used when they cannot be inferred from
particle_ref.
circumference (float, optional) – Ring circumference in m. Required when no line is provided.
momentum_compaction_factor (float or array_like, optional) – Momentum compaction factor.
rf_harmonic (float or array_like, optional) – RF harmonic number or numbers.
rf_voltage (float or array_like, optional) – RF voltage or voltages in V.
rf_phase (float or array_like, optional) – RF phase or phases in rad.
rf_shift_zeta (float or array_like, optional) – Longitudinal RF shifts in m.
energy_ref_increment (float, optional) – Reference energy increment in eV.
energy_loss_from_radiation (float, optional) – Energy loss from radiation in eV.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
m (float, optional) – Binomial distribution parameter.
q (float, optional) – q-Gaussian distribution parameter.
zeta0 (float, optional) – Reference longitudinal position in m.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line) – Line used to infer the RF and optics parameters. The line must already
have a tracker.
Defaults to the line owning this xpart container.
return_matcher (bool, optional) – If True, also return the SingleRFHarmonicMatcher object.
m (float, optional) – Binomial distribution parameter. Larger values give lighter tails.
Returns:
zeta (np.ndarray) – Longitudinal position in m.
delta (np.ndarray) – Relative momentum deviation.
matcher (xpart.longitudinal.SingleRFHarmonicMatcher) – Matcher object used for the generation. Returned only when
return_matcher is True.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line) – Line used to infer the RF and optics parameters. The line must already
have a tracker.
Defaults to the line owning this xpart container.
return_matcher (bool, optional) – If True, also return the SingleRFHarmonicMatcher object.
Returns:
zeta (np.ndarray) – Longitudinal position in m.
delta (np.ndarray) – Relative momentum deviation.
matcher (xpart.longitudinal.SingleRFHarmonicMatcher) – Matcher object used for the generation. Returned only when
return_matcher is True.
Generate longitudinal coordinates with a q-Gaussian distribution.
This is a convenience wrapper around generate_longitudinal_coordinates
using distribution=’qgaussian’ and engine=’single-rf-harmonic’. The
longitudinal line density is proportional to
[1 - (1 - q) beta tau**2]**(1 / (1 - q))
where tau = zeta / beta0. In the limit q -> 1, this becomes a
Gaussian. Values below 1 give compact, lighter-tailed profiles; values
above 1 give heavier-tailed profiles.
Parameters:
num_particles (int) – Number of particles to generate.
nemitt_x (float, optional) – Accepted for backward compatibility; not used by this function.
nemitt_y (float, optional) – Accepted for backward compatibility; not used by this function.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line) – Line used to infer the RF and optics parameters. The line must already
have a tracker.
Defaults to the line owning this xpart container.
return_matcher (bool, optional) – If True, also return the SingleRFHarmonicMatcher object.
q (float, optional) – q-Gaussian parameter.
Returns:
zeta (np.ndarray) – Longitudinal position in m.
delta (np.ndarray) – Relative momentum deviation.
matcher (xpart.longitudinal.SingleRFHarmonicMatcher) – Matcher object used for the generation. Returned only when
return_matcher is True.
The radial and angular grids can be provided explicitly with r_grid and
theta_grid, or built from ranges. For each coordinate, provide either an
explicit grid, or a range together with either a step size or a number of
points. The returned arrays are flattened over all (r, theta)
combinations.
Parameters:
r_range (tuple of float, optional) – Radial range (r_min, r_max). Required if r_grid is not provided.
r_grid (array_like, optional) – Explicit uniformly spaced radial grid. If provided, r_range, dr,
and nr must not be provided.
dr (float, optional) – Radial step used with r_range. Cannot be provided together with nr.
nr (int, optional) – Number of radial points used with r_range. Required when r_grid and
dr are not provided.
theta_range (tuple of float, optional) – Angular range (theta_min, theta_max) in rad. Required if
theta_grid is not provided.
theta_grid (array_like, optional) – Explicit uniformly spaced angular grid in rad. If provided,
theta_range, dtheta, and ntheta must not be provided.
dtheta (float, optional) – Angular step in rad used with theta_range. Cannot be provided
together with ntheta.
ntheta (int, optional) – Number of angular points used with theta_range. Required when
theta_grid and dtheta are not provided.
Returns:
a1 (np.ndarray) – First Cartesian normalized coordinate, equal to
r_all * cos(theta_all).
a2 (np.ndarray) – Second Cartesian normalized coordinate, equal to
r_all * sin(theta_all).
r_all (np.ndarray) – Radial coordinate for each generated point.
theta_all (np.ndarray) – Angular coordinate in rad for each generated point.
Generate a 2D pencil distribution in normalized coordinates.
The generated points lie outside a position cut and within a radial
thickness dr_sigmas, expressed in units of the normalized beam size. For
side=’+’, the cut is applied on the positive side of the first
coordinate; for side=’-’, on the negative side. With side=’+-’, the
particles are split between the two sides.
Parameters:
num_particles (int) – Number of points to generate.
pos_cut_sigmas (float) – Position cut in units of sigma.
dr_sigmas (float) – Radial thickness of the pencil distribution in units of sigma.
side ({'+', '-', '+-'}, optional) – Side on which to generate the pencil distribution.
Returns:
x_norm (np.ndarray) – First normalized coordinate.
px_norm (np.ndarray) – Second normalized coordinate.
r_points (np.ndarray) – Radial coordinate of the generated points.
theta_points (np.ndarray) – Angular coordinate in rad of the generated points.
Generate points uniformly distributed inside a scaled 6D hypersphere.
The generated coordinates satisfy an ellipsoidal scaling where the x and
px axes use radius rx, the y and py axes use radius ry, and the
zeta and pzeta axes use radius rzeta.
Parameters:
num_particles (int) – Number of points to generate.
rx (float, optional) – Radius used for the x_norm and px_norm coordinates.
ry (float, optional) – Radius used for the y_norm and py_norm coordinates.
rzeta (float, optional) – Radius used for the zeta_norm and pzeta_norm coordinates.
rng_seed (int, optional) – Seed for the random number generator.
Returns:
x_norm (np.ndarray) – First horizontal normalized coordinate.
px_norm (np.ndarray) – Second horizontal normalized coordinate.
y_norm (np.ndarray) – First vertical normalized coordinate.
py_norm (np.ndarray) – Second vertical normalized coordinate.
zeta_norm (np.ndarray) – First longitudinal normalized coordinate.
pzeta_norm (np.ndarray) – Second longitudinal normalized coordinate.
LineTable stores one row per line element plus the '_end_point' row.
It summarizes the line layout: element names, element types, longitudinal
positions, lengths, thickness flags, and optional element attributes.
Create a line table.
Parameters:
data (mapping) – Mapping containing line-table columns. Typical columns include
name, element_type, s, length, isthick, and
optional element attributes.
*args – Additional positional arguments passed to xtrack.Table.
**kwargs – Additional keyword arguments passed to xtrack.Table.
The returned view is used to select multiple columns while preserving
the table type. Columns can be selected from a whitespace-separated
string or from an iterable of column names. String selectors can also
contain simple expressions involving table columns, for example
"dx/sqrt(betx)".
Returns:
Accessor exposing column selection and column utilities.
The returned view is used to select rows while preserving the table
type. Rows can be selected by name, by regular expression, by a list of
names, by a range of row names, by a range on a chosen column, or by
offsets relative to named rows. It also provides methods such as
match() and
match_not() to select rows using regular
expressions on any column.
Returns:
Accessor exposing row selection, iteration, and row utilities.
rows (str, slice, list, or None, optional) – Rows to show. If None, show all rows. See table.rows for
accepted row selectors.
cols (str, list, or None, optional) – Columns to show. If None, show all columns. See table.cols
for accepted column selectors.
maxrows (int or None, optional) – Maximum number of rows to show. If None, show all rows.
maxwidth (int, "auto", "full", or None, optional) – Maximum width of the output. If "auto", use the terminal width.
If "full" or None, use the full width.
max_col_width (int or None, optional) – Maximum width of a column. If None, do not truncate column
values.
output (None, str, file-like object, or path-like, optional) – If None, print the output. If str, return the output as a
string. If a file-like object, write the output to the file. Other
values are interpreted as output paths.
digits (int, optional) – Number of digits to use for floats.
fixed ({"g", "f"}, optional) – If "g", use general floating-point format. If "f", use
fixed-point format.
header (bool, optional) – If True, show the header.
Returns:
String representation when outputisstr. Otherwise None.
include (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to include. If
omitted, all columns and attributes are included.
exclude (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to exclude.
missing ({"error", "ignore"}, optional) – Policy for names requested in include or exclude that are
not present in the table.
include_meta (bool, optional) – If True, include metadata describing dropped columns,
dropped attributes, table class, and xtrack version when relevant.
Returns:
Serialized table data with columns and attrs entries.
default_column_width (int, optional) – Minimum column width to enforce for headers and data cells.
float_precision (int, optional) – Significant digits used when writing floating-point values.
numeric_column_width (int, optional) – If provided, enforces this uniform width for all numeric columns.
When omitted, numeric columns still share a common width derived
from the widest numeric entry.
column_formats (Mapping[str, str], optional) – Per-column Python/C-style format specifiers (e.g. ‘.3f’, ‘10.4g’).
Applied to data cells while falling back to float_precision
defaults when unspecified.
column_widths (Mapping[str, int], optional) – Per-column minimum widths overriding the defaults. Non-numeric
columns stay left-aligned; numeric ones keep right alignment.
The xtrack.Aperture class represents the physical aperture model of a
beam line: a set of transverse cross-section profiles (pipes) placed along the
survey of a xtrack.Line. It provides methods to build the model from
different data sources, to query aperture cross-sections, to compute the maximum
number of beam sigmas that fit inside the aperture, and to visualise the results.
Compute the maximum number of sigmas at which the beam fits in the aperture at element element_name.
Parameters:
elment_name – The name of the element at which the sigmas should be computed.
resolution – The desired resolution, in meters along s, at which the sigmas should be computed. If not provided only the
values at the entry and exit will be output.
twiss – Optionally provided twiss table from which to derive the initial beam parameters at the element.
A method to use for the computation:
- ‘rays’ - the aperture sigma is estimated from sampled rays and the minimum over the sampled directions
is returned (faster method, O(R) where R is the number of rays)
’exact’ - the aperture sigma is estimated from sampled points on the halo racetrack, at which new sample
rays are emitted to compare the local directional sigma to the aperture (O(R^2), where R is the number
of rays).
’bisection’ - the smallest number of sigmas for the beam to fit in the aperture is computed by bisecting
on a polygon-inside-polygon problem (slower method, O(EAK), where E is the number of envelope points,
A is the number of aperture points, and K is the number of bisection steps; currently K <= 25, this
depends on the tolerance and search space set in beam_aperture.h).
envelopes_num_points – Number of points to use when discretising the beam cross-section.
num_rays – Only for methods rays and exact: number of evenly-spaced ray directions to sample in [0, 2 * pi).
output_max_envelopes – If true, output beam-envelope polygons at the computed n1.
output_cross_sections – If true, output interpolated aperture cross-sections.
with_progress – Whether to show progress while slicing the line. Defaults to
True.
Returns:
A two-tuple (table,sliced_twiss), where
table is an xdeps.table.Table with columns s and n1.
if output_cross_sections is true, table also contains cross_section.
if output_max_envelopes is true, table also contains envelope.
sliced_twiss is the twiss table computed as part of the calculation.
Compute the maximum aperture sigmas from an already sampled Twiss table.
Unlike get_aperture_sigmas_at_s(), this method does not slice the
line or calculate Twiss parameters. Each row of sliced_twiss is used
directly to determine the maximum beam size that fits in the aperture.
Parameters:
sliced_twiss – Twiss table containing the longitudinal positions and optical
quantities at which to compute the aperture sigmas.
method –
Algorithm used to determine the limiting sigma:
'rays' estimates the limit along evenly spaced ray directions.
'exact' samples the halo racetrack and emits additional rays
from those points.
'bisection' searches for the largest envelope polygon contained
in the aperture polygon.
envelopes_num_points – Number of points used to discretise beam-envelope polygons.
num_rays – Number of evenly spaced ray directions used by the 'rays' and
'exact' methods.
output_max_envelopes – Whether to include beam-envelope polygons at the computed sigma.
output_cross_sections – Whether to include the interpolated aperture cross-sections.
Returns:
Table with one row per row of sliced_twiss and the following
columns:
index: row index.
s: longitudinal position.
n1: maximum number of beam sigmas that fit in the aperture.
cross_section: aperture polygon, included when
output_cross_sections is true.
envelope: beam-envelope polygon at n1, included when
output_max_envelopes is true.
Compute beam-envelope polygons at the cuts of element_name for a fixed sigma value.
Parameters:
element_name – The name of the element at which the envelope should be computed.
sigmas – The beam size, in sigmas, at which the envelope should be evaluated.
resolution – The desired resolution, in meters along s, at which the envelope should be computed. If not provided only
the values at the entry and exit will be output.
twiss – Optionally provided twiss table from which to derive the initial beam parameters at the element.
**kwargs – Other parameters to be forwarded to Aperture.get_envelope_at_s.
Compute beam envelopes from an already sampled Twiss table.
Unlike get_envelope_at_s(), this method does not slice the line or
calculate Twiss parameters. Each row of sliced_twiss is used directly
to construct the beam envelope at the requested sigma level.
Parameters:
sliced_twiss – Twiss table containing the longitudinal positions and optical
quantities at which to compute the envelopes.
sigmas – Sigma level at which to evaluate the beam envelope.
envelopes_num_points – Number of points used to discretise each envelope polygon.
include_aper_tols – Whether to enlarge the beam envelope by the mechanical tolerances of
the active aperture profile at each longitudinal position.
polygons – Whether to include the discretised envelope polygons in the output.
extents – Whether to include the minimum and maximum horizontal and vertical
coordinates of each envelope.
Returns:
Table with one row per row of sliced_twiss and the following
columns:
index: row index.
s: longitudinal position.
cross_section: envelope polygon, included when polygons is
true.
min_x and max_x: horizontal extents, included when
extents is true.
min_y and max_y: vertical extents, included when
extents is true.
Compute horizontal, vertical and diagonal (45°) max aperture sigmas at element element_name.
Parameters:
elment_name – The name of the element at which the sigmas should be computed.
resolution – The desired resolution, in meters along s, at which the sigmas should be computed. If not provided only the
values at the entry and exit will be output.
twiss – Optionally provided twiss table from which to derive the initial beam parameters at the element.
Return installed-pipe interval information as a table.
Returns:
Table with the following columns:
- name: pipe-position name
- pipe_name: underlying pipe (type) name
- survey_reference: survey element used as the placement reference
- s_start, s_end: interval covered by the installed profile
centre positions
length: length of that centre-position interval
s_span_start, s_span_end: longitudinal footprint of the
projected aperture itself
span: length of that aperture-footprint interval
For rings, wrapped intervals are represented with s_start>s_end
and likewise for s_span_start>s_span_end.
Return an s interval split at the ring boundary when needed.
For ring apertures, start and end are interpreted modulo the
line length. If the interval wraps around the end of the line, the
result contains two non-wrapping segments. For non-ring apertures, the
interval is returned unchanged.
Return sampling positions around aperture-profile transitions.
The positions are built from the longitudinal locations of the
installed aperture bounds. For each stored s position, the method
emits points at s-tol and s+tol. This is useful when
sampling quantities that can change abruptly at profile transitions.
Parameters:
tol – Offset applied on both sides of each transition bound. If omitted,
use self.s_tol.
resolution – If provided, add a regular grid of sampling points spaced by this
step size and union it with the transition-based points.
s_range – If provided, restrict the returned positions to this longitudinal
interval. For rings, wrapped intervals are supported.
Returns:
Sorted, unique s positions clipped to the line extent.
Dictionary of halo parameters controlling beam-envelope and aperture-sigma computations.
The keys and their default values are:
Key
Default
Description
emitx_norm
3.5e-6
Normalised horizontal emittance [m·rad]
emity_norm
3.5e-6
Normalised vertical emittance [m·rad]
delta_rms
0.0
RMS momentum spread
tol_co
0.0
Closed-orbit tolerance [m]
tol_disp
0.0
Normalised dispersion tolerance [m]
tol_disp_ref
1.8
Reference dispersion derivative tolerance [m]
tol_disp_ref_beta
170
Reference dispersion beta-function [m]
tol_beta_beating
1.0
Beta-beating tolerance [sigma]
halo_x
6.0
Horizontal halo size [sigma]
halo_y
6.0
Vertical halo size [sigma]
halo_r
6.0
45° halo size [sigma]
halo_primary
6.0
Primary halo size [sigma]
The dictionary is mutable; individual entries can be changed with
aperture.halo_params['key']=value or in bulk with
aperture.halo_params.update({...}).
Plot beam-envelope and aperture extents along the beam line.
Parameters:
s_positions – Longitudinal positions at which the aperture cross-sections and beam
envelopes are evaluated.
sigmas – Sigma level used to build the beam envelope. If omitted, the minimum
available aperture sigma across s_positions is computed using
method.
twiss_init – Twiss initial conditions forwarded to the envelope and aperture-sigma
computations.
method – Method used to compute the maximum aperture sigmas when sigmas is not given.
envelopes_num_points – Number of points used to discretise each transverse beam envelope.
include_aper_tols – Whether aperture tolerances should be included in the beam-envelope
computation.
plot_s_positions – Coordinates to be used on the horizontal axis. If omitted, s_positions
are used directly. This is useful when the data are evaluated at one
set of longitudinal positions but should be displayed against another
abscissa, for example a shifted, reversed, or externally defined coordinate.
axs – Two axes on which to draw the horizontal and vertical extents. If
not provided, a new figure with two shared-x subplots is created.
with_progress – Whether to show progress while slicing the line. Defaults to
True.
Returns:
fig (matplotlib.figure.Figure) – Figure containing the plots.
axs (sequence of matplotlib.axes.Axes) – The x- and y-extent axes, in that order.
Plot installed pipe segments projected onto the floor plane.
Parameters:
ax – Axes object to plot on. If not given, use the current axes.
max_curve_angle_rad – Maximum angular step used to draw curved pipe boundaries and axes.
origin – Name of a pipe position to use as the plotting origin. When given,
the floor projection is expressed in the local frame of that pipe
position.
s_range – Longitudinal window, relative to origin when provided, used to
restrict which pipe segments are plotted. On rings, wrapped ranges
are handled across the end of the line.
aspect – Aspect ratio applied to the axes after plotting.
The xtrack.ApertureBuilder class provides a programmatic interface to
construct an xtrack.Aperture model by defining named profiles and
pipes and installing them at positions in the survey. Once all components are
registered, build() materialises the model into
an xtrack.aperture.structures.ApertureModel object that can be passed
to xtrack.Aperture.
at (str) – Survey entry used as the installation reference. The syntax
element@anchor can be used with anchors start, center,
centre, and end. The stored survey reference remains the
element name; the requested anchor offset is encoded in the stored
transformation.
transformation (np.ndarray, optional) – Full 4x4 homogeneous transform from the survey reference to the
pipe frame.
shift_x (float, optional) – Translation component used when transformation is not given.
shift_y (float, optional) – Translation component used when transformation is not given.
shift_z (float, optional) – Translation component used when transformation is not given.
rot_y_rad (float, optional) – Rotation component used when transformation is not given.
rot_x_rad (float, optional) – Rotation component used when transformation is not given.
rot_z_rad (float, optional) – Rotation component used when transformation is not given.
Returns:
The created pipe-position blueprint.
Return type:
PipePositionBlueprint
Raises:
ValueError – If the pipe-position name already exists, or if both a full matrix
and transform components are supplied.
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.
multi_element_monitor_at (list of str, optional) – If provided, a multi-element monitor is created and coordinates of the
trcked particles are recorded at the elements whose names are in the list.
The recorded data can be retrieved in line.record_multi_element_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.
Compute the Twiss parameters of the beam line. If no initial conditions
are provided, the periodic solution is computed.
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.
particle_ref (xpart.Particles, optional) – Reference particle used to search for the closed orbit. If not provided,
line.particle_ref is used.
chi (float, optional) – Relative charge-to-mass ratio q/q0*mass0/mass. The particle
used for the Twiss calculation is a copy; particle_ref is not
modified. If provided alone, its charge_ratio is preserved and
mass_ratio is adjusted consistently.
charge_ratio (float, optional) – Relative charge q/q0. If provided alone, the mass_ratio of
particle_ref is preserved and chi is adjusted consistently.
mass_ratio (float, optional) – Relative rest mass mass/mass0. If provided alone, the
charge_ratio of particle_ref is preserved and chi is
adjusted consistently.
with_progress (bool, optional) – Whether to show progress when temporary slicing is needed for at_s.
Defaults to True.
start (str, optional) – Name of the element at which the computation starts. If not provided,
the periodic solution is computed. Initial conditions must be provided if
start is provided.
end (str, optional) – Name 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.
Instead of passing init, initial conditions can be provided directly
as keyword arguments, e.g. line.twiss(betx=1,bety=2,x=1e-3).
Accepted fields: x, px, y, py, zeta, delta, betx,
alfx, bety, alfy, bets, dx, dpx, dy, dpy,
dzeta, mux, muy, muzeta, ax_chrom, bx_chrom,
ay_chrom, by_chrom, ddx, ddpx, ddy, ddpy, spin_x,
spin_y, spin_z.
init_at (str, optional) – Element name at which the initial conditions are defined. If not provided,
the initial conditions are defined at start.
delta0 (float, optional) – Closed-orbit delta at the start of the beam line, used when solving
the closed orbit in method='4d'. Mutually exclusive with zeta0.
Cannot be used in 6d mode.
zeta0 (float, optional) – Closed-orbit zeta at the start of the beam line, used when solving
the closed orbit in method='4d'. Mutually exclusive with delta0.
Cannot be used in 6d mode.
zeta_shift (float, optional) – Offset applied to zeta during closed-orbit search (closed orbit is
found for zeta[out]=zeta[in]-zeta_shift). Default is 0.
co_guess (xpart.Particles or dict, optional) – Initial guess for the closed orbit. If not provided, zero is assumed.
co_search_at (str, optional) – Element name at which the closed orbit is searched. If not provided,
the closed orbit is searched at the start of the line.
strengths (bool, optional) – If True, the strengths of the magnetic elements are added to the table.
include_collective (bool, optional) – If True, keep collective elements active during the twiss computation.
Default is False.
disable_apertures (bool, optional) – If True (default), aperture checks on tracked particles are disabled
while computing twiss.
reverse (bool, optional) – If True, the output is computed in the reversed reference frame, i.e.
s = -s, x = -x, y = y, zeta = -zeta, px=px, py=-py, delta=delta.
Default is False.
chrom (bool, optional) – If True, compute chromatic properties. Default is None, which means
chromatic properties are computed only for the periodic solution, but
not for open twiss.
radiation_analysis (bool, optional) – If True, the energy loss, radiation damping constants, and equilibrium
emittances are computed. Default is False.
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.
radiation_integrals (bool, optional) – If True, the radiation integrals are computed.
spin (bool, optional) – If True, for periodic twiss compute spin closed solution (n0);
for open twiss, propagate spin components.
polarization_analysis (bool, optional) – If True, compute quantititis related to spin polarization.
delta_chrom (float, optional) – Momentum deviation for the chromaticity computation.
steps_R_matrix (dict, optional) – Steps to be used for the finite difference computation of the R matrix.
If not provided, the default values are used.
matrix_responsiveness_tol (float, optional) – Tolerance to be used to check the responsiveness of the R matrix.
If not provided, the default value is used.
matrix_stability_tol (float, optional) – Tolerance to be used to check the stability of the R matrix.
If not provided, the default value is used.
step_W_sigma (float, optional.) – Deviation in sigmas used for the propagation of the W matrix.
nemitt_x (float, optional) – Horizontal emittance assumed for the computation of the deviation
used for the propagation of the W matrix.
nemitt_y (float, optional) – Vertical emittance assumed for the computation of the deviation
used for the propagation of the W matrix.
coupling_edw_teng (bool, optional) – If True, Edwards-Teng coupling quantities are computed. Default is
False.
zero_at (str, optional) – Element name at which the s coordinate and the phase advances are set to
zero.
compute_R_element_by_element (bool, optional) – If True, the element-by-element R matrices are computed and stored in
the output table. Default is False.
num_turns (int, optional) – If specified the periodic solution and the twiss table are computed
on multiple turns.
search_for_t_rev (bool, optional) – If True, the revolution period is searched for, otherwise the revolution
period computed from the line length is assumed.
num_turns_search_t_rev (int, optional) – Number of turns used for the search of the revolution period. Used only
if search_for_t_rev is True.
symplectify (bool, optional) – If True, the R matrix is symplectified before computing the linear normal
form. Default is False.
particle_on_co (xpart.Particles, optional) – Particle on the closed orbit. If not provided, the closed orbit is searched for.
co_search_settings (dict, optional) – Settings to be used by the optimizer for the closed orbit search. If not
provided, the default values are used.
R_matrix (np.ndarray, optional) – R matrix to be used for the computation. If not provided, the R matrix is
computed using finite differences.
W_matrix (np.ndarray, optional) – W matrix to be used for the computation. If not provided, the W matrix is
computed from the R matrix.
use_full_inverse (bool, optional) – If True, the full inverse of the W matrix is used. If False, the inverse is
computed from the symplectic condition.
Output fields depending on selected options (for detailed definitions and
explanations refer to the Xsuite Physics Guide (https://xsuite.readthedocs.io/en/latest/physicsguide.html):
Fields marked as “ebe” are element-by-element quantities.
Default output fields:
name: element name, when repeated elements are present “::1”, “::2”, …
suffixes are added to make the names unique. (ebe)
env_name: environment name of the element, i.e. name without suffix
for repeated elements. (ebe)
s: element position [m] (ebe)
x, px, y, py, zeta, delta, ptau: coordinates
of the closed orbit for the periodic twiss and of the beam trajectory
for the open twiss. (ebe)
betx, bety, alfx, alfy, gamx, gamy: Twiss parameters.
In the presence of linear coupling, these are respectively betx1,
bety2, alfx1, alfy2, gamx1, gamy2 in the Mais-Ripken sense. (ebe)
TwissTable stores element-by-element optics and closed-orbit data
produced by Twiss calculations. Typical columns include longitudinal
position, beta functions, alpha functions, dispersion, phase advances,
coordinates, momenta, and element strengths when requested.
Create a Twiss table.
TwissTable stores element-by-element optics, closed orbit,
transfer information, and global quantities produced by Twiss
calculations.
Parameters:
data (mapping) – Mapping containing Twiss-table columns and scalar attributes.
*args – Positional arguments passed to xtrack.Table.
periodic (bool, optional) – Whether the stored Twiss solution is periodic. If not provided,
the value is taken from data["periodic"] when available,
otherwise it defaults to False.
**kwargs – Keyword arguments passed to xtrack.Table.
Add integrated element strengths to the Twiss table.
The strength columns are computed from the elements in line and added
to this table in place. If line is not provided, the line stored in the
Twiss action is used when available.
Parameters:
line (xtrack.Line, optional) – Line from which the element strengths are read.
Returns:
This Twiss table, with strength columns added when a line is available.
The returned view is used to select multiple columns while preserving
the table type. Columns can be selected from a whitespace-separated
string or from an iterable of column names. String selectors can also
contain simple expressions involving table columns, for example
"dx/sqrt(betx)".
Returns:
Accessor exposing column selection and column utilities.
The input tables are joined in order. Common boundary rows are removed
when needed to avoid duplicating the shared element, and cyclic quantities
such as phase advances are shifted to remain continuous across table
boundaries.
Parameters:
tables_to_concat (sequence of xtrack.TwissTable) – Twiss tables to concatenate. All tables must have the same
values_at and reference_frame.
Compute the transfer matrix between two table locations.
The matrix is reconstructed from the W matrices and phase advances stored
in the Twiss table. Both start and end identify rows in the table
and are used as the boundary locations of the transfer. For tables with
values_at=="entry" (default), this is the transfer from the entry of
start to the entry of end.
Parameters:
start (str or int) – Element name or row index at which the transfer starts.
end (str or int) – Element name or row index at which the transfer ends. The end row must
be after the start row in the table.
Compute transfer matrices from the first table row to all rows.
For each row, the transfer matrix is reconstructed from the W matrix at
that row, the W matrix at the first row, and the phase advances relative
to the first row.
Returns:
Table with one row per Twiss-table row. It contains the element names,
longitudinal positions, the full R_matrix array for each row, and
scalar columns r11 through r66 with the individual matrix
elements.
Compute the beam covariance matrix along the line.
The covariance matrix is built from the W matrices stored in the Twiss
table and the provided transverse and longitudinal emittances. Normalized
emittances are converted to geometric emittances using the reference
particle beta and gamma.
Compute the evolution of emittances due to Synchrotron Radiation
and Intra-Beam Scattering until convergence to equilibrium values.
The equilibrium state is determined by an iterative process which
consists in computing the IBS growth rates and the emittance time
derivatives, then computing the emittances at the next time step,
potentially including the effect of transverse constraints, and
checking for convergence. The convergence criteria can be chosen
by the user.
Transverse emittances can be constrained to follow two scenarios:
An emittance exchange originating from betatron coupling.
A vertical emittance originating from an excitation.
The impact from the longitudinal impedance (e.g. bunch lengthening
or microwave instability) can be accounted for by specifying the RMS
bunch length and momentum spread.
Notes
It is required that radiation has been configured in the line,
and that this TwissTable holds information on the equilibrium
state from Synchrotron Radiation. This means calling first
line.configure_radiation(model="mean") and then the .twiss()
method with radiation_analysis=True.
Warning
If the user does not provide a starting emittance, the program
defaults to using the SR equilibrium value from this TwissTable,
which is a reasonable defaults for light sources. If a constraint
is provided via emittance_constraint the starting emittances are
re-computed to respect that constraint (this is logged to the user).
If the user does provide starting emittances and a constraint, it
is up to the user to make sure these provided values are consistent
with the provided constraint!
Parameters:
formalism (str) – Which formalism to use for the computation of the IBS growth rates.
Can be Nagaitsev or Bjorken-Mtingwa (also accepts B&M),
case-insensitively.
total_beam_intensity (int) – The bunch intensity, in [particles per bunch].
gemitt_x (float, optional) – Starting horizontal geometric emittance, in [m]. If neither this nor
the normalized one is provided, the SR equilibrium value from this
TwissTable is used.
nemitt_x (float, optional) – Starting horizontal normalized emittance, in [m]. If neither this nor
the geometric one is provided, the SR equilibrium value from this
TwissTable is used.
gemitt_y (float, optional) – Starting vertical geometric emittance, in [m]. If neither this nor
the normalized one is provided, the SR equilibrium value from this
TwissTable is used.
nemitt_y (float, optional) – Starting vertical normalized emittance, in [m]. If neither this nor
the geometric one is provided, the SR equilibrium value from this
TwissTable is used.
gemitt_zeta (float, optional) – Starting longitudinal geometric emittance, in [m]. If neither this
nor the normalized one is provided, the SR equilibrium value from
this TwissTable is used.
nemitt_zeta (float, optional) – Starting longitudinal normalized emittance, in [m]. If neither this
nor the geometric one is provided, the SR equilibrium value from this
TwissTable is used.
emittance_coupling_factor (float, optional) – The ratio of perturbed transverse emittances due to betatron coupling.
If a value is provided, it is taken into account for the evolution of
emittances and induces an emittance sharing between the two planes.
See the next parameter for possible scenarios and how this value is
used. Defaults to 0.
emittance_constraint (str, optional) –
If an accepted value is provided, enforces constraints on the transverse
emittances. Can be either “coupling” or “excitation”, case-insensitively.
Defaults to “coupling”.
- If coupling, vertical emittance is the result of linear coupling. In
this case both the vertical and horizontal emittances are altered and
determined based on the value of emittance_coupling_factor and the
damping partition numbers. If the horizontal and vertical partition
numbers are equal then the total transverse emittance is preserved.
If excitation, vertical emittance is the result of an excitation
(e.g. from a feedback system) and is determined from the horizontal
emittance based on the value of emittance_coupling_factor. In this
case the total transverse emittance is NOT preserved.
Providing None allows one to study a scenario without constraint. Note
that as emittance_coupling_factor defaults to 0, the constraint has no
effect unless a non-zero factor is provided.
overwrite_sigma_zeta (float, optional) – The RMS bunch length, in [m]. If provided, overwrites the one computed from
the longitudinal emittance and forces a recompute of the longitudinal
emittance. Defaults to None.
overwrite_sigma_delta (float, optional) – The RMS momentum spread of the bunch. If provided, overwrites the one
computed from the longitudinal emittance and forces a recompute of the
longitudinal emittance. Defaults to None.
rtol (float, optional) – Relative tolerance to determine when convergence is reached: if the relative
difference between the computed emittances and those at the previous step is
below rtol, then convergence is considered achieved. Defaults to 1e-6.
tstep (float, optional) – Time step to use for each iteration, in [s]. If not provided, an
adaptive time step is computed based on the IBS growth rates and
the damping constants. Defaults to None.
max_steps (float, optional) – The maximum number of iterations to perform before stopping the iterative
process. If not provided, the process continues until it reaches convergence
(according to the provided rtol). Defaults to None.
verbose (bool, optional) – Whether to print out information on the current iteration step and estimated
convergence progress. Defaults to True.
**kwargs (dict) – Keyword arguments are passed to the growth rates computation method of
the chosen IBS formalism implementation. See the formalism classes in
the xfields.ibs._analytical for more details.
Returns:
The convergence calculations results. The table contains the following
columns, as time-step by time-step quantities:
time: time values at which quantities are computed, in [s].
gemitt_x: horizontal geometric emittances, in [m].
nemitt_x: horizontal normalized emittances, in [m].
gemitt_y: vertical geometric emittances, in [m].
nemitt_y: vertical normalized emittances, in [m].
gemitt_zeta: longitudinal geometric emittances, in [m].
nemitt_zeta: longitudinal normalized emittances, in [m].
sigma_zeta: bunch lengths, in [m].
sigma_delta: momentum spreads, in [-].
Kx: horizontal IBS amplitude growth rates, in [s^-1].
Ky: vertical IBS amplitude growth rates, in [s^-1].
Kz: longitudinal IBS amplitude growth rates, in [s^-1].
The table also contains the following global quantities:
damping_constants_s: radiation damping constants used, in [s].
formalism (str) – Which formalism to use for the computation. Can be Nagaitsev
or Bjorken-Mtingwa (also accepts B&M), case-insensitively.
total_beam_intensity (int, optional) – The beam intensity. Required if particles is not provided.
gemitt_x (float, optional) – Horizontal geometric emittance in [m]. If particles is not
provided, either this parameter or nemitt_x is required.
nemitt_x (float, optional) – Horizontal normalized emittance in [m]. If particles is not
provided, either this parameter or gemitt_x is required.
gemitt_y (float, optional) – Vertical geometric emittance in [m]. If particles is not
provided, either this parameter or nemitt_y is required.
nemitt_y (float, optional) – Vertical normalized emittance in [m]. If particles is not
provided, either this parameter or gemitt_y is required.
sigma_delta (float, optional) – The momentum spread. Required if particles is not provided.
bunch_length (float, optional) – The bunch length in [m]. Required if particles is not provided.
bunched (bool, optional) – Whether the beam is bunched or not (coasting). Defaults to True.
Required if particles is not provided.
**kwargs (dict) – Keyword arguments are passed to the growth rates computation method of
the chosen IBS formalism implementation. See the IBS details from the
xfields package directly.
Returns:
An IBSGrowthRates object with the computed growth rates.
Convert particle coordinates to normalized coordinates.
Particle physical coordinates are transformed using the closed orbit and
W matrix stored in this Twiss table at each particle’s at_element.
If normalized emittances are provided, the normalized coordinates are
scaled by the square root of the corresponding emittance.
Parameters:
particles (xtrack.Particles) – Particles whose coordinates are converted.
nemitt_x (float, optional) – Horizontal normalized emittance used to scale x_norm and
px_norm.
nemitt_y (float, optional) – Vertical normalized emittance used to scale y_norm and
py_norm.
nemitt_zeta (float, optional) – Longitudinal normalized emittance used to scale zeta_norm and
pzeta_norm.
Returns:
Table indexed by particle_id with columns particle_id,
at_element, x_norm, px_norm, y_norm, py_norm,
zeta_norm, and pzeta_norm.
Build Twiss initial conditions from this table at an element.
The returned object contains the closed-orbit particle, W matrix, phase
advances, and available chromatic quantities extracted from the selected
row of the table. It can be passed as the init argument to
xtrack.Line.twiss() to start a Twiss calculation from the same
optics conditions.
Parameters:
at_element (str or int) – Element name or row index at which the initial conditions are
extracted. The table must contain values at element entry.
Returns:
Initial conditions for a Twiss calculation at the selected element.
Build a Twiss table for the reverse local reference frame.
The returned table has the element order reversed and optics quantities
transformed to the reverse local reference frame. The transverse and
longitudinal coordinates are transformed as x->-x, y->y,
and zeta->-zeta. The momenta and longitudinal position are
transformed as px->px, py->-py, and
s->line_length-s. The phase advances are transformed as
mux->mux[0]-mux and muy->muy[0]-muy. The reference frame
is switched between "proper" and "reverse".
Returns:
Twiss table corresponding to the reverse local reference frame.
The returned view is used to select rows while preserving the table
type. Rows can be selected by name, by regular expression, by a list of
names, by a range of row names, by a range on a chosen column, or by
offsets relative to named rows. It also provides methods such as
match() and
match_not() to select rows using regular
expressions on any column.
Returns:
Accessor exposing row selection, iteration, and row utilities.
rows (str, slice, list, or None, optional) – Rows to show. If None, show all rows. See table.rows for
accepted row selectors.
cols (str, list, or None, optional) – Columns to show. If None, show all columns. See table.cols
for accepted column selectors.
maxrows (int or None, optional) – Maximum number of rows to show. If None, show all rows.
maxwidth (int, "auto", "full", or None, optional) – Maximum width of the output. If "auto", use the terminal width.
If "full" or None, use the full width.
max_col_width (int or None, optional) – Maximum width of a column. If None, do not truncate column
values.
output (None, str, file-like object, or path-like, optional) – If None, print the output. If str, return the output as a
string. If a file-like object, write the output to the file. Other
values are interpreted as output paths.
digits (int, optional) – Number of digits to use for floats.
fixed ({"g", "f"}, optional) – If "g", use general floating-point format. If "f", use
fixed-point format.
header (bool, optional) – If True, show the header.
Returns:
String representation when outputisstr. Otherwise None.
include (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to include. If
omitted, all columns and attributes are included.
exclude (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to exclude.
missing ({"error", "ignore"}, optional) – Policy for names requested in include or exclude that are
not present in the table.
include_meta (bool, optional) – If True, include metadata describing dropped columns,
dropped attributes, table class, and xtrack version when relevant.
Returns:
Serialized table data with columns and attrs entries.
The output survey table contains the following columns:
name: element name (with occurrence counts for repeated names).
element_type: type of the element (e.g. Drift, Marker, Bend).
prototype: name of the element prototype, when present.
s: longitudinal coordinate at the element entrance [m].
X, Y, Z: position of the element entrance in the global frame [m].
theta, phi, psi: orientation angles of the local frame
(azimuth, elevation, roll) unwrapped along the line [rad].
ex, ey, ez: unit vectors of the local frame expressed in
the global frame (they are the columns of E_matrix).
E_matrix: 3x3 rotation matrices describing the local frame at each
element entrance.
XYZ: position vectors stacked as [X,Y,Z].
isthick: True for thick elements, False for markers.
drift_length: length used while advancing the survey (zero for
thin elements) [m].
length: physical length of the element [m].
Examples
importxtrackasxt# Create a simple lineenv=xt.Environment(particle_ref=xt.Particles(p0c=1e9))line=env.new_line(length=6,components=[env.new('b1',xt.Bend,length=0.2,angle=0.1,at=1),env.new('q1',xt.Quadrupole,length=0.1,k1=0.5,at=2),env.new('b2',xt.Bend,length=0.2,angle=-0.1,at=3),env.new('q2',xt.Quadrupole,length=0.1,k1=-0.5,at=4),])# Compute the surveysv=line.survey()# sv.X, sv.Y, sv.Z contain the coordinates of the reference# trajectory in the global frame# Compute the trajectory of a particle entering with x=1 mm and y=2 mmtw=line.twiss4d(betx=1,bety=1,x=1e-3,y=2e-3)# tw.x, tw.y contain the coordinates of the particle in the local frame# Compute the trajectory of the particle in the global framep_global=tw.x[:,None]*sv.ex+tw.y[:,None]*sv.ey+sv.XYZX_trajectory=p_global[:,0]Y_trajectory=p_global[:,1]Z_trajectory=p_global[:,2]
SurveyTable stores the surveyed position and orientation of each
element along a line. Typical columns include the longitudinal position
s, global coordinates such as X, Y, and Z, and orientation
data such as the local reference-frame basis vectors or rotation matrices.
Create a table from column data.
Tables are used throughout xtrack to return structured results, such as
line descriptions, survey data, and Twiss data. They behave like
lightweight data frames with named columns, a configurable row index,
readable text output, row and column selection helpers, and
serialization methods.
Parameters:
data (mapping) – Mapping from names to numpy arrays or scalar attributes. Entries
listed in col_names are table columns and must all have the
same length when verify is True.
col_names (sequence of str, optional) – Column names to expose as table columns. If omitted, all keys in
data are used as columns.
index (str or None, optional) – Column used for named row lookup. If None, named row selection
is disabled.
sep_count (str, optional) – Separator used to select repeated row names, for example
"mb::1".
sep_previous (str, optional) – Separator used to select rows upstream of a named row, for example
"mb<<2".
sep_next (str, optional) – Separator used to select rows downstream of a named row, for
example "mb>>2".
cast_strings (bool, optional) – If True, string arrays are stored with object dtype.
regex_flags (int, optional) – Flags passed to re.compile() for row and column matching.
verify (bool, optional) – If True, validate column types, column lengths, and the index
column.
_copy_cols (bool, optional) – If True, copy column arrays during construction.
The returned view is used to select multiple columns while preserving
the table type. Columns can be selected from a whitespace-separated
string or from an iterable of column names. String selectors can also
contain simple expressions involving table columns, for example
"dx/sqrt(betx)".
Returns:
Accessor exposing column selection and column utilities.
Build a survey table for the reverse local reference frame.
The returned table has the element order reversed and survey quantities
transformed to the reverse local reference frame. The longitudinal position
is transformed as s->line_length-s. The global coordinates are
transformed as X->-X, Y->Y, and Z->-Z. The survey
orientation matrix is transformed consistently with the reversed global
frame and reversed local frame axes.
Returns:
Survey table corresponding to the reverse local reference frame.
The returned view is used to select rows while preserving the table
type. Rows can be selected by name, by regular expression, by a list of
names, by a range of row names, by a range on a chosen column, or by
offsets relative to named rows. It also provides methods such as
match() and
match_not() to select rows using regular
expressions on any column.
Returns:
Accessor exposing row selection, iteration, and row utilities.
rows (str, slice, list, or None, optional) – Rows to show. If None, show all rows. See table.rows for
accepted row selectors.
cols (str, list, or None, optional) – Columns to show. If None, show all columns. See table.cols
for accepted column selectors.
maxrows (int or None, optional) – Maximum number of rows to show. If None, show all rows.
maxwidth (int, "auto", "full", or None, optional) – Maximum width of the output. If "auto", use the terminal width.
If "full" or None, use the full width.
max_col_width (int or None, optional) – Maximum width of a column. If None, do not truncate column
values.
output (None, str, file-like object, or path-like, optional) – If None, print the output. If str, return the output as a
string. If a file-like object, write the output to the file. Other
values are interpreted as output paths.
digits (int, optional) – Number of digits to use for floats.
fixed ({"g", "f"}, optional) – If "g", use general floating-point format. If "f", use
fixed-point format.
header (bool, optional) – If True, show the header.
Returns:
String representation when outputisstr. Otherwise None.
include (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to include. If
omitted, all columns and attributes are included.
exclude (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to exclude.
missing ({"error", "ignore"}, optional) – Policy for names requested in include or exclude that are
not present in the table.
include_meta (bool, optional) – If True, include metadata describing dropped columns,
dropped attributes, table class, and xtrack version when relevant.
Returns:
Serialized table data with columns and attrs entries.
default_column_width (int, optional) – Minimum column width to enforce for headers and data cells.
float_precision (int, optional) – Significant digits used when writing floating-point values.
numeric_column_width (int, optional) – If provided, enforces this uniform width for all numeric columns.
When omitted, numeric columns still share a common width derived
from the widest numeric entry.
column_formats (Mapping[str, str], optional) – Per-column Python/C-style format specifiers (e.g. ‘.3f’, ‘10.4g’).
Applied to data cells while falling back to float_precision
defaults when unspecified.
column_widths (Mapping[str, int], optional) – Per-column minimum widths overriding the defaults. Non-numeric
columns stay left-aligned; numeric ones keep right alignment.
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 returned, 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.
check_limits (bool) – If True (default), the limits of the knobs are checked before the
optimization. If False, if the knobs are out of limits, the optimization
knobs are set to the limits on the first iteration.
**kwargs (dict) – Additional arguments to be passed to the twiss.
Returns:
optimizer – xdeps optimizer object used for the optimization.
# Match tunes and chromaticities to assigned valuesline.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 bumptw_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 anglext.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 closedxt.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 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.
Returns:
Returned xtrack.match.KnobOptimizer used to match and
generate the knob. It exposes the underlying
xdeps.Optimize methods, and provides
generate_knob() to install the matched knob expression.
Generate the knob expression from the matched auxiliary variables.
The generated knob is linear between knob_value_start and
knob_value_end. The line variables listed in vary receive an
added expression term controlled by knob_name.
The optimizer changes the variables described by vary until the
quantities described by targets are within their tolerances. In
Xtrack this object is returned by xtrack.Line.match() when
solve=False. It can also be used directly with xdeps
Vary, Target and Action objects.
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 {}.
show_call_counter (bool, optional) – If True, show the number of merit-function calls while optimizing.
Defaults to True.
check_limits (bool, optional) – If True, reject knob values outside their limits. If False, values
outside limits are clipped before a Jacobian step. Defaults to True.
name (str, optional) – Name printed in optimization progress messages.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON False -1 -1 0 0, val=0, tol=1e-12, weight=1# 1 ON False 2 2 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 0 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 0 1e+200 0 1e-06 1opt.solve(verbose=False)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1opt.log().show()# iteration penalty alpha tag tol_met target_active hit_limits vary_active ...# 0 2.23607 -1 nn yy nn yy# 1 2.23607 -1 nn yy nn yy# 2 2.81031e-10 0 nn yy nn yy# 3 0 0 yy yy nn yy
The callable is evaluated as function(x) and must return a sequence
with the same length as tar. The input vector x is optimized so
that each returned value reaches the corresponding target value within
the corresponding tolerance.
Parameters:
function (callable) – Callable receiving the current input vector and returning the
quantities to match.
x0 (array-like) – Initial input vector.
tar (array-like) – Target values for the callable output.
steps (array-like, optional) – Finite-difference steps used to build the Jacobian. If not provided,
STEP_DEFAULT is used for all variables.
tols (array-like, optional) – Tolerance for each target. If not provided, TOL_DEFAULT is used
for all targets.
limits (array-like, optional) – Lower and upper limits for each input variable, as
[(lower,upper),...].
show_call_counter (bool, optional) – If True, show the number of merit-function calls while optimizing.
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.solve(verbose=False)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1opt.log().show()# iteration penalty alpha tag tol_met target_active hit_limits vary_active ...# 0 2.23607 -1 nn yy nn yy# 1 2.23607 -1 nn yy nn yy# 2 2.81031e-10 0 nn yy nn yy# 3 0 0 yy yy nn yy
Perform optimization steps using the Jacobian solver.
This is equivalent to calling step() with the provided number of
steps.
Parameters:
n_steps (int, optional) – Number of steps to perform. Defaults to 1.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.verbose=Falseopt.run_jacobian(n_steps=3)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 1 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
Perform the least squares optimization using the Trust Region Reflective algorithm.
This method uses scipy.optimize.least_squares() with
method="trf".
Parameters:
n_steps (int, optional) – Maximum number of steps to perform. Defaults to 1000.
ftol (float, optional) – Tolerance for the cost function. Defaults to 1e-12.
gtol (float, optional) – Tolerance for the gradient. Defaults to None.
xtol (float, optional) – Tolerance for the step. Defaults to 1e-12.
verbose (int, optional) – Verbosity level. Defaults to 0.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.run_ls_trf(n_steps=200)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 1 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
Perform the least squares optimization using the Dogbox algorithm.
This method uses scipy.optimize.least_squares() with
method="dogbox".
Parameters:
n_steps (int, optional) – Maximum number of steps to perform. Defaults to 1000.
ftol (float, optional) – Tolerance for the cost function. Defaults to 1e-12.
gtol (float, optional) – Tolerance for the gradient. Defaults to None.
xtol (float, optional) – Tolerance for the step. Defaults to 1e-12.
verbose (int, optional) – Verbosity level. Defaults to 0.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.run_ls_dogbox(n_steps=200)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 1 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
Perform the optimization using the L-BFGS-B algorithm.
This method uses scipy.optimize.minimize() with
method="L-BFGS-B".
Parameters:
n_steps (int, optional) – Maximum number of steps to perform. Defaults to 1000.
ftol (float, optional) – Tolerance for the cost function. Defaults to 1e-24.
gtol (float, optional) – Tolerance for the gradient. Defaults to 1e-24.
disp (bool, optional) – If True, display convergence messages. Defaults to False.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.run_l_bfgs_b(n_steps=200)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 1 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
Perform the optimization using the BFGS algorithm.
This method uses scipy.optimize.minimize() with
method="BFGS".
Parameters:
n_steps (int, optional) – Maximum number of steps to perform. Defaults to 1000.
xrtol (float, optional) – Relative tolerance for the step. Defaults to 1e-10.
gtol (float, optional) – Tolerance for the gradient. Defaults to 1e-18.
disp (bool, optional) – If True, display convergence messages. Defaults to False.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-11,1e-11],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.run_bfgs(n_steps=200)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True -1.41642e-12 -1.41642e-12 0 0, val=0, tol=1e-11, weight=1# 1 ON True 3.23319e-12 3.23319e-12 0 1, val=0, tol=1e-11, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 1 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
Perform the optimization using the Nelder-Mead Simplex algorithm.
This method uses scipy.optimize.minimize() with
method="Nelder-Mead".
Parameters:
n_steps (int, optional) – Maximum number of steps to perform. Defaults to 1000.
fatol (float, optional) – Absolute tolerance for the cost function. Defaults to 1e-11.
xatol (float, optional) – Absolute tolerance for the step. Defaults to 1e100 (no effect).
adaptive (bool, optional) – If True, adapt algorithm parameters to dimensionality of problem. Defaults to True.
disp (bool, optional) – If True, display convergence messages. Defaults to False.
verbose (bool or int, optional) – Verbosity used for xdeps progress messages.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-5,1e-5],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.run_nelder_mead(n_steps=500,verbose=False)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True -8.87276e-06 -8.87276e-06 0 0, val=0, tol=1e-05, weight=1# 1 ON True 2.76274e-06 2.76274e-06 0 1, val=0, tol=1e-05, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 0.999991 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
Perform the optimization using the DIRECT algorithm.
This method uses scipy.optimize.direct().
Parameters:
n_steps (int, optional) – Maximum number of steps to perform. Defaults to 1000.
verbose (bool or int, optional) – Verbosity used for xdeps progress messages.
**kwargs – Additional keyword arguments passed to
scipy.optimize.direct().
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],limits=[[-5,5],[-5,5]],show_call_counter=False)opt.run_direct(n_steps=1000,verbose=False)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True -4.4631e-14 -4.4631e-14 0 0, val=0, tol=1e-12, weight=1# 1 ON True 8.74856e-14 8.74856e-14 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -5 1 5 0 1e-06 1# 1 ON OK 1 -5 -2 5 0 1e-06 1
A step updates the active variables using the active targets and records
the result in the optimization log. Variables and targets can be enabled
or disabled only for the duration of these steps using the corresponding
keyword arguments.
Parameters:
n_steps (int, optional) – Number of steps to perform. Defaults to 1.
take_best (bool, optional) – If True and the final point is not within tolerance, reload the best
point found during this call. Defaults to True.
enable_target (list of int or strings, optional) – For the performed steps, enable target with corresponding id or tag
enable_vary (list of int or strings, optional) – For the performed steps, enable variables with corresponding id or tag
enable_vary_name (list of str, optional) – For the performed steps, enable variables with corresponding name
disable_target (list of int or strings, optional) – For the performed steps, disable target with corresponding id or tag
disable_vary (list of int or strings, optional) – For the performed steps, disable variables with corresponding id or tag
disable_vary_name (list of str, optional) – For the performed steps, disable variables with corresponding name
rcond (float, optional) – Cutoff passed to the Jacobian linear solve.
sing_val_cutoff (float, optional) – Singular-value cutoff passed to the Jacobian linear solve.
verbose (bool or int, optional) – Verbosity for progress messages. If not provided, self.verbose
is used.
broyden (bool or int, optional) – If True, update the Jacobian with Broyden updates between full
finite-difference Jacobian evaluations. If an integer is provided,
a full Jacobian is recomputed every broyden+1 steps.
Run the optimizer until convergence or until the step limit is reached.
The optimizer performs up to n_steps Jacobian steps. If n_steps
is not provided, self.n_steps_max is used. If
assert_within_tol is True, an error is raised when no point within
tolerance is found. If restore_if_fail is True, the initial knob
values are restored when an error is raised.
Parameters:
n_steps (int, optional) – Maximum number of Jacobian steps. If not provided,
self.n_steps_max is used.
verbose (bool or int, optional) – Verbosity for progress messages. If not provided, self.verbose
is used.
take_best (bool, optional) – If True and the final point is not within tolerance, reload the best
point found during this call. Defaults to True.
rcond (float, optional) – Cutoff passed to the Jacobian linear solve.
sing_val_cutoff (float, optional) – Singular-value cutoff passed to the Jacobian linear solve.
broyden (bool or int, optional) – If True, use Broyden updates between full finite-difference
Jacobian evaluations. If an integer is provided, a full Jacobian is
recomputed every broyden+1 steps.
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.solve(verbose=False)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1opt.log().show()# iteration penalty alpha tag tol_met target_active hit_limits vary_active ...# 0 2.23607 -1 nn yy nn yy# 1 2.23607 -1 nn yy nn yy# 2 2.81031e-10 0 nn yy nn yy
The target values are approached in equidistant linear steps from the
current values to the requested target values. This can improve
convergence when the full problem is too far from the initial point.
If a subproblem fails, the last successful tagged point is reloaded.
Parameters:
n_steps (int, optional) – Number of intermediate subproblems to solve.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.verbose=Falseopt.solve_homotopy(n_steps=5)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON True 0 0 0 0, val=0, tol=1e-12, weight=1# 1 ON True 0 0 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1opt.log().show()# iteration penalty alpha tag tol_met target_active hit_limits vary_active ...# 0 2.23607 -1 nn yy nn yy# 1 2.23607 -1 nn yy nn yy# 2 2.81031e-10 0 nn yy nn yy
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.solve(verbose=False)opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1vary_table=opt.vary_status(ret=True)vary_table.cols["id state met name current_val"]# id state met name current_val# 0 ON OK 0 1# 1 ON OK 1 -2
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.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.show()# Vary:# id tag state description# 0 ON name=0, limits=(-1e+200, 1e+200), step=1e-06, weight=1# 1 ON name=1, limits=(-1e+200, 1e+200), step=1e-06, weight=1# Targets:# id tag state description# 0 ON 0, val=0, tol=1e-12, weight=1# 1 ON 1, val=0, tol=1e-12, weight=1opt.show(targets=False)# Vary:# id tag state description# 0 ON name=0, limits=(-1e+200, 1e+200), step=1e-06, weight=1# 1 ON name=1, limits=(-1e+200, 1e+200), step=1e-06, weight=1
Reload the knob values from a given iteration in the optimization log.
Parameters:
iteration (int, optional) – Iteration to use.
tag (str, optional) – Reload the last log entry with the given tag. Exactly one of
iteration and tag must be provided.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.solve(verbose=False)opt.tag("matched")opt.reload(iteration=0)opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 0 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 0 1e+200 0 1e-06 1opt.reload(tag="matched")opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1
Selectors can be a single id/tag/name, a list of selectors, True to
select all, or False to select none. String selectors are matched as
regular expressions.
Parameters:
target (str, int, list of int or string, True, False.) – If target is True, enable all targets, if False, disable all targets,
else enable the targets with corresponding id if target is int or tag if target is str.
String are matched as regular expression.
vary (list of int or string) – If True, enable all variables. If False, disable all variables.
Else enable the variables with corresponding id or tag or all if True.
String are matched as regular expression.
vary_name (list of str) – Enable the variables with corresponding name.
String are matched as regular expression.
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.disable(target=True,vary=True)opt.enable(target=0,vary=0)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON False -1 -1 0 0, val=0, tol=1e-12, weight=1# 1 OFF False 2 2 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 0 1e+200 0 1e-06 1# 1 OFF OK 1 -1e+200 0 1e+200 0 1e-06 1
Selectors can be a single id/tag/name, a list of selectors, True to
select all, or False to select none. String selectors are matched as
regular expressions.
Parameters:
target (list of int or string) – If True, disable all targets. If False, enable all targets.
Else enable the targets with corresponding id or tag or all if True.
String are matched as regular expression.
vary (list of int or string) – If True, disable all variables. If False, enable all variables.
Else enable the variables with corresponding id or tag or all if True.
String are matched as regular expression.
vary_name (list of str) – Disable the variables with corresponding name.
String are matched as regular expression.
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)opt.disable(target=0,vary=0)opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 OFF False -1 -1 0 0, val=0, tol=1e-12, weight=1# 1 ON False 2 2 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 OFF OK 0 -1e+200 0 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 0 1e+200 0 1e-06 1
Get the merit function that can be used with a different optimizer.
The returned object exposes the current optimizer variables as a vector
and evaluates the residuals used by the optimizer. It also provides a
finite-difference Jacobian through get_jacobian.
Parameters:
check_limits (bool, optional) – If True, enforce that the knob values are within the limits.
An error is raised if a knob value is outside the limits.
Defaults to True.
return_scalar (bool, optional) – If True, return a scalar value. If False, return an array.
If None, use the default value for the solver. Defaults to None.
rescale_x (tuple, optional) – If set, merit_function normalizes x to the given interval.
If None, x is used as is.
Returns:
Callable merit-function view.
Return type:
MeritFunctionView
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)merit=opt.get_merit_function(return_scalar=False)x=merit.get_x()residuals=merit(x)# [-1. 2.]jacobian=merit.get_jacobian(x)# [[1. 0.]# [0. 1.]]opt.target_status()# Target status:# id state tag tol_met residue current_val target_val description# 0 ON False -1 -1 0 0, val=0, tol=1e-12, weight=1# 1 ON False 2 2 0 1, val=0, tol=1e-12, weight=1opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 0 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 0 1e+200 0 1e-06 1
Container with the active and inactive variables of the optimizer.
The container can be inspected directly and supports convenience display
through its representation in notebooks and terminals. Use
vary_status() for a tabular view with current values and limits.
Set active variable values from an optimizer vector.
Parameters:
x (array-like) – Vector in the optimizer coordinates. Values are converted to native
knob values using the internal variable scaling before assignment.
Examples
importxdepsasxddeff(x):return[x[0]-1,x[1]+2]opt=xd.Optimize.from_callable(f,x0=[0.,0.],tar=[0,0],steps=[1e-6,1e-6],tols=[1e-12,1e-12],show_call_counter=False)merit=opt.get_merit_function()x=merit.get_x()x[0]=1.x[1]=-2.opt.set_knobs_from_x(x)opt.vary_status()# Vary status:# id state tag met name lower_limit current_val upper_limit val_at_iter_0 step weight# 0 ON OK 0 -1e+200 1 1e+200 0 1e-06 1# 1 ON OK 1 -1e+200 -2 1e+200 0 1e-06 1
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.
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 selected twiss range.
start (str, optional) – Initali wlement at which the phase advance is evaluated. Default is the
first element of the selected twiss range.
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 ‘’.
Closed-orbit or transfer-line trajectory correction.
This object stores the response-matrix correction setup used by
xtrack.Line.correct_trajectory(). It can be used to inspect and
customize the correction before applying it.
Build a trajectory correction from a linearized response matrix.
Parameters:
line (xtrack.Line) – Line object on which the trajectory correction is performed.
start (str) – Start of the line range in which the correction is performed.
If start is provided end must also be provided.
If start is None, the correction is performed on the periodic
solution (closed orbit).
end (str) – End of the line range in which the correction is performed.
If end is provided start must also be provided.
If start is None, the correction is performed on the periodic
solution (closed orbit).
twiss_table (TwissTable) – Twiss table used to compute the response matrix for the correction.
If None, the twiss table is computed from the line.
monitor_names_x (list of str) – List of elements used as monitors in the horizontal plane.
corrector_names_x (list of str) – List of elements used as correctors in the horizontal plane. They
must have knl and ksl attributes.
monitor_names_y (list of str) – List of elements used as monitors in the vertical plane.
corrector_names_y (list of str) – List of elements used as correctors in the vertical plane. They
must have knl and ksl attributes.
monitor_alignment (dict or None) – Optional monitor alignment information passed to the response
matrix computation.
x_init (float) – Initial trajectory coordinates used when correcting a line range.
px_init (float) – Initial trajectory coordinates used when correcting a line range.
y_init (float) – Initial trajectory coordinates used when correcting a line range.
py_init (float) – Initial trajectory coordinates used when correcting a line range.
zeta_init (float) – Initial trajectory coordinates used when correcting a line range.
delta_init (float) – Initial trajectory coordinates used when correcting a line range.
n_micado (int) – If n_micado is not None, the MICADO algorithm is used for the
correction. In that case, the number of correctors to be used is
given by n_micado.
n_singular_values (int) – Number of singular values used for the correction.
rcond (float) – Cutoff for small singular values (relative to the largest singular
value). Singular values smaller than rcond are considered zero.
corrector_limits_x (tuple of array-like or None) – Limits for the horizontal corrector strengths. If not None, it should be a tuple
of two arrays (lower_limits, upper_limits) with the same length as
the number of horizontal correctors. If None, no limits are applied.
corrector_limits_y (tuple of array-like or None) – Limits for the vertical corrector strengths. If not None, it should be a tuple
of two arrays (lower_limits, upper_limits) with the same length as
the number of vertical correctors. If None, no limits are applied.
Correct the trajectory in the horizontal and/or vertical plane.
Parameters:
planes (str) – Plane(s) in which the correction is performed. Possible values are
‘x’, ‘y’, ‘xy’.
n_micado (int or tuple of int) – If n_micado is not None, the MICADO algorithm is used for the
correction. In that case, the number of correctors to be used is
given by n_micado.
n_singular_values (int or tuple of int) – Number of singular values used for the correction.
rcond (float or tuple of float) – Cutoff for small singular values (relative to the largest singular
value). Singular values smaller than rcond are considered zero.
n_iter (int or 'auto') – Number of iterations for the correction. If ‘auto’, the correction
stops when the rms of the position does not decrease by more than
stop_iter_factor with respect to the previous iteration.
verbose (bool) – If True, print the rms of the position at each iteration.
stop_iter_factor (float) – If n_iter is ‘auto’, the correction stops when the rms of the
position does not decrease by more than stop_iter_factor with
respect to the previous iteration.
tol_position_std (float) – Stop the automatic iteration when the rms position is below this
value.
delta0 (float or None) – Closed-orbit momentum deviation used when recomputing the orbit
during iterative correction.
Thread the trajectory along the line. The correction is performed in
portions of length ds_thread. For each portion the correction is
first performed only on the new added part, then on the whole portion up
to the end of the new added part.
Parameters:
ds_thread (float) – Length of the portion added at each iteration.
rcond_short (float or tuple of float) – Cutoff for small singular values used for the correction of the
newly added part.
rcond_long (float or tuple of float) – Cutoff for small singular values (relative to the largest singular
value) used for the correction of the whole portion up to the end
of the new added part.
Returns:
threader – Object containing the threaded correction setup.
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. If this is None (default), the
reference particle associated with this line is used.
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.
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).
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:
pdg_id_0 (int or str, optional, define reference mass and charge from) – PDG id or particle name.
_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]
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
rigidity0 (array_like of float, optional) – Reference magnetic rigidity [T.m]
kinetic_energy0 (array_like of float, optional) – Reference kinetic energy [eV]
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 per macro-particle
(used for collective simulations, e.g. space charge, beam-beam,
wakefields, etc.)
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)
t_sim (float, optional) – Simulation frame time (typically one revolution period)
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.
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).
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.
The transverse coordinates are generated from independent Gaussian
distributions in normalized phase space and converted to physical
coordinates using build_particles. The longitudinal coordinates are
matched to the RF bucket using generate_longitudinal_coordinates with
distribution=’gaussian’.
Parameters:
num_particles (int) – Number of macroparticles to generate.
nemitt_x (float) – Normalized horizontal emittance in m rad.
nemitt_y (float) – Normalized vertical emittance in m rad.
sigma_z (float) – RMS bunch length in m.
total_intensity_particles (float, optional) – Total bunch intensity in physical particles. If not provided, the
particle weights are set to one.
particle_on_co (xpart.Particles, optional) – Particle on the closed orbit used as reference for the generated bunch.
Cannot be provided together with particle_ref.
R_matrix (array_like, optional) – Linear transfer matrix passed to build_particles.
circumference (float, optional) – Ring circumference in m. Required when no line is provided.
momentum_compaction_factor (float, optional) – Momentum compaction factor. Required when no line is provided.
rf_harmonic (float or array_like, optional) – RF harmonic number or numbers. Required when no line is provided.
rf_voltage (float or array_like, optional) – RF voltage or voltages in V. Required when no line is provided.
rf_phase (float or array_like, optional) – RF phase or phases in rad. Required when no line is provided.
energy_ref_increment (float, optional) – Reference energy increment used for the longitudinal matching.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line, optional) – Line for which the bunch is generated. If provided, missing RF and
lattice parameters are inferred from the line.
particle_ref (xpart.Particles, optional) – Reference particle. If not provided, line.particle_ref is used when
available. Cannot be provided together with particle_on_co.
engine (str, optional) – Longitudinal matching engine passed to
generate_longitudinal_coordinates.
return_matcher (bool, optional) – If True, also return the longitudinal matcher object.
_context (xobjects.Context, optional) – Context on which to allocate the returned particles.
_buffer (xobjects.Buffer, optional) – Buffer on which to allocate the returned particles.
_offset (int, optional) – Offset in _buffer at which to allocate the returned particles.
**kwargs – Additional keyword arguments passed to generate_longitudinal_coordinates
and build_particles.
Generate longitudinal coordinates matched to an RF bucket.
The RF and optics parameters can be inferred from line, or provided
explicitly. With the default engine, linear longitudinal elements use a
linear Gaussian match, while nonlinear RF buckets use the PyHEADTAIL-style
RF bucket matcher.
Parameters:
line (xtrack.Line, optional) – Line for which the longitudinal coordinates are generated.
num_particles (int) – Number of particles to generate.
distribution ({'gaussian', 'parabolic', 'binomial', 'qgaussian'}, optional) – Longitudinal distribution to generate. Non-Gaussian distributions
require engine=’single-rf-harmonic’.
sigma_z (float) – RMS bunch length in m.
engine ({'linear', 'pyheadtail', 'single-rf-harmonic'}, optional) – Matching engine. If not provided, it is selected from the line.
return_matcher (bool, optional) – If True, also return the matcher object.
particle_ref (xpart.Particles, optional) – Reference particle. If not provided, line.particle_ref is used.
mass0 (float, optional) – Reference-particle properties used when they cannot be inferred from
particle_ref.
q0 (float, optional) – Reference-particle properties used when they cannot be inferred from
particle_ref.
gamma0 (float, optional) – Reference-particle properties used when they cannot be inferred from
particle_ref.
circumference (float, optional) – Ring circumference in m. Required when no line is provided.
momentum_compaction_factor (float or array_like, optional) – Momentum compaction factor.
rf_harmonic (float or array_like, optional) – RF harmonic number or numbers.
rf_voltage (float or array_like, optional) – RF voltage or voltages in V.
rf_phase (float or array_like, optional) – RF phase or phases in rad.
rf_shift_zeta (float or array_like, optional) – Longitudinal RF shifts in m.
energy_ref_increment (float, optional) – Reference energy increment in eV.
energy_loss_from_radiation (float, optional) – Energy loss from radiation in eV.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
m (float, optional) – Binomial distribution parameter.
q (float, optional) – q-Gaussian distribution parameter.
zeta0 (float, optional) – Reference longitudinal position in m.
The radial and angular grids can be provided explicitly with r_grid and
theta_grid, or built from ranges. For each coordinate, provide either an
explicit grid, or a range together with either a step size or a number of
points. The returned arrays are flattened over all (r, theta)
combinations.
Parameters:
r_range (tuple of float, optional) – Radial range (r_min, r_max). Required if r_grid is not provided.
r_grid (array_like, optional) – Explicit uniformly spaced radial grid. If provided, r_range, dr,
and nr must not be provided.
dr (float, optional) – Radial step used with r_range. Cannot be provided together with nr.
nr (int, optional) – Number of radial points used with r_range. Required when r_grid and
dr are not provided.
theta_range (tuple of float, optional) – Angular range (theta_min, theta_max) in rad. Required if
theta_grid is not provided.
theta_grid (array_like, optional) – Explicit uniformly spaced angular grid in rad. If provided,
theta_range, dtheta, and ntheta must not be provided.
dtheta (float, optional) – Angular step in rad used with theta_range. Cannot be provided
together with ntheta.
ntheta (int, optional) – Number of angular points used with theta_range. Required when
theta_grid and dtheta are not provided.
Returns:
a1 (np.ndarray) – First Cartesian normalized coordinate, equal to
r_all * cos(theta_all).
a2 (np.ndarray) – Second Cartesian normalized coordinate, equal to
r_all * sin(theta_all).
r_all (np.ndarray) – Radial coordinate for each generated point.
theta_all (np.ndarray) – Angular coordinate in rad for each generated point.
Generate a 2D pencil distribution in normalized coordinates.
The generated points lie outside a position cut and within a radial
thickness dr_sigmas, expressed in units of the normalized beam size. For
side=’+’, the cut is applied on the positive side of the first
coordinate; for side=’-’, on the negative side. With side=’+-’, the
particles are split between the two sides.
Parameters:
num_particles (int) – Number of points to generate.
pos_cut_sigmas (float) – Position cut in units of sigma.
dr_sigmas (float) – Radial thickness of the pencil distribution in units of sigma.
side ({'+', '-', '+-'}, optional) – Side on which to generate the pencil distribution.
Returns:
x_norm (np.ndarray) – First normalized coordinate.
px_norm (np.ndarray) – Second normalized coordinate.
r_points (np.ndarray) – Radial coordinate of the generated points.
theta_points (np.ndarray) – Angular coordinate in rad of the generated points.
Generate a 2D pencil distribution with a cut in physical coordinates.
The requested absolute_cut is converted to normalized coordinates at the
selected location using the line optics and the provided normalized
emittances. A normalized pencil distribution is then generated with
generate_2D_pencil and converted back to physical coordinates.
Parameters:
num_particles (int) – Number of points to generate.
plane ({'x', 'y'}) – Plane in which to generate the pencil distribution.
absolute_cut (float) – Position cut in m.
dr_sigmas (float) – Radial thickness of the pencil distribution in units of sigma.
side ({'+', '-'}, optional) – Side on which to generate the pencil distribution.
tracker (xtrack.Tracker, optional) – Deprecated. Use line instead.
line (xtrack.Line) – Line used to compute the optics and physical coordinates.
nemitt_x (float) – Normalized horizontal emittance in m rad.
nemitt_y (float) – Normalized vertical emittance in m rad.
at_element (int or str, optional) – Element at which the cut is defined. If not provided, the start of the
line is used.
match_at_s (float, optional) – Longitudinal position in m at which the cut is defined, downstream of
at_element. If provided, at_element must also be provided.
twiss (xtrack.TwissTable or table row, optional) – Twiss data at the selected location. If not provided, it is computed
from line.
**kwargs – Additional keyword arguments passed to line.twiss and
line.build_particles.
Returns:
v (np.ndarray) – Physical coordinate in the selected plane, x for plane=’x’ or y
for plane=’y’, in m.
pv (np.ndarray) – Conjugate physical coordinate in the selected plane, px for
plane=’x’ or py for plane=’y’.
The xtrack.Table class is the base table used by xtrack table outputs
and provides selection, display, and serialization helpers. Row and column
selection is available through the inherited rows and
cols accessors.
Table with row and column selection plus xtrack serialization helpers.
Create a table from column data.
Tables are used throughout xtrack to return structured results, such as
line descriptions, survey data, and Twiss data. They behave like
lightweight data frames with named columns, a configurable row index,
readable text output, row and column selection helpers, and
serialization methods.
Parameters:
data (mapping) – Mapping from names to numpy arrays or scalar attributes. Entries
listed in col_names are table columns and must all have the
same length when verify is True.
col_names (sequence of str, optional) – Column names to expose as table columns. If omitted, all keys in
data are used as columns.
index (str or None, optional) – Column used for named row lookup. If None, named row selection
is disabled.
sep_count (str, optional) – Separator used to select repeated row names, for example
"mb::1".
sep_previous (str, optional) – Separator used to select rows upstream of a named row, for example
"mb<<2".
sep_next (str, optional) – Separator used to select rows downstream of a named row, for
example "mb>>2".
cast_strings (bool, optional) – If True, string arrays are stored with object dtype.
regex_flags (int, optional) – Flags passed to re.compile() for row and column matching.
verify (bool, optional) – If True, validate column types, column lengths, and the index
column.
_copy_cols (bool, optional) – If True, copy column arrays during construction.
The returned view is used to select multiple columns while preserving
the table type. Columns can be selected from a whitespace-separated
string or from an iterable of column names. String selectors can also
contain simple expressions involving table columns, for example
"dx/sqrt(betx)".
Returns:
Accessor exposing column selection and column utilities.
The returned view is used to select rows while preserving the table
type. Rows can be selected by name, by regular expression, by a list of
names, by a range of row names, by a range on a chosen column, or by
offsets relative to named rows. It also provides methods such as
match() and
match_not() to select rows using regular
expressions on any column.
Returns:
Accessor exposing row selection, iteration, and row utilities.
rows (str, slice, list, or None, optional) – Rows to show. If None, show all rows. See table.rows for
accepted row selectors.
cols (str, list, or None, optional) – Columns to show. If None, show all columns. See table.cols
for accepted column selectors.
maxrows (int or None, optional) – Maximum number of rows to show. If None, show all rows.
maxwidth (int, "auto", "full", or None, optional) – Maximum width of the output. If "auto", use the terminal width.
If "full" or None, use the full width.
max_col_width (int or None, optional) – Maximum width of a column. If None, do not truncate column
values.
output (None, str, file-like object, or path-like, optional) – If None, print the output. If str, return the output as a
string. If a file-like object, write the output to the file. Other
values are interpreted as output paths.
digits (int, optional) – Number of digits to use for floats.
fixed ({"g", "f"}, optional) – If "g", use general floating-point format. If "f", use
fixed-point format.
header (bool, optional) – If True, show the header.
Returns:
String representation when outputisstr. Otherwise None.
include (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to include. If
omitted, all columns and attributes are included.
exclude (str or iterable of str, optional) – Names of columns, attributes, or metadata entries to exclude.
missing ({"error", "ignore"}, optional) – Policy for names requested in include or exclude that are
not present in the table.
include_meta (bool, optional) – If True, include metadata describing dropped columns,
dropped attributes, table class, and xtrack version when relevant.
Returns:
Serialized table data with columns and attrs entries.
default_column_width (int, optional) – Minimum column width to enforce for headers and data cells.
float_precision (int, optional) – Significant digits used when writing floating-point values.
numeric_column_width (int, optional) – If provided, enforces this uniform width for all numeric columns.
When omitted, numeric columns still share a common width derived
from the widest numeric entry.
column_formats (Mapping[str, str], optional) – Per-column Python/C-style format specifiers (e.g. ‘.3f’, ‘10.4g’).
Applied to data cells while falling back to float_precision
defaults when unspecified.
column_widths (Mapping[str, int], optional) – Per-column minimum widths overriding the defaults. Non-numeric
columns stay left-aligned; numeric ones keep right alignment.
The object is available as table.rows and provides row selection,
iteration, and row-oriented helper methods. Rows can be selected by name,
by regular expression, by a list of names, by a range of row names, by a
range on a chosen column, or by offsets relative to named rows. The
match() and match_not() methods select rows using regular
expressions on any column.
row (int, str, or tuple) – Row selector. Strings can use "name::count<<offset" or
"name::count>>offset" syntax. Tuples are interpreted as
(name,count,offset) or (name,count).
The object is available as table.cols and provides column selection,
iteration, and column-oriented helper methods. Columns can be selected from
a whitespace-separated string or from an iterable of column names. String
selectors can also contain simple expressions involving table columns, for
example "dx/sqrt(betx)".
Examples
Select a subset of columns:
>>> table.cols["betx bety alfx alfy"]
Select columns together with an expression:
>>> table.cols["betx dx dx/sqrt(betx)"]
Column selections return table objects and can be chained with row
selections:
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).
Creates a Cupy Context object, that allows performing the computations
on nVidia GPUs.
xobjects.settings.cuda_fast_compile controls whether NVRTC fast compile
tuning is enabled. By default it is True, so CUDA kernels built with
NVRTC >= 12.9 use --Ofast-compile=min to reduce compilation time and
memory usage, at the cost of some runtime performance. Set
xobjects.settings.cuda_fast_compile=False, or equivalently the
environment variable XSUITE_CUDA_FAST_COMPILE=0, to disable it.
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.
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)
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 kernelsrc_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 descriptionkernel_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 contextctx.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)
Returns a list of C paths registered in dependent packages.
In a package that depends on xobjects, you can register C source and
library paths using the entry point xobjects.build_info. These paths
will be added to the C include path and the library path when building
kernels. For example, the following will allow to write
#include<xcoll/path/to/some/header.h> in kernel sources, and
allow to use functions from the library xcoll/lib/libFlukaIO.a:
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.
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)
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 kernelsrc_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 descriptionkernel_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 contextctx.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)
Returns a list of C paths registered in dependent packages.
In a package that depends on xobjects, you can register C source and
library paths using the entry point xobjects.build_info. These paths
will be added to the C include path and the library path when building
kernels. For example, the following will allow to write
#include<xcoll/path/to/some/header.h> in kernel sources, and
allow to use functions from the library xcoll/lib/libFlukaIO.a:
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.:
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 kernelsrc_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 descriptionkernel_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 contextctx.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)
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.
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
copy (bool) – If True, a copy of the array is made.
Returns:
Numpy array with the same data, original or a copy.
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
copy (bool) – If True, a copy of the array is made.
Returns:
Numpy array with the same data, original or a copy.
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.
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)
Returns a list of C paths registered in dependent packages.
In a package that depends on xobjects, you can register C source and
library paths using the entry point xobjects.build_info. These paths
will be added to the C include path and the library path when building
kernels. For example, the following will allow to write
#include<xcoll/path/to/some/header.h> in kernel sources, and
allow to use functions from the library xcoll/lib/libFlukaIO.a:
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_loss_refinement are automatically
added to the list.
Refine the location of the lost particles within the line.
Parameters:
particles (xt.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.
with_progress (bool, optional) – Whether to show progress while constructing interpolation lines.
Defaults to True.