Track

Tracking particles with Xsuite

The tracking of particles through a beam line can be simulated using the xtrack.Line.track() method of the xtrack.Line class. This is illustrated in the following example:

import numpy as np

import xobjects as xo
import xtrack as xt

## Generate a simple line
line = xt.Line(
    elements=[xt.Drift(length=2.),
              xt.Multipole(knl=[0, 0.5], ksl=[0,0]),
              xt.Drift(length=1.),
              xt.Multipole(knl=[0, -0.5], ksl=[0,0])],
    element_names=['drift_0', 'quad_0', 'drift_1', 'quad_1'])

## Attach a reference particle to the line (optional)
## (defines the reference mass, charge and energy)
line.set_particle_ref('proton', p0c=6.5e12)

## 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

## Transfer lattice on context and compile tracking code if necessary
line.build_tracker(_context=context)

## Build particle object on context
n_part = 20
particles = line.build_particles(
                        x=np.random.uniform(-1e-3, 1e-3, n_part),
                        px=np.random.uniform(-1e-5, 1e-5, n_part),
                        y=np.random.uniform(-2e-3, 2e-3, n_part),
                        py=np.random.uniform(-3e-5, 3e-5, n_part),
                        zeta=np.random.uniform(-1e-2, 1e-2, n_part),
                        delta=np.random.uniform(-1e-4, 1e-4, n_part))
# Reference mass, charge, energy are taken from the reference particle.
# Particles are allocated on the context chosen for the line.

## Track (no saving of turn-by-turn data)
n_turns = 100
line.track(particles, num_turns=n_turns)

particles.state # > 0 for particles still alive
particles.at_turn # turn number (for lost particles, it is the turn of loss)
particles.x # x position after tracking
particles.px # x momentum after tracking
# etc...

## Track (saving turn-by-turn data)
particles = line.build_particles( # fresh particles
                        x=np.random.uniform(-1e-3, 1e-3, n_part),
                        px=np.random.uniform(-1e-5, 1e-5, n_part),
                        y=np.random.uniform(-2e-3, 2e-3, n_part),
                        py=np.random.uniform(-3e-5, 3e-5, n_part),
                        zeta=np.random.uniform(-1e-2, 1e-2, n_part),
                        delta=np.random.uniform(-1e-4, 1e-4, n_part))
n_turns = 100
line.track(particles, num_turns=n_turns,
              turn_by_turn_monitor=True)

## Turn-by-turn data is available at:
line.record_last_track.x
line.record_last_track.px
# etc...

# Complete source: xtrack/examples/tracker/000_track.py

Dynamic aperture

The following example illustrates how to use Xsuite to study the Dynamic Aperture of a ring.

import numpy as np

import xtrack as xt
import xpart as xp
import xobjects as xo

line = xt.load('../../test_data/hllhc14_no_errors_with_coupling_knobs/line_b1.json')

# Switch on LHC octupole circuits to have a smaller dynamic aperture
for arc in ['12', '23', '34', '45', '56', '67', '78', '81']:
    line.vars[f'kod.a{arc}b1'] = 2.0
    line.vars[f'kof.a{arc}b1'] = 2.0

# Generate normalized particle coordinates on a polar grid
n_r = 50
n_theta = 60
x_normalized, y_normalized, r_xy, theta_xy = xp.generate_2D_polar_grid(
    r_range=(0, 40.), # beam sigmas
    theta_range=(0, np.pi/2),
    nr=n_r, ntheta=n_theta)

# Set initial momentum deviation
delta_init = 0 # In case off-momentum DA is needed

# Match particles to the machine optics and orbit
particles = line.build_particles(
    x_norm=x_normalized, px_norm=0,
    y_norm=y_normalized, py_norm=0,
    nemitt_x=3e-6, nemitt_y=3e-6, # normalized emittances
    delta=delta_init)

# # Optional: activate multi-core CPU parallelization
# line.discard_tracker()
# line.build_tracker(_context=xo.ContextCpu(omp_num_threads='auto'))

# Track
line.track(particles, num_turns=200, time=True, with_progress=5)

print(f'Tracked in {line.time_last_track} seconds')

# Sort particles to get the initial order
# (during tracking lost particles are moved to the end)
particles.sort(interleave_lost_particles=True)

# Plot result using scatter or pcolormesh
import matplotlib.pyplot as plt
plt.close('all')
plt.figure(1)
plt.scatter(x_normalized, y_normalized, c=particles.at_turn)
plt.xlabel(r'$A_x [\sigma]$')
plt.ylabel(r'$A_y [\sigma]$')
cb = plt.colorbar()
cb.set_label('Lost at turn')

plt.figure(2)
plt.pcolormesh(
    x_normalized.reshape(n_r, n_theta), y_normalized.reshape(n_r, n_theta),
    particles.at_turn.reshape(n_r, n_theta), shading='gouraud')
plt.xlabel(r'$A_x [\sigma]$')
plt.ylabel(r'$A_y [\sigma]$')
ax = plt.colorbar()
ax.set_label('Lost at turn')

plt.show()

# Complete source: xtrack/examples/dynamic_aperture/000_tracking_for_da.py
_images/dynamic_aperture.png

On-momentum dynamic aperture for the LHC lattice with octupoles active.

Particles Monitors

The xtrack.ParticlesMonitor records particle coordinates over selected turns. It can be used through the default turn-by-turn monitor, configured as a custom monitor, or inserted as a beam element.

The easy way

When starting a tracking simulation with the Xtrack Line object, the easiest way of logging the coordinates of all particles for all turns is to enable the default turn-by-turn monitor, as illustrated by the following example. Note: this mode requires that particles.at_turn is 0 for all particles at the beginning of the simulation.

import xtrack as xt
import xpart as xp
import xobjects as xo

context = xo.ContextCpu()

line = xt.load('../../test_data/hllhc15_noerrors_nobb/line_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

num_particles = 50
particles = xp.generate_matched_gaussian_bunch(line=line,
                                               num_particles=num_particles,
                                               nemitt_x=2.5e-6,
                                               nemitt_y=2.5e-6,
                                               sigma_z=9e-2)

num_turns = 30
line.track(particles, num_turns=num_turns,
              turn_by_turn_monitor=True # <--
             )
# line.record_last_track contains the measured data. For example,
# line.record_last_track.x contains the x coordinate for all particles
# and all turns, e.g. line.record_last_track.x[3, 5] for the particle
# having particle_id = 3 and for the turn number 5.

# Monitor objects can be dumped to a dictionary and loaded back
mon = line.record_last_track
dct = mon.to_dict()
mon2 = xt.ParticlesMonitor.from_dict(dct)

# Complete source: xtrack/examples/monitor/000_example_quick_monitor.py

Custom monitors

In order to customize the monitor’s behaviour, a custom monitor object can be built and passed to the Line.track function.

Particles coordinates can be recorded only in a selected range of turns by specifying start_at_turn and stop_at_turn. The monitoring can also be limited to a selected range of particles IDs, by using the argument particle_id_range of the ParticlesMonitor class to provide a tuple defining the range to be recorded. In that case the num_particles input of the monitor is omitted.

The example above is changed as follows:

...

monitor = xt.ParticlesMonitor(_context=context,
    particle_id_range=(5, 42),
    start_at_turn=5, # <-- first turn to monitor (including)
    stop_at_turn=15, # <-- last turn to monitor (excluding)
)

line.track(particles, num_turns=num_turns,
           turn_by_turn_monitor=monitor, # <-- pass the monitor here
)

Now, line.record_last_track.x[3, 5] gives the x coordinates for the particle 3 (which has the id 8) and the recorded turn 5 (which is turn number 10). The particle ids that are recorded can be inspected in line.record_last_track.particle_id and the turn indices in line.record_last_track.at_turn.

Multi-frame particles monitor

The particles monitor can also record periodically spaced intervals of turns (frames). This feature can be activated by providing the arguments n_repetitions and repetition_period when creating the monitor. In the following example, we record turns in range 5 to 10 (first frame), range 25 to 30 (second frame) and range 45 to 50 (third frame). Note that each frame consists of 5 turns since stop_at_turn is excluding.

monitor = xt.ParticlesMonitor(_context=context,
    num_particles=num_particles,
    start_at_turn=5,
    stop_at_turn=10,
    n_repetitions=3,      # <--
    repetition_period=20, # <--
)

Now, the measured data are a 3D array with the first index being the frame number. For example, line.record_last_track.x[0, :, :] contains the recorded x position for the first frame (turns 5, 6, 7, 8 and 9) and line.record_last_track.x[-1, :, 0] refers to the last frame and the first turn within, which is turn number 45. As before, the turn numbers recorded can be inspected with line.record_last_track.at_turn.

Particles monitor as beam elements

Particles monitors can be used as regular beam elements to record the particle coordinates at specific locations in the beam line. For this purpose they can be inserted in the line, as illustrated in the following example.

import xtrack as xt
import xpart as xp
import xobjects as xo

line = xt.load('../../test_data/hllhc15_noerrors_nobb/line_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

env = line.env

num_particles = 50

# Create the monitors
env.elements['mymon5'] = xt.ParticlesMonitor(start_at_turn=5, stop_at_turn=15,
                                    num_particles=num_particles)
env.elements['mymon8'] = xt.ParticlesMonitor(start_at_turn=5, stop_at_turn=15,
                                    num_particles=num_particles)

# Place the monitors in the line
line.insert([
    env.place('mymon5', at='ip5'),
    env.place('mymon8', at='ip8'),
])

particles = xp.generate_matched_gaussian_bunch(line=line,
                                               num_particles=num_particles,
                                               nemitt_x=2.5e-6,
                                               nemitt_y=2.5e-6,
                                               sigma_z=9e-2)

num_turns = 30
monitor = xt.ParticlesMonitor(start_at_turn=5, stop_at_turn=15,
                              num_particles=num_particles)
line.track(particles, num_turns=num_turns)

# monitor_ip5 contains the data recorded in before the element 'ip5', while
# monitor_ip8 contains the data recorded in before the element 'ip8'
# The element index at which the recording is made can be inspected in
# monitor_ip5.at_element.

# Complete source: xtrack/examples/monitor/003_monitors_as_beam_elements.py

Like all Xtrack elements, the Particles Monitor has a track method and can be used in stand-alone mode as illustrated in the following example.

# line.track(particles, num_turns=num_turns)
for iturn in range(num_turns):
    monitor.track(particles)
    line.track(particles)

Multi-element monitor

It is possible to log particle coordinates at multiple selected elements in the beamline for all tracked turns. This can be activated by adding the argument multi_element_monitor_at when calling the track method of the Line object. This is illustrated in the following example, where the coordinates are recorded at all BPMs of a ring.

import xtrack as xt
import numpy as np

line = xt.load('../../test_data/hllhc15_thick/lhc_thick_with_knobs.json')

# Get names of all BPMs in the line
tt = line.get_table()
tt_obs = tt.rows.match(name='bpm.*')
tt_obs.name # is ['bpmw.4r7.b1', 'bpmwe.4r7.b1', 'bpmw.5r7.b1', ...,

# Generate some particles
p = xt.Particles(p0c=7e12, x=1e-6*np.arange(20),
                           delta=0)

# Track particles for 10 turns, monitoring at all BPMs
line.track(p, num_turns=10, multi_element_monitor_at=tt_obs.name)

# Get the recorded data
mon = line.record_multi_element_last_track

# Access all data for a given coordinate
mon.get('x') # shape is (nom_turns, n_particles, n_obs_points)

# Access data for a given coordinate and observation point
mon.get('x', obs_name='bpmw.4r7.b1') # shape is (nom_turns, n_particles)

# Access data for a given coordinate, observation point and particle_id
mon.get('x', obs_name='bpmw.4r7.b1', particle_id=10) # shape is (nom_turns,)

# Access data for a given coordinate, observation point, particle_id and turn
mon.get('x', obs_name='bpmw.4r7.b1', particle_id=10, turn=5) # is a scalar

# Get all BPMs for a given particles and turn
mon.get('x', particle_id=10, turn=5) # shape is (n_obs_points,)

# Complete source: xtrack/examples/monitor_multi_element/000_multi_element_monitor.py

Beam Statistics Monitor

The xtrack.BeamStatsMonitor records weighted beam statistics for the whole beam, per bunch, or per longitudinal slice. It is intended for diagnostics such as intensity, centroids, beam sizes, covariances, and projected emittances.

See also: BeamStatsMonitor API reference.

The quantity num_particles is the sum of particles.weight in each bin, not the number of macroparticles. All statistics are computed with the same weights. Particle species diagnostics can be requested with sum_charge_ratio, mean_charge_ratio, sum_mass_ratio, and mean_mass_ratio; these quantities use the same particles.weight weighting. The optional particle_id_range=(start, stop) argument restricts recording to particles with particle_id in the inclusive-lower, exclusive-upper range [start, stop).

In this monitor, slot means a bunch position on the bunch pattern grid, where adjacent slots are separated in zeta by bunch_spacing_zeta. Note that bunch_spacing_zeta is distinct from an RF bucket, which can be finer than the bunch spacing.

The bunch pattern to be monitored can be specified using either filling_scheme or filled_slots. For example, filling_scheme=[1, 0, 1, 1] is equivalent to filled_slots=[0, 2, 3]. The selected_slots argument can be used to record only a subset of the filled slots. A slice is a longitudinal subdivision inside a bunch, or a full-turn subdivision in coasting mode.

Whole-beam statistics are available through monitor.get(..., level="beam"). They are computed from all accepted particles for the same effective turn. In bunched and sliced modes, this means summing the recorded weighted sums over the selected slots and slices; filled slots that are not selected do not contribute.

The monitor exposes the most detailed level available from its constructor inputs. With no bunch or slice inputs, recorded arrays have shape:

(n_logged_turns,)

With bunch inputs and no slice inputs, recorded arrays have shape:

(n_logged_turns, n_selected_slots)

With slice inputs, recorded arrays have shape:

(n_logged_turns, n_selected_slots, num_slices)

The level argument of xtrack.BeamStatsMonitor.get() selects a reduction level:

monitor.get("mean_x", level="beam")
monitor.get("mean_x", level="bunch", slot=3)
monitor.get("mean_x", level="slice", slot=3, slice_index=12)

The examples below also show the main inspection tools: monitor.stats lists the recorded quantities, monitor.available_levels lists the available aggregation levels, monitor.default_level gives the level returned by statistic attributes, monitor.turns maps the first array axis to machine turns, monitor.zeta_centers gives the slice coordinates when slices are available, and each requested statistic is available both as an attribute and through monitor.get("stat_name").

Whole-beam stats

The following example records stats for the full beam over a subset of turns in a PIMMS lattice with an RF cavity added, and plots mean_x and mean_zeta as a function of turn. No zeta_range or num_slices is needed.

import numpy as np


import xtrack as xt

# Load the PIMMS lattice and set particle_ref
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity
line.insert("pimms_cavity", xt.Cavity(harmonic=7, voltage=10e3), at=0.001)

# Create a BeamStatsMonitor to record beam statistics at each turn.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=300,
    stats=["num_particles", "mean_x", "mean_zeta", "sigma_x"],
)

# Insert the monitor at the beginning of the line
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a bunch
np.random.seed(12345)
particles = line.xpart.generate_matched_gaussian_bunch(
    num_particles=50,
    total_intensity_particles=1e10,
    nemitt_x=1e-6,
    nemitt_y=1e-6,
    sigma_z=0.01,
)

# Track
line.track(particles, num_turns=300,
           with_progress=10 # progress bar updated every 10 turns
)

# Inspect what has been recorded by the monitor
monitor.stats  # is ('num_particles', 'mean_x', 'mean_zeta', 'sigma_x')
monitor.available_levels  # is ('beam',)
monitor.default_level  # is 'beam'
monitor.turns  # is array([0, 1, 2, ..., 299])

# The shape is (logged turns,).
monitor.mean_x.shape  # is (300,)

# num_particles is the sum of particle weights in the whole beam.
monitor.num_particles.shape  # is (300,)

# A recorded statistic can be accessed as an attribute or with monitor.get().
monitor.mean_x[monitor.record_index(10)]
monitor.get("mean_x", turn=10)  # same as above

# Plot the beam centroids as a function of turn.
import matplotlib.pyplot as plt
plt.close('all')
fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].plot(monitor.turns, monitor.mean_x * 1000)
axes[0].set_ylabel("mean_x [mm]")
axes[1].plot(monitor.turns, monitor.mean_zeta * 1000)
axes[1].set_ylabel("mean_zeta [mm]")
axes[1].set_xlabel("turn")
plt.show()

# Complete source: xtrack/examples/beam_stats_monitor/000_beam_stats.py
_images/beam_stats_monitor_beam_stats.png

Evolution of the horizontal and longitudinal beam centroids recorded with BeamStatsMonitor.

Bunch-by-bunch stats

The following example records stats for a bunch train generated from a matched Gaussian bunch. A sinusoidal horizontal offset is applied to the initial bunch centroids, and the recorded arrays are inspected and plotted as bunch-by-bunch profiles over consecutive turns. No zeta_range or num_slices is needed.

import numpy as np

import xtrack as xt

NUM_TURNS = 100
NUM_SLOTS = 7
NUM_PARTICLES_PER_BUNCH = 30
BUNCH_INTENSITY = 1e10

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity and use its bucket spacing to define the bunch train.
harmonic = 7
bunch_spacing_zeta = line.get_length() / harmonic
line.insert("pimms_cavity", xt.Cavity(harmonic=harmonic, voltage=10e3),
            at=0.001)

filling_scheme = np.ones(NUM_SLOTS, dtype=int)

# Define a monitor to record bunch-by-bunch statistics at each turn
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=NUM_TURNS,
    filling_scheme=filling_scheme,
    bunch_spacing_zeta=bunch_spacing_zeta,
    stats=["num_particles", "mean_x", "mean_zeta", "sigma_x"],
)

# Insert the monitor at the beginning of the line
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a multi-bunch beam with a sinusoidal offset in x.
np.random.seed(12345)
particles = line.xpart.generate_matched_gaussian_multibunch_beam(
    filling_scheme=filling_scheme,
    bunch_num_particles=NUM_PARTICLES_PER_BUNCH,
    bunch_intensity_particles=BUNCH_INTENSITY,
    nemitt_x=1e-8,
    nemitt_y=1e-8,
    sigma_z=0.01,
    bucket_length=bunch_spacing_zeta,
)
particles.x = -1e-3 * np.sin(
    2 * np.pi * particles.zeta / (NUM_SLOTS * bunch_spacing_zeta))

# Track
line.track(particles, num_turns=NUM_TURNS,
           with_progress=10)  # progress bar updated every 10 turns

# Inspect what has been recorded.
monitor.stats  # is ('num_particles', 'mean_x', 'mean_zeta', 'sigma_x')
monitor.available_levels  # is ('beam', 'bunch')
monitor.default_level  # is 'bunch'
monitor.selected_slots  # is array([0, 1, 2, ..., 6])
monitor.turns  # is array([0, 1, 2, ..., 99])

# The shape is (logged turns, selected slots).
monitor.mean_x.shape  # is (100, 7)

# Bunch-level stats are the default when bunches are configured.
mean_x_by_bunch = monitor.get("mean_x")
mean_x_by_bunch.shape  # is (100, 7)

# The selected-slot axis follows monitor.selected_slots.
monitor.get("mean_x", slot=3).shape  # is (100,)
monitor.get("mean_x", turn=20, slot=[0, 3, 6]).shape  # is (3,)

# Beam-level stats are also available as weighted sums over bunches.
mean_x_beam = monitor.get("mean_x", level="beam")
mean_x_beam.shape  # is (100,)

# Extract and plot bunch centroids for 10 consecutive turns.
turns_to_plot = monitor.turns[:10]
mean_x_to_plot = monitor.get("mean_x", turn=turns_to_plot) * 1000

import matplotlib.pyplot as plt
plt.close('all')
fig, ax = plt.subplots()

for ii, turn in enumerate(turns_to_plot):
    ax.plot(monitor.selected_slots, mean_x_to_plot[ii],
            "o-", label=f"turn {turn}")
ax.set_xlabel("slot")
ax.set_ylabel("mean_x [mm]")
ax.legend(bbox_to_anchor=(1.02, 1), loc="upper left")
fig.tight_layout()

plt.show()

# Complete source: xtrack/examples/beam_stats_monitor/001_bunch_by_bunch_stats.py
_images/beam_stats_monitor_bunch_by_bunch_stats.png

Horizontal bunch centroids over consecutive turns, recorded with BeamStatsMonitor.

Slice-by-slice stats

Providing zeta_range and num_slices enables slice mode. This can be combined with filled_slots, selected_slots, and bunch_spacing_zeta to record slice-by-slice statistics for multiple physical bunch slots. In this mode the most detailed recorded arrays have axes (turn, selected slot, slice). The following example generates a multi-bunch beam, imposes a horizontal sinusoidal pattern with a wavelength comparable to the bunch spacing, and plots mean_x * num_particles versus absolute zeta for a few consecutive bunches and turns. Per-bunch and whole-beam statistics remain available through monitor.get(..., level="bunch") and monitor.get(..., level="beam").

import numpy as np

import xtrack as xt


NUM_TURNS = 10
NUM_SLOTS = 3
NUM_SLICES = 48
NUM_PARTICLES_PER_BUNCH = 600
BUNCH_INTENSITY = 1e10
SIGMA_Z = 2.0
ZETA_RANGE = (-10.0, 10.0)

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity and use its bucket spacing to define the bunch train.
harmonic = NUM_SLOTS
bunch_spacing_zeta = line.get_length() / harmonic
line.insert("pimms_cavity", xt.Cavity(harmonic=harmonic, voltage=10e3),
            at=0.001)

filling_scheme = np.ones(NUM_SLOTS, dtype=int)
selected_slots = [0, 1, 2]

# Define a monitor to record slice-by-slice statistics at each turn.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=NUM_TURNS,
    filling_scheme=filling_scheme,
    selected_slots=selected_slots,
    bunch_spacing_zeta=bunch_spacing_zeta,
    zeta_range=ZETA_RANGE,
    num_slices=NUM_SLICES,
    stats=["num_particles", "mean_x", "mean_zeta", "sigma_x"],
)

# Insert the monitor at the beginning of the line.
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a multi-bunch beam.
np.random.seed(12345)
particles = line.xpart.generate_matched_gaussian_multibunch_beam(
    filling_scheme=filling_scheme,
    bunch_num_particles=NUM_PARTICLES_PER_BUNCH,
    bunch_intensity_particles=BUNCH_INTENSITY,
    nemitt_x=1e-12,
    nemitt_y=1e-12,
    sigma_z=SIGMA_Z,
    bucket_length=bunch_spacing_zeta,
)

# Impress a horizontal sinusoidal pattern with a wavelength comparable to the
# bunch spacing, so the phase changes visibly along the bunch train.
train_wavelength = 0.3 * bunch_spacing_zeta
particles.x += 1.0e-3 * np.sin(2 * np.pi * particles.zeta
                                / train_wavelength)

# Track.
line.track(particles, num_turns=NUM_TURNS,
           with_progress=1)  # progress bar updated every turn

# Inspect what has been recorded.
monitor.stats  # is ('num_particles', 'mean_x', 'mean_zeta', 'sigma_x')
monitor.available_levels  # is ('beam', 'bunch', 'slice')
monitor.default_level  # is 'slice'
monitor.selected_slots  # is array([0, 1, 2])
monitor.turns  # is array([0, 1, 2, ..., 9])

# The default slice-level shape is (logged turns, selected slots, slices).
monitor.mean_x.shape  # is (10, 3, 48)
monitor.zeta_centers.shape  # is (3, 48) - zeta_centers are the histogram centers
                            # for the slices, and are the same for all turns.

# Slice-level stats can be selected by turn and  slot
slices_1_bunch_1_turn = monitor.get("mean_x", level="slice", turn=5, slot=1)
slices_1_bunch_1_turn.shape  # is (48,)

# Bunch-level and beam-level statistics are also available as reductions of
# the recorded slice data.
mean_x_bunch = monitor.get("mean_x", level="bunch")
mean_x_bunch.shape  # is (10, 3)

mean_x_beam = monitor.get("mean_x", level="beam")
mean_x_beam.shape  # is (10,)

# Plot the dipole moment (mean_x * num_particles) versus absolute zeta for all turns.
import matplotlib.pyplot as plt
plt.close('all')
fig, ax = plt.subplots(figsize=(8, 4.5))

for turn in monitor.turns:
    for slot_index, slot in enumerate(monitor.selected_slots):
        label = f"turn {turn}" if slot_index == 0 else None
        ax.plot(
            monitor.zeta_centers[slot_index],
            (monitor.get("mean_x", turn=turn, slot=slot)
             * monitor.get("num_particles", turn=turn, slot=slot)),
            "-", label=label)

ax.set_xlabel("zeta [m]")
ax.set_ylabel("mean_x * num_particles [m]")
ax.grid(True)
ax.legend(bbox_to_anchor=(1.02, 1), loc="upper left")
fig.tight_layout()

plt.show()

# Complete source: xtrack/examples/beam_stats_monitor/002_slice_by_slice_stats.py
_images/beam_stats_monitor_slice_by_slice_stats.png

Slice-by-slice horizontal dipole moment recorded for three bunches with BeamStatsMonitor.

Coasting-beam stats

For a coasting beam, pass coasting=True together with num_slices. The monitor slices the full machine turn periodically. In this mode no zeta_range, filling scheme, selected slots, or bunch_spacing_zeta is needed. Particles whose zeta coordinate is outside one circumference are wrapped into the corresponding recorded turn.

The default recorded arrays have axes (turn, slice). Since the physical slice coordinates depend on the machine circumference, monitor.zeta_centers is None in coasting mode and no bunch level is exposed. Use xtrack.BeamStatsMonitor.time_centers() or xtrack.BeamStatsMonitor.zeta_centers_unwrapped() with the line length to plot data over multiple turns.

The following example uses the PIMMS lattice, creates a coasting distribution spanning one turn, imposes a tune-matched sinusoidal horizontal modulation as a function of zeta, tracks the beam for several turns, and plots the recorded slice centroids with unwrapped time coordinates.

import numpy as np

import xtrack as xt


NUM_TURNS = 8
NUM_SLICES = 80
NUM_PARTICLES = 4000
TOTAL_INTENSITY = 1e10
AMPLITUDE_X = 1.0e-3
MODULATION_PHASE = 0.3

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Use the periodic Twiss parameters at the monitor location to initialize a
# matched transverse wave.
tw = line.twiss(method="4d")
qx = tw.qx
betx = tw.betx[0]
alfx = tw.alfx[0]

# Create a coasting BeamStatsMonitor to record full-turn slice statistics.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=NUM_TURNS,
    coasting=True,
    num_slices=NUM_SLICES,
    stats=["num_particles", "mean_x", "mean_zeta"],
)

# Insert the monitor at the beginning of the line.
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a coasting distribution spanning one full turn.
line_length = line.get_length()
mass0 = np.asarray(line.particle_ref.mass0).ravel()[0]
p0c = np.asarray(line.particle_ref.p0c).ravel()[0]
beta0 = np.asarray(line.particle_ref.beta0).ravel()[0]
zeta = np.linspace(-0.5 * line_length, 0.5 * line_length,
                   NUM_PARTICLES, endpoint=False)
zeta += 0.5 * line_length / NUM_PARTICLES
particles = xt.Particles(
    mass0=mass0,
    p0c=p0c,
    zeta=zeta,
    weight=np.full(NUM_PARTICLES, TOTAL_INTENSITY / NUM_PARTICLES),
)

# Impress a sinusoidal horizontal modulation over the coasting beam.
theta = -2 * np.pi * qx * particles.zeta / line_length + MODULATION_PHASE
particles.x = AMPLITUDE_X * np.sin(theta)
particles.px = (
    AMPLITUDE_X / betx * (np.cos(theta) - alfx * np.sin(theta)))

# Track for multiple turns.
line.track(particles, num_turns=NUM_TURNS,
           with_progress=1)  # progress bar updated every turn

# Inspect what has been recorded.
monitor.stats  # is ('num_particles', 'mean_x', 'mean_zeta')
monitor.available_levels  # is ('beam', 'slice')
monitor.default_level  # is 'slice'
monitor.turns  # is array([0, 1, 2, ..., 7])

# In coasting mode the default slice-level shape is (logged turns, slices).
monitor.mean_x.shape  # is (8, 80)
monitor.zeta_centers  # is None

# Use line-length-aware helpers to build unwrapped coordinates.
tt = monitor.time_centers(line_length=line_length, beta0=beta0)
tt.shape  # is (8, 80)

zz = monitor.zeta_centers_unwrapped(line_length=line_length)
zz.shape  # is (8, 80)

# Plot the coasting-beam centroid as a function of unwrapped time.
import matplotlib.pyplot as plt
plt.close("all")
fig, ax = plt.subplots(figsize=(8, 4.5))

num_particles = np.asarray(monitor.num_particles)
mean_x = np.asarray(monitor.mean_x)

valid = num_particles > 0
tt_plot = tt[valid]
mean_x_plot = mean_x[valid]

ax.plot(
    tt_plot * 1e6,
    mean_x_plot * 1e3,
    "-",
    linewidth=1.5,
)

ax.set_xlabel("time [us]")
ax.set_ylabel("mean_x [mm]")
ax.grid(True)
fig.tight_layout()

plt.show()

# Complete source: xtrack/examples/beam_stats_monitor/006_coasting_beam_stats.py
_images/beam_stats_monitor_coasting_beam_stats.png

Coasting-beam horizontal centroid recorded over multiple turns with BeamStatsMonitor.

Beam profiles

The same monitor can also record weighted beam profiles. Pass a profiles dictionary whose keys are particle coordinates and whose values define the profile range and num_bins. The key is the coordinate to histogram; for example "x" records the horizontal profile and "delta" records the momentum-deviation profile.

Profile counts are weighted in the same way as num_particles. The bin metadata and counts are available through dictionaries keyed by coordinate:

monitor.profile_bin_edges["x"]
monitor.profile_bin_centers["x"]
monitor.profiles["x"]

The profile arrays use the same leading axes as the most detailed statistics, with one additional trailing profile-bin axis. For example, whole-beam profile data have shape (turn, profile_bin), bunched slice profile data have shape (turn, selected slot, slice, profile_bin), and coasting profile data have shape (turn, slice, profile_bin).

The following example records scalar beam statistics together with horizontal and momentum profiles. A horizontal offset is applied to the bunch before tracking, and the recorded horizontal profile is plotted at selected turns.

import numpy as np

import xtrack as xt


NUM_TURNS = 32
NUM_PARTICLES = 2000
TOTAL_INTENSITY = 1e10
NUM_X_BINS = 80
NUM_DELTA_BINS = 60

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity.
line.insert("pimms_cavity", xt.Cavity(harmonic=7, voltage=10e3), at=0.001)

# Create a BeamStatsMonitor that records scalar statistics and profiles.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=NUM_TURNS,
    stats=["num_particles", "mean_x", "sigma_x"],
    profiles={
        "x": {"range": (-20e-3, 20e-3), "num_bins": NUM_X_BINS},
        "delta": {"range": (-3e-3, 3e-3), "num_bins": NUM_DELTA_BINS},
    },
)

# Insert the monitor at the beginning of the line.
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a bunch and apply a horizontal offset so the profile motion is
# visible over consecutive turns.
rng = np.random.default_rng(12345)
mass0 = np.asarray(line.particle_ref.mass0).ravel()[0]
p0c = np.asarray(line.particle_ref.p0c).ravel()[0]
particles = xt.Particles(
    mass0=mass0,
    p0c=p0c,
    x=rng.normal(loc=4e-3, scale=1.5e-3, size=NUM_PARTICLES),
    px=rng.normal(loc=0.0, scale=0.2e-3, size=NUM_PARTICLES),
    y=rng.normal(loc=0.0, scale=1.0e-3, size=NUM_PARTICLES),
    py=rng.normal(loc=0.0, scale=0.2e-3, size=NUM_PARTICLES),
    zeta=rng.normal(loc=0.0, scale=0.01, size=NUM_PARTICLES),
    delta=rng.normal(loc=0.0, scale=0.8e-3, size=NUM_PARTICLES),
    weight=np.full(NUM_PARTICLES, TOTAL_INTENSITY / NUM_PARTICLES),
)

# Track.
line.track(particles, num_turns=NUM_TURNS,
           with_progress=4)  # progress bar updated every 4 turns

# Inspect what has been recorded.
monitor.profile_coordinates  # is ('x', 'delta')
monitor.profile_num_bins  # is {'x': 80, 'delta': 60}
monitor.profile_bin_edges["x"].shape  # is (81,)
monitor.profile_bin_centers["x"].shape  # is (80,)

# With no bunch or slice inputs, profile arrays have axes
# (logged turns, profile bin).
monitor.profiles["x"].shape  # is (32, 80)
monitor.profiles["delta"].shape  # is (32, 60)

# Scalar statistics are recorded in the same monitor.
monitor.mean_x.shape  # is (32,)
monitor.sigma_x.shape  # is (32,)

# Plot the horizontal profile at selected turns.
import matplotlib.pyplot as plt
plt.close("all")
fig, ax = plt.subplots(figsize=(8, 4.5))

x_centers = monitor.profile_bin_centers["x"] * 1e3
x_profiles = monitor.profiles["x"]

for turn in [0, 8, 16, 24]:
    profile = x_profiles[monitor.record_index(turn)]
    normalized_profile = profile / np.max(profile)
    ax.step(
        x_centers,
        normalized_profile,
        where="mid",
        label=f"turn {turn}",
    )

ax.set_xlabel("x [mm]")
ax.set_ylabel("normalized profile")
ax.grid(True)
ax.legend()
fig.tight_layout()

plt.show()

# Complete source: xtrack/examples/beam_stats_monitor/007_beam_profiles.py
_images/beam_stats_monitor_beam_profiles.png

Horizontal beam profiles recorded at selected turns with BeamStatsMonitor.

Emittance and optics from covariance

Requesting normal-mode emittance or covariance-optics quantities makes BeamStatsMonitor store the full 6D covariance moment set in the canonical coordinate order (x, px, y, py, zeta, pzeta). These quantities can be requested explicitly, combined with projected emittances such as nemitt_x_projected, and mixed with ordinary beam statistics such as mean_x and sigma_x in the same monitor. The tracking kernel still records only weighted primitive moments; normal-mode emittances, beta functions, alpha functions, and dispersions are computed afterwards from the measured covariance matrix.

The normal-mode emittances, for example nemitt_x, are obtained from the full coupled 6D covariance matrix. The projected emittances, for example nemitt_x_projected, are instead computed from the corresponding 2D coordinate-plane covariance. The normalized projected emittance is obtained by multiplying the geometric projected emittance by the weighted average of beta0 * gamma0. The same convention is used for y and for the longitudinal (zeta, pzeta) plane.

The following example generates a matched Gaussian bunch, records the covariance-derived quantities turn by turn, and compares the measured beta functions at the monitor location with the model Twiss values. The requested scalar arrays are available as ordinary monitor attributes such as monitor.mean_x, monitor.nemitt_x, monitor.nemitt_x_projected, and monitor.betx.

import numpy as np

import xtrack as xt


NUM_TURNS = 20
NUM_PARTICLES = 10_000
NEMITT_X = 1.0e-6
NEMITT_Y = 2.0e-6
SIGMA_Z = 0.01

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity so that a matched bunch can be generated.
line.insert("pimms_cavity", xt.Cavity(harmonic=7, voltage=10e3), at=0.001)

# The monitor is inserted at the start of the line. The first row of the Twiss
# table is therefore the model reference for the measured beta functions.
tw = line.twiss()
betx_model = tw.betx[0]
bety_model = tw.bety[0]

# Requesting normal-mode emittances or covariance optics makes the monitor store
# the full 6D covariance moment set. These stats can be mixed with ordinary beam
# statistics in the same monitor. The covariance and optics calculations are
# done as Python-side postprocessing from the stored primitive moments.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=NUM_TURNS,
    stats=[
        "num_particles",
        "mean_x", "mean_y", "sigma_x", "sigma_y",
        "gemitt_x", "gemitt_y", "gemitt_zeta",
        "nemitt_x", "nemitt_y", "nemitt_zeta",
        "gemitt_x_projected", "gemitt_y_projected",
        "gemitt_zeta_projected",
        "nemitt_x_projected", "nemitt_y_projected",
        "nemitt_zeta_projected",
        "betx", "bety",
        "alfx", "alfy",
        "dx", "dpx",
    ],
)

line.insert("beam_stats_monitor", monitor, at=0)

# Generate a matched Gaussian bunch for the line. The particle weights sum to
# the total bunch intensity, and the monitor uses these weights for all
# statistics.
np.random.seed(12345)
particles = line.xpart.generate_matched_gaussian_bunch(
    num_particles=NUM_PARTICLES,
    total_intensity_particles=1e10,
    nemitt_x=NEMITT_X,
    nemitt_y=NEMITT_Y,
    sigma_z=SIGMA_Z,
)

# Track and record the covariance-derived quantities turn by turn.
line.track(particles, num_turns=NUM_TURNS,
           with_progress=1)  # progress bar updated every turn

# Inspect the recorded quantities.
monitor.stats  # includes ordinary stats, emittances, optics, and dispersion
monitor.available_levels  # is ('beam',)
monitor.default_level  # is 'beam'
monitor.turns  # is array([0, 1, 2, ..., 19])

# Ordinary beam statistics are recorded together with covariance-derived stats.
monitor.mean_x.shape  # is (20,)
monitor.sigma_x.shape  # is (20,)

# Normal-mode emittances are available as arrays indexed by logged turn.
monitor.nemitt_x.shape  # is (20,)
monitor.nemitt_y.shape  # is (20,)
monitor.nemitt_zeta.shape  # is (20,)

# Projected emittances are available separately with the _projected suffix.
monitor.nemitt_x_projected.shape  # is (20,)
monitor.nemitt_y_projected.shape  # is (20,)

# Covariance optics are also available turn by turn.
monitor.betx.shape  # is (20,)
monitor.bety.shape  # is (20,)

# Plot measured emittances and beta functions versus turn.
import matplotlib.pyplot as plt
plt.close("all")
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(8, 6))

axes[0].plot(monitor.turns, monitor.nemitt_x * 1e6, "o-", label="x mode")
axes[0].plot(monitor.turns, monitor.nemitt_y * 1e6, "o-", label="y mode")
axes[0].axhline(NEMITT_X * 1e6, color="C0", linestyle="--", linewidth=1)
axes[0].axhline(NEMITT_Y * 1e6, color="C1", linestyle="--", linewidth=1)
axes[0].set_ylabel("nemitt [um]")
axes[0].set_ylim(0, None)
axes[0].legend()
axes[0].grid(True)

axes[1].plot(monitor.turns, monitor.betx, "o-", label="betx from covariance")
axes[1].plot(monitor.turns, monitor.bety, "o-", label="bety from covariance")
axes[1].axhline(betx_model, color="C0", linestyle="--", linewidth=1)
axes[1].axhline(bety_model, color="C1", linestyle="--", linewidth=1)
axes[1].set_ylabel("beta [m]")
axes[1].set_xlabel("turn")
axes[1].set_ylim(0, None)
axes[1].legend()
axes[1].grid(True)

fig.tight_layout()
plt.show()

# Complete source: xtrack/examples/beam_stats_monitor/005_emittance_and_optics.py
_images/beam_stats_monitor_emittance_and_optics.png

Normal-mode emittances and beta functions reconstructed turn by turn from the covariance measured with BeamStatsMonitor.

Saving to file during a simulation

The monitor can also write the requested statistics to an HDF5 file. When output_file is passed to the constructor, the file is initialized in write mode immediately. Calling xtrack.BeamStatsMonitor.save_to_file() during tracking appends only the records that have not already been written, while the full configured monitor frame remains available in memory.

The saved HDF5 file is a flat time series. The recorded turns are stored in /turns and the statistics are stored under /stats/<level>/<stat>. Since each save operation flushes and closes the file, another script can reopen it between saves to inspect partial results. The following example uses a bunch-by-bunch monitor, tracks in chunks, saves after each chunk, and reads both the reduced beam-level data from /stats/beam and the bunch-level data from /stats/bunch.

import h5py
import numpy as np

import xtrack as xt


NUM_TURNS = 60
SAVE_EVERY = 15
NUM_SLOTS = 3
NUM_PARTICLES_PER_BUNCH = 30
BUNCH_INTENSITY = 1e10

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity and use its bucket spacing to define the bunch train.
harmonic = NUM_SLOTS
bunch_spacing_zeta = line.get_length() / harmonic
line.insert("pimms_cavity", xt.Cavity(harmonic=harmonic, voltage=10e3),
            at=0.001)

filling_scheme = np.ones(NUM_SLOTS, dtype=int)

output_file = "beam_stats_monitor_progress.h5"

# The monitor is configured for the full simulation, so all records remain
# available in memory. The output file is initialized at construction.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=NUM_TURNS,
    filling_scheme=filling_scheme,
    bunch_spacing_zeta=bunch_spacing_zeta,
    stats=["num_particles", "mean_x", "sigma_x"],
    output_file=output_file,
)
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a multi-bunch beam.
np.random.seed(12345)
particles = line.xpart.generate_matched_gaussian_multibunch_beam(
    filling_scheme=filling_scheme,
    bunch_num_particles=NUM_PARTICLES_PER_BUNCH,
    bunch_intensity_particles=BUNCH_INTENSITY,
    nemitt_x=1e-6,
    nemitt_y=1e-6,
    sigma_z=0.01,
    bucket_length=bunch_spacing_zeta,
)

# Track in chunks and save the newly recorded suffix after each chunk.
for _ in range(NUM_TURNS // SAVE_EVERY):
    line.track(particles, num_turns=SAVE_EVERY)
    monitor.save_to_file()

# The monitor still keeps the full configured frame in memory.
monitor.turns  # is array([0, 1, 2, ..., 59])
monitor.mean_x.shape  # is (60, 3)

# Open the HDF5 file and access the saved statistics.
with h5py.File(output_file, "r") as h5file:
    turns_from_file = h5file["turns"][...]
    mean_x_beam_from_file = h5file["stats/beam/mean_x"][...]
    sigma_x_beam_from_file = h5file["stats/beam/sigma_x"][...]
    mean_x_bunch_from_file = h5file["stats/bunch/mean_x"][...]
    sigma_x_bunch_from_file = h5file["stats/bunch/sigma_x"][...]

turns_from_file.shape  # is (60,)
mean_x_beam_from_file.shape  # is (60,)
sigma_x_beam_from_file.shape  # is (60,)
mean_x_bunch_from_file.shape  # is (60, 3)
sigma_x_bunch_from_file.shape  # is (60, 3)

# Complete source: xtrack/examples/beam_stats_monitor/003_save_to_file_during_simulation.py

Saving long simulations with frame reuse

For simulations where a full run would be too large to keep in one monitor allocation, the user can save one frame, clear the in-memory arrays, and reuse the same monitor for the next turn interval with xtrack.BeamStatsMonitor.start_new_frame(). This frame-reuse helper is not available in coasting mode. The HDF5 file remains unaware of frames: each call to xtrack.BeamStatsMonitor.save_to_file() appends the new records to the same flat /turns and /stats datasets.

The following example keeps only 20 turns in memory at a time while saving 60 turns to the file. After the loop, the monitor contains the last frame only, whereas the file contains all saved turns.

import h5py
import numpy as np

import xtrack as xt


TOTAL_TURNS = 60
FRAME_TURNS = 20

# Load the PIMMS lattice and set particle_ref.
env = xt.load(["../../test_data/pimms/PIMMS.seq",
               "../../test_data/pimms/pimms_optics.str"])
line = env.pimms
line.set_particle_ref("proton", kinetic_energy0=100e6)

# Add an RF cavity.
line.insert("pimms_cavity", xt.Cavity(harmonic=7, voltage=10e3), at=0.001)

output_file = "beam_stats_monitor_frames.h5"

# The monitor stores only one frame in memory. The HDF5 file receives all
# frames as one flat time series.
monitor = xt.BeamStatsMonitor(
    start_at_turn=0,
    stop_at_turn=FRAME_TURNS,
    stats=["num_particles", "mean_x", "sigma_x"],
    output_file=output_file,
)
line.insert("beam_stats_monitor", monitor, at=0)

# Generate a bunch.
np.random.seed(12345)
particles = line.xpart.generate_matched_gaussian_bunch(
    num_particles=50,
    total_intensity_particles=1e10,
    nemitt_x=1e-6,
    nemitt_y=1e-6,
    sigma_z=0.01,
)

# Track, save, clear the in-memory frame, and retarget the same monitor to
# the next turn interval.
for start_turn in range(0, TOTAL_TURNS, FRAME_TURNS):
    if start_turn != 0:
        monitor.start_new_frame(start_at_turn=start_turn)

    line.track(particles, num_turns=FRAME_TURNS)
    monitor.save_to_file()

# The in-memory arrays contain only the last frame.
monitor.turns  # is array([40, 41, ..., 59])
monitor.mean_x.shape  # is (20,)

# The HDF5 file contains all saved frames as one flat sequence.
with h5py.File(output_file, "r") as h5file:
    turns_from_file = h5file["turns"][...]
    mean_x_from_file = h5file["stats/beam/mean_x"][...]
    sigma_x_from_file = h5file["stats/beam/sigma_x"][...]

turns_from_file  # is array([0, 1, 2, ..., 59])
mean_x_from_file.shape  # is (60,)
sigma_x_from_file.shape  # is (60,)

# Complete source: xtrack/examples/beam_stats_monitor/004_save_to_file_with_new_frame.py

Legacy monitors

The monitors below are kept for compatibility with existing workflows. For new beam-statistics use cases, prefer xtrack.BeamStatsMonitor.

Last turns monitor

The xtrack.LastTurnsMonitor records particle data in the last turns before respective particle loss (or the end of tracking).

The idea is to use a rolling buffer instead of saving all the turns. This saves a lot of memory resources when the interest lies only in the last few turns. For each particle, the recorded data will cover up to n_last_turns*every_n_turns turns before it is lost (or the tracking ends).

monitor = LastTurnsMonitor(
    particle_id_range=(0, 5),
    n_last_turns=5,            # amount of turns to store
    every_n_turns=3,           # only consider turns which are multiples of this
)

... # track

monitor.at_turn[:,-1]  # turn number of each particle before it is lost (last turn alive)
monitor.x[3,-2]        # x coordinate of particle 3 in one but last turn (-2)

The monitor provides the following data as 2D arrays of shape (num_particles, n_last_turns), where the first index corresponds to the particle in particle_id_range and the second index corresponds to the turn (or every_n_turns) before the respective particle is lost: particle_id, at_turn, x, px, y, py, delta, zeta

Beam position monitor

The xtrack.BeamPositionMonitor records transverse beam positions, i.e. it stores the x and y centroid positions of particles. This can be useful for tune or beam-transfer-function diagnostics as well as transverse Schottky spectra.

The monitor allows for arbitrary sampling frequencies and can thus not only be used for bunch positions, but also coasting beam positions. Higher sampling frequencies give access to transverse beam oscillations at higher harmonics, which is especially useful for Schottky diagnostics. Internally, the particle arrival time is used when determining the record index. For coasting beams this ensures that the centroid is computed considering all particles which arrive at the monitor at the same time (as in a real-world measurement device), even if some particles might have made more or less turns than the synchronous particle due to a non-negligible momentum deviation.

\[i = f_{samp} \times \left(\frac{n-n_0}{f_{rev}} - \frac{\zeta}{\beta_0 c_0}\right)\]

where \(f_{samp}\) is the sampling frequency, \(f_{rev}\) is the revolution frequency, \(n\) is the current turn number and \(n_0\) is the first turn recorded, \(\zeta=(s-\beta_0\cdot c_0\cdot t)\) is the longitudinal zeta coordinate of the particle, \(\beta_0\) is the relativistic beta factor of the particle and \(c_0\) is the speed of light. For non-circular lines \(n\) is always zero and \(f_{rev}\) can be omitted.

Note that the index is rounded, i.e. the result array represents data of particles equally distributed around the reference particle, which is useful for bunched beams. For example, if the sampling frequency is twice the revolution frequency, the first item contains data from particles in the range zeta/circumference = -0.25 .. 0.25, the second item in the range 0.25 .. 0.75 and so on.

monitor = xt.BeamPositionMonitor(
    #particle_id_range=(5, 42),        # optional, defaults to all particles if not given
    start_at_turn=5, stop_at_turn=10,  # turn refers to the synchronous particle (at zeta=0)
    frev=1e6,                          # revolution frequency (only for circular lines)
    sampling_frequency=2e6,            # sampling frequency
)

... # track

print(monitor.count)   # waveform of number of particles (intensity)
print(monitor.x_mean)  # waveform of horizontal centroid positions (alias monitor.x_cen)
print(monitor.y_mean)  # waveform of vertical centroid positions (alias monitor.y_cen)

The result arrays can be understood as waveforms recorded at the specified sampling frequency. In the special case where the sampling frequency is set to the same value as the revolution frequency, the indices are identical to the recorded turn numbers (of the synchronous particle).

Beam size monitor

The xtrack.BeamSizeMonitor records transverse beam sizes, i.e. it stores the standard deviation of the particles’ x and y positions.

Like the Beam position monitor, the beam size monitor is also based on particle arrival time and an arbitrary sampling frequency.

monitor = xt.BeamSizeMonitor(
    #particle_id_range=(5, 42),        # optional, defaults to all particles if not given
    start_at_turn=5, stop_at_turn=10,  # turn refers to the synchronous particle (at zeta=0)
    frev=1e6,                          # revolution frequency (only for circular lines)
    sampling_frequency=2e6,            # sampling frequency
)

... # track

print(monitor.count)   # waveform of number of particles (intensity)
print(monitor.x_mean)  # waveform of horizontal centroid positions
print(monitor.y_std)   # waveform of vertical position standard deviation (i.e. beam size)
print(monitor.x_var)   # waveform of horizontal position variances

Beam profile monitor

The xtrack.BeamProfileMonitor records transverse beam profiles, i.e. it stores the number of particles on a defined raster (like a histogram).

Like the Beam position monitor, the beam profile monitor is also based on particle arrival time and an arbitrary sampling frequency.

monitor = xt.BeamProfileMonitor(
    #particle_id_range=(5, 42),        # optional, defaults to all particles if not given
    start_at_turn=5, stop_at_turn=10,  # turn refers to the synchronous particle (at zeta=0)
    frev=1e6,                          # revolution frequency (only for circular lines)
    sampling_frequency=2e6,            # sampling frequency
    n=100,                             # number of bins in the profile (can also specify nx and ny separately)
    x_range=(-4,2),                    # save horizontal profile extending from -4 to 2
    y_range=5,                         # shorthand for (-2.5, 2.5)
)

... # track

print(monitor.x_edges)      # the bin edges
print(monitor.x_grid)       # the bin midpoints
print(monitor.x_intensity)  # the actual profile (particle count per bin)

The recorded profiles are 2D arrays of shape (sample_size, n) where sample_size = round(( stop_at_turn - start_at_turn ) * sampling_frequency / frev). I.e. monitor.x_intensity[0,:] is the first recorded profile and monitor.x_intensity[-1,:] the last.

Start/stop tracking at specific elements

It is possible to start and/or stop the tracking at specific elements of the beam line. This is illustrated in the following example:

import xtrack as xt

### Behavior:

# For num_turns = 1 (default):
#  - line.track(particles, ele_start=3, ele_stop=5) tracks once from element 3 to
#    element 5 e. particles.at_turn is not incremented as the particles never pass through
#    the end of the beam line.
#  - line.track(particles, ele_start=7, ele_stop=3) tracks once from element 5 to
#    the end of the beamline and then from element 0 to element 3 excluded.
#    particles.at_turn is incremented to one as the particles pass once
#    the end of the beam line.

# When indicating num_turns = N with N > 1, additional (N-1) full turns are added to logic
# above. Therefore:
# - if ele_stop < ele_start: stops at element ele_stop when particles.at_turn = N - 1
# - if ele_stop >= ele_start: stops at element ele_stop when particles.at_turn = N

elements = [xt.Drift(length=1.) for _ in range(10)]
line=xt.Line(elements=elements)
line.reset_s_at_end_turn = False

# Standard mode
p = xt.Particles(x=[1e-3, 2e-3, 3e-3], p0c=7e12)
line.track(p, num_turns=4)
p.at_turn # is [4, 4, 4]

# ele_start > 0
p = xt.Particles(x=[1e-3, 2e-3, 3e-3], p0c=7e12, s=4., at_element=2)
line.track(p, num_turns=3, ele_start=2)
p.at_turn # is [3, 3, 3]

# 0 <= ele_start < ele_stop
p = xt.Particles(x=[1e-3, 2e-3, 3e-3], p0c=7e12, s=5 * 2., at_element=5)
line.track(p, num_turns=4, ele_start=5, ele_stop=8)
p.at_turn # is [3, 3, 3]

# 0 <= ele_start < ele_stop -- num_turns = 1
p = xt.Particles(x=[1e-3, 2e-3, 3e-3], p0c=7e12, s=5 * 2., at_element=5)
line.track(p, num_turns=1, ele_start=5, ele_stop=2)
p.at_turn # is [1, 1, 1]

# 0 <= ele_start < ele_stop -- num_turns > 1
p = xt.Particles(x=[1e-3, 2e-3, 3e-3], p0c=7e12, s=5 * 2., at_element=5)
line.track(p, num_turns=4, ele_start=5, ele_stop=2)
p.at_turn # is [4, 4, 4]

# Use ele_start and num_turns
p = xt.Particles(x=[1e-3, 2e-3, 3e-3], p0c=7e12, s=5 * 2., at_element=5)
line.track(p, ele_start=5, num_elements=7)
p.at_turn # is [1, 1, 1]

# Complete source: xtrack/examples/tracker/001_tracker_start_stop.py

Backtracking

It is possible to track particles backwards through a beam line, provided that all elements included in the line support backtracking. The following example illustrates how to backtrack for a full turn or between specified elements:

import xtrack as xt

line = xt.load('../../test_data/hllhc15_noerrors_nobb/line_w_knobs_and_particle.json')

p = xt.Particles(
    p0c=7000e9, x=1e-4, px=1e-6, y=2e-4, py=3e-6, zeta=0.01, delta=1e-4)
p.get_table().show(digits=3)
# prints:
#
# particle_id s      x    px      y    py zeta  delta chi ...
#           0 0 0.0001 1e-06 0.0002 3e-06 0.01 0.0001   1

# Track one turn
line.track(p)
p.get_table().show()
# prints:
#
# particle_id s        x        px        y        py    zeta  delta chi ...
#           0 0 0.000324 -1.07e-05 1.21e-05 -1.42e-06 0.00909 0.0001   1

# Track back one turn
line.track(p, backtrack=True)
# The particle is back to the initial coordinates
p.get_table().show(digits=3)
# prints:
#
# particle_id s      x    px      y    py zeta  delta chi ...
#           0 0 0.0001 1e-06 0.0002 3e-06 0.01 0.0001   1

# It is also possible to backtrack with a specified start/stop elements

# Track three elements
line.track(p, ele_start=0, ele_stop=3)
p.get_table().cols['x px y py zeta delta at_element'].show()
# prints:
#
# particle_id           x    px           y    py zeta  delta at_element
#           0 0.000121028 1e-06 0.000263084 3e-06 0.01 0.0001          3

# Track back three elements
line.track(p, ele_start=0, ele_stop=3, backtrack=True)
p.get_table().cols['x px y py zeta delta at_element'].show()
# prints:
#
# particle_id      x    px      y    py zeta  delta at_element
#           0 0.0001 1e-06 0.0002 3e-06 0.01 0.0001          0

# Complete source: xtrack/examples/tracker/002_backtrack.py

Freeze longitudinal coordinates

In certain studies, it is convenient to track particles updating only the transverse coordinates, while keeping the longitudinal coordinates fixed (frozen). Xsuite offers the possibility to freeze the longitudinal coordinates within a single method call or by changing the state of the Line, as illustrated in the following sections.

Freezing longitudinal coordinates when calling methods

The Line.twiss and Line.track methods can work with frozen longitudinal coordinates. This is done by setting the freeze_longitudinal argument to True, as shown in the following example:

import json

import xtrack as xt

# import a line and add reference particle
line = xt.load(
    '../../test_data/hllhc15_noerrors_nobb/line_w_knobs_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

# Track some particles with frozen longitudinal coordinates
particles = line.build_particles(delta=1e-3, x=[-1e-3, 0, 1e-3])
line.track(particles, num_turns=10, freeze_longitudinal=True)
print(particles.delta) # gives [0.001 0.001 0.001], same as initial value

# Track some particles with unfrozen longitudinal coordinates
particles = line.build_particles(delta=1e-3, x=[-1e-3, 0, 1e-3])
line.track(particles, num_turns=10)
print(particles.delta) # gives [0.00099218, ...], different from initial value

# Twiss with unfrozen longitudinal coordinates (can be 6d)
twiss = line.twiss(method='6d')
print(twiss.slip_factor) # gives 0.00032151, from longitudinal motion

# Complete source: xtrack/examples/freeze_longitudinal/002_freeze_individual_methods.py

Freezing longitudinal coordinates within a with block

A context manager is also available to freeze the longitudinal coordinates within a with block. The normal tracking mode, updating the longitudinal coordinates, is automatically restored when exiting the with block, as illustrated in the following example:

import json

import xtrack as xt

# import a line and add reference particle
# import a line and add reference particle
line = xt.load(
    '../../test_data/hllhc15_noerrors_nobb/line_w_knobs_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

# Perform a set of operations with frozen longitudinal coordinates
with xt.freeze_longitudinal(line):
    # Track some particles with frozen longitudinal coordinates
    particles = line.build_particles(delta=1e-3, x=[-1e-3, 0, 1e-3])
    line.track(particles, num_turns=10)
    print(particles.delta) # gives [0.001 0.001 0.001], same as initial value

    # Twiss with frozen longitudinal coordinates (needs to be 4d)
    twiss = line.twiss(method='4d')
    print(twiss.slip_factor) # gives 0 (no longitudinal motion)

# 6d tracking is automatically restored when the with block is exited

# Track some particles with unfrozen longitudinal coordinates
particles = line.build_particles(delta=1e-3, x=[-1e-3, 0, 1e-3])
line.track(particles, num_turns=10)
print(particles.delta) # gives [0.00099218, ...], different from initial value

# Twiss with unfrozen longitudinal coordinates (can be 6d)
twiss = line.twiss(method='6d')
print(twiss.slip_factor) # gives 0.00032151, from longitudinal motion

# Complete source: xtrack/examples/freeze_longitudinal/001_freeze_context_manager.py

Freezing longitudinal coordinates with Line method

The xtrack.Line class provides a method called freeze_longitudinal() to explicitly freeze the longitudinal coordinates. The normal tracking mode, updating the longitudinal coordinates, can be restored by calling freeze_longitudinal(False). This is illustrated in the following example:

import xtrack as xt

# import a line and set reference particle
line = xt.load(
    '../../test_data/hllhc15_noerrors_nobb/line_w_knobs_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

# Freeze longitudinal coordinates
line.freeze_longitudinal()

# Track some particles with frozen longitudinal coordinates
particles = line.build_particles(delta=1e-3, x=[-1e-3, 0, 1e-3])
line.track(particles, num_turns=10)
print(particles.delta) # gives [0.001 0.001 0.001], same as initial value

# Twiss with frozen longitudinal coordinates (needs to be 4d)
twiss = line.twiss(method='4d')
print(twiss.slip_factor) # gives 0 (no longitudinal motion)

# Unfreeze longitudinal coordinates
line.freeze_longitudinal(False)

# Track some particles with unfrozen longitudinal coordinates
particles = line.build_particles(delta=1e-3, x=[-1e-3, 0, 1e-3])
line.track(particles, num_turns=10)
print(particles.delta) # gives [0.00099218, ...], different from initial value

# Twiss with unfrozen longitudinal coordinates (can be 6d)
twiss = line.twiss(method='6d')
print(twiss.slip_factor) # gives 0.00032151, from longitudinal motion

# Complete source: xtrack/examples/freeze_longitudinal/000_freeze_unfreeze_explicit.py

Time-dependent line properties

Time-dependent elements whose properties change slowly (compared to the revolution period) such as Bumpers or Tune-Ramps can be modelled using Time dependent knobs or Multisetters (the latter being more performant when a large number of elements is affected). For some specific use cases there exist also specialized elements, such as the xtrack.ACDipole.

If the time-dependent change is of the order of the revolution period or faster, specialized elements such as an Exciter beam element (time-dependent thin multipole) or xtrack.RFMultipole have to be used.

Time dependent knobs

To simulate the effect of time-changing properties of the beam line it is possible to control any lattice element attribute with a time-dependent function. For this purpose, the variable t_turn_s provides the time in seconds since the start of the simulation and is updated automatically every turn during tracking:

\[\verb|t_turn_s| = \verb|at_turn| \times \frac{L_0}{\beta_0 c_0}\]

where at_turn is the turn number of the reference particle, \(L_0\) is the line length (design circumference), \(\beta_0\) is the relativistic beta factor of the particle tracked first and \(c_0\) is the speed of light.

The simulation of an orbit bump driven by a sinusoidal function is shown in the following example.

import numpy as np
import matplotlib.pyplot as plt

import xtrack as xt

# Build a simple ring
env = xt.Environment()
pi = np.pi
lbend = 3
line = env.new_line(components=[
    # Three dipoles to make a closed orbit bump
    env.new('d0.1',  xt.Drift,  length=0.05),
    env.new('bumper_0',  xt.Bend, length=0.05, k0=0, h=0),
    env.new('d0.2',  xt.Drift, length=0.3),
    env.new('bumper_1',  xt.Bend, length=0.05, k0=0, h=0),
    env.new('d0.3',  xt.Drift, length=0.3),
    env.new('bumper_2',  xt.Bend, length=0.05, k0=0, h=0),
    env.new('d0.4',  xt.Drift, length=0.2),

    # Simple ring with two FODO cells
    env.new('mqf.1', xt.Quadrupole, length=0.3, k1=0.1),
    env.new('d1.1',  xt.Drift, length=1),
    env.new('mb1.1', xt.Bend, length=lbend, k0=pi / 2 / lbend, h=pi / 2 / lbend),
    env.new('d2.1',  xt.Drift, length=1),
    env.new('mqd.1', xt.Quadrupole, length=0.3, k1=-0.7),
    env.new('d3.1',  xt.Drift, length=1),
    env.new('mb2.1', xt.Bend, length=lbend, k0=pi / 2 / lbend, h=pi / 2 / lbend),
    env.new('d3.4',  xt.Drift, length=1),
    env.new('mqf.2', xt.Quadrupole, length=0.3, k1=0.1),
    env.new('d1.2',  xt.Drift, length=1),
    env.new('mb1.2', xt.Bend, length=lbend, k0=pi / 2 / lbend, h=pi / 2 / lbend),
    env.new('d2.2',  xt.Drift, length=1),
    env.new('mqd.2', xt.Quadrupole, length=0.3, k1=-0.7),
    env.new('d3.2',  xt.Drift, length=1),
    env.new('mb2.2', xt.Bend, length=lbend, k0=pi / 2 / lbend, h=pi / 2 / lbend),
])
line.set_particle_ref('proton', kinetic_energy0=50e6)

# Twiss
tw = line.twiss(method='4d')

# Power the correctors to make a closed orbit bump
line['bumper_strength'] = 0.
line['bumper_0'].k0 = '-bumper_strength'
line['bumper_1'].k0 = '2 * bumper_strength'
line['bumper_2'].k0 = '-bumper_strength'

# Drive the correctors with a sinusoidal function
T_sin = 100e-6
sin = line.functions.sin
line['bumper_strength'] = (0.1 * sin(2 * np.pi / T_sin * line.ref['t_turn_s']))

# --- Probe behavior with twiss at different t_turn_s ---

t_test = np.linspace(0, 100e-6, 15)
tw_list = []
bumper_0_list = []
for tt in t_test:
    line['t_turn_s'] = tt
    bumper_0_list.append(line['bumper_0'].k0) # Inspect bumper
    tw_list.append(line.twiss(method='4d')) # Twiss

# Plot
plt.close('all')
plt.figure(1, figsize=(6.4*1.2, 4.8*0.85))
ax1 = plt.subplot(1, 2, 1, xlabel='Time [us]', ylabel='x at bump center [mm]')
ax2 = plt.subplot(1, 2, 2, xlabel='s [m]', ylabel='x [mm]')

colors = plt.cm.jet(np.linspace(0, 1, len(t_test)))

for ii, tt in enumerate(t_test):
    tw_tt = tw_list[ii]
    ax1.plot(tt * 1e6, tw_tt['x', 'bumper_1'] * 1e3, 'o', color=colors[ii])
    ax2.plot(tw_tt.s, tw_tt.x * 1e3, color=colors[ii], label=f'{tt * 1e6:.1f} us')

ax2.set_xlim(0, tw_tt['s', 'bumper_2'] + 1)
plt.subplots_adjust(left=.1, right=.97, top=.92, wspace=.27)
ax2.legend()


# --- Track particles with time-dependent bumpers ---

num_particles = 100
num_turns = 1000

# Install monitor in the middle of the bump
monitor = xt.ParticlesMonitor(num_particles=num_particles,
                              start_at_turn=0,
                              stop_at_turn =num_turns)
line.insert('monitor', monitor, at='bumper_1@start')

# Generate particles
particles = line.build_particles(
                        x=np.random.uniform(-0.1e-3, 0.1e-3, num_particles),
                        px=np.random.uniform(-0.1e-3, 0.1e-3, num_particles))

# Enable time-dependent variables
line.enable_time_dependent_vars = True

# Track
line.track(particles, num_turns=num_turns, with_progress=True)

# Plot
plt.figure(2, figsize=(6.4*0.8, 4.8*0.8))
plt.plot(1e6 * monitor.at_turn.T * tw.t_rev0, 1e3 * monitor.x.T,
         lw=1, color='r', alpha=0.05)
plt.plot(1e6 * monitor.at_turn[0, :] * tw.t_rev0, 1e3 * monitor.x.mean(axis=0),
         lw=2, color='k')
plt.xlabel('Time [us]')
plt.ylabel('x [mm]')
plt.show()

# Complete source: xtrack/examples/toy_ring/006a_dynamic_bump_sin.py
_images/time_dep_knob_sin_twiss.png

Orbit bump behavior as obtained from the twiss for different settings of t_turn_s.

_images/time_dep_knob_sin_tracking.png

Beam position at the bump center during the tracking simulation. The red lines indicate the position of individual particles, the black line is their average position.

# Control the bumpers with a piece-wise linear function of time
# (outside the defined time interval, first and last point are held constant)
line.functions['my_fun'] = xt.FunctionPieceWiseLinear(
    x=np.array([10,    40,     70,   100]) * 1e-6, # time in s
    y=np.array([0,    0.5,    0.5,   1.0])        # value
)
line['bumper_strength'] = 0.1 * line.functions['my_fun'](line.ref['t_turn_s'])

# Complete source: xtrack/examples/toy_ring/006b_dynamic_bump_piece_wise_linear.py

Instead of built-in functions, it is also possible to use piece-wise linear functions defined by the user. For example, the function in the figure below can be obtained with the following code:

_images/time_dep_knob_pwlin_twiss.png

Orbit bump behavior as obtained from the twiss for different settings of t_turn_s.

_images/time_dep_knob_pwlin_tracking.png

Beam position at the bump center during the tracking simulation. The red lines indicate the position of individual particles, the black line is their average position.

It is also possible to combine piece-wise linear functions with built-in functions in the same expression. For example, the following code can be used to generate a modulated sinusoidal function:

# Control the bumpers with a modulated sinusoidal function of time
line.functions['pulse'] = xt.FunctionPieceWiseLinear(
    x=np.array([10, 50, 150, 190]) * 1e-6, # s
    y=np.array([0,   1,   1,   0])         # knob value
)

T_sin = 10e-6
sin = line.functions.sin
line['bumper_strength'] = (0.1 * line.functions['pulse'](line.ref['t_turn_s'])
                                * sin(2 * np.pi / T_sin * line.ref['t_turn_s']))

# Complete source: xtrack/examples/toy_ring/006c_dynamic_bump_sin_env.py
_images/time_dep_knob_sin_pulse_tracking.png

Beam position at the bump center during the tracking simulation. The red lines indicate the position of individual particles, the black line is their average position.

Multisetters

When the number of beam elements to be changed is very large, this can introduce a significant overhead on the simulation time. For these cases it is possible to use the xtrack.MultiSetter class, to perform the changes in a more efficient way, bypassing the expressions and acting directly on the element properties. Furthermore, the MultiSetter stores the memory addresses of the quantities to be changed and performs the changes with a single compiled kernel, using multithreading when allowed by the context.

The following example shows how to use the MultiSetter to apply a sinusoidal ripple to the strength of several quadrupoles of a synchrotron.

See also: xtrack.MultiSetter

import numpy as np
from cpymad.madx import Madx

import xobjects as xo
import xtrack as xt
import xpart as xp

# Choose a context

env = xt.load('../../test_data/sps_w_spacecharge/sps_thin.seq')
line = env.sps
line.set_particle_ref('proton', p0c=400e9)

# Switch on RF and twiss
line['acta.31637'].voltage = 7e6
line['acta.31637'].phase = np.pi
twxt = line.twiss()

# Get revolution period
t_rev = twxt['t_rev0']

# Extract list of elements to trim (all focusing quads)
tt = line.get_table()
elements_to_trim = tt.rows[tt.element_type == 'Multipole'].rows['qf.*'].name
# => contains ['qf.52010', 'qf.52210', 'qf.52410', 'qf.52610', 'qf.52810',
#              'qf.53010', 'qf.53210', 'qf.53410', 'qf.60010', 'qf.60210', ...]

# Build a custom setter
qf_setter = xt.MultiSetter(line, elements_to_trim,
                            field='knl', index=1 # we want to change knl[1]
                            )

# Get the initial values of the quad strength
k1l_0 = qf_setter.get_values()

# Generate particles to be tracked
# (we choose to match the distribution without accounting for spacecharge)
particles = xp.generate_matched_gaussian_bunch(
         num_particles=100, total_intensity_particles=1e10,
         nemitt_x=3e-6, nemitt_y=3e-6, sigma_z=15e-2,
         line=line)

# Define amplitude and phase of the quadrupole ripple
f_quad = 50. # Hz
A_quad = 0.01 # relative amplitude

# Track the particles and apply turn-by-turn change to all selected quads
num_turns = 2000

check_trim  = []

for ii in range(num_turns):
    if ii % 100 == 0: print(f'Turn {ii} of {num_turns}')

    # Change the strength of the quads
    k1l = k1l_0 * (1 + A_quad * np.sin(2*np.pi*f_quad*ii*t_rev))
    qf_setter.set_values(k1l)

    # Track one turn
    line.track(particles)

    # Log the strength of one quad to check
    check_trim.append(line['qf.52010'].knl[1])

# Plot the evolution of the quad strength
import matplotlib.pyplot as plt
plt.plot(check_trim)
plt.show()

# Complete source: xtrack/examples/multisetter/000_sps_50hz_ripple.py

Exciter beam element

The beam element xtrack.Exciter provides a model for a transverse exciter as a time-dependent thin multipole.

By providing an array of samples, and the sampling frequency, the element can provide an arbitrary excitation waveform.

This can be used for RFKO slow extraction, excitation tune measurement, power supply ripples, etc.

The given multipole components knl and ksl (normal and skew respectively) are multiplied according to an array of samples which allows for arbitrary time dependence:

\[\verb|knl|(t) = \verb|knl| \times \verb|samples|(t)\]

To provide for an arbitrary frequency spectrum, the variations are not assumed to be slow compared to the revolution frequency \(f_{rev}\), and the particle arrival time is taken into account when determining the sample index

\[\verb|i| = f_{samp} \times \left(\frac{n-n_0}{f_{rev}} - \frac{\zeta}{\beta_0 c_0}\right)\]

where \(\zeta=(s-\beta_0\cdot c_0\cdot t)\) is the longitudinal coordinate of the particle, \(\beta_0\) is the relativistic beta factor of the particle, \(c_0\) is the speed of light, \(n\) is the current turn number, \(f_{rev}\) is the revolution frequency, and \(f_{samp}\) is the sample frequency.

The excitation starts with the first sample when the reference particle arrives at the element at turn \(n_0\).

The samples can therefore be considered as a waveform sampled at the sampling frequency. To compute a sample for a sinusoidal excitation at frequency f_ex using NumPy:

samples[i] = np.sin(2*np.pi*f_ex*i/sampling_freq)

To generate the full samples array at sampling_freq sampling frequency, for n_turns turns at f_rev revolution frequency:

total_time = n_turns / f_rev
time = np.arange(0, total_time, 1/sampling_freq)
samples = np.sin(2*np.pi*f_ex*time)

To generate a chirp array at sampling_freq, between frequencies f_start and f_stop, lasting n_turns turns at f_rev revolution frequency:

chirp_time = n_turns / f_rev
time = np.arange(0, chirp_time, 1/sampling_freq)
samples = sp.signal.chirp(time, f_start, chirp_time, f_stop)
_images/exciter_signals.png

To then define an Exciter element with the custom waveform (array of samples at sampling frequency sampling_freq) and normal and skew components KNL and KSL:

# Create beam element
exciter = xt.Exciter(_context = ctx,
    samples = samples,
    sampling_frequency = sampling_freq,
    duration = None,  # defaults to waveform duration
    frev = f_rev,
    start_turn = 0,  # default, seconds
    knl = KNL,
    ksl = KSL,
)

# Add it to the line for tracking as usual
line.insert_element(
    element = exciter,
    name = 'RF_KO_EXCITER',
    index = 42,
)

The optional parameter duration (seconds) may be used to repeat (or truncate) the excitation waveform. It defaults to len(samples)/sampling_freq, the duration of samples.

The element also provides the read-only parameter order, the multipole order, equal to the order of the largest non-zero multipole component knl or ksl.

Acceleration

An energy ramp with an arbitrary time dependence of the beam energy can be simulated by attaching an xtrack.EnergyProgram object to the line, as shown in the example below.

import numpy as np
from cpymad.madx import Madx
import xtrack as xt

# Import a line
line = xt.load('../../test_data/psb_injection/line_and_particle.json')
line.set_particle_ref('proton', kinetic_energy0=160e6)

tw0 = line.twiss4d()

# User-defined energy ramp
t_s = np.array([0., 0.0006, 0.0008, 0.001 , 0.0012, 0.0014, 0.0016, 0.0018,
                0.002 , 0.0022, 0.0024, 0.0026, 0.0028, 0.003, 0.01, 0.1])
E_kin_GeV = np.array([0.16000000,0.16000000,
    0.16000437, 0.16001673, 0.16003748, 0.16006596, 0.16010243, 0.16014637,
    0.16019791, 0.16025666, 0.16032262, 0.16039552, 0.16047524, 0.16056165,
    0.163586, 0.20247050000000014])

# Attach energy program to the line
line.energy_program = xt.EnergyProgram(t_s=t_s, kinetic_energy0=E_kin_GeV*1e9)

# Plot energy and revolution frequency vs time
t_plot = np.linspace(0, 10e-3, 20)
E_kin_plot = line.energy_program.get_kinetic_energy0_at_t_s(t_plot)
f_rev_plot = line.energy_program.get_frev_at_t_s(t_plot)

import matplotlib.pyplot as plt
plt.close('all')
plt.figure(1, figsize=(6.4 * 1.5, 4.8))
ax1 = plt.subplot(2,2,1)
plt.plot(t_plot * 1e3, E_kin_plot * 1e-6)
plt.ylabel(r'$E_{kin}$ [MeV]')
ax2 = plt.subplot(2,2,3, sharex=ax1)
plt.plot(t_plot * 1e3, f_rev_plot * 1e-3)
plt.ylabel(r'$f_{rev}$ [kHz]')
plt.xlabel('t [ms]')

# Setup frequency of the RF cavity  to stay on the second harmonic of the
# revolution frequency during the acceleration

t_rf = np.linspace(0, 3e-3, 100) # time samples for the frequency program
f_rev = line.energy_program.get_frev_at_t_s(t_rf)
h_rf = 2 # harmonic number
f_rf = h_rf * f_rev # frequency program

# Build a function with these samples and link it to the cavity
line.functions['fun_f_rf'] = xt.FunctionPieceWiseLinear(x=t_rf, y=f_rf)
line['br.c02'].frequency = line.functions['fun_f_rf'](line.ref['t_turn_s'])

# Setup voltage and phase
line['br.c02'].voltage = 3000 # V
line['br.c02'].phase = 0 # rad

# When setting line['t_turn_s'] the reference energy and the rf frequency
# are updated automatically
line['t_turn_s'] = 0
line.particle_ref.kinetic_energy0 # is 160.00000 MeV
line['br.c02'].frequency # is 1983931.935 Hz

line['t_turn_s'] = 3e-3
line.particle_ref.kinetic_energy0 # is 160.56165 MeV
line['br.c02'].frequency # is 1986669.0559674294

# Back to zero for tracking!
line['t_turn_s'] = 0

# Track a few particles to visualize the longitudinal phase space
p_test = line.build_particles(x_norm=0, zeta=np.linspace(0, line.get_length(), 101))

# Enable time-dependent variables (t_turn_s and all the variables that depend on
# it are automatically updated at each turn)
line.enable_time_dependent_vars = True

# Track
line.track(p_test, num_turns=9000, turn_by_turn_monitor=True, with_progress=True)
mon = line.record_last_track

# Plot
plt.subplot2grid((2,2), (0,1), rowspan=2)
plt.plot(mon.zeta[:, -2000:].T, mon.delta[:, -2000:].T, color='C0')
plt.xlabel(r'$\zeta$ [m]')
plt.ylabel('$\delta$')
plt.xlim(-40, 30)
plt.ylim(-0.0025, 0.0025)
plt.title('Last 2000 turns')
plt.subplots_adjust(left=0.08, right=0.95, wspace=0.26)


# Check transverse beam size reduction
line['t_turn_s'] = 0
line.enable_time_dependent_vars = False

n_part_test = 500
# Generate Gaussian distribution with fixed rng seed
rng = np.random.default_rng(seed=123)
x_norm = rng.normal(loc=0, scale=1, size=n_part_test)
px_norm = rng.normal(loc=0, scale=1, size=n_part_test)
y_norm = rng.normal(loc=0, scale=1, size=n_part_test)
py_norm = rng.normal(loc=0, scale=1, size=n_part_test)

# rescale to have exact std dev.
x_norm = x_norm / np.std(x_norm)
px_norm = px_norm / np.std(px_norm)
y_norm = y_norm / np.std(y_norm)
py_norm = py_norm / np.std(py_norm)

p_test2 = line.build_particles(x_norm=x_norm, px_norm=px_norm,
                               y_norm=x_norm, py_norm=px_norm,
                               nemitt_x=3e-6, nemitt_y=3e-6,
                               delta=0)

line.enable_time_dependent_vars = True
line.track(p_test2, num_turns=50_000, turn_by_turn_monitor=True, with_progress=True)
mon2 = line.record_last_track

std_y = np.std(mon2.y, axis=0)
std_x = np.std(mon2.x, axis=0)

# Apply moving average filter
from scipy.signal import savgol_filter
std_y_smooth = savgol_filter(std_y, 10000, 2)
std_x_smooth = savgol_filter(std_x, 10000, 2)

i_turn_match = 10000
std_y_expected = std_y_smooth[i_turn_match] * np.sqrt(
    mon2.gamma0[0, i_turn_match]* mon2.beta0[0, i_turn_match]
    / mon2.gamma0[0, :] / mon2.beta0[0, :])
std_x_expected = std_x_smooth[i_turn_match] * np.sqrt(
    mon2.gamma0[0, i_turn_match]* mon2.beta0[0, i_turn_match]
    / mon2.gamma0[0, :] / mon2.beta0[0, :])

d_sigma_x = std_x_expected[0] - std_x_expected[-1]
d_sigma_y = std_y_expected[0] - std_y_expected[-1]

import xobjects as xo
xo.assert_allclose(std_y_expected[40000:45000].mean(),
                   std_y_smooth[40000:45000].mean(),
                   rtol=0, atol=0.07 * d_sigma_y)
xo.assert_allclose(std_x_expected[40000:45000].mean(),
                   std_x_smooth[40000:45000].mean(),
                   rtol=0, atol=0.07 * d_sigma_x)

plt.figure(2)
ax1 = plt.subplot(2,1,1)
plt.plot(std_x, label='raw')
plt.plot(std_x_smooth, label='smooth')
plt.plot(std_x_expected, label='expected')
plt.legend()

ax2 = plt.subplot(2,1,2, sharex=ax1)
plt.plot(std_y, label='raw')
plt.plot(std_y_smooth, label='smooth')
plt.plot(std_y_expected, label='expected')


plt.show()

# Complete source: xtrack/examples/acceleration/001_energy_ramp.py
_images/acceleration.png

Time evolution of the beam energy and the RF frequency and particle motion in the longitudinal phase space as obtained from the example above.

Off-momentum from RF frequency change

By default, the RF cavities in Xtrack are synchronized with the reference particle (simply because of the coordinate choice). For this reason a change of the RF frequency does not result in a change in the revolution frequency. To obtain a change in the revolution frequency (and hence in the momentum) it is necessary to introduce explicitly a time delay, using the element xtrack.ZetaShift. This is illustrated in the following example:

import numpy as np
import xtrack as xt

# Load a line
line = xt.load('../../test_data/hllhc15_noerrors_nobb/line_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

# Frequency trim to make
df_hz = 50 # Frequency trim

# Twiss
tw0 = line.twiss()

# Compute corresponding delay to be introduced in the line:
#
# t_rev = h_rf/f_rf
# dt = h_rf/(f_rf + df_hz) - h_rf/f_rf = h_rf/f_rf (1/(1+df_hz/f_rf) - 1)
#                                       ~= h_rf/f_rf * (1 - df_hz/f_rf -1)
#                                       = -h_rf/(f_rf^2) * df_hz
#                                       = -t_rev / f_rf * df_hz
# dzeta = -beta0 * clight * dt = circumference * df_hz / f_rf

h_rf = 35640
f_rf = h_rf/tw0.t_rev0
beta0 = line.particle_ref.beta0[0]
dzeta = tw0.line_length * df_hz / f_rf

# Append delay element to the line
line.append('time_delay', xt.TimeDelay(shift_zeta=dzeta))

# Twiss
tw1 = line.twiss()

# Expected momentum from slip factor (eta = -df_rev / f_rev / delta)
f_rev = 1/tw0.t_rev0
df_rev = df_hz / h_rf
eta = tw0.slip_factor
delta_expected = -df_rev / f_rev / eta

tw1.delta[0]    # is -0.00035789
delta_expected  # is -0.00035803

# Check that particle stays off momentum in multi-turn tracking
p = tw1.particle_on_co.copy()

p_test = line.build_particles(x_norm=0,
            delta=np.linspace(delta_expected - 8e-4, delta_expected + 8e-4, 60))
# p_test = line.build_particles(x_norm=0, delta=delta_expected,
#                               zeta=np.linspace(0, 0.5, 101))

# Track
line.track(p_test, num_turns=1000, turn_by_turn_monitor=True, with_progress=True)
mon = line.record_last_track

# Plot
import matplotlib.pyplot as plt
plt.close('all')
plt.figure()
plt.plot(mon.zeta[:, :].T, mon.delta[:, :].T * 1e4, color='C0')
plt.xlabel(r'$\zeta$ [m]')
plt.ylabel(r'$\delta$ [$10^{-4}$]')
plt.xlim(-.8, .8)
plt.ylim(delta_expected * 1e4 - 4, delta_expected * 1e4 + 4)
plt.axhline(delta_expected * 1e4, color='r', linestyle='--',
            label=r'$\delta$ expected')
plt.show()

# Complete source: xtrack/examples/radial_steering/000_radial_steering.py
_images/radial_steering.png

Longitudinal phase space from tracking. The bucket is centered around the expected momentum.

Optimize line for multi-turn tracking speed

When the tracker is used for multi-turn tracking, the line and tracker can be optimized to increase the tracking speed. This can be done with the Line.optimize_for_tracking() method, as shown in the following example.

See also: Line.optimize_for_tracking()

import time
import numpy as np

import xtrack as xt
import xpart as xp
import xobjects as xo

#################################
# Load a line and build tracker #
#################################
line = xt.load('../../test_data/hllhc15_noerrors_nobb/line_w_knobs_and_particle.json')
line.set_particle_ref('proton', p0c=7e12)

###########################
# Generate some particles #
###########################

particles = line.build_particles(
    x_norm=np.linspace(-2, 2, 1000), y_norm=0.1, delta=3e-4,
    nemitt_x=2.5e-6, nemitt_y=2.5e-6)

p_no_optimized = particles.copy()
p_optimized = particles.copy()

##############################
# Track without optimization #
##############################

num_turns = 10
line.track(p_no_optimized, num_turns=num_turns, time=True)
t_not_optimized = line.time_last_track

####################
# Optimize tracker #
####################

line.optimize_for_tracking()

# This performs the following actions (physics model is unchanged):
# - Disables xdeps expressions
# - Removes inactive multipoles
# - Merges consecutive multipoles
# - Removes drifts with zero length
# - Merges consecutive drifts

###########################
# Track with optimization #
###########################

line.track(p_optimized, num_turns=num_turns, time=True)
t_optimized = line.time_last_track

#################
# Compare times #
#################

num_particles = len(p_no_optimized.x)
print(f'Time not optimized {t_not_optimized*1e6/num_particles/num_turns:.1f} us/part/turn')
print(f'Time optimized {t_optimized*1e6/num_particles/num_turns:.1f} us/part/turn')

###################################
# Check that result are identical #
###################################

assert np.all(p_no_optimized.state == 1)
assert np.all(p_optimized.state == 1)

xo.assert_allclose(p_no_optimized.x, p_optimized.x, rtol=0, atol=1e-14)
xo.assert_allclose(p_no_optimized.y, p_optimized.y, rtol=0, atol=1e-14)
xo.assert_allclose(p_no_optimized.px, p_optimized.px, rtol=0, atol=1e-14)
xo.assert_allclose(p_no_optimized.py, p_optimized.py, rtol=0, atol=1e-14)
xo.assert_allclose(p_no_optimized.zeta, p_optimized.zeta, rtol=0, atol=1e-12)
xo.assert_allclose(p_no_optimized.delta, p_optimized.delta, rtol=0, atol=1e-14)

# Complete source: xtrack/examples/optimized_tracker/000_optimized_tracker.py