Members - short description

Editing, Inspection, Variables and Configuration

Member

Description

eval(…)

Get the value of an expression

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 rel_​knl and rel_​ksl attributes of the elements.

get(…)

Get an element or the value of a variable.

get_​expr(…)

Get expression associated to a variable

import_​line(…)

Import a line into this environment.

info(…)

Get information about an element or a variable.

new(…)

Create a new element or line.

new_​expr(…)

Create a new expression

new_​line(…)

Create a new line.

place(…)

Create a place object.

remove(…)

Remove an element, particle, line, or variable by name.

replace_​replica(…)

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

set(…)

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

element_​dict

Dictionary-like container of elements in the environment.

element_​refs

xdeps reference container for element fields.

elements

Container of named beam elements stored in the environment.

functions

xdeps function container used in expressions.

line_​names

Names of all lines currently in the environment.

lines

Container of named lines registered in this environment.

metadata

User metadata associated with the environment.

ref

xdeps reference container for variables, elements, particles, and lines.

ref_​manager

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

vars

Variables container associated with the environment.

xcoll

Xcoll-specific helpers associated with this environment.

xfields

Xfields-specific helpers associated with this environment.

Reference Particle and Particle Generation

Member

Description

new_​particle(…)

Associate a particle type to a name. The particle is stored in Environment.particles, its properties can be controlled with deferred expressions and it can be used as reference particle for lines.

set_​particle_​ref(…)

Set the environment reference particle and optionally propagate it to lines.

particle_​ref

Reference particle associated with the environment.

particles

Container of named particle references stored in the environment.

Analysis and Matching

Member

Description

match(…)

Change a set of knobs in the beam lines 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.

twiss(…)

Compute the twiss parameters for the lines.

Tracker Setup

Member

Description

build_​trackers(…)

Build the trackers for the lines.

discard_​trackers(…)

Discard all trackers in all lines of the environment.

Constructors and Serialization

Member

Description

call(…)

Call a file with xtrack commands.

copy(…)

Create a deep copy of the environment.

from_​dict(…)

Rebuild an environment from a serialized dictionary.

from_​json(…)

Construct an environment from a JSON file.

to_​dict(…)

Serialize the environment to a JSON-compatible dictionary.

to_​json(…)

Save the environment to a JSON file.

Deprecated

Member

Description

from_​madx(…)

Load a multiline from a MAD-X file.

new_​builder(…)

Deprecated. Create a new composer.

set_​multipolar_​errors(…)

Deprecated: set multipolar errors for specified elements of the environment.

varval

Convenience accessor to variable values.

vv

Short alias for variable values.

Upcoming deprecations

Member

Description

apply_​filling_​pattern(…)

Deprecated alias for env.xfields.apply_​filling_​pattern(...).

configure_​beambeam_​interactions(…)

Deprecated alias for env.xfields.configure_​beambeam_​interactions(...).

install_​beambeam_​interactions(…)

Deprecated alias for env.xfields.install_​beambeam_​interactions(...).

Members - full description

Editing, Inspection, Variables and Configuration

Go to Summary table

Environment.eval(expr)

Get the value of an expression

Parameters:

expr (str) – Expression to evaluate.

Returns:

value – Value of the expression.

Return type:

float

Examples

import xtrack as xt

env = xt.Environment()
env['a'] = 2.0

value = env.eval('3*a + 1')

# value is 7.0
Environment.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.

Environment.extend_knl_rel_ksl_rel(order, element_names=None)

Extend the order of the rel_knl and rel_ksl attributes of the elements.

Parameters:
  • order (int) – New order of the rel_knl and rel_ksl attributes.

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

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

Examples

import xtrack as xt

env = xt.Environment()
env['kq'] = 0.2
env.new('qf', 'Quadrupole', length=1.0, k1='kq')

element = env.get('qf')
value = env.get('kq')

# element is the Quadrupole object; value is 0.2
Environment.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

Examples

import xtrack as xt

env = xt.Environment()
env['a'] = 2.0
env['b'] = '3*a'

expr = env.get_expr('b')

# expr is the expression controlling b.
# env.get_expr('a') returns None because a is a constant.
Environment.import_line(line, suffix_for_common_elements=None, rename_elements={}, line_name=None, overwrite_vars=False)

Import a line into this environment.

Parameters:
  • line (xtrack.Line) – Line to import. Its elements, variables, particle reference, configuration, and metadata are copied into this environment.

  • suffix_for_common_elements (str, optional) – Suffix to be added to the names of the elements that are common to the imported line and the line in this environment. If None, '/{line_name}' is used.

  • rename_elements (dict, optional) – Dictionary with the elements to be renamed. The keys are the names of the elements in line, and the values are the new names.

  • line_name (str, optional) – Name of the new line. If None, the name of the imported line is used.

  • overwrite_vars (bool, optional) – If True, the variables in the imported line will overwrite the variables with the same name in this environment. Default is False.

Returns:

This method modifies the environment in place.

Return type:

None

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

Examples

import xtrack as xt

env = xt.Environment()
env['a'] = 2.0
env['kq'] = '3*a'
env.new('qf', 'Quadrupole', length=1.0, k1='kq')

env.info('kq')
# Info for vars['kq']
#
# value: 6.0
#
# controlled by expr:
#   vars['kq'] = (3.0 * vars['a'])
#
# expr_dependencies:
#   vars['a'] = 2.0
#
# controlled_targets:
#    element_refs['qf'].k1

env.info('qf')
# Element of type:  Quadrupole
# name                value   expr
# k1                  6.0     vars['kq']
# k1s                 0.0     None
# length              1.0     None
# ...
Environment.new(name, prototype=None, mode=None, at=None, from_=None, anchor=None, from_anchor=None, extra=None, mirror=False, force=False, import_from=None, parent=None, **kwargs)

Create a new element or line.

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

  • prototype (str or class) – Prototype class or name of the prototype element

  • parent (str or class, optional) – Deprecated alias for prototype.

  • mode (str, optional) –

    • clone: clone the prototype element or line. The prototype element or line is copied, together with the associated expressions.

    • replica: replicate the prototype elements or lines are made.

    • import: clone from a different environment. import_from must be provided.

  • at (float or str, optional) – Position of the created object.

  • from (str, optional) – Name of the element from which the position is calculated (its center is used as reference).

  • mirror (bool, optional) – Can only be used when cloning lines. If True, the order of the elements is reversed.

  • import_from (Environment, optional. Only to be used when mode is 'import'.) –

Notes

Environment.new can instantiate only the built-in element classes supported by the line builder. For user-defined element classes, or other element types that are not supported by Environment.new, instantiate the element explicitly, store it in env.elements, and attach deferred expressions through the environment view.

Returns:

Name of the created element or line or a Place object if at or from_ is provided.

Return type:

str or Place

Examples

import xtrack as xt

env = xt.Environment()
env['kqf'] = 0.2
env.new('qf', 'Quadrupole', length=1.0, k1='kqf')
env.new('qd', 'qf', k1='-kqf')

env.ref['qd'].k1.xdeps.info()
# Info for element_refs['qd'].k1
#
# value: -0.2
#
# controlled by expr:
#   element_refs['qd'].k1 = (-vars['kqf'])
#
# expr_dependencies:
#   vars['kqf'] = 0.2
#
# controlled_targets: None

Unsupported or user-defined element classes can be added explicitly:

import xtrack as xt

class MyElement:
    def __init__(self, myparam=0):
        self.myparam = myparam

    def track(self, particles):
        pass

env = xt.Environment()
env['a'] = 2.0
env.elements['myelem'] = MyElement(myparam=0)
env['myelem'].myparam = '3*a'

env['myelem'].myparam
# 6.0
Environment.new_expr(expr)

Create a new expression

Parameters:

expr (str) – Expression to create.

Returns:

expr – New expression.

Return type:

Expression

Examples

import xtrack as xt

env = xt.Environment()
env['a'] = 2.0

expr = env.new_expr('3*a + 1')
env['b'] = expr

# env['b'] is 7.0
Environment.new_line(components=None, name=None, refer: Literal['start', 'center', 'centre', 'end'] = 'center', length=None, mirror=False, s_tol=1e-06, compose=False) Line

Create a new line.

Parameters:
  • components (list, optional) – List of components to be added to the line. It can include strings, place objects, and lines.

  • name (str, optional) – Name of the new line.

  • refer (str, optional) – Specifies which part of the component the at position will refer to. Allowed values are start, center (default; also allowed is centre), and end.

  • length (float | str, optional) – Length of the line to be built by the composer. Can be an expression. If not specified, the length will be the minimum length that can fit all the components.

  • mirror (bool, optional) – Whether the line should be mirrored after creation.

  • compose (bool, optional) – Whether to instantiate the line in compose mode, which allows the components to be added to the line after creation.

  • s_tol (float, optional) – Difference between two s positions below which they should be treated as the same location.

Returns:

The new line.

Return type:

line

Examples

import xtrack as xt

env = xt.Environment()
env['a'] = 3 # Define a variable
env.new('mq1', 'Quadrupole', length=0.3, k1='a')
env.new('mq2', 'Quadrupole', length=0.3, k1='-a')

ln = env.new_line(name='myline', components=[
    'mq1',
    env.new('mymark', 'Marker', at=10.0),
    env.new('mq1_clone', 'mq1', k1='2*a'),
    env.place('mq2', at=20.0, from_='mymark'),
])
Environment.place(name, obj=None, at=None, from_=None, anchor=None, from_anchor=None)

Create a place object.

Parameters:
  • name (str or Line) – Name of the element or line to be placed.

  • at (float or str, optional) – Position of the created object.

  • from (str, optional) – Name of the element from which the position is calculated (its center is used as reference).

Returns:

The new place object.

Return type:

Place

Examples

import xtrack as xt

env = xt.Environment()
env.new('qf', 'Quadrupole', length=2.0)
env.new('mk', 'Marker')

line = env.new_line(components=[
    env.place('qf', at=3.0),
])

line.insert([
    env.place('mk', at=0, from_='qf', from_anchor='center'),
])

line.get_table().show()
# name                      s element_type             isthick ...
# ||drift_1                 0 Drift                       True
# qf_entry                  2 Marker                     False
# qf..entry_map             2 ThinSliceQuadrupoleEntry   False
# qf..0                     2 ThickSliceQuadrupole        True
# mk                        3 Marker                     False
# qf..1                     3 ThickSliceQuadrupole        True
# qf..exit_map              4 ThinSliceQuadrupoleExit    False
# qf_exit                   4 Marker                     False
# _end_point                4                            False
Environment.remove(key)

Remove an element, particle, line, or variable by name.

Parameters:

key (str) – Name of the object to remove.

Examples

import xtrack as xt

env = xt.Environment()
env.new('qf', 'Quadrupole', length=1.0)

env.remove('qf')

# 'qf' is no longer in env
Environment.replace_replica(name)

Replace a replica element with 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 environment in place.

Return type:

None

Environment.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 Environment.element_dict

Dictionary-like container of elements in the environment.

Returns:

element_dict – Mapping from element names to element objects.

Return type:

dict

property Environment.element_refs

xdeps reference container for element fields.

Returns:

element_refs – Dictionary-like container of xdeps element references, or None when variable management is disabled.

Return type:

object

property Environment.elements

Container of named beam elements stored in the environment.

Use this container to inspect, add, replace, or remove elements by name. Element names share the environment namespace with variables, particles, and lines.

Returns:

elements – Dictionary-like container of elements. When expression management is enabled, item access returns reference-aware views.

Return type:

xtrack.environment.EnvElements

Examples

import xtrack as xt

env = xt.Environment()
env.elements['qf'] = xt.Quadrupole(length=1.0, k1=0.2)

env.elements.get_table().show()
# name element_type isthick isreplica parent_name ... length
# qf   Quadrupole      True     False None        ...      1
property Environment.functions

xdeps function container used in expressions.

Returns:

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

Return type:

object

Examples

import xtrack as xt

env = xt.Environment()
env['t_turn_s'] = 0.5
env.functions['ramp'] = xt.FunctionPieceWiseLinear(
    x=[0, 1], y=[0.2, 0.4])
env['kq'] = env.functions['ramp'](env.ref['t_turn_s'])

env.ref['kq'].xdeps.info()
# Info for vars['kq']
#
# value: 0.30000000000000004
#
# controlled by expr:
#   vars['kq'] = f['ramp'](vars['t_turn_s'])
#
# expr_dependencies:
#   f['ramp'] = <xdeps.functions.FunctionPieceWiseLinear object at ...>
#   vars['t_turn_s'] = 0.5
property Environment.line_names

Names of all lines currently in the environment.

Returns:

line_names – Line names in insertion order.

Return type:

list of str

property Environment.lines

Container of named lines registered in this environment.

Returns:

lines – Dictionary-like container exposing lines by name.

Return type:

xtrack.environment.EnvLines

Examples

import xtrack as xt

env = xt.Environment()
env.new('qf', 'Quadrupole', length=1.0)
env.new('qd', 'Quadrupole', length=1.0)
env.new('ip', 'Marker')

env.new_line(name='cell', components=[
    env.place('ip', at=0.0),
    env.place('qf', at=2.0, from_='ip'),
    env.place('qd', at=4.0, from_='qf'),
])

env.lines['cell'].get_table().show()
# name                   s element_type isthick ...
# ip                     0 Marker         False
# ||drift_1              0 Drift           True
# qf                   1.5 Quadrupole      True
# ||drift_2            2.5 Drift           True
# qd                   5.5 Quadrupole      True
# _end_point           6.5                False
property Environment.metadata

User metadata associated with the environment.

Returns:

metadata – Mutable dictionary storing user metadata.

Return type:

dict

property Environment.ref

xdeps reference container for variables, elements, particles, and lines.

References can be used to build deferred expressions that stay linked to the underlying environment quantities.

Returns:

ref – Reference container for environment objects.

Return type:

xtrack.environment.EnvRef

Examples

import xtrack as xt

env = xt.Environment()
env['kq'] = 0.2
env.new('qf', 'Quadrupole', length=1.0)
env.ref['qf'].k1 = 2 * env.ref['kq']

env.ref['qf'].k1.xdeps.info()
# Info for element_refs['qf'].k1
#
# value: 0.4
#
# controlled by expr:
#   element_refs['qf'].k1 = (2 * vars['kq'])
property Environment.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 Environment.vars

Variables container associated with the 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:

xtrack.environment.EnvVars

Examples

import xtrack as xt

env = xt.Environment()
env.vars['a'] = 2.0
env.vars['b'] = '3*a'

env.vars.get_table().show()
# name       value expr
# t_turn_s       0 None
# a              2 None
# b              6 (3.0 * a)
property Environment.xcoll

Xcoll-specific helpers associated with this environment.

Returns:

xcoll – Accessor exposing Xcoll helper methods.

Return type:

xcoll.environment_tools.XcollEnvironmentAPI

property Environment.xfields

Xfields-specific helpers associated with this environment.

Returns:

xfields – Accessor exposing Xfields helper methods.

Return type:

xtrack.environment.EnvXfields

Reference Particle and Particle Generation

Go to Summary table

Environment.new_particle(name, parent=None, force=False, **kwargs)

Associate a particle type to a name. The particle is stored in Environment.particles, its properties can be controlled with deferred expressions and it can be used as reference particle for lines.

Note that this method is not meant to create particles distributions for tracking. For that purpose use xt.Particles(…), Line.build_particles(…) or the generation functions for particles distributions available in xpart. See https://xsuite.readthedocs.io/en/latest/particlesmanip.html for more details.

Parameters:
  • name (str) – Name of the new particle type

  • parent (str or class) – Parent class or name of the parent particle type

  • pdg_id_0 (int or str, optional, define reference mass and charge from) – PDG id or particle name.

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

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

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

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

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

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

  • rigidity0 (array_like of float, optional) – Reference magnetic rigidity [T.m]

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

Examples

Create a positron particle type with gamma0 controlled by a deferred expression:

>>> env = xt.Environment()
>>> env['a'] = 5
>>> env.new_particle('my_particle_type', pdg_id_0='positron', gamma0='3*a')
'my_particle_type'
>>> env['my_particle_type'].gamma0
View of LinkedArrayCpu([15.])
>>> env['a'] = 10
>>> env['my_particle_type'].gamma0
View of LinkedArrayCpu([30.])
Environment.set_particle_ref(*args, lines=True, **kwargs)

Set the environment reference particle and optionally propagate it to lines.

Parameters:
  • *args – Either a single xtrack.Particles, a particle name, or arguments passed to xtrack.Particles.

  • lines (bool, str, iterable of str, optional) – Which lines receive the same reference particle. True updates all lines, False/None updates none.

  • **kwargs – Extra keyword arguments forwarded to xtrack.Particles when constructing a new particle reference.

property Environment.particle_ref

Reference particle associated with the environment.

Returns:

particle_ref – Proxy to the configured reference particle, or None when no reference particle is configured.

Return type:

xtrack.environment.EnvParticleRef or None

property Environment.particles

Container of named particle references stored in the environment.

Named particles can be used as reusable reference particles for lines or accessed directly through the environment.

Returns:

particles – Dictionary-like container of particles. When expression management is enabled, item access returns reference-aware views.

Return type:

xtrack.environment.EnvParticles

Examples

import xtrack as xt

env = xt.Environment()
env['pc'] = 7e12
env.new_particle('lhc_proton', 'proton', p0c='pc')

env.particles.get_table().show()
# name          mass0 charge0 energy0   p0c gamma0 beta0
# lhc_proton 9.38272e+08   1   7e+12 7e+12 7460.52     1

Analysis and Matching

Go to Summary table

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

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

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

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

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

  • solver (str) – Solver to be used for the matching.

  • check_limits (bool) – If True (default), the limits of the knobs are checked before the optimization. If False, if the knobs are out of limits, the optimization knobs are set to the limits on the first iteration.

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

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

Returns:

result_info – Dictionary containing information about the matching result.

Return type:

dict

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

Environment.twiss(lines=None, **kwargs)

Compute the twiss parameters for the lines.

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

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

Returns:

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

Return type:

MultiTwiss

Tracker Setup

Go to Summary table

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

Build the trackers for the lines.

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

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

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

Environment.discard_trackers()

Discard all trackers in all lines of the environment.

Returns:

This method modifies the environment lines in place.

Return type:

None

Constructors and Serialization

Go to Summary table

Environment.call(filename)

Call a file with xtrack commands.

Parameters:

filename (str) – Name of the file to be called.

Environment.copy()

Create a deep copy of the environment.

Returns:

Independent copy of the environment, including elements, lines, particles, variables, expressions and metadata.

Return type:

Environment

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

Rebuild an environment from a serialized dictionary.

Parameters:
  • dct (dict) – Dictionary produced by to_dict().

  • _context (xobjects.Context, optional) – Context used to rebuild xobjects-backed data.

  • _buffer (xobjects.Buffer, optional) – Buffer used to rebuild xobjects-backed data.

  • classes (tuple, optional) – Extra element classes accepted during element deserialization.

Returns:

Reconstructed environment.

Return type:

Environment

classmethod Environment.from_json(file, **kwargs)

Construct an environment from a JSON file.

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

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

Returns:

environment – Environment object.

Return type:

Environment

Environment.to_dict(include_var_management=True, include_version=True)

Serialize the environment to a JSON-compatible dictionary.

Parameters:
  • include_var_management (bool, optional) – If True, include deferred-expression data and variable manager state. Default is True.

  • include_version (bool, optional) – If True, include the xtrack version that generated the dictionary. Default is True.

Returns:

Serialized environment data.

Return type:

dict

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

Save the environment 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.

  • indent (int, optional) – Indentation level used for the JSON output. Default is 1.

  • **kwargs – Additional keyword arguments passed to Environment.to_dict.

Returns:

This method writes the serialized environment to file.

Return type:

None

Deprecated

Go to Summary table

classmethod Environment.from_madx(filename=None, madx=None, stdout=None, return_lines=False, **kwargs)

Load a multiline from a MAD-X file.

Warning

This function is deprecated and will be removed in a future version. Please use xtrack.load(…), which uses the xsuite native MAD-X parser, without requiring Cpymad. In case you need to use cpymad for specific features, please load the individual lines using Line.from_madx_sequence(…) and add them to the environment using Environment.import_line(…).

Parameters:
  • filename (str, optional) – The MAD-X file to load from.

  • madx (cpymad.madx.Madx, optional) – Existing MAD-X instance to load from.

  • stdout (object, optional) – Stream used by the legacy MAD-X loader.

  • return_lines (bool, optional) – Whether to return individual lines instead of an environment.

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

Returns:

new_multiline – The multiline object.

Return type:

Multiline

Environment.new_builder(components=None, name=None, refer: Literal['start', 'center', 'centre', 'end'] = 'center', length=None, s_tol=1e-06)

Deprecated. Create a new composer.

Warning

The new_builder method is deprecated and will be removed in a future version. Use new_line with compose=True instead.

Parameters:
  • components (list, optional) – List of components to be added to the composer. It can include strings, place objects, and lines.

  • name (str, optional) – Name of the line that will be built by the composer.

  • refer (str, optional) – Specifies which part of the component the at position will refer to. Allowed values are start, center (default; also allowed is centre), and end.

  • length (float | str, optional) – Length of the line to be built by the composer. Can be an expression. If not specified, the length will be the minimum length that can fit all the components.

Returns:

The new composer.

Return type:

Composer

Environment.set_multipolar_errors(errors)

Deprecated: set multipolar errors for specified elements of the environment.

Warning

This function is deprecated and will be removed in a future version. Please use the attributes knl_rel and ksl_rel of the elements to set relative multipolar errors directly on the elements.

Parameters:

errors (dict) –

Dictionary with the errors to be set. The keys are the names of the elements, and the values are dictionaries with the following keys:

  • rel_knl: list of relative errors for the normal multipolar strengths.

  • rel_ksl: list of relative errors for the skew multipolar strengths.

  • refer: name of the strength to be used as reference, which is multiplied by the length. If None, the default reference strength is used (k0 for bends, k1 for quadrupoles, k2 for sextupoles, and k3 for octupoles).

Examples

env = xt.Environment()
env.vars.default_to_zero = True
line = env.new_line(components=[
    env.new('mq', 'Quadrupole', length=0.5, k1='kq'),
    env.new('mqs', 'Quadrupole', length=0.5, k1s='kqs'),
    env.new('mb', 'Bend', length=0.5, angle='ang', k0_from_h=True),
])

env.set_multipolar_errors({
    'mq': {'rel_knl': [1e-6, 1e-5, 1e-4],
           'rel_ksl': [-1e-6, -1e-5, -1e-4]},
    'mqs': {'rel_knl': [2e-6, 2e-5, 2e-4],
            'rel_ksl': [3e-6, 3e-5, 3e-4],
            'refer': 'k1s'},
    'mb': {'rel_knl': [2e-6, 3e-5, 4e-4],
           'rel_ksl': [5e-6, 6e-5, 7e-4]},
    })
property Environment.varval

Convenience accessor to variable values.

Warning

Environment.varval[...] is deprecated and will be removed in a future version. To access the value of a variable you can simply use Environment[...].

Equivalent to environment.vars.val.

Returns:

values – Mapping-like view exposing variable values.

Return type:

object

property Environment.vv

Short alias for variable values.

Warning

Environment.vv[...] is deprecated and will be removed in a future version. To access the value of a variable you can simply use Environment[...].

Equivalent to environment.varval (or environment.vars.val).

Returns:

values – Mapping-like view exposing variable values.

Return type:

object

Upcoming deprecations

Go to Summary table

Environment.apply_filling_pattern(filling_pattern_cw, filling_pattern_acw, i_bunch_cw, i_bunch_acw)

Deprecated alias for env.xfields.apply_filling_pattern(...).

Warning

This method is deprecated and will be removed in a future version. Use env.xfields.apply_filling_pattern(...) instead.

Parameters:
  • filling_pattern_cw (array_like) – Filling pattern for the clockwise beam.

  • filling_pattern_acw (array_like) – Filling pattern for the anticlockwise beam.

  • i_bunch_cw (int) – Bunch index for the clockwise beam.

  • i_bunch_acw (int) – Bunch index for the anticlockwise beam.

Returns:

Result returned by env.xfields.apply_filling_pattern(...).

Return type:

object

Environment.configure_beambeam_interactions(num_particles, nemitt_x, nemitt_y, crab_strong_beam=True, use_antisymmetry=False, separation_bumps=None)

Deprecated alias for env.xfields.configure_beambeam_interactions(...).

Warning

This method is deprecated and will be removed in a future version. Use env.xfields.configure_beambeam_interactions(...) instead.

Parameters:
  • num_particles (float) – Number of particles per bunch.

  • nemitt_x (float) – Horizontal normalized emittance.

  • nemitt_y (float) – Vertical normalized emittance.

  • crab_strong_beam (bool, optional) – Whether to include strong-beam crabbing.

  • use_antisymmetry (bool, optional) – Whether to use antisymmetry when configuring the interactions.

  • separation_bumps (object, optional) – Separation bump configuration passed to the Xfields helper.

Returns:

Result returned by env.xfields.configure_beambeam_interactions(...).

Return type:

object

Environment.install_beambeam_interactions(clockwise_line, anticlockwise_line, ip_names, num_long_range_encounters_per_side, num_slices_head_on, harmonic_number, bunch_spacing_buckets, sigmaz, delay_at_ips_slots=None)

Deprecated alias for env.xfields.install_beambeam_interactions(...).

Warning

This method is deprecated and will be removed in a future version. Use env.xfields.install_beambeam_interactions(...) instead.

Parameters:
  • clockwise_line (str or xtrack.Line) – Clockwise line or line name.

  • anticlockwise_line (str or xtrack.Line) – Anticlockwise line or line name.

  • ip_names (sequence of str) – Interaction point names.

  • num_long_range_encounters_per_side (int or sequence of int) – Number of long-range encounters per side.

  • num_slices_head_on (int) – Number of longitudinal slices for head-on interactions.

  • harmonic_number (int) – RF harmonic number.

  • bunch_spacing_buckets (int) – Bunch spacing in RF buckets.

  • sigmaz (float) – RMS bunch length.

  • delay_at_ips_slots (sequence of int, optional) – Delay at interaction points in bunch slots.

Returns:

Result returned by env.xfields.install_beambeam_interactions(...).

Return type:

object