Upgrade Guide

This guide covers the changes that need attention when moving an existing script or build to a newer ImpactX version: changed behavior, replaced APIs, and raised requirements. Newest release first.

26.11

Maximum multipole order

Multipole raises a ValueError for multipole > 13, and ExactMultipole and ExactCFbend for k_normal and k_skew arrays longer than 12 and 5 entries, respectively. Importing a MAD-X MULTIPOLE with a nonzero KNL or KSL entry above index 12 raises the same error.

Look for high-order terms in your lattices and for arrays padded with zeros, and remove the zero entries:

elements.ExactMultipole(ds=0.2, k_normal=[0.0, k1, 0.0, 0.0], k_skew=[0.0, 0.0, 0.0, 0.0])
# same field
elements.ExactMultipole(ds=0.2, k_normal=[0.0, k1], k_skew=[0.0, 0.0])

DipEdge: default linear model changed to linear_slac75

For the DipEdge element, there were previously two models: linear (default) and nonlinear.

Both of these models were based on the paper:

  1. Hwang and S. Y. Lee, “Dipole fringe field map for compact synchrotrons”, Phys. Rev. ST Accel. Beams 18, 122401 (2015),

which performs an expansion in powers of g/rc, where g is the magnetic gap, and rc is the bend radius of curvature.

In this release, the default model (linear, which is now an alias for the new linear_slac75) has been changed to coincide with the linear part of the map described in:

  1. Brown, “A First- and Second-Order Matrix Theory for the Design of Beam Transport Systems and Charged Particle Spectrometers”, SLAC Report-75, 1982.

The previous default linear model is still available as linear_hwang_lee. It coincides with linear_slac75 through first order in g/rc.

The nonlinear DipEdge model is unchanged, and is now an alias for nonlinear_hwang_lee.

The new linear default model linear_slac75 was chosen to match the commonly used MAD-X model.

DipEdge: reference particle deflection with modify_ref_part = True

With modify_ref_part = True, the nonlinear DipEdge model now deflects the reference particle by the angle by which it deflects a beam particle on the reference orbit with modify_ref_part = False. Previously, the sine of the reference deflection angle had an extra factor of \(1/(\beta\gamma)\). This changes the reference trajectory, and the beam coordinates relative to it, downstream of such an edge.

Elements and distributions take keyword arguments only

The constructors of all elements in impactx.elements and all distributions in impactx.distribution take their arguments by keyword only. These arguments can still be passed by position:

What to check in your scripts: a constructor call that passes any other value by position raises a TypeError. This includes super().__init__(...) in a subclass. Name these arguments:

quad = elements.Quad(0.5, 1.2)                    # before
quad = elements.Quad(ds=0.5, k=1.2)               # now

pge = elements.Programmable(0.5, 2)               # before
pge = elements.Programmable(ds=0.5, nslice=2)     # now

At fixed \(t\), the longitudinal attributes are named position_z and momentum_z

While the beam is at fixed \(t\), inside a at_fixed_t() block or after coordinate_transformation() to CoordSystem.t, the longitudinal attributes are named position_z and momentum_z. Previously, they kept the names position_t and momentum_t while holding \(z\) and \(p_z\).

What to check in your scripts: code that reads position_t or momentum_t by name while the beam is at fixed \(t\) raises a KeyError. Use the new names:

with sim.beam.at_fixed_t() as beam:
    for pti in ImpactXParIter(beam, level=0):
        soa = pti.soa().to_xp()
        z = soa.real["position_t"]   # before
        z = soa.real["position_z"]   # now

Access by index, e.g., soa.get_real_data()[2], is unchanged. A BeamMonitor and beam.plot_phasespace() now raise at fixed \(t\), where they used to label \(z\) and \(p_z\) as \(t\) and \(p_t\); use them at fixed \(s\).

Particle weights count real particles, also for ions

The weight of a particle is the number of real particles it represents, each with the charge of the reference particle, in all collective effects (space charge, CSR) and in the beam charge charge_C. Previously, weights set from a bunch charge counted elementary charges, and so did the 1D charge deposition of the Gauss2p5D, 2p5D and CSR models for all weights. This changes the results for ions with a charge other than \(\pm q_e\), which are set up in Python.

What to check in your scripts with ions:

  • sim.add_particles(bunch_charge, distr, npart) and beam.add_n_particles(..., bunch_charge=...) set up particles of the total charge bunch_charge. Before, charge_C read \(|Z|\) times the bunch charge.

  • Weights passed as w are the number of real particles:

    w = np.full(npart, bunch_charge / scipy.constants.e / npart)  # before
    w = np.full(npart, bunch_charge / abs(sim.beam.ref.charge) / npart)  # now
    
  • Ion beams that a BeamMonitor wrote with an earlier version carry weights in elementary charges, \(|Z|\) times the number of real particles.

What to check in all scripts: add_n_particles() raises a RuntimeError for a negative bunch_charge: it is a magnitude, and the sign of the charge is the one of the reference particle. It also raises for a nonzero bunch_charge if the reference particle has no charge yet. Set up the reference particle first:

sim.beam.ref.set_mass_MeV(3727.4).set_charge_qe(2.0).set_kin_energy_MeV(1.0e3)
sim.beam.add_n_particles(x, y, t, px, py, pt, qm, bunch_charge=1.0e-9)

wakeconvolution: charge density with sign, derivative_charge without GetNumberDensity

wakeconvolution.deposit_charge deposits the charge \(q w\) of each particle, with the charge \(q\) of the reference particle: the charge density is negative for electrons. wakeconvolution.derivative_charge returns the slopes of this charge density.

What to check in your scripts: derivative_charge with a fourth argument GetNumberDensity raises a TypeError. Remove the argument and divide the slopes by the reference particle charge for the number density:

wakeconvolution.derivative_charge(charge_distribution, slopes, bin_size, True)  # before

wakeconvolution.derivative_charge(charge_distribution, slopes, bin_size)  # now
slopes.to_xp()[:] /= sim.beam.ref.charge  # number density

ExactCFbend: the skew dipole coefficient deflects the particles

The skew dipole coefficient k_skew[0] of ExactCFbend now deflects the particles vertically: it changes py by k_skew[0] per meter (divided by the magnetic rigidity with unit=1). Previously, only the spin push used it. This changes the results of lattices with a nonzero k_skew[0] in an ExactCFbend.

ExactCFbend: sign of the skew decapole

The horizontal kick of the skew decapole coefficient k_skew[4] of ExactCFbend now has the sign of its field: to leading order, the kick of the same coefficient in ExactMultipole. Previously, this kick and the vertical field in the spin push had the opposite sign, so the particle map was not symplectic. This changes the results of lattices with a nonzero k_skew[4] in an ExactCFbend.

MAD-X BEAM: reference particle and energy as in MAD-X

RefPart.load_file and KnownElementsList.load_file now resolve each BEAM command of a MAD-X file following MAD-X. Previously, only ENERGY was read, so PC, GAMMA, BETA and BRHO left 1 GeV: remove workarounds that set the energy after loading.

What to check in your MAD-X files:

BEAM, ENERGY=2;                 ! now a positron: add PARTICLE
BEAM, SEQUENCE=B2, BV=-1;       ! now a positron at 1 GeV: add PARTICLE and ENERGY
BEAM, PARTICLE=ION, MASS=193.7, CHARGE=82, ENERGY=574;  ! now uses MASS and CHARGE

! now errors
BEAM, MASS=2, CHARGE=1;         ! the 1 GeV default is below the mass: add ENERGY
BEAM, PARTICLE=PROTN, PC=2;     ! an unknown particle needs a MASS
BEAM, PARTICLE="PROTON", PC=2;  ! a quoted name keeps its case, also in SEQUENCE and USE
BEAM, ENERGIE=3;                ! an unknown parameter
BEAM, ENERGY=2 PC=3;            ! a number without a comma
USE, SEQUENCE=FOOD;             ! an unknown sequence, in KnownElementsList.load_file

RefPart.load_file also raises without BEAM or a valid reference particle. KnownElementsList.load_file raises for USE without BEAM, an RFCAVITY with VOLT but no valid mass, and a NaN or infinite attribute of an element in use, and warns otherwise.

Also as in MAD-X: CIRC sets FREQ0, a parameter without a value is zero, a label does not change a command, beam->energy reads and sets BEAM parameters, RESBEAM resets a beam, redefining a constant warns, math outside of its domain gives NaN or infinity, and FRAC(-2.5) is -0.5. Masses now use the MAD-X constants, a change of at most 4 parts in \(10^8\).

Thermal: invalid parameters raise an error

Thermal parameters without a stationary radial density, which mostly gave NaN coordinates, now raise an error, e.g., a RuntimeError in sim.add_particles.

What to check in your scripts and inputs files:

  • normalize or normalize_halo for which the space charge exceeds the focusing on the axis makes the radial density diverge: reduce it below the limit in the error message.

  • halo > 0 with normalize_halo = 0: for a beam without a halo, set halo = 0.

  • halo < 1 with normalize = 0: for a beam without a core, set halo = 1.

MAD-X files: powers and signs

KnownElementsList.load_file and RefPart.load_file now evaluate a sign before a power in MAD-X files as MAD-X does: -a^b is -(a^b). A chained power, a^b^c, a sign directly after an operator, as in a*-b or a^-b, and two signs in a row, --a, now raise a MADXInputError, because MAD-X rejects them or evaluates them differently from the usual rules.

What to check in your MAD-X files: a sign directly before a power, more than one ^ in an expression, and a sign directly after an operator or another sign. A subtraction, a-b^2, is not affected. To keep the previous values, add parentheses:

k = (-a)^b;      ! previously -a^b:   -2^2 was 4, now -4
k = a^(b^c);     ! previously a^b^c,  now an error
k = a*(-b);      ! previously a*-b,   now an error
k = a*(-b)^c;    ! previously a*-b^c, now an error
k = a^((-b)^c);  ! previously a^-b^c, now an error
k = -(-a);       ! previously --a,    now an error

Hminus: gyromagnetic anomaly follows the shielded proton moment

The species Hminus now sets the gyromagnetic anomaly \(a = -3.7958216277\), the value for the magnetic moment of the shielded proton. Previously, it set the proton value \(a = 1.7928473446\), which together with the negative charge reversed the magnetic moment and the direction of spin precession.

What to check in your scripts: spin tracking with set_species("Hminus") or beam.particle = Hminus gives different spin results. Orbits are not affected, nor is an anomaly set explicitly after selecting the species. To compare with earlier results, set the previous value:

ref.set_species("Hminus").set_gyromagnetic_anomaly(1.7928473446)

PolygonAperture: periodic polygons are repeated by translation

With repeat_x or repeat_y, PolygonAperture now repeats the polygon by translation with that period. Previously, it reflected negative coordinates, which mirrored polygons that are not symmetric about \(x = 0\) or \(y = 0\). This changes the results of periodic polygon apertures with such polygons.

Aperture: overlapping shifted rows act as their union

With shift_odd_x and aperture_y > repeat_y / 2, the shifted rows of Aperture overlap. The aperture now acts as the union of all rows; previously, each row was cut at its edges.

What to check in your scripts and inputs files: shift_odd_x with aperture_y > repeat_y / 2. For the rectangular shape, a plane without a boundary, aperture_y = 0, gives the previous result; the elliptical shape has no exact replacement:

Aperture(aperture_x=0.1e-3, aperture_y=0.7e-3, repeat_x=1.0e-3, repeat_y=1.0e-3, shift_odd_x=True)  # before
Aperture(aperture_x=0.1e-3, aperture_y=0.0, repeat_x=1.0e-3, repeat_y=1.0e-3, shift_odd_x=True)  # now

New in this release

  • beam.at_fixed_t() represents the beam at fixed \(t\) inside a with block, e.g., to exchange particles with a code that uses time as the independent variable. The beam returns to fixed \(s\) when the block ends, also if it raises.

  • Programmable.includes_collective_effects declares that a push already models collective effects, e.g., by calling an external code. ImpactX then applies no additional space charge, wakefield, CSR or ISR kicks for this element.

26.10

sim.lattice holds elements

The lattice now holds the element objects it is given, the way a Python list holds its items. Previously it stored a copy of each element.

q = elements.Quad(ds=0.3, k=2.0)
sim.lattice.append(q)

assert sim.lattice[0] is q
q.k = 3.0                       # applies to tracking

What to check in your scripts: previously, when storing an element in a variable and adding that variable more than once used to place independent copies. Now, this places the same element at several positions. Changing the variable (tuning the element) afterwards affects every one of those positions.

q = elements.Quad(ds=0.3, k=2.0)
sim.lattice.extend([q, q])      # one element at two positions

The same holds for extend(), which holds every element of the list it is given. A repeated cell is the pattern most likely to be affected:

cell = [elements.Drift(ds=0.25), elements.Quad(ds=1.0, k=1.0)]
sim.lattice.extend(cell * 3)    # 6 positions, 2 elements

This is harmless for elements that carry no per-position state, which is the common case: a BeamMonitor at the head and tail of a lattice, or a drift repeated through a FODO cell, behave as before. It matters where each position is expected to be tuned separately.

For separate elements, construct one per position or add a copy:

sim.lattice.append(elements.Quad(ds=0.3, k=2.0))
sim.lattice.append(elements.Quad(ds=0.3, k=2.0))

template = elements.Quad(ds=0.3, k=2.0)
sim.lattice.extend([template.copy(), template.copy()])

To repeat a cell as independent elements, copy the list per repetition:

for _ in range(3):
    sim.lattice.extend([element.copy() for element in cell])

sim.tracking_element writes take effect

sim.tracking_element yields the element being tracked, so writing to it from a hook changes the push that follows. It previously yielded a copy, and such writes were discarded.

If a hook retunes an element relative to its own current value, and that element occupies several positions, read the reference value once before tracking instead of reading it back from the element:

phase_shift = rf.phase          # once, before tracking

def hook_before_element(sim):
    element = sim.tracking_element
    if type(element) is elements.RFCavity:
        element.phase = optimize(sim.beam.ref, element) + phase_shift

The same applies to the free functions impactx.reverse() and impactx.push(), which now act on the element passed in.

Changing the lattice during tracking

Adding or removing elements from a tracking hook raises, because tracking is walking the sequence at that moment. Changing an element’s own parameters from a hook is unaffected and remains the intended way to retune a lattice mid-run.

sim.lattice needs its simulation

A lattice reached through sim.lattice belongs to that simulation and does not keep it alive. Using the lattice after the simulation is gone raises, where it used to keep working:

def build():
    sim = ImpactX()
    sim.lattice.extend(cell)
    return sim.lattice        # the simulation ends here

lattice = build()
len(lattice)                  # raises

Return the simulation, or keep a reference to it for as long as you use its lattice. Alternatively, keep the lattice alive across simulations by storing it in a pure Python list and call extend() directly before tracking, see Manipulate a Lattice.

Selections describe the lattice they were taken from

select() returns a set of positions. Adding, removing or moving elements afterwards makes those positions describe something else, so the selection raises rather than reporting the wrong elements:

quads = sim.lattice.select(kind="Quad")
sim.lattice.append(elements.Drift(ds=0.1))
quads[0]                      # raises; select() again

Changing an element’s own parameters moves nothing and leaves a selection usable.

select(kind=...) matches the element kind

An element written as a Python subclass is still of its element kind, so select() with kind="Drift" or kind=elements.Drift now matches it. The name of the subclass matches as well.

replace_each() needs a template it can copy

replace_each() copies the template into each selected position, so a Python subclass must define copy(). Passing one that does not raises, where it previously inserted plain base-class elements.

finalize() always empties the lattice

sim.finalize() releases the elements whether or not init_grids() was ever called. They have been finalized by then, so keeping them would leave elements that are done with, e.g., a BeamMonitor with its output closed, still in the lattice.

Setting a single aperture plane represents a jaw

An element that sets only one of aperture_x or aperture_y now represents a jaw (slit) aperture: with only aperture_x set, particles outside the slab |x| <= aperture_x, which is unbounded in y, are lost. This makes the beam pipe of the thick elements behave like the Aperture collimator (see the convention for inputs files and Python). Previously, a beam pipe with one plane set and the other left at zero, the default, applied no aperture at all, and the whole beam passed.

What to check in your scripts: look for elements that give a positive value to exactly one of aperture_x and aperture_y, in Python or in an inputs file:

elements.Drift(ds=0.1, aperture_x=1e-4)   # loses particles with |x| > 1e-4
drift1.type = drift
drift1.ds = 0.1
drift1.aperture_x = 1e-4

Where such an element used to transmit the whole beam, it now removes particles, which changes the transmitted charge and every beam moment downstream of it.

To keep the beam pipe open, as the element used to behave, leave out the half-aperture (or set it to zero):

elements.Drift(ds=0.1)

To bound the beam in both planes, set both:

elements.Drift(ds=0.1, aperture_x=1e-4, aperture_y=1e-4)

The Aperture collimator follows the same convention. A half-aperture of zero or less now removes the boundary in that plane, where the constructor used to raise. For example, elements.Aperture(aperture_x=0, aperture_y=1e-3) is a jaw (slit) that cuts only in y.

New in this release

  • copy() on every element type, for a new element with the same configuration. Keyword arguments give the copy a different value for a parameter, so that one element can serve as the template for many: [quad.copy(k=k) for k in scan].

  • The array-valued element parameters (Fourier coefficients, multipole coefficients and polygon vertices) can be set after construction, via their properties or the paired setter (set_coefficients(), set_vertices()).

  • sim.lattice supports additional list operations: slices, negative indices, insert(), remove(), index(), count(), in, del, lattice[i] = element and reversed(). pop_back() returns the element it removed, and a position that is not there raises IndexError.

  • lattice.generation counts the structural edits made to a lattice.