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:
AcceleratorFCC-ee (LCC optics) accelerator configuration.
The LCC lattices are a single ring (
fccee_p_ring) with lower-case element names: BPMsbpm_<quad>, quadrupolesq*, and paired correctorshcor_<quad>/vcor_<quad>(MAD-Xkickerwithhkick/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
nochargeas 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).
- 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:
AcceleratorLarge 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.*$'¶
- class pymadng_utils.PSB(sequence_file, ring=None, kinetic_energy=0.16, bpm_pattern=None, particle='proton', **kwargs)[source]¶
Bases:
AcceleratorProton Synchrotron Booster accelerator configuration.
- Parameters:
- BPM_PATTERN_TEMPLATE = '^BR{ring}%.BPM.*{ring}$'¶
- SEXTUPOLE_PATTERN = '^BR%d+%.XNO.*'¶
- class pymadng_utils.AcceleratorErrorsMadInterface(accelerator, **mad_kwargs)[source]¶
Bases:
AcceleratorMadInterfaceMAD 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:
objectBase 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()
- 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
.madcache 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
- observe_element(element_name, unobserve_first=False)[source]¶
Observe a single element matched by its exact name (see
observe_elements()).
- 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.
- 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 asBPH.13008as 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 markerOMC_MARKER_BPH.13008), corrupting the observed-BPM count.
- 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:
- Returns:
The name of the marker that replaces the original element.
- Return type:
- make_elements_thin(element_names, marker_names=None, observe_after=True, require_kind=None)[source]¶
Make many elements thin with a single
sequence:replacecall.Each replacement inherits from the original element (preserving its kind and attributes) but with
l = 0andatpinned 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,k1andk2are 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
kindmust contain this text (e.g."monitor")
- Returns:
The names of the markers that replace the original elements.
- Return type:
- insert_acd_markers()[source]¶
Insert thin monitor endpoints immediately before and after the AC-dipole element.
- 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
cotoldefaults 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 deferreddknl/dksltables so they actually move the closed orbit / TWISS; misalignments (.dx/.dy) go through the elementmisaligntable; anything else is set as a direct field.
- get_magnet_strengths(names)[source]¶
Get effective magnet strengths, including any dknl/dksl perturbations.
- get_base_magnet_strengths(names)[source]¶
Get underlying magnet strengths without any dknl/dksl perturbation.
- 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, quadrupolek1, sextupolek2) 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.
Noneuses the accelerator’s per-familyrelative_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 codesd(dipole),q(quadrupole),s(sextupole), as a string or list.
- Returns:
(magnet_strengths, true_strengths).magnet_strengthsmaps the knob name (ELEMENT.dk1lfor multipoles, the integrated changedelta * l) to its value.true_strengthsmaps each element name to its perturbed per-metre strength.- Return type:
- set_madx_variables(**kwargs)[source]¶
Set multiple MADX variables.
- Parameters:
**kwargs – Variable names and their values
- Return type:
None
- 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
- 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_variablesunless both are given)deltap (float | None) – Momentum deviation
dp/pat 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:
- 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 atmachine_deltapas model and the MAD-NG twiss table namedtwiss_nameas target; that table must already exist in the MAD-NG session.- Parameters:
machine_deltap (float) – Momentum deviation
dp/pof the machine.target_qx (float | None) – Tunes to rematch at
machine_deltap(required ifcorrect_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:
- 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.
- install_ac_kickers(kicks, freqs)[source]¶
Install the
AC_KICKERSat the thin AC-dipole element (seeinsert_acd_markers()).
- class pymadng_utils.KnobMadInterface(accelerator, **mad_kwargs)[source]¶
Bases:
AcceleratorMadInterfaceBase 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.
- 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.