MAD-NG Interfaces

pymadng_utils.mad contains the reusable object model for working with MAD-NG sessions.

Overview

  • AcceleratorMadInterface exposes sequence loading, beam setup, variable management, marker installation, TWISS execution, magnet perturbations, tune matching, AC-dipole and AC-kicker installation, and orbit correction.

  • AcceleratorErrorsMadInterface is the opt-in variant that applies accelerator-defined startup errors after loading the sequence.

  • pymadng_utils.mad.ac_kickers installs and drives thin flattop AC kickers.

  • KnobMadInterface adds helpers for applying corrector tables and knob files.

  • ModelCreatorMadInterface specialises the interface stack for model-export workflows.

Interface layering

The MAD interface stack is intentionally split:

  • Use AcceleratorMadInterface when you want a clean loaded machine with no automatic machine-specific error application.

  • Use AcceleratorErrorsMadInterface when the accelerator descriptor provides an apply_accelerator_specific_errors hook and you want that hook executed automatically.

  • Use KnobMadInterface or ModelCreatorMadInterface on top when the workflow also needs corrector-file, knob-file, or export helpers.

Practical guidance

  • Start with AcceleratorMadInterface unless you know you need one of the specialised wrappers.

  • Use ModelCreatorMadInterface indirectly through update_model_with_madng for model-directory workflows.

  • Treat the accelerator descriptor as part of the runtime contract: tune variables, sequence naming, BPM patterns, and AC-dipole placement all come from that object.

Package exports

MAD-NG interface utilities.

class pymadng_utils.mad.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.mad.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()

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

Core interface

MAD-NG interfaces with a small, composable class hierarchy.

AcceleratorMadInterface provides the core MAD-NG operations: sequence loading, beam setup, variable management, marker installation, TWISS, tune matching and magnet perturbations.

class pymadng_utils.mad.accelerator_mad_interface.MultipoleInfo(dk_table, base_table, index, dk_suffix, is_delta)[source]

Bases: NamedTuple

Where a multipole attribute lives in MAD-NG’s knl/dknl (or skew) tables.

Create new instance of MultipoleInfo(dk_table, base_table, index, dk_suffix, is_delta)

Parameters:
dk_table: str

Alias for field number 0

base_table: str

Alias for field number 1

index: int

Alias for field number 2

dk_suffix: str

Alias for field number 3

is_delta: bool

Alias for field number 4

class pymadng_utils.mad.accelerator_mad_interface.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.mad.accelerator_mad_interface.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()

AC kickers

Thin flattop AC kickers: install them at the AC-dipole element and drive their knobs.

Each plane has two fixed-phase kickers, a (lag 0, sin) and b (lag 1/4, cos), so the kick 0.3 / pc (a sin(phi) + b cos(phi)) with phi = 2 pi turn freq is linear in the volts a and b. turn is the MAD-NG turn counter.

pymadng_utils.mad.ac_kickers.KICKER_SPECS = (('hackicker_a', 0, 0.0), ('hackicker_b', 0, 0.25), ('vackicker_a', 1, 0.0), ('vackicker_b', 1, 0.25))

(name, plane, lag in turns) per kicker; plane 0 = horizontal, 1 = vertical.

pymadng_utils.mad.ac_kickers.AC_KICKERS = ('hackicker_a', 'hackicker_b', 'vackicker_a', 'vackicker_b')

Kicker element names in KICKER_SPECS order.

pymadng_utils.mad.ac_kickers.install_ac_kickers(mad, acd_name, kicks, freqs)[source]

Install the kickers at the position of the thin element acd_name, which is kept.

kicks = (a_x, b_x, a_y, b_y) are the initial volts; freqs = (h, v) drive tunes.

Parameters:
Return type:

None

pymadng_utils.mad.ac_kickers.set_ac_kicker_freqs(mad, freqs)[source]

Set every kicker’s freq to its plane’s drive tune freqs = (h, v).

Parameters:
Return type:

None

pymadng_utils.mad.ac_kickers.bind_ac_kicker_volts(mad, variables)[source]

Make each kicker’s volt follow loaded_sequence[variable] (deferred).

Parameters:
Return type:

None

pymadng_utils.mad.ac_kickers.shift_ac_kicker_phase(mad, turn_offset)[source]

Make MAD turn t act as turn t + turn_offset: lag = lag0 + turn_offset freq.

Parameters:
  • mad (MAD)

  • turn_offset (int)

Return type:

None

Knob helpers

MAD-NG interface with knob and corrector management functionality.

pymadng_utils.mad.knob_mad_interface.resolve_knobs(knobs)[source]

Knob name/value pairs, whether given directly or as a file to read.

Callers that already hold the knobs in memory pass the mapping and no file is ever written; callers holding a user-authored name<TAB>value file pass the path and it is read here, in exactly one place.

Parameters:

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

Return type:

dict[str, float]

class pymadng_utils.mad.knob_mad_interface.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

Model-creation interfaces

MAD-NG interface that matches tunes and exports the model twiss tables.

class pymadng_utils.mad.model_creator_mad_interface.ModelCreatorMadInterface(accelerator, model_dir, tunes=None, drv_tunes=None, deltap=0.0, **mad_kwargs)[source]

Bases: AcceleratorMadInterface

MAD-NG interface specialised for model creation workflows.

Load the sequence and match the model tunes at deltap.

Parameters:
  • accelerator (Accelerator) – Accelerator configuration object

  • model_dir (Path) – Model directory; the tables are written here

  • tunes (list[float] | None) – Natural fractional tunes to match (default: from model_dir/twiss.dat)

  • drv_tunes (list[float] | None) – Driven fractional tunes; None leaves the AC dipole out

  • deltap (float) – Momentum deviation dp/p of the model

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

TUNE_MATCH_TOLERANCE = 1e-06
match_model_tunes()[source]

Match model tunes using standard tune knobs for the current beam.

Return type:

None

add_strength_columns(table_name)[source]

Add multipole strength columns to a MAD-NG table.

Parameters:

table_name (str)

Return type:

None

get_current_tunes(label='')[source]

Retrieve current tunes from the loaded sequence.

Parameters:

label (str)

Return type:

tuple[float, float]

compute_and_export_twiss_tables(export_madx_names=True)[source]

Write twiss_elements.dat, twiss.dat and twiss_ac.dat into the model dir.

twiss_ac.dat is the twiss with the AC dipole installed; without drv_tunes it repeats the natural twiss.

Parameters:

export_madx_names – Use MAD-X column names (betx …) instead of MAD-NG’s.

Return type:

None