Members - short description

Line Editing

Member

Description

append(…)

Append elements to the line.

clone(…)

Create a cloned copy of the line with renamed independent elements.

copy(…)

Return a copy of the line.

cut_​at_​s(…)

Slice the line so that positions in s never fall inside an element.

cycle(…)

Cycle the line to start from a given element.

extend_​knl_​ksl(…)

Extend the order of the knl and ksl attributes of the elements.

extend_​knl_​rel_​ksl_​rel(…)

Extend the order of the knl_​rel and ksl_​rel attributes of the elements.

insert(…)

Insert elements in the line.

mirror(…)

Reverse the order of elements in the line.

remove(…)

Remove an element from the line. If the element is thick, it is replaced by a drift.

replace(…)

Replace an element in the line with another element having the same length.

replace_​all_​repeated_​elements(…)

Replace repeated element occurrences with newly named elements.

replace_​all_​replicas(…)

Replace all replica elements found in the line with clones of their parent elements. Expressions on element attributes are preserved.

replace_​replica(…)

Replace a replica element a clone of its parent element. Expressions on element attributes are preserved.

replicate(…)

Create a replicated copy of the line with renamed elements.

select(…)

Select a part of the line and return it as a new line (shallow copy, i.e. the elements are in common with the original line).

slice_​thick_​elements(…)

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

element_​dict

Dictionary-like container of elements in the line environment.

element_​names

Ordered list of element names defining the line sequence.

element_​refs

Dictionary-like container of xdeps element references.

elements

Tuple-like container of element-object views in line order.

Compose Mode

Member

Description

end_​compose(…)

Resolve compose-mode placements and switch the line back to normal mode.

new(…)

Create a new element and append it to the compose-mode component list.

place(…)

Place an existing object or name in the compose-mode component list.

regenerate_​from_​composer(…)

Re-enter compose mode using the attached composer.

composer

Builder used when the line is in compose mode.

mode

Current line mode.

Inspection, Variables and Configuration

Member

Description

eval(…)

Get the value of an expression

get(…)

Get an element or the value of a variable.

get_​expr(…)

Get expression associated to a variable

get_​length(…)

Get total length of the line

get_​strengths(…)

Return integrated magnet strengths as a table.

get_​table(…)

Return a table with line element information and longitudinal positions.

info(…)

Get information about an element or a variable.

items(…)

Iterate over line elements in sequence.

new_​expr(…)

Create a new xdeps expression object.

set(…)

Set the values or expressions of variables or element properties. A single call can set one or multiple variables or elements.

attr

Line-attribute accessor.

env

Environment to which this line belongs.

functions

xdeps function container used in expressions.

metadata

User metadata associated with the line.

name

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

ref

xdeps reference container for variables and element fields.

ref_​manager

xdeps dependency manager for variables, element references, and expressions.

vars

Variables container associated with the line environment.

Reference Particle and Particle Generation

Member

Description

build_​particles(…)

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

set_​particle_​ref(…)

Set the reference particle of the line. See particle_​ref property.

particle_​ref

Reference particle used by the line for optics and tracking defaults.

Tracking and Analysis

Member

Description

find_​closed_​orbit(…)

Find the closed orbit of the beamline.

get_​R_​matrix(…)

Compute the one turn matrix using finite differences.

get_​T_​matrix(…)

Compute the second order tensor of the beamline.

get_​amplitude_​detuning_​coefficients(…)

Compute the amplitude detuning coefficients (det_​xx = dQx / dJx, det_​yy = dQy / dJy, det_​xy = dQx / dJy, det_​yx = dQy / dJx) using tracking.

get_​footprint(…)

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

get_​line_​with_​second_​order_​maps(…)

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

get_​non_​linear_​chromaticity(…)

Get non-linear chromaticity for given range of delta values

survey(…)

Compute the geometrical layout, i.e. the coordinates of all beam line elements in the global reference system.

track(…)

Track particles through the line.

twiss(…)

Compute the Twiss parameters of the beam line. If no initial conditions are provided, the periodic solution is computed.

twiss4d(…)

Compute the 4D Twiss parameters. Equivalent to twiss with method=’4d’.

twiss6d(…)

Compute the 6D Twiss parameters. Equivalent to twiss with method=’6d’.

dt_​update_​time_​dependent_​vars

Time interval between updates of time-dependent variables.

enable_​time_​dependent_​vars

Flag controlling updates of time-dependent variables during tracking.

energy_​program

Reference energy program to be followed during the simulation.

matrix_​responsiveness_​tol

Responsiveness tolerance used in finite-difference matrix computations.

matrix_​stability_​tol

Stability tolerance used in finite-difference matrix computations.

record_​last_​track

Particle coordinates recorded during the most recent track(...) call.

record_​multi_​element_​last_​track

Particle coordinates recorded for selected elements in the most recent track(...) call.

time_​last_​track

Execution time of the most recent track(...) call.

twiss_​default

Default options used by Twiss-related computations.

Matching and Corrections

Member

Description

correct_​trajectory(…)

Correct the beam trajectory using linearized response matrix from optics table.

match(…)

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

match_​knob(…)

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.

target(…)

Create a target object for line-level matching expressions.

corrector_​limits_​x

Horizontal steering-corrector limits used by trajectory correction.

corrector_​limits_​y

Vertical steering-corrector limits used by trajectory correction.

steering_​correctors_​x

Names of horizontal steering correctors used by trajectory correction.

steering_​correctors_​y

Names of vertical steering correctors used by trajectory correction.

steering_​monitors_​x

Names of horizontal trajectory monitors used by trajectory correction.

steering_​monitors_​y

Names of vertical trajectory monitors used by trajectory correction.

Magnet Model Configuration

Member

Description

configure_​bend_​model(…)

Configure the method used to track bends.

configure_​drift_​model(…)

Configure the method used to track drifts.

configure_​octupole_​model(…)

Configure the model for all octupoles in the line.

configure_​quadrupole_​model(…)

Configure the model for all quadrupoles in the line.

configure_​sextupole_​model(…)

Configure the model for all sextupoles in the line.

Radiation, Spin and Intra-Beam Scattering

Member

Description

compensate_​radiation_​energy_​loss(…)

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

configure_​intrabeam_​scattering(…)

Configures the IBS kick element in the line for tracking.

configure_​radiation(…)

Configure radiation within the line.

configure_​spin(…)

Configure the spin model for the line.

xcoll

Xcoll-specific helpers associated with this line.

Energy & Longitudinal State

Member

Description

freeze_​energy(…)

Freeze energy in tracked Particles objects.

freeze_​longitudinal(…)

Freeze longitudinal coordinates in tracked Particles objects.

Tracker Setup

Member

Description

build_​tracker(…)

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.

discard_​tracker(…)

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

config

Tracking configuration flags and options.

iscollective

Whether the built tracker runs in collective mode.

reset_​s_​at_​end_​turn

Whether longitudinal position s is reset at the end of each turn.

skip_​end_​turn_​actions

Whether end-turn actions are skipped during tracking.

tracker

Tracker associated with this line, if built.

Constructors and Serialization

Member

Description

from_​dict(…)

Create a Line object from a dictionary.

from_​json(…)

Constructs a line from a JSON file.

from_​madx_​sequence(…)

Build a line from a MAD-X sequence.

from_​sequence(…)

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

to_​dict(…)

Returns a dictionary representation of the line.

to_​json(…)

Save the line to a json file.

to_​madng(…)

Build a MAD NG instance from present state of the line.

to_​madx_​sequence(…)

Return a MAD-X sequence corresponding to the line.

Element Internal Logging

Member

Description

start_​internal_​logging_​for_​elements_​of_​type(…)

Start internal logging for all elements of a given type.

stop_​internal_​logging_​for_​all_​elements(…)

Stop internal logging for all elements.

stop_​internal_​logging_​for_​elements_​of_​type(…)

Stop internal logging for all elements of a given type.

Cleanup and Simplification

Member

Description

merge_​consecutive_​drifts(…)

Merge consecutive drifts into a single drift

merge_​consecutive_​multipoles(…)

Merge consecutive multipoles into one multipole.

optimize_​for_​tracking(…)

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

remove_​inactive_​multipoles(…)

Remove inactive multipoles from the line

remove_​markers(…)

Remove markers from the line

remove_​redundant_​apertures(…)

Remove redundant apertures from the line

remove_​zero_​length_​drifts(…)

Remove zero length drifts from the line

use_​simple_​bends(…)

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

use_​simple_​quadrupoles(…)

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

MAD-NG Integration

Member

Description

build_​madng_​model(…)

Build and attach the MAD-NG model associated with this line.

discard_​madng_​model(…)

Discard the attached MAD-NG model for this line.

madng_​survey(…)

Run a survey using the MAD-NG model.

madng_​twiss(…)

Run a Twiss calculation using the MAD-NG model.

regen_​madng_​model(…)

Regenerate the MAD-NG model associated with this line.

Deprecated

Member

Description

append_​element(…)

Append element to the end of the lattice

compute_​R_​matrix(…)

Compute the one turn matrix using finite differences.

compute_​T_​matrix(…)

Compute the second order tensor of the beamline.

compute_​one_​turn_​matrix_​finite_​differences(…)

Deprecated. Compute the one turn matrix using finite differences.

from_​sixinput(…)

Line.from_​sixinput has been removed in favour of sixinput.generate_​xtrack_​line().

get_​elements_​of_​type(…)

Get all elements of given type(s)

get_​s_​elements(…)

Get s position for all elements

get_​s_​position(…)

Get s position for given elements

insert_​element(…)

Insert an element in the line.

to_​pandas(…)

Return a pandas DataFrame with the elements of the line.

unfreeze(…)

Use Line.discard_​tracker() instead.

builder

Deprecated alias for line.composer.

varval

Convenience accessor to variable values.

vv

Short alias for variable values.

Upcoming Deprecations

Member

Description

check_​aperture(…)

Check that all active elements have an associated aperture.

extend(…)

Append existing element names to this line.

filter_​elements(…)

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

freeze_​vars(…)

Freeze variables in tracked Particles objects.

get_​aperture_​table(…)

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.

unfreeze_​vars(…)

Unfreeze variables in tracked Particles objects.

collimators

Deprecated alias for line.xcoll.collimators.

scattering

Deprecated alias for line.xcoll.scattering.

Members - full description

Line Editing

Go to Summary table

Line.append(what, obj=None)

Append elements to the line.

Parameters:
  • 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 placed
env.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 line
line.append(['m1', 's1', 'm2', 's2', 'm3'])
## Appending elements instantiated by the user using the class
## constructor

myoct = xt.Octupole(length=0.1, k3=0.3)
line.append('o1', myoct)
Line.clone(suffix, mirror=False)

Create a cloned copy of the line with renamed independent elements.

Elements are cloned with the new name and expressions on element attributes are preserved.

Parameters:
  • suffix (str) – Suffix appended to each cloned element name.

  • mirror (bool, optional) – If True, the cloned line is mirrored before being returned.

Returns:

New line containing independent element copies.

Return type:

Line

Line.copy(shallow=False, _context=None, _buffer=None)

Return a copy of the line.

Parameters:
  • shallow (bool, optional) – If False (default), a deep copy is returned. If True, a shallow copy is returned, i.e. the line is plced 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

Returns:

line_copy – Copy of the line.

Return type:

Line

Line.cut_at_s(s: Iterable[float], s_tol=1e-06, return_slices=False)

Slice the line so that positions in s never fall inside an element.

Line.cycle(index_first_element=None, name_first_element=None, inplace=True)

Cycle the line to start from a given element.

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

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

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

Returns:

new_line – A new line with the elements cycled.

Return type:

Line

Line.extend_knl_ksl(order, element_names=None)

Extend the order of the knl and ksl attributes of the elements.

Parameters:
  • order (int) – New order of the knl and ksl attributes.

  • element_names (list of str) – Names of the elements to extend. If None, all elements having knl and ksl attributes are extended.

Line.extend_knl_rel_ksl_rel(order, element_names=None)

Extend the order of the knl_rel and ksl_rel attributes of the elements.

Parameters:
  • order (int) – New order of the knl_rel and ksl_rel attributes.

  • element_names (list of str) – Names of the elements to extend. If None, all elements having knl_rel and ksl_rel attributes are extended.

Line.insert(what, obj=None, at=None, from_=None, anchor=None, from_anchor=None, s_tol=1e-10)

Insert elements in the line.

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’.

Example

## Insertion of elements from the environment

# Create a set of new elements to be placed
env.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 line
line.insert([
    env.place('s1', at=5.),
    env.place('s2', anchor='end', at=-5., from_='start@q1'),
    env.place(['m1', 'm2'], at='start@m0'),
    env.place('m3', at='end@m0'),
    ])
## Insertion of elements instantiated by the user using the class
## constructor

# Instantiate elements using the
mysext =  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('s1', mysext, at=5., from_='q1')

# Alternatively, add the element to the environment and then do the insertion:
env.elements['ap1'] = myaperture
line.insert('ap1', at='start@q0')
Line.mirror(inplace=True)

Reverse the order of elements in the line.

Parameters:

inplace (bool, optional) – If True (default), the line is modified in place. If False, a mirrored shallow copy is returned. Default is True.

Returns:

Mirrored line when inplace=False, otherwise None.

Return type:

Line or None

Line.remove(name, s_tol=1e-10)

Remove an element from the line. If the element is thick, it is replaced by a drift.

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

  • s_tol (float (optional)) – If the element is shorter than s_tol, it is removed without creating a replacement drift. Default is 1e-10.

Line.replace(name, new_name, s_tol=1e-10)

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.error is raised. Default is 1e-10.

Line.replace_all_repeated_elements(separator='.', mode='clone', replace_generated_drifts=False)

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.

Returns:

This method modifies the line in place.

Return type:

None

Line.replace_all_replicas()

Replace all replica elements found in the line with clones of their parent elements. Expressions on element attributes are preserved.

Parameters:

None

Returns:

This method modifies the line and its environment in place.

Return type:

None

Line.replace_replica(name)

Replace a replica element a clone of its parent element. Expressions on element attributes are preserved.

Parameters:

name (str) – Name of the replica element to replace.

Returns:

This method modifies the line environment in place.

Return type:

None

Line.replicate(suffix, mirror=False)

Create a replicated copy of the line with renamed elements.

Elements that are not autogenerated drifts are added to the environment as xt.Replica objects pointing to the original elements.

Parameters:
  • suffix (str) – Suffix appended to each element name in the replicated line.

  • mirror (bool, optional) – If True, the replicated line is mirrored before being returned.

Returns:

New line containing xt.Replica references to the original elements (except shared drift entries).

Return type:

Line

Line.select(start=None, end=None, name=None)

Select a part of the line and return it as a new line (shallow copy, i.e. the elements are in common with the original line).

Parameters:
  • start (str) – Name of the starting point

  • end (str) – Name of the ending point

  • name (str) – Name of the new line (default: None)

Returns:

out – New line containing the selected portion.

Return type:

Line

Line.slice_thick_elements(slicing_strategies)

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

Parameters:

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

Examples

line.slice_thick_elements(
    slicing_strategies=[
        # Slicing with thin elements
        xt.Strategy(slicing=xt.Teapot(1)), # (1) Default applied to all elements
        xt.Strategy(slicing=xt.Uniform(2), element_type=xt.Bend), # (2) Selection by element type
        xt.Strategy(slicing=xt.Teapot(3), element_type=xt.Quadrupole),  # (4) Selection by element type
        xt.Strategy(slicing=xt.Teapot(4), name='mb1.*'), # (5) Selection by name pattern
        # Slicing with thick elements
        xt.Strategy(slicing=xt.Uniform(2, mode='thick'), name='mqf.*'), # (6) Selection by name pattern
        # Do not slice (leave untouched)
        xt.Strategy(slicing=None, name='mqd.1') # (7) Selection by name
])
property Line.element_dict

Dictionary-like container of elements in the line environment.

property Line.element_names

Ordered list of element names defining the line sequence.

property Line.element_refs

Dictionary-like container of xdeps element references.

property Line.elements

Tuple-like container of element-object views in line order.

Compose Mode

Go to Summary table

Line.end_compose()

Resolve compose-mode placements and switch the line back to normal mode.

Parameters:

None

Returns:

This method updates the line in place.

Return type:

None

Line.new(*args, **kwargs)

Create a new element and append it to the compose-mode component list.

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

  • cls (str or class) – Element type (or parent element name when cloning/replicating).

  • at (float or str, optional) – Position at which the created element is placed.

  • from (str, optional) – Name of the reference element used to define the placement position.

  • extra (dict, optional) – Extra metadata associated with the created element.

  • force (bool, optional) – If True, allow replacing an existing element with the same name.

  • **kwargs – Element attributes forwarded to Environment.new(...).

Returns:

Name of the created element, or a Place object when placement arguments are provided.

Return type:

str or Place

Line.place(*args, **kwargs)

Place an existing object or name in the compose-mode component list.

Parameters:
  • name (str) – Name assigned to the placed component.

  • obj (object, optional) – Existing object to place. If omitted, name is resolved in the environment.

  • at (float or str, optional) – Placement position.

  • from (str, optional) – Reference element used to define the placement position.

  • anchor (str, optional) – Anchor on the placed object used for positioning.

  • from_anchor (str, optional) – Anchor on the reference element used for positioning.

Returns:

The placed component descriptor appended to the composer.

Return type:

Place

Line.regenerate_from_composer()

Re-enter compose mode using the attached composer.

Any modification done in normal mode is lost.

Parameters:

None

Returns:

This method switches the line state in place.

Return type:

None

property Line.composer

Builder used when the line is in compose mode.

property Line.mode

Current line mode.

Returns:

'normal' or 'compose'.

Return type:

str

Inspection, Variables and Configuration

Go to Summary table

Line.eval(expr)

Get the value of an expression

Parameters:

expr (str) – Expression to evaluate.

Returns:

value – Value of the expression.

Return type:

float

Line.get(key)

Get an element or the value of a variable.

Parameters:

key (str) – Name of the element or variable.

Returns:

element – Element or value of the variable.

Return type:

Element or float

Line.get_expr(var)

Get expression associated to a variable

Parameters:

var (str) – Name of the variable

Returns:

expr – Expression associated to the variable

Return type:

Expression

Line.get_length() float

Get total length of the line

Line.get_strengths(reverse=None)

Return integrated magnet strengths as a table.

Parameters:

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.

Return type:

xtrack.Table

Examples

>>> env = xt.Environment()
>>> line = env.new_line(length=10, components=[
...    env.new('qf', 'Quadrupole', length=1., k1=2., at=2.5),
...    env.new('qd', 'Quadrupole', length=1., k1=-2., at=7.5)])
>>> line.get_strengths()
Table: 6 rows, 20 cols
name                   k0l           k1l           k2l           k3l ...
||drift_1::0             0             0             0             0
qf                       0             2             0             0
||drift_2                0             0             0             0
qd                       0            -2             0             0
||drift_1::1             0             0             0             0
_end_point               0             0             0             0
Line.get_table(attr=False)

Return a table with line element information and longitudinal positions.

Parameters:

attr (bool, optional) – If True, include element attribute columns from line.attr.

Returns:

table – Table containing one row per element plus the '_end_point' row.

Return type:

LineTable

Examples

>>> env = xt.Environment()
>>> line = env.new_line(length=10, components=[
...    env.new('qf', 'Quadrupole', at=2.5),
...    env.new('qd', 'Quadrupole', at=7.5)])
>>> line.get_table().cols['s_start s_center s_end']
Table: 6 rows, 4 cols
name               s_start      s_center         s_end
||drift_1::0             0          1.25           2.5
qf                     2.5           2.5           2.5
||drift_2              2.5             5           7.5
qd                     7.5           7.5           7.5
||drift_1::1           7.5          8.75            10
_end_point              10            10            10
Line.info(key, limit=30)

Get information about an element or a variable.

Parameters:
  • key (str) – Name of the element or variable.

  • limit (int, optional) – Maximum number of expression terms shown for variable info.

Returns:

This method displays information and does not return a value.

Return type:

None

Line.items()

Iterate over line elements in sequence.

Parameters:

None

Yields:
  • name (str) – Element name in line order.

  • element_view (View) – Element view associated with name.

Line.new_expr(var)

Create a new xdeps expression object.

Parameters:

expr (str) – Expression to create.

Returns:

expr – New xdeps expression object.

Return type:

Expression

Line.set(name, *args, **kwargs)

Set the values or expressions of variables or element properties. A single call can set one or multiple variables or elements.

Parameters:
  • name (str or iterable of str) – Name or names of the variable(s) or element(s).

  • value (float or str) – Value or expression of the variable to set. Can be provided only if the name is associated to a variable.

  • **kwargs – Attributes to set. Can be provided only if the name is associated to an element.

  • str (float or) – Attributes to set. Can be provided only if the name is associated to an element.

Examples

>>> line.set('a', 0.1)
>>> line.set('k1', '3*a')
>>> line.set('quad', k1=0.1, k2='3*a')
>>> line.set(['quad1', 'quad2'], k1=0.1, k2='3*a')
>>> line.set(['c', 'd'], 0.1)
>>> line.set(['e', 'f'], '3*a')
property Line.attr

Line-attribute accessor.

Examples

>>> env = xt.Environment()
>>> line = env.new_line(length=10, components=[
...    env.new('qf', 'Quadrupole', length=1., k1=2., at=2.5),
...    env.new('qd', 'Quadrupole', length=1., k1=-2., at=7.5)])
>>> line.attr['k1l']
array([ 0.,  2.,  0., -2.,  0.])
>>> line.attr['length']
array([2., 1., 4., 1., 2.])
property Line.env

Environment to which this line belongs.

property Line.functions

xdeps function container used in expressions.

Returns:

functions – Dictionary-like container of functions available in expressions.

Return type:

object

property Line.metadata

User metadata associated with the line.

property Line.name

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

property Line.ref

xdeps reference container for variables and element fields.

Returns:

ref – Dictionary-like container of references used in expressions.

Return type:

object

Examples

>>> env = xt.Environment()
>>> env['a'] = 3
>>> line = env.new_line(length=10, components=[
...     env.new('qf', 'Quadrupole', length=1, k1='2*a', at=2.5),
...     env.new('qd', 'Quadrupole', length=1, k1='-2*a', at=7.5)])
>>> line.ref['a']._info()
#  vars['a']._get_value()
   vars['a'] = 3
#
#  vars['a']._expr is None
#
#  vars['a']._find_dependant_targets()
   element_refs['qd'].k1
   element_refs['qf'].k1
>>> line.ref['qd'].k1._info()
#  element_refs['qd'].k1._get_value()
   element_refs['qd'].k1 = -6.0
#
#  element_refs['qd'].k1._expr
   element_refs['qd'].k1 = (-2.0 * vars['a'])
#
#  element_refs['qd'].k1._expr._get_dependencies()
   vars['a'] = 3
#
#  element_refs['qd'].k1 does not influence any target
>>> line.ref['qd'].k1._expr
(-2.0 * vars['a'])
>>> env['b'] = line.functions.sqrt(line.ref['a'])
>>> env.ref['b']._info()
#  vars['b']._get_value()
   vars['b'] = 1.7320508075688772
#
#  vars['b']._expr
   vars['b'] = f.sqrt(vars['a'])
#
#  vars['b']._expr._get_dependencies()
   vars['a'] = 3
   f.sqrt = <built-in function sqrt>
#
#  vars['b'] does not influence any target
property Line.ref_manager

xdeps dependency manager for variables, element references, and expressions.

Returns:

ref_manager – Dependency manager used to register and update expression tasks.

Return type:

object

property Line.vars

Variables container associated with the line environment.

The container provides variable-management utilities such as keys(), get_table(), load() (JSON and MAD-X files), remove(), rename(), and update().

Returns:

vars – Dictionary-like container of variables.

Return type:

object

Reference Particle and Particle Generation

Go to Summary table

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

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

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

Return type:

Particles object

Line.set_particle_ref(*args, **kwargs)

Set the reference particle of the line. See particle_ref property.

property Line.particle_ref

Reference particle used by the line for optics and tracking defaults.

Returns:

particle_ref – Reference particle, if set.

Return type:

xtrack.Particles or None

Tracking and Analysis

Go to Summary table

Line.find_closed_orbit(co_guess=None, particle_ref=None, co_search_settings={}, delta0=None, zeta0=None, zeta_shift=0, continue_on_closed_orbit_error=False, freeze_longitudinal=False, start=None, end=None, num_turns=1, co_search_at=None, search_for_t_rev=False, spin=None, num_turns_search_t_rev=None, symmetrize=False, include_collective=False)

Find the closed orbit of the beamline.

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

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

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

  • delta_zeta (float) – Initial delta_zeta coordinate.

  • delta0 (float) – Initial delta coordinate.

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

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

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

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

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

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

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

Returns:

particle_on_co – Particle at the closed orbit.

Return type:

Particle

Line.get_R_matrix(particle_on_co, steps=None, start=None, end=None, num_turns=1, element_by_element=False, only_markers=False, symmetrize=False, include_collective=False, steps_r_matrix=None)

Compute the one turn matrix using finite differences.

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

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

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

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

Returns:

one_turn_matrix – One turn matrix.

Return type:

np.ndarray

Line.get_T_matrix(start=None, end=None, particle_on_co=None, steps=None, steps_t_matrix=None)

Compute the second order tensor of the beamline.

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

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

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

  • steps (dict) – Finite difference step for computing the second order tensor.

Returns:

T_matrix – Second order tensor of the beamline.

Return type:

ndarray

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

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

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

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

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

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

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

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

Returns:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • linear_rescale_on_knobs (list of xt.LinearRescale) –

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

    ``line.get_footprint(…, linear_rescale_on_knobs=[

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

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

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

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

Returns:

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

Return type:

Footprint

Line.get_line_with_second_order_maps(split_at)

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

Parameters:

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

Returns:

line_maps – Line with segments replaced by second order maps.

Return type:

Line

Line.get_non_linear_chromaticity(delta0_range=(-0.001, 0.001), num_delta=5, fit_order=3, **kwargs)

Get non-linear chromaticity for given range of delta values

Parameters:
  • delta0_range (tuple of float) – Range of delta values for chromaticity computation.

  • num_delta (int) – Number of delta values for chromaticity computation.

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

Returns:

chromaticity – Table containing the non-linear chromaticity information.

Return type:

Table

Line.survey(X0=0, Y0=0, Z0=0, theta0=0, phi0=0, psi0=0, element0=0, reverse=None)

Compute the geometrical layout, i.e. the coordinates of all beam line elements in the global reference system.

For detailed definitions of the involved quantities please refer to the Xsuite Physics Guide (https://xsuite.readthedocs.io/en/latest/physicsguide.html)

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

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

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

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

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

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

  • element0 (int or str) – Element at which the given coordinates are defined. Default is the first element in the beam line.

Returns:

survey – Survey table.

Return type:

SurveyTable

Notes

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

import xtrack as xt

# Create a simple line
env = 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 survey
sv = 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 mm
tw = 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 frame
p_global = tw.x[:, None] * sv.ex + tw.y[:, None] * sv.ey + sv.XYZ

X_trajectory = p_global[:, 0]
Y_trajectory = p_global[:, 1]
Z_trajectory = p_global[:, 2]
Line.track(particles, ele_start=0, ele_stop=None, num_elements=None, num_turns=None, turn_by_turn_monitor=None, multi_element_monitor_at=None, freeze_longitudinal=False, time=False, with_progress=False, **kwargs)

Track particles through the line.

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

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

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

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

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

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

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

  • 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.

Line.twiss(particle_ref=None, method=None, particle_on_co=None, R_matrix=None, W_matrix=None, delta0=None, zeta0=None, zeta_shift=None, nemitt_x=None, nemitt_y=None, step_W_sigma=None, delta_disp=None, delta_chrom=None, zeta_disp=None, co_guess=None, steps_R_matrix=None, co_search_settings=None, continue_on_closed_orbit_error=None, values_at_element_exit=None, radiation_method=None, radiation_integrals=None, radiation_analysis=None, start=None, end=None, init=None, num_turns=None, skip_global_quantities=None, matrix_responsiveness_tol=None, matrix_stability_tol=None, symplectify=None, reverse=None, use_full_inverse=None, strengths=None, hide_thin_groups=None, search_for_t_rev=None, num_turns_search_t_rev=None, only_twiss_init=None, only_markers=None, only_orbit=None, spin=None, polarization_analysis=None, compute_R_element_by_element=None, compute_lattice_functions=None, chrom=None, coupling_edw_teng=False, init_at=None, x=None, px=None, y=None, py=None, zeta=None, delta=None, betx=None, alfx=None, bety=None, alfy=None, bets=None, dx=None, dpx=None, dy=None, dpy=None, dzeta=None, mux=None, muy=None, muzeta=None, ax_chrom=None, bx_chrom=None, ay_chrom=None, by_chrom=None, ddx=None, ddpx=None, ddy=None, ddpy=None, spin_x=None, spin_y=None, spin_z=None, zero_at=None, co_search_at=None, include_collective=None, disable_apertures=None, _continue_if_lost=None, _keep_tracking_data=None, _keep_initial_particles=None, _initial_particles=None, _ebe_monitor=None, ele_start='__discontinued__', ele_stop='__discontinued__', ele_init='__discontinued__', twiss_init='__discontinued__', compute_chromatic_properties=None, at_s=None, at_elements=None, r_sigma=None, freeze_longitudinal=None, freeze_energy=None, polarization=None, eneloss_and_damping=None, steps_r_matrix=None)

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.

  • 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.

Returns:

twiss

Return type:

xtrack.TwissTable

Notes

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 (ebe)

  • dx, dpx, dy, dpy: dispersion functions (ebe)

  • ddx, ddpx, ddy, ddpy: second-order dispersion functions (ebe)

  • dx_zeta, dpx_zeta, dy_zeta, dpy_zeta: crab dispersion functions (ebe)

  • bets0: longitudinal beta function at start ring.

  • W_matrix: linear normal-form matrix. (ebe)

  • kin_px, kin_py, kin_ps: kinetic momenta (different from px, py which are canonical momenta). (ebe)

  • kin_xp, kin_yp: transverse slopes kin_px/kin_ps, kin_py/kin_ps. (ebe)

  • mux, muy, muzeta: phase advances in units of 2 pi. (ebe)

  • nux, nuy, nuzeta: damping exponents. (ebe)

  • betx1, bety1, betx2, bety2, alfx1, alfy1, alfx2, alfy2, gamx1, gamy1, gamx2, gamy2: Mais-Ripken coupled optics functions (ebe)

  • wx_chrom, wy_chrom, bx_chrom, by_chrom, ax_chrom, ay_chrom: chromatic functions, see physics guide for definitions (ebe)

  • particle_on_co: particle on closed orbit or reference trajecory, placed at the first element in the selected range.

  • reference_frame: reference frame used for the output (can be proper or reversed)

  • periodic: True if periodic twiss, False if open twiss

  • method: method used for the computation (4d or 6d)

Output fields present only for periodic twiss:
  • qx, qy: transverse tunes

  • qs: synchrotron tune (present only when method is 6d)

  • dqx, dqy: linear chromaticities

  • ddqx, ddqy: second-order chromaticities

  • line_length: length of the beam line

  • p0c, gamma0, beta0: reference momentum and relativistic factors

  • t_rev0: reference revolution period

  • slip_factor: slip factor, i.e. eta = -(dfrev / frev) / ddelta

  • momentum_compaction_factor: momentum compaction factor (d C / C) / ddelta where C the closed orbit path length

  • slip_factor_dzeta_ddelta: d (zeta) / ddelta

  • bets0: longitudinal beta function at start of the ring.

  • c_minus, c_minus_re_0, c_minus_im_0: closest tune approach coefficient (absolute, real and imaginary parts). See physics guide for definitions.

  • c_minus_re, c_minus_im, c_r1, c_r2, c_phi1, c_phi2: element-by-element coupling coefficients. See physics guide for definitions. (ebe)

  • R_matrix: one-turn transfer matrix

  • steps_R_matrix: steps used for the finite-difference computation of the R matrix

  • R_matrix_ebe: element-by-element transfer matrices, from the start of the line to the selected element. (ebe)

  • eigenvalues, rotation_matrix: additional linear-normal-form data

  • dmux, dmuy: phase-advance derivatives vs delta

  • dzeta: longitudinal dispersion vs delta

Output fields present when strengths=True (or radiation_integrals=True):
  • k0lk5l, k0slk5sl: normal/skew multipole integrated strengths

  • angle, rot_s_rad, hkick, vkick, ks, bs, length, element_type, isthick, parent_name, prototype: element properties

Output fields present when radiation_analysis=True:
  • energy_loss: energy loss per turn [eV]

  • damping_constants_turns, damping_constants_s: damping constants in 1/turn or 1/s.

  • partition_numbers: radiation partition numbers

  • eq_gemitt_x, eq_gemitt_y, eq_gemitt_zeta: equilibrium geometric emittances.

  • eq_nemitt_x, eq_nemitt_y, eq_nemitt_zeta: equilibrium normalized emittances.

Output fields present when radiation_integrals=True:
  • rad_int_i1x, rad_int_i1y, rad_int_i2, rad_int_i3, rad_int_i4, rad_int_i4x, rad_int_i4y, rad_int_i5x, rad_int_i5y: radiation integrals (see physics guide for definitions)

  • rad_int_i1x_integrand, rad_int_i1y_integrand, rad_int_l2_integrand, rad_int_i3_integrand, rad_int_i4_integrand, rad_int_i4x_integrand, rad_int_i4y_integrand, rad_int_i5x_integrand, rad_int_i5y_integrand: integrands of the radiation integrals (ebe)

  • rad_int_curly_hx, rad_int_curly_hy: curly-H functions (see physics guide for definitions) (ebe)

  • rad_int_eq_gemitt_x, rad_int_eq_gemitt_y: geometric equilibrium emittances from radiation integrals.

  • rad_int_damping_constant_x_s, rad_int_damping_constant_y_s, rad_int_damping_constant_zeta_s: damping constants from radiation integrals

  • rad_int_kappa0_x, rad_int_kappa0_y, rad_int_kappa0: reference curvature used in the computation (ebe)

  • rad_int_kappa_x, rad_int_kappa_y, rad_int_kappa: closed orbit curvature used in the computation (ebe)

  • rad_int_iv_x, rad_int_iv_y, rad_int_iv_z: velocity direction cosines (ebe)

Output fields present when spin=True:
  • spin_x, spin_y, spin_z: spin components of the closed spin solution (n0) for periodic twiss, or propagated spin components for open twiss. (ebe)

Output fields present when polarization_analysis=True:
  • spin_tune_fractional: fractional spin tune

  • spin_polarization_eq: equilibrium polarization in the linear approximation

  • spin_polarization_inf_no_depol: infinite-time polarization without depolarization effects

  • spin_t_pol_buildup_s: polarization buildup time in seconds

  • spin_t_pol_component_s: polarization component of the buildup time in seconds

  • spin_t_depol_component_s: depolarization component of the buildup time in seconds

  • spin_n_matrix: invariant spin field matrix in local frame (ebe)

  • spin_eigenvectors: eigenvectors of the spin one-turn matrix (ebe)

  • spin_dn_ddelta_x, spin_dn_ddelta_y, spin_dn_ddelta_z: derivatives of the invariant spin field w.r.t. delta (ebe)

  • spin_n0_iv, spin_n0_ib: projections of equilibrium spin along the closed orbit velocity and magnetic field directions (ebe)

  • spin_int_kappa3_n0_ib, spin_int_kappa3_dn_ddelta_ib, spin_int_kappa3_11_18_dn_ddelta_sq: integrals involved in polarization computations

Output fields present when coupling_edw_teng=True:
  • r11_edw_teng, r12_edw_teng, r21_edw_teng, r22_edw_teng: Elements of the Edwards-Teng coupling matrix (ebe)

Output fields present when search_for_t_rev=True:
  • t_rev: measured revolution period [s]

Line.twiss4d(**kwargs)

Compute the 4D Twiss parameters. Equivalent to twiss with method=’4d’.

See Line.twiss method documentation for all available options.

Line.twiss6d(**kwargs)

Compute the 6D Twiss parameters. Equivalent to twiss with method=’6d’.

See Line.twiss method documentation for all available options.

property Line.dt_update_time_dependent_vars

Time interval between updates of time-dependent variables.

Returns:

dt – Update interval in seconds.

Return type:

float

property Line.enable_time_dependent_vars

Flag controlling updates of time-dependent variables during tracking.

Returns:

enabledTrue to enable time-dependent variable updates, False otherwise.

Return type:

bool

property Line.energy_program

Reference energy program to be followed during the simulation.

Returns:

energy_program – Attached energy program, or None if not set.

Return type:

EnergyProgram or None

property Line.matrix_responsiveness_tol

Responsiveness tolerance used in finite-difference matrix computations.

Returns:

tol – Responsiveness tolerance.

Return type:

float

property Line.matrix_stability_tol

Stability tolerance used in finite-difference matrix computations.

Returns:

tol – Stability tolerance.

Return type:

float

property Line.record_last_track

Particle coordinates recorded during the most recent track(...) call.

Returns:

record – Track record object from the last call to track(...).

Return type:

object

property Line.record_multi_element_last_track

Particle coordinates recorded for selected elements in the most recent track(...) call.

Returns:

record – Multi-element track record object from the last call to track(...).

Return type:

object

property Line.time_last_track

Execution time of the most recent track(...) call.

Returns:

dt – Elapsed tracking time in seconds.

Return type:

float

property Line.twiss_default

Default options used by Twiss-related computations.

Returns:

twiss_default – Dictionary of default keyword values used by Twiss methods.

Return type:

dict

Matching and Corrections

Go to Summary table

Line.correct_trajectory(run=True, n_iter='auto', start=None, end=None, twiss_table=None, planes=None, monitor_names_x=None, corrector_names_x=None, monitor_names_y=None, corrector_names_y=None, n_micado=None, n_singular_values=None, rcond=None, monitor_alignment=None, corrector_limits_x=None, corrector_limits_y=None)

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.

Returns:

correction – Trajectory correction object.

Return type:

TrajectoryCorrection

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

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

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

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

  • solve (bool) – If True (default), the matching is performed immediately. If not an Optimize object is 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.

Return type:

xdeps.Optimize

Examples

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

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

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

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

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

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

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

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

Line.target(tar, value, **kwargs)

Create a target object for line-level matching expressions.

Parameters:
  • tar (callable) – Target expression evaluated on the line action, for example lambda ll: ll['qf'].k1.

  • value (object) – Desired target value or constraint object (for example xt.GreaterThan(...) / xt.LessThan(...)).

  • **kwargs – Additional keyword arguments forwarded to xt.Target (for example weighting or tolerance options).

Returns:

target – Target object to be passed to matching routines such as line.match.

Return type:

xt.Target

Examples

>>> env = xt.Environment()
>>> env['kqf'] = 0.1
>>> line = env.new_line(components=[
...     env.new('qf', 'Quadrupole', length=1.0, k1='kqf')])
>>> opt = line.match(
...     solve=False,
...     vary=xt.Vary('kqf', step=1e-8, limits=[-1, 1]),
...     targets=[
...         line.target(lambda ll: ll['qf'].k1, xt.GreaterThan(0.0)),
...     ])
property Line.corrector_limits_x

Horizontal steering-corrector limits used by trajectory correction.

Returns:

limits – Lower and upper limits for horizontal steering correctors, or None if no limits are set.

Return type:

tuple of 2 floats or None

property Line.corrector_limits_y

Vertical steering-corrector limits used by trajectory correction.

Returns:

limits – Lower and upper limits for vertical steering correctors, or None if no limits are set.

Return type:

tuple of 2 floats or None

property Line.steering_correctors_x

Names of horizontal steering correctors used by trajectory correction.

Any element with knl/ksl can be used as a corrector.

Returns:

names – Horizontal steering-corrector names, or None if not configured.

Return type:

list of str or None

property Line.steering_correctors_y

Names of vertical steering correctors used by trajectory correction.

Any element with knl/ksl can be used as a corrector.

Returns:

names – Vertical steering-corrector names, or None if not configured.

Return type:

list of str or None

property Line.steering_monitors_x

Names of horizontal trajectory monitors used by trajectory correction.

Any element can be used as a monitor.

Returns:

names – Horizontal monitor names, or None if not configured.

Return type:

list of str or None

property Line.steering_monitors_y

Names of vertical trajectory monitors used by trajectory correction.

Any element can be used as a monitor.

Returns:

names – Vertical monitor names, or None if not configured.

Return type:

list of str or None

Magnet Model Configuration

Go to Summary table

Line.configure_bend_model(core=None, edge=None, num_multipole_kicks=None, integrator=None)

Configure the method used to track bends.

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’.

Line.configure_drift_model(model=None)

Configure the method used to track drifts.

See documentation of xt.Drift for more details on the values of the models used below.

Parameters:

model (str) – Model to be used for the drifts. Can be ‘adaptive’, ‘exact’ or ‘expanded’.

Line.configure_octupole_model(model: Optional[str] = None, edge: Optional[Literal['full']] = None, num_multipole_kicks: Optional[int] = None, integrator: Optional[str] = None)

Configure the model for all octupoles in the line.

Parameters:
  • model (str, optional) – Magnet model to assign to all octupole elements.

  • edge ({'full', None}, optional) – Edge-fringe configuration. Use 'full' to enable fringes and None to leave edge settings unchanged.

  • num_multipole_kicks (int, optional) – Number of multipole kicks to assign to octupole elements.

  • integrator (str, optional) – Integrator to assign to octupole elements.

Returns:

This method modifies matching elements in place.

Return type:

None

Line.configure_quadrupole_model(model: Optional[str] = None, edge: Optional[Literal['full']] = None, num_multipole_kicks: Optional[int] = None, integrator: Optional[str] = None)

Configure the model for all quadrupoles in the line.

Parameters:
  • model (str, optional) – Magnet model to assign to all quadrupole elements.

  • edge ({'full', None}, optional) – Edge-fringe configuration. Use 'full' to enable fringes and None to leave edge settings unchanged.

  • num_multipole_kicks (int, optional) – Number of multipole kicks to assign to quadrupole elements.

  • integrator (str, optional) – Integrator to assign to quadrupole elements.

Returns:

This method modifies matching elements in place.

Return type:

None

Line.configure_sextupole_model(model: Optional[str] = None, edge: Optional[Literal['full']] = None, num_multipole_kicks: Optional[int] = None, integrator: Optional[str] = None)

Configure the model for all sextupoles in the line.

Parameters:
  • model (str, optional) – Magnet model to assign to all sextupole elements.

  • edge ({'full', None}, optional) – Edge-fringe configuration. Use 'full' to enable fringes and None to leave edge settings unchanged.

  • num_multipole_kicks (int, optional) – Number of multipole kicks to assign to sextupole elements.

  • integrator (str, optional) – Integrator to assign to sextupole elements.

Returns:

This method modifies matching elements in place.

Return type:

None

Radiation, Spin and Intra-Beam Scattering

Go to Summary table

Line.compensate_radiation_energy_loss(delta0='zero_mean', rtol_eneloss=1e-10, max_iter=100, **kwargs)

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

Parameters:
  • delta0 (float) – Initial energy deviation. 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.

Line.configure_intrabeam_scattering(element=None, update_every: int = None, **kwargs) None

Configures the IBS kick element in the line for tracking.

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:
  • line (xtrack.Line) – The line in which the IBS kick element was inserted.

  • 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.

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

Configure radiation within the line.

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

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

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

Line.configure_spin(spin_model: Literal[True, False, None, 'auto'] = None)

Configure the spin model for the line.

Parameters:

spin_model (str) – Spin model to use. Can be None, ‘auto’, True, False.

property Line.xcoll

Xcoll-specific helpers associated with this line.

Energy & Longitudinal State

Go to Summary table

Line.freeze_energy(state=True, force=False)

Freeze energy in tracked Particles objects.

Parameters:

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

Line.freeze_longitudinal(state=True)

Freeze longitudinal coordinates in tracked Particles objects.

Parameters:

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

Tracker Setup

Go to Summary table

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

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

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

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

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

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

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

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

Examples

## Choose a context
context = 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 GPUs

line.build_tracker(_context=context)
Line.discard_tracker()

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

property Line.config

Tracking configuration flags and options.

property Line.iscollective

Whether the built tracker runs in collective mode.

Returns:

iscollectiveTrue if the tracker is collective, False otherwise.

Return type:

bool

property Line.reset_s_at_end_turn

Whether longitudinal position s is reset at the end of each turn.

Default is True.

Returns:

resetTrue to reset s at end turn, False to keep cumulative s.

Return type:

bool

property Line.skip_end_turn_actions

Whether end-turn actions are skipped during tracking.

Default is False.

Returns:

skipTrue to skip end-turn actions, False to execute them.

Return type:

bool

property Line.tracker

Tracker associated with this line, if built.

Constructors and Serialization

Go to Summary table

classmethod Line.from_dict(dct, _context=None, _buffer=None, classes=(), verbose=True, _env=None)

Create a Line object from a dictionary.

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

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

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

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

Returns:

line – Line object.

Return type:

Line

classmethod Line.from_json(file, **kwargs)

Constructs a line from a JSON file.

Parameters:
  • file (str or file-like object) – Path to the JSON file or file-like object. If filename ends with ‘.gz’ file is decompressed.

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

Returns:

line – Line object.

Return type:

Line

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

Build a line from a MAD-X sequence.

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

  • deferred_expressions (bool, optional) – If true, deferred expressions from MAD-X are imported.

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

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

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

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

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

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

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

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

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

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

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

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

  • enable_layout_data (bool, optional) – If true, the layout data is imported.

Returns:

line – Line object.

Return type:

Line

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

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

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

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

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

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

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

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

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

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

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

Returns:

line – Line object.

Return type:

Line

Examples

Line.to_dict(include_var_management=True, include_element_dict=True, include_version=False)

Returns a dictionary representation of the line.

Parameters:

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

Returns:

out – Dictionary representation of the line.

Return type:

dict

Line.to_json(file, indent=1, **kwargs)

Save the line to a json file.

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

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

Line.to_madng(sequence_name='seq', temp_fname=None, keep_files=False, **kwargs)

Build a MAD NG instance from present state of the line.

Parameters:
  • sequence_name (str) – Name of the sequence.

  • temp_fname (str) – Name of the temporary file to be used for the MAD NG instance.

Returns:

mng – MAD NG instance.

Return type:

MAD

Line.to_madx_sequence(sequence_name, mode='sequence')

Return a MAD-X sequence corresponding to the line.

Parameters:

sequence_name (str) – Name of the sequence.

Returns:

madx_sequence – MAD-X sequence.

Return type:

str

Element Internal Logging

Go to Summary table

Line.start_internal_logging_for_elements_of_type(element_type, capacity)

Start internal logging for all elements of a given type.

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

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

Returns:

record – Record object containing the elements internal logging.

Return type:

Record

Line.stop_internal_logging_for_all_elements(reinitialize_io_buffer=False)

Stop internal logging for all elements.

Parameters:

reinitialize_io_buffer (bool) – If True, the IO buffer is reinitialized (default: False).

Line.stop_internal_logging_for_elements_of_type(element_type)

Stop internal logging for all elements of a given type.

Parameters:

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

Cleanup and Simplification

Go to Summary table

Line.merge_consecutive_drifts(inplace=True, keep=None)

Merge consecutive drifts into a single drift

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

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

Returns:

line – Line with consecutive drifts merged

Return type:

Line

Line.merge_consecutive_multipoles(inplace=True, keep=None)

Merge consecutive multipoles into one multipole.

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

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

Returns:

line – The modified line.

Return type:

Line

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

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

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

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

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

Line.remove_inactive_multipoles(inplace=True, keep=None)

Remove inactive multipoles from the line

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

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

Returns:

line – Line with inactive multipoles removed

Return type:

Line

Line.remove_markers(inplace=True, keep=None)

Remove markers from the line

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

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

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

Remove redundant apertures from the line

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

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

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

Returns:

line – Line with redundant apertures removed

Return type:

Line

Line.remove_zero_length_drifts(inplace=True, keep=None)

Remove zero length drifts from the line

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

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

Returns:

line – Line with zero length drifts removed

Return type:

Line

Line.use_simple_bends()

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

Line.use_simple_quadrupoles()

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

MAD-NG Integration

Go to Summary table

Line.build_madng_model(sequence_name='seq', **kwargs)

Build and attach the MAD-NG model associated with this line.

Parameters:
  • sequence_name (str, optional) – Name of the MAD-NG sequence to be created.

  • **kwargs – Additional keyword arguments forwarded to MAD-NG model creation.

Returns:

model – Built MAD-NG model.

Return type:

object

Line.discard_madng_model()

Discard the attached MAD-NG model for this line.

Returns:

Removes the current MAD-NG model association.

Return type:

None

Line.madng_survey()

Run a survey using the MAD-NG model.

If the MAD-NG model is not available, it is created automatically.

Returns:

survey – Survey result produced by MAD-NG.

Return type:

xtrack.survey.SurveyTable

Line.madng_twiss(rdts=(), normal_form=False, mapdef_twiss=2, mapdef_normal_form=4, nslice=3, xsuite_tw=True, X0=None, compute_chromatic_properties=False, coupling_edw_teng=False, method=4, **tw_kwargs)

Run a Twiss calculation using the MAD-NG model.

If the MAD-NG model is not available, it is created automatically.

Parameters:
  • rdts (tuple, optional) – Resonance driving terms to compute.

  • normal_form (bool, optional) – If True, also compute normal-form quantities.

  • mapdef_twiss (int, optional) – Map order used for the MAD-NG Twiss computation.

  • mapdef_normal_form (int, optional) – Map order used for the MAD-NG normal-form computation.

  • nslice (int, optional) – Number of slices used in MAD-NG tracking/Twiss internals.

  • xsuite_tw (bool, optional) – If True, use Xsuite Twiss output structure and enrich it with MAD-NG data.

  • X0 (object, optional) – Initial condition object for open Twiss calculations.

  • method (int, optional) – MAD-NG method identifier for Twiss/tracking calls.

  • **tw_kwargs – Additional keyword arguments forwarded to Twiss setup.

Returns:

twiss – Twiss table with MAD-NG columns.

Return type:

xtrack.TwissTable

Line.regen_madng_model()

Regenerate the MAD-NG model associated with this line.

Returns:

Rebuilds the MAD-NG model association.

Return type:

None

Deprecated

Go to Summary table

Line.append_element(element, name)

Append element to the end of the lattice

Warning

This method is deprecated. Use Line.append() instead.

Parameters:
  • element (object) – Element to append

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

Line.compute_R_matrix(*args, **kwargs)

Compute the one turn matrix using finite differences.

Warning

This function is deprecated and will be removed in a future version. Please use Line.get_R_matrix(…) instead.

Line.compute_T_matrix(*args, **kwargs)

Compute the second order tensor of the beamline.

Warning

This method is deprecated and will be removed in future versions. Please use get_T_matrix() instead.

Line.compute_one_turn_matrix_finite_differences(*args, **kwargs)

Deprecated. Compute the one turn matrix using finite differences.

Warning

This function is deprecated and will be removed in a future version. Please use Line.get_R_matrix(…) instead.

classmethod Line.from_sixinput(sixinput, classes=())

Line.from_sixinput has been removed in favour of sixinput.generate_xtrack_line().

Line.get_elements_of_type(types)

Get all elements of given type(s)

Warning

This method is deprecated and will be removed in a future version. Use tt = line.get_table() and then tt.rows.match(element_type='MyType') instead.

Parameters:

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

Returns:

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

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

Line.get_s_elements(mode='upstream')

Get s position for all elements

Warning

This method is deprecated and will be removed in a future version. Use tt = line.get_table() and then tt.s instead.

Parameters:

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

Returns:

s – s position for all elements

Return type:

list of float

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

Get s position for given elements

Warning

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”)

Returns:

s – s position for given element(s)

Return type:

float or list of float

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

Insert an element in the line.

Warning

This method is deprecated. Use Line.insert() instead.

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

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

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

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

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

Line.to_pandas()

Return a pandas DataFrame with the elements of the line.

Warning

This method is deprecated and will be removed in a future version. A similar functionality is provided by the method Line.get_table().

Returns:

line_df – DataFrame with the elements of the line.

Return type:

pandas.DataFrame

Line.unfreeze()

Use Line.discard_tracker() instead.

Warning

This function is deprecated.

property Line.builder

Deprecated alias for line.composer.

Returns:

Compose-mode builder object associated with the line.

Return type:

Composer or None

property Line.varval

Convenience accessor to variable values.

Equivalent to line.vars.val.

Returns:

values – Mapping-like view exposing variable values.

Return type:

object

property Line.vv

Short alias for variable values.

Equivalent to line.varval` (or line.vars.val`).

Returns:

values – Mapping-like view exposing variable values.

Return type:

object

Upcoming Deprecations

Go to Summary table

Line.check_aperture(needs_aperture=[])

Check that all active elements have an associated aperture.

Parameters:

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

Returns:

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

Return type:

pandas.DataFrame

Line.extend(what)

Append existing element names to this line.

Parameters:

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.

Line.filter_elements(mask=None, exclude_types_starting_with=None)

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

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

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

Returns:

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

Return type:

Line

Line.freeze_vars(variable_names)

Freeze variables in tracked Particles objects.

Parameters:

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

Line.get_aperture_table(dx=0.001, dy=0.001, x_range=(-0.1, 0.1), y_range=(-0.1, 0.1))

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.

Return type:

xtrack.Table

Line.unfreeze_vars(variable_names)

Unfreeze variables in tracked Particles objects.

Parameters:

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

property Line.collimators

Deprecated alias for line.xcoll.collimators.

Returns:

collimators – Xcoll collimator API bound to this line.

Return type:

object

property Line.scattering

Deprecated alias for line.xcoll.scattering.

Returns:

scattering – Xcoll scattering API bound to this line.

Return type:

object