Top-level package

The top-level package identifies the available subsystems. Public classes and functions are exported by their respective subpackages rather than flattened into this namespace.

Utilities for working with accelerator descriptors, MAD-NG, MAD-X, and model workflows.

class pymadng_utils.FCC(sequence_file, kinetic_energy=None, bpm_pattern='^BPM_.*$', particle='electron', mode='z', **kwargs)[source]

Bases: Accelerator

FCC-ee (LCC optics) accelerator configuration.

The LCC lattices are a single ring (fccee_p_ring) with lower-case element names: BPMs bpm_<quad>, quadrupoles q*, and paired correctors hcor_<quad> / vcor_<quad> (MAD-X kicker with hkick / vkick). MAD-NG upper-cases element names when loading the madx, so the Lua patterns here are upper case (MAD-X variables stay lower case).

Initialise the FCC-ee accelerator.

Parameters:
  • sequence_file (Path | str) – Path to the MAD-X sequence file (e.g. fccee_z.madx)

  • kinetic_energy (float | None) – Particle kinetic energy in GeV (default: the mode’s beam energy minus the particle mass)

  • bpm_pattern (str) – Pattern for selecting BPMs

  • particle (str) – Type of particle (default “electron”; MAD-NG runs with nocharge as the madx ignores the charge)

  • mode (str) – FCC-ee running mode, one of z, w, h, t

Raises:

ValueError – If an unknown mode is given

SEQUENCE_NAME = 'fccee_p_ring'
BPM_PATTERN = '^BPM_.*$'
CORRECTOR_PATTERN = '^[HV]COR_'
QUAD_REL_STD = 0.005

Relative k1 calibration error used for the FCC-ee LOCO studies.

RBARC = True

The LCC madx is written for MAD-X’s default rbarc=true (rbend l is the chord).

NOCHARGE = True

Ignore the beam charge like MAD-X does (otherwise an electron flips every magnet strength).

property seq_name: str

Return the sequence name of the FCC-ee ring.

property tune_variables: tuple[str, str]

The LCC lattice files define no tune knobs.

property tune_integers: tuple[int, int]

Return the integer tunes (Z lattice).

property ac_dipole_name: str

FCC-ee has no AC dipole.

get_perturbation_families()[source]

Return perturbation-family metadata for FCC-ee magnets.

Return type:

dict[str, dict[str, float | str | dict]]

class pymadng_utils.LHC(beam, sequence_file, kinetic_energy=6800.0, bpm_pattern='^BPM.*$', particle='proton', tune_knobs_suffix='_op', seq_dir=None, **kwargs)[source]

Bases: Accelerator

Large Hadron Collider accelerator configuration.

Holds the beam number, sequence direction, BPM pattern, operational tune knobs (dqx_b<beam><suffix>) and the integer tunes (62, 60).

Initialise LHC accelerator for a specific beam.

Parameters:
  • beam (int) – Beam number (1 or 2)

  • sequence_file (Path | str) – Path to sequence file

  • kinetic_energy (float) – Particle kinetic energy in GeV (default 6800 GeV for LHC)

  • bpm_pattern (str) – Pattern for selecting BPMs

  • particle (str) – Type of particle (default “proton”)

  • tune_knobs_suffix (str) – Suffix of the MAD-X tune knobs dqx_b<beam> / dqy_b<beam>

  • seq_dir (int | None) – MAD-NG sequence direction. Required for beam 2: -1 for the MAD-X beam-2 sequence (listed in beam-1 order), 1 for the beam-4 tracking sequence (also named lhcb2). Defaults to 1 for beam 1.

Raises:

ValueError – If an invalid beam number is provided

BPM_PATTERN = '^BPM.*$'
QUAD_ERROR_TABLE: ClassVar[dict[str, float]] = {'MQ.': 0.0018, 'MQM': 0.0012, 'MQW': 0.0015, 'MQX': 0.001, 'MQY': 0.0008}
property seq_name: str

Return the sequence name for this LHC beam.

property tune_variables: tuple[str, str]

Return LHC operational tune knob names.

property tune_integers: tuple[int, int]

Return LHC integer tunes.

property ac_dipole_name: str

Return the LHC AC-dipole element name.

get_perturbation_families()[source]

Return perturbation-family metadata for LHC magnets.

Return type:

dict[str, dict[str, float | str | dict]]

class pymadng_utils.PSB(sequence_file, ring=None, kinetic_energy=0.16, bpm_pattern=None, particle='proton', **kwargs)[source]

Bases: Accelerator

Proton Synchrotron Booster accelerator configuration.

Parameters:
  • sequence_file (Path | str)

  • ring (int | None)

  • kinetic_energy (float)

  • bpm_pattern (str | None)

  • particle (str)

BPM_PATTERN_TEMPLATE = '^BR{ring}%.BPM.*{ring}$'
SEXTUPOLE_PATTERN = '^BR%d+%.XNO.*'
property seq_name: str

Return the sequence name for the selected PSB ring.

property ac_dipole_name: str

Return the PSB AC-dipole installation element.

property tune_variables: tuple[str, str]

Return PSB tune variable names.

property tune_integers: tuple[int, int]

Return PSB integer tunes.

static infer_monitor_plane(bpm_name)[source]

Return "HV" (both planes) for a PSB monitor name; raise for other names.

Parameters:

bpm_name (str)

Return type:

str

class pymadng_utils.AcceleratorErrorsMadInterface(accelerator, **mad_kwargs)[source]

Bases: AcceleratorMadInterface

MAD interface variant that applies accelerator-specific startup errors.

Initialise base MAD interface.

Starts a MAD-NG process, then loads the accelerator’s sequence and sets its beam. If loading fails the process is closed before the error propagates.

Parameters:
  • accelerator (Accelerator) – Accelerator configuration object

  • **mad_kwargs – Keyword arguments passed to pymadng.MAD()

class pymadng_utils.AcceleratorMadInterface(accelerator, **mad_kwargs)[source]

Bases: object

Base class for MAD-NG interfaces providing core functionality.

This class provides essential MAD-NG operations without automatic initialization, allowing subclasses to customise setup as needed.

Initialise base MAD interface.

Starts a MAD-NG process, then loads the accelerator’s sequence and sets its beam. If loading fails the process is closed before the error propagates.

Parameters:
  • accelerator (Accelerator) – Accelerator configuration object

  • **mad_kwargs – Keyword arguments passed to pymadng.MAD()

beta: float
dp2pt(dp)[source]

Convert relative momentum deviation dp/p to MAD-NG pt using the loaded beam.

Parameters:

dp (float)

Return type:

float

pt2dp(pt)[source]

Convert MAD-NG pt to relative momentum deviation dp/p using the loaded beam.

Parameters:

pt (float)

Return type:

float

load_sequence(cache_translation=False)[source]

Load a sequence file into MAD-NG from the accelerator configuration.

Parameters:

cache_translation (bool) – When True, translate the MAD-X sequence into a sibling .mad cache for faster subsequent loads. Off by default: the translation is cheap and the shared cache is a concurrency hazard (parallel loaders racing on the same file), so only enable it when the same sequence is reloaded many times.

Return type:

None

setup_beam()[source]

Set up beam parameters in MAD-NG based on the accelerator configuration.

Return type:

None

setup_sequence(cache_translation=False)[source]

Load the sequence and set up the beam in MAD-NG.

This method combines sequence loading and beam setup for convenience.

Parameters:

cache_translation (bool) – Forwarded to load_sequence(); off by default.

Return type:

None

unobserve_all_elements()[source]

Unobserve all elements in the loaded sequence.

Return type:

None

observe(pattern=None, unobserve_first=True)[source]

Configure element observation for tracking.

Parameters:
  • pattern (str | None) – Pattern to match elements for observation (default: None, which uses the accelerator’s BPM pattern)

  • unobserve_first (bool) – Whether to unobserve all elements before observing the new pattern (default: True)

Return type:

None

observe_element(element_name, unobserve_first=False)[source]

Observe a single element matched by its exact name (see observe_elements()).

Parameters:
  • element_name (str)

  • unobserve_first (bool)

Return type:

None

unobserve(pattern=None)[source]

Remove observation for elements matching a pattern.

Parameters:

pattern (str | None) – Pattern to match elements for unobserving, (default: None, which uses the accelerator’s BPM pattern)

Return type:

None

unobserve_elements(elements)[source]

Remove the elements with these exact names from observation, in one MAD-NG call.

Unlike unobserve(), the names are not Lua patterns.

Parameters:

elements (list[str]) – List of element names to unobserve

Return type:

None

observe_elements(element_names, unobserve_first=True)[source]

Observe the elements matched by their exact names, in one MAD-NG call.

Unlike observe(), which treats its argument as a Lua pattern, this selects by exact name. Observing a bare name such as BPH.13008 as an unanchored Lua pattern, where . is a wildcard, would also select any neighbour whose name contains it as a substring (e.g. the centre-reference marker OMC_MARKER_BPH.13008), corrupting the observed-BPM count.

Parameters:
Return type:

None

cycle_sequence(marker_name=None)[source]

Cycle sequence to start from a specific marker.

Parameters:

marker_name (str | None) – Name of marker to cycle to

Return type:

None

make_element_thin(element_name, marker_name=None, observe_after=True)[source]

Make an element thin by replacing it with a zero-length copy of itself.

Convenience wrapper around make_elements_thin() for a single element.

Parameters:
  • element_name (str) – Name of the element to replace

  • marker_name (str | None) – Name of the new marker (default: the element’s own name)

  • observe_after (bool) – Whether to observe the new marker after replacement

Returns:

The name of the marker that replaces the original element.

Return type:

str

make_elements_thin(element_names, marker_names=None, observe_after=True, require_kind=None)[source]

Make many elements thin with a single sequence:replace call.

Each replacement inherits from the original element (preserving its kind and attributes) but with l = 0 and at pinned to the original element’s centre position, so the optics at the thin element match those at the centre of the thick original.

Thinning is only permitted when the element does not bend or focus the beam, i.e. k0, k1 and k2 are all zero (or nil). Collapsing a focusing/bending element to zero length would silently drop its effect on the optics, so that case is rejected.

Everything is validated and replaced in MAD-NG in one go: replacing the elements one by one costs a round trip plus a full sequence index rebuild per element (O(N^2); minutes for the ~2600 FCC-ee BPMs).

Parameters:
  • element_names (list[str]) – Names of the elements to replace

  • marker_names (list[str] | None) – Names of the new markers, same order as element_names (default: each element’s own name)

  • observe_after (bool) – Whether to observe the new markers after replacement

  • require_kind (str | None) – If given, every element’s kind must contain this text (e.g. "monitor")

Returns:

The names of the markers that replace the original elements.

Return type:

list[str]

insert_acd_markers()[source]

Insert thin monitor endpoints immediately before and after the AC-dipole element.

Returns:

Tuple of (before_marker_name, after_marker_name). The historical names are kept, but the installed elements are monitors so MAD-NG monitor callbacks include them in tracking output.

Return type:

tuple[str, str]

run_twiss(**twiss_kwargs)[source]

Run TWISS calculation and return results. If ‘observe’ is not specified, it defaults to 1 (observing observed elements every turn). If ‘method’ is not specified, it defaults to 6 (MAD-NG’s highest-order thick-element integrator), matching xsuite’s exact drift-kick-drift + yoshida4 integrator to ~1e-8 relative instead of the coarser ~1e-6-1.7e-5 relative disagreement seen with MAD-NG’s default integrator. The closed-orbit tolerance cotol defaults to 1e-11, where the orbit reaches the twiss/tracking floor; MAD-NG’s default misses it by up to 5e-11 m once the lattice carries orbit and momentum errors together.

Parameters:

**twiss_kwargs – Additional arguments for twiss calculation.

Returns:

TFS DataFrame with twiss results

Return type:

pd.DataFrame

set_variables(**kwargs)[source]

Set multiple MAD variables.

Parameters:

**kwargs – Variable names and their values

Return type:

None

set_magnet_strengths(strengths)[source]

Set magnet strengths, routing multipole updates through dknl/dksl.

Names must end with one of MAGNET_STRENGTH_SUFFIXES. Multipole knobs (absolute .k0/.k1… or integrated-delta .dk0l/.dk1l…) are folded into the deferred dknl/dksl tables so they actually move the closed orbit / TWISS; misalignments (.dx/.dy) go through the element misalign table; anything else is set as a direct field.

Parameters:

strengths (dict[str, float])

Return type:

None

get_magnet_strengths(names)[source]

Get effective magnet strengths, including any dknl/dksl perturbations.

Parameters:

names (list[str])

Return type:

dict[str, float]

get_base_magnet_strengths(names)[source]

Get underlying magnet strengths without any dknl/dksl perturbation.

Parameters:

names (list[str])

Return type:

dict[str, float]

apply_magnet_perturbations(rel_error=None, seed=42, magnet_type='all')[source]

Apply random Gaussian perturbations to the loaded sequence’s magnets.

Each selected element’s strength (dipole k0, quadrupole k1, sextupole k2) is shifted by a normal deviate with standard deviation |strength| * relative error; elements with zero strength are skipped.

Parameters:
  • rel_error (float | None) – Relative standard deviation applied to every selected magnet. None uses the accelerator’s per-family relative_error_table / default_rel_std; elements matching neither are left unperturbed.

  • seed (int) – Seed of the random generator.

  • magnet_type (str | list[str]) – "all" or family codes d (dipole), q (quadrupole), s (sextupole), as a string or list.

Returns:

(magnet_strengths, true_strengths). magnet_strengths maps the knob name (ELEMENT.dk1l for multipoles, the integrated change delta * l) to its value. true_strengths maps each element name to its perturbed per-metre strength.

Return type:

tuple[dict[str, float], dict[str, float]]

set_madx_variables(**kwargs)[source]

Set multiple MADX variables.

Parameters:

**kwargs – Variable names and their values

Return type:

None

get_variables(*names)[source]

Get MAD variable values.

Parameters:

names (str) – Variable names

Returns:

Variable values

Return type:

tuple[float, …]

check_madng_succeded(fail_message)[source]

Check if the last MAD-NG command succeeded, raise error if not.

Parameters:

fail_message (str)

Return type:

None

close()[source]

Close the MAD-NG interface.

Return type:

None

match_tunes(target_qx, target_qy, qx_knob=None, qy_knob=None, deltap=None, pt=None)[source]

Match tunes using tune variables provided by the accelerator.

Parameters:
  • target_qx (float) – Target horizontal tune (fractional or full)

  • target_qy (float) – Target vertical tune (fractional or full)

  • qx_knob (str | None) – MAD variable name for horizontal tune knob

  • qy_knob (str | None) – MAD variable name for vertical tune knob (both knobs default to accelerator.tune_variables unless both are given)

  • deltap (float | None) – Momentum deviation dp/p at which to match. Mutually exclusive with pt.

  • pt (float | None) – MAD-NG native longitudinal momentum at which to match. Mutually exclusive with deltap; omit both to match on momentum.

Return type:

dict[str, float]

perform_orbit_correction(machine_deltap, target_qx=None, target_qy=None, corrector_file=None, twiss_name='zero_twiss', correct_tunes=True, bpms=None, correctors=None, plane='x')[source]

Correct the off-momentum orbit towards an on-momentum twiss, then rematch the tunes.

Runs MAD-NG correct (SVD) with the off-momentum twiss at machine_deltap as model and the MAD-NG twiss table named twiss_name as target; that table must already exist in the MAD-NG session.

Parameters:
  • machine_deltap (float) – Momentum deviation dp/p of the machine.

  • target_qx (float | None) – Tunes to rematch at machine_deltap (required if correct_tunes).

  • target_qy (float | None) – See target_qx.

  • corrector_file (Path | None) – If given, the corrector table is written to this file.

  • twiss_name (str) – Name of the target twiss table in MAD-NG.

  • correct_tunes (bool) – Rematch the tunes after the correction.

  • bpms (list[str] | None) – If given, only these monitors are used.

  • correctors (list[str] | None) – If given, only these kickers are used.

  • plane (str) – Correction plane, "x", "y" or "xy".

Returns:

The tune knob values {qx_knob: value, qy_knob: value}.

Return type:

dict[str, float]

install_ac_dipole(nat_tunes, drv_tunes, deltap=0.0)[source]

Install AC dipole kickers at the location given by the accelerator’s AC dipole marker, with specified natural and driven tunes.

The AC dipole consists of horizontal and vertical kicker elements that drive the beam at specified tunes. The beta functions at the marker location are automatically retrieved from the twiss table.

Parameters:
  • nat_tunes (tuple[float, float]) – Natural tunes (qx, qy)

  • drv_tunes (tuple[float, float]) – Driven tunes (qx_drv, qy_drv)

  • deltap (float) – Relative momentum deviation for the marker beta functions.

Return type:

None

install_ac_kickers(kicks, freqs)[source]

Install the AC_KICKERS at the thin AC-dipole element (see insert_acd_markers()).

Parameters:
Returns:

The kicker element names, AC_KICKERS.

Raises:

RuntimeError – If the AC-dipole element is not thin.

Return type:

tuple[str, …]

class pymadng_utils.KnobMadInterface(accelerator, **mad_kwargs)[source]

Bases: AcceleratorMadInterface

Base class for accelerator-specific MAD-NG interfaces with common setup methods.

Initialise base MAD interface.

Starts a MAD-NG process, then loads the accelerator’s sequence and sets its beam. If loading fails the process is closed before the error propagates.

Parameters:
  • accelerator (Accelerator) – Accelerator configuration object

  • **mad_kwargs – Keyword arguments passed to pymadng.MAD()

apply_corrector_strengths(corrector_table)[source]

Apply corrector strengths from a table to MAD sequence.

Parameters:

corrector_table (pd.DataFrame)

Return type:

None

observe_bpms(bpm_pattern, bad_bpms=None, unobserve_first=True)[source]

Set up the MAD-NG session to observe BPMs.

Parameters:
  • bpm_pattern (str)

  • bad_bpms (list[str] | None)

  • unobserve_first (bool)

Return type:

None

set_corrector_strengths(corrector_knobs)[source]

Apply corrector settings, given as knobs or as a corrector table file.

A mapping is a set of MAD-X knob variables and is sent as such. A path is read first: a TFS corrector table (ename/kind/hkick…) is applied element by element, anything else is parsed as a knobs file. The two are different data shapes, not two spellings of one, so the format is decided by reading – never by catching a failure to apply. A path that does not exist logs a warning and changes nothing.

Parameters:

corrector_knobs (Mapping[str, float] | str | Path)

Return type:

None

set_knobs(tune_knobs)[source]

Set predefined knobs, given directly or as a knobs file.

Parameters:

tune_knobs (Mapping[str, float] | str | Path)

Return type:

None