"""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.
"""
from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, NamedTuple, Self
import numpy as np
from pymadng import MAD
from pymadng_utils.config import MATCH_TUNES_SCRIPT, SHUSHING_SCRIPT
from pymadng_utils.mad.ac_kickers import AC_KICKERS, install_ac_kickers
if TYPE_CHECKING:
import pandas as pd
from pymadng_utils.accelerators.base import Accelerator
logger = logging.getLogger(__name__)
[docs]
class MultipoleInfo(NamedTuple):
"""Where a multipole attribute lives in MAD-NG's ``knl``/``dknl`` (or skew) tables."""
dk_table: str # MAD-NG table storing perturbations: "dknl" or "dksl"
base_table: str # MAD-NG table storing base strengths: "knl" or "ksl"
index: int # 1-based Lua index into the table
dk_suffix: str # knob name suffix used in MAD variables (e.g. "dk1l", "dk1sl")
is_delta: bool # True when attr is already a delta (e.g. dk1l), False for absolute (k1)
# Maximum multipole order supported (k0 through k{MAX_MULTIPOLE-1}).
# This also sets the size of the dknl/dksl deferred tables allocated in MAD-NG.
MAX_MULTIPOLE = 3
def _build_multipole_attrs(max_order: int) -> dict[str, MultipoleInfo]:
"""Generate multipole metadata from MAX_MULTIPOLE.
Normal components use dknl/knl, skew use dksl/ksl.
"""
attrs: dict[str, MultipoleInfo] = {}
for n in range(max_order):
idx = n + 1 # MAD-NG tables are 1-based
for dk_table, base_table, abs_attr, delta_attr in [
("dknl", "knl", f"k{n}", f"dk{n}l"),
("dksl", "ksl", f"k{n}s", f"dk{n}sl"),
]:
info_abs = MultipoleInfo(dk_table, base_table, idx, delta_attr, is_delta=False)
info_delta = MultipoleInfo(dk_table, base_table, idx, delta_attr, is_delta=True)
attrs[abs_attr] = info_abs
attrs[delta_attr] = info_delta
return attrs
MULTIPOLE_ATTRS = _build_multipole_attrs(MAX_MULTIPOLE)
MISALIGN_ATTRS = frozenset({"dx", "dy", "ds"})
# Absolute, non-multipole element fields set directly (see the ``else`` branch
# of ``set_magnet_strengths``): unlike ``dx``/``dy``/``ds`` these are not part of the
# element's ``misalign`` table in MAD-NG.
DIRECT_FIELD_ATTRS = frozenset({"tilt", "volt", "lag", "freq"})
MAGNET_STRENGTH_SUFFIXES = (
{f".{attr}" for attr in MULTIPOLE_ATTRS}
| {f".{attr}" for attr in MISALIGN_ATTRS}
| {f".{attr}" for attr in DIRECT_FIELD_ATTRS}
| {".kick"}
)
_PERTURBATION_BASE_SPECS: dict[str, dict[str, Any]] = {
"d": {"kind": ("sbend", "rbend"), "attr": "k0"},
"q": {"kind": ("quadrupole",), "attr": "k1"},
"s": {"kind": ("sextupole",), "attr": "k2"},
}
[docs]
class AcceleratorMadInterface:
"""
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.
"""
def __init__(self, accelerator: Accelerator, **mad_kwargs):
"""
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.
Args:
accelerator: Accelerator configuration object
**mad_kwargs: Keyword arguments passed to pymadng.MAD()
"""
self.accelerator = accelerator
self.mad = MAD(**mad_kwargs)
logger.debug("Initialised MAD core interface")
self.py_name = self.mad.py_name
self.mad.send(SHUSHING_SCRIPT.read_text())
self.mad.send("__observed_flag__ = MAD.element.flags.observed")
if self.accelerator.NOCHARGE:
self.mad.send("MAD.option.nocharge = true")
self.mad.send(f"MADX.option.rbarc = {str(self.accelerator.RBARC).lower()}")
# Load the default sequence and set up the beam immediately, as these are common to all workflows.
try:
self.setup_sequence()
except BaseException:
self.mad.close()
raise
self.beta: float = self.mad.loaded_sequence.beam.beta
def __repr__(self) -> str:
"""Return a concise developer-facing interface representation."""
return (
f"{type(self).__name__}("
f"seq_name={self.accelerator.seq_name!r}, "
f"py_name={self.py_name!r})"
)
def __str__(self) -> str:
"""Return a concise human-readable interface summary."""
return f"{type(self).__name__}({self.accelerator.seq_name})"
def _gphys_convert(self, func: str, value: float) -> float:
"""Run a ``MAD.gphys`` momentum conversion on the loaded sequence's beam.
The value is sent and received over the pipe rather than interpolated
into the MAD chunk as a formatted string, so the double crossing the
boundary is bit-exact in both directions. Using MAD-NG's own conversion
with MAD-NG's own ``beam.beta`` is what makes a converted ``deltap``
identical to what ``twiss{deltap=...}`` would have seeded internally.
"""
self.mad.send(
f"{self.py_name}:send("
f"MAD.gphys.{func}({self.py_name}:recv(), loaded_sequence.beam.beta))"
).send(float(value))
return float(self.mad.recv())
[docs]
def dp2pt(self, dp: float) -> float:
"""Convert relative momentum deviation ``dp/p`` to MAD-NG ``pt`` using the loaded beam."""
return self._gphys_convert("dp2pt", dp)
[docs]
def pt2dp(self, pt: float) -> float:
"""Convert MAD-NG ``pt`` to relative momentum deviation ``dp/p`` using the loaded beam."""
return self._gphys_convert("pt2dp", pt)
[docs]
def load_sequence(self, cache_translation: bool = False) -> None:
"""
Load a sequence file into MAD-NG from the accelerator configuration.
Args:
cache_translation: 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.
"""
logger.debug(f"Loading sequence from {self.accelerator.sequence_file}")
file_path = Path(self.accelerator.sequence_file).resolve()
if not file_path.exists():
raise FileNotFoundError(f"Sequence file not found: {file_path}")
self.mad.send("shush()")
# cache_translation writes a sibling .mad cache for faster reloads. It is
# off by default because a shared cache is a concurrency hazard: parallel
# loaders of the same sequence race on the file and one can read a
# half-written .mad that never defines the sequence. Only turn it on when
# loads are serial within a single process.
cache_target = f'"{file_path.with_suffix(".mad")}"' if cache_translation else "nil"
self.mad.send(
f'MADX:load("{file_path}", {cache_target}, {{rbarc={str(self.accelerator.RBARC).lower()}}})'
)
if self.mad.MADX[self.accelerator.seq_name] == 0:
raise ValueError(
f"Sequence '{self.accelerator.seq_name}' not found in MAD file '{self.accelerator.sequence_file}'"
)
self.mad.send(f"loaded_sequence = MADX.{self.accelerator.seq_name}")
self.mad["SEQ_NAME"] = self.accelerator.seq_name
self.mad.send("unshush()")
[docs]
def setup_beam(self) -> None:
"""
Set up beam parameters in MAD-NG based on the accelerator configuration.
"""
self.mad.send(
f'loaded_sequence.beam = beam {{ particle = "{self.accelerator.particle}", energy={self.accelerator.energy:.15e} }}',
)
logger.debug(
f"Setting beam: particle={self.accelerator.particle}, energy={self.accelerator.energy:.15e} GeV"
)
if self.accelerator.seq_dir != 1:
self.mad.send(f"loaded_sequence.dir = {int(self.accelerator.seq_dir)}")
logger.debug(f"Setting sequence direction: dir={int(self.accelerator.seq_dir)}")
[docs]
def setup_sequence(self, cache_translation: bool = False) -> None:
"""
Load the sequence and set up the beam in MAD-NG.
This method combines sequence loading and beam setup for convenience.
Args:
cache_translation: Forwarded to :meth:`load_sequence`; off by default.
"""
self.load_sequence(cache_translation=cache_translation)
self.setup_beam()
[docs]
def unobserve_all_elements(self) -> None:
"""Unobserve all elements in the loaded sequence."""
self.mad.send("loaded_sequence:deselect(__observed_flag__)")
[docs]
def observe(self, pattern: str | None = None, unobserve_first: bool = True) -> None:
"""
Configure element observation for tracking.
Args:
pattern: Pattern to match elements for observation (default: None, which uses the accelerator's BPM pattern)
unobserve_first: Whether to unobserve all elements before observing the new pattern (default: True)
"""
if pattern is None:
pattern = self.accelerator.bpm_pattern
logger.debug(f"Setting observation pattern: {pattern}")
if unobserve_first:
self.unobserve_all_elements()
self.mad.send(f"loaded_sequence:select(__observed_flag__, {{pattern='{pattern}'}})")
[docs]
def observe_element(self, element_name: str, unobserve_first: bool = False) -> None:
"""Observe a single element matched by its exact name (see :meth:`observe_elements`)."""
self.observe_elements([element_name], unobserve_first=unobserve_first)
[docs]
def unobserve(self, pattern: str | None = None) -> None:
"""
Remove observation for elements matching a pattern.
Args:
pattern: Pattern to match elements for unobserving, (default: None, which uses the accelerator's BPM pattern)
"""
if pattern is None:
pattern = self.accelerator.bpm_pattern
logger.debug(f"Unobserving elements matching pattern: {pattern}")
self.mad.send(f"loaded_sequence:deselect(__observed_flag__, {{pattern='{pattern}'}})")
[docs]
def unobserve_elements(self, elements: list[str]) -> None:
"""Remove the elements with these exact names from observation, in one MAD-NG call.
Unlike :meth:`unobserve`, the names are not Lua patterns.
Args:
elements: List of element names to unobserve
"""
if not elements:
return
self.mad["__unobserve_names"] = list(elements)
self.mad.send("loaded_sequence:deselect(__observed_flag__, {list = __unobserve_names})")
[docs]
def observe_elements(self, element_names: list[str], unobserve_first: bool = True) -> None:
"""Observe the elements matched by their exact names, in one MAD-NG call.
Unlike :meth:`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.
"""
logger.debug(f"Observing exact elements: {element_names}")
if unobserve_first:
self.unobserve_all_elements()
if not element_names:
return
self.mad["__observe_names"] = list(element_names)
self.mad.send("loaded_sequence:select(__observed_flag__, {list = __observe_names})")
[docs]
def cycle_sequence(self, marker_name: str | None = None) -> None:
"""
Cycle sequence to start from a specific marker.
Args:
marker_name: Name of marker to cycle to
"""
logger.debug(f"Cycling sequence to start from {marker_name}")
success_script = f"\n{self.py_name}:send(true)\n"
if marker_name is None:
self.mad.send("loaded_sequence:cycle()" + success_script)
else:
self.mad.send(f"loaded_sequence:cycle('{marker_name}')" + success_script)
try:
cycled = self.mad.recv()
except RuntimeError as e:
logger.error(f"Error during sequence cycling: {e}")
raise RuntimeError("Cycle failed - check MAD output for details") from e
if not cycled:
raise RuntimeError("Sequence cycling failed, you may have left something in the pipe.")
[docs]
def make_element_thin(
self,
element_name: str,
marker_name: str | None = None,
observe_after: bool = True,
) -> str:
"""
Make an element thin by replacing it with a zero-length copy of itself.
Convenience wrapper around :meth:`make_elements_thin` for a single element.
Args:
element_name: Name of the element to replace
marker_name: Name of the new marker (default: the element's own name)
observe_after: Whether to observe the new marker after replacement
Returns:
str: The name of the marker that replaces the original element.
"""
marker_names = None if marker_name is None else [marker_name]
return self.make_elements_thin([element_name], marker_names, observe_after)[0]
[docs]
def make_elements_thin(
self,
element_names: list[str],
marker_names: list[str] | None = None,
observe_after: bool = True,
require_kind: str | None = None,
) -> list[str]:
"""
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).
Args:
element_names: Names of the elements to replace
marker_names: Names of the new markers, same order as ``element_names``
(default: each element's own name)
observe_after: Whether to observe the new markers after replacement
require_kind: If given, every element's ``kind`` must contain this
text (e.g. ``"monitor"``)
Returns:
list[str]: The names of the markers that replace the original elements.
"""
if marker_names is None:
marker_names = list(element_names)
if len(marker_names) != len(element_names):
raise ValueError("marker_names must have one name per element name")
if not element_names:
return []
self.mad["__thin_elements"] = list(element_names)
self.mad["__thin_markers"] = list(marker_names)
self.mad["__thin_kind"] = require_kind or ""
self.mad.send(f"""
local found, order = {{}}, {{}}
for i, name in ipairs(__thin_elements) do
local elm = MADX[name]
if elm == nil or type(elm) == "number" then -- MADX returns 0 for an undefined name
{self.py_name}:send({{"missing", name}}, true)
return
end
found[#found + 1] = {{ elm = elm, marker = __thin_markers[i], index = loaded_sequence:index_of(elm) }}
end
table.sort(found, function(a, b) return a.index < b.index end) -- replace pairs new elements with selected ones in sequence order
local new, old = {{}}, {{}}
for i, f in ipairs(found) do
local elm = f.elm
if __thin_kind ~= "" and not tostring(elm.kind):find(__thin_kind, 1, true) then
{self.py_name}:send({{"kind", elm.name}}, true)
return
end
if (elm.k0 or 0) ~= 0 or (elm.k1 or 0) ~= 0 or (elm.k2 or 0) ~= 0 then
{self.py_name}:send({{"strength", elm.name}}, true)
return
end
new[i] = elm(f.marker) {{ l = 0, at = loaded_sequence:upos(f.index) }}
old[i] = elm.name
end
local replaced = loaded_sequence:replace(new, {{ list = old }})
for _, elm in ipairs(new) do MADX[elm.name] = elm end ! Replace in the madx environment for later reference
{self.py_name}:send({{"ok", replaced and #replaced or 0}}, true)
""")
status, detail = self.mad.recv()
if status == "missing":
raise ValueError(f"Could not find element: {detail}")
if status == "kind":
raise ValueError(f"Element '{detail}' is not of kind '{require_kind}'")
if status == "strength":
raise ValueError(
f"Refusing to thin '{detail}': it has non-zero k0, k1 or k2; "
"collapsing a bending/focusing element to zero length would change the optics."
)
if detail != len(element_names):
raise ValueError(
f"Element replacement failed, replaced {detail} elements instead of {len(element_names)}"
)
if observe_after:
self.observe_elements(marker_names, unobserve_first=False)
return marker_names
[docs]
def insert_acd_markers(self) -> tuple[str, str]:
"""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.
"""
# MAD-NG uses lowercase element names in the loaded sequence
element_name = self.accelerator.ac_dipole_name
before_marker = self.accelerator.acd_marker_name("before")
after_marker = self.accelerator.acd_marker_name("after")
self.mad.send(f"""
{self.py_name}:send(loaded_sequence['{element_name}'] and 1 or 0, true) ! 0 or nil?
""")
if not bool(self.mad.recv()):
raise ValueError(f"Could not find element: {element_name}")
self.mad.send(f"""
local seq_elm = loaded_sequence['{element_name}']
{self.py_name}:send(loaded_sequence:upos(seq_elm), true)
{self.py_name}:send({{seq_elm.refpos or (loaded_sequence.refer or "centre"), seq_elm.l}}, true)
""")
element_pos = self.mad.recv()
element_refpos, element_length = self.mad.recv()
logger.debug(
f"ACD element '{element_name}' position: {element_pos}, refpos: {element_refpos}, length: {element_length}"
)
if element_refpos != "centre":
raise ValueError("ACD marker insertion currently only supports centre reference")
if element_length > 0:
self.mad.send(f"""
-- Replace the thick ACD element with a thin copy so the before/after markers
-- are not inside a thick body and can be used as valid range endpoints.
-- loaded_sequence:replace recomputes surrounding drifts automatically.
local seq_elm = loaded_sequence['{element_name}']
local replaced = loaded_sequence:replace({{seq_elm {{ l = 0, at = {self.py_name}:recv() }}}}, '{element_name}')
{self.py_name}:send(replaced and #replaced or 0)
""").send(element_pos)
if (n_replaced := self.mad.recv()) != 1:
raise ValueError(
f"Element replacement failed during ACD marker insertion, replaced {n_replaced} elements instead of 1"
)
start_pos = element_pos - 1e-10
end_pos = element_pos + 1e-10
self.mad.send(f"""
local monitor in MAD.element
loaded_sequence:install{{
monitor "{before_marker}" {{ at = {start_pos:.15e} }},
monitor "{after_marker}" {{ at = {end_pos:.15e} }},
}}
MADX['{before_marker}'] = loaded_sequence['{before_marker}']
MADX['{after_marker}'] = loaded_sequence['{after_marker}']
{self.py_name}:send({{MADX['{before_marker}'] ~= 0, MADX['{after_marker}'] ~= 0}}, true)
""")
before_exists, after_exists = self.mad.recv()
if not bool(before_exists) or not bool(after_exists):
raise ValueError(f"ACD marker insertion failed for element {element_name}")
return before_marker, after_marker
def _normalise_twiss_kwargs(self, caller: str, twiss_kwargs: dict[str, Any]) -> dict[str, Any]:
"""Apply the shared ``pt`` convenience handling used by Twiss callers."""
twiss_kwargs = dict(twiss_kwargs)
if twiss_kwargs.get("pt") is not None:
if twiss_kwargs.get("X0") is not None or twiss_kwargs.get("deltap") is not None:
raise ValueError(f"{caller}: 'pt' cannot be combined with 'X0' or 'deltap'")
twiss_kwargs["X0"] = [0.0, 0.0, 0.0, 0.0, 0.0, twiss_kwargs.pop("pt")]
else:
twiss_kwargs.pop("pt", None)
for key in ("X0", "deltap"):
if twiss_kwargs.get(key) is None:
twiss_kwargs.pop(key, None)
return twiss_kwargs
[docs]
def run_twiss(self, **twiss_kwargs) -> pd.DataFrame:
"""
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.
Args:
**twiss_kwargs: Additional arguments for twiss calculation.
Returns:
TFS DataFrame with twiss results
"""
logger.debug("Running twiss calculation")
twiss_kwargs = self._normalise_twiss_kwargs("run_twiss", twiss_kwargs)
if "observe" not in twiss_kwargs:
twiss_kwargs["observe"] = 1
if "method" not in twiss_kwargs:
twiss_kwargs["method"] = 6 # Match xsuite's integrator order
if "cotol" not in twiss_kwargs:
# The MAD-NG default leaves ~5e-11 m on distorted orbits. Do not go tighter:
# at 1e-12 the LHC off-momentum closed-orbit search sits at its floor, and
# whether it converges depends on the last bit of the pt seed. When it
# fails, a twiss with chrom aborts with "Xset or Mset damap expected".
twiss_kwargs["cotol"] = 1e-11
try:
self.mad["tws", "flw"] = self.mad.twiss(sequence="loaded_sequence", **twiss_kwargs)
except ValueError as e:
logger.error(f"Error during twiss calculation: {e}")
raise RuntimeError("Twiss failed - check MAD output for details") from e
df = self.mad.tws.to_df()
df.headers["particle"] = self.accelerator.particle
df.headers["energy"] = self.accelerator.energy
if "name" in df.columns:
df = df.set_index("name")
return df
[docs]
def set_variables(self, **kwargs) -> None:
"""
Set multiple MAD variables.
Args:
**kwargs: Variable names and their values
"""
self.mad.send_vars(**kwargs)
# --- multipole perturbation table helpers ---
def _ensure_deferred_dk_table(self, element_name: str, dk_table: str) -> None:
"""Initialise the dknl/dksl table as deferred without resetting values."""
zeros_or_old = ",\n".join([f"old[{i}] or 0.0" for i in range(1, MAX_MULTIPOLE + 1)])
self.mad.send(f"""
if not MAD.typeid.is_deferred(loaded_sequence['{element_name}'].{dk_table}) then
local old = loaded_sequence['{element_name}'].{dk_table} or {{}}
loaded_sequence['{element_name}'].{dk_table} = MAD.typeid.deferred {{\n{zeros_or_old}}}
end
""")
def _set_dk_component(self, element_name: str, info: MultipoleInfo, delta: float) -> None:
"""Write a delta strength into the correct dknl/dksl slot."""
self._ensure_deferred_dk_table(element_name, info.dk_table)
self.mad.send(f"""
loaded_sequence['{element_name}'].{info.dk_table}[{info.index}] = {self.py_name}:recv()
""")
self.mad.send(delta)
# --- misalignment helpers (separate from multipole logic) ---
def _set_misalignment(self, element_name: str, attr: str, value: float) -> None:
"""Set a misalignment value, preserving other misalignment attributes already set."""
# The plain `if not mad[...]` truthiness test is unreliable here because pymadng
# returns a MadRef object even for an unset table, which is always truthy.
self.mad.send(f"{self.py_name}:send(loaded_sequence['{element_name}'].misalign, true)")
misalign_dict = self.mad.recv()
if not isinstance(misalign_dict, dict) or len(misalign_dict) == 0:
self.mad[f"loaded_sequence['{element_name}'].misalign"] = []
self.mad[f"loaded_sequence['{element_name}'].misalign.{attr}"] = value
def _get_misalignment(self, element_name: str, attr: str) -> float:
"""Get a misalignment value, returning 0.0 if not set."""
self.mad.send(f"{self.py_name}:send(loaded_sequence['{element_name}'].misalign, true)")
misalign_dict = self.mad.recv()
if not isinstance(misalign_dict, dict) or len(misalign_dict) == 0:
return 0.0
return float(misalign_dict.get(attr, 0.0))
# --- generic element strength get/set ---
def _get_effective_element_strength(self, element_name: str, attr: str) -> float:
"""Return the effective element strength, including any dknl/dksl perturbations."""
if attr in MISALIGN_ATTRS:
return self._get_misalignment(element_name, attr)
info = MULTIPOLE_ATTRS.get(attr)
if info is None:
return self.mad[f"loaded_sequence['{element_name}'].{attr}"]
# If the dk table hasn't been initialised yet, return the base attribute directly.
if len(getattr(self.mad.loaded_sequence[element_name], info.dk_table)) == 0:
return self.mad[f"loaded_sequence['{element_name}'].{attr}"]
if info.is_delta:
return float(
self.mad[f"loaded_sequence['{element_name}'].{info.dk_table}[{info.index}]"]
)
# Absolute attrs: the perturbation is stored in the *integrated* dknl/dksl
# table, so its per-metre contribution to the gradient is dknl[i]/l. The
# effective per-metre strength is therefore base + dknl[i]/l. (A dknl[i]=X
# is equivalent to changing the per-metre strength by X/l -- verified by
# tune equivalence.) Thin elements (l==0) have no per-metre form, so fall
# back to the raw sum.
length = self.mad[f"loaded_sequence['{element_name}'].l"]
denom = float(length) if length not in (None, 0) else 1.0
self.mad.send(f"""
local {info.dk_table}, {attr} in loaded_sequence['{element_name}']
{self.py_name}:send({attr} + {info.dk_table}[{info.index}]/{denom!r})
""")
return self.mad.recv()
def _get_base_element_strength(self, element_name: str, attr: str) -> float:
"""Return the element strength ignoring any dknl/dksl perturbation."""
if self.mad[f"loaded_sequence['{element_name}'].{attr}"] is not None:
return float(self.mad[f"loaded_sequence['{element_name}'].{attr}"])
info = MULTIPOLE_ATTRS[attr]
return float(self.mad[f"loaded_sequence['{element_name}'].{info.base_table}[{info.index}]"])
def _set_effective_element_strength(self, element_name: str, attr: str, target: float) -> None:
"""Set an element strength, routing multipole updates through dknl/dksl."""
info = MULTIPOLE_ATTRS.get(attr)
if info is None:
self.mad[f"loaded_sequence['{element_name}'].{attr}"] = target
return
if info.is_delta:
# Delta attrs (dk1l, ...) are already the integrated dknl value.
delta = float(target)
else:
# Absolute attrs: target is a per-metre strength. The perturbation is
# stored integrated in dknl/dksl, so the delta to write is the per-metre
# change times the element length. (Inverse of the /l applied when
# reading; thin elements l==0 fall back to the raw per-metre delta.)
base = float(self.mad[f"loaded_sequence['{element_name}'].{attr}"])
length = self.mad[f"loaded_sequence['{element_name}'].l"]
delta_per_metre = float(target) - base
delta = delta_per_metre * float(length) if length not in (None, 0) else delta_per_metre
self._set_dk_component(element_name, info, delta)
# --- public magnet-strength API ---
[docs]
def set_magnet_strengths(self, strengths: dict[str, float]) -> None:
"""Set magnet strengths, routing multipole updates through dknl/dksl.
Names must end with one of :data:`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.
"""
logger.debug(f"Setting {len(strengths)} magnet strengths")
direct_variables: dict[str, float] = {}
for name, strength in strengths.items():
if not any(name.endswith(suffix) for suffix in MAGNET_STRENGTH_SUFFIXES):
raise ValueError(
f"Magnet name '{name}' must end with one of {MAGNET_STRENGTH_SUFFIXES}"
)
magnet_name, attr = name.rsplit(".", 1)
if attr in MISALIGN_ATTRS:
self._set_misalignment(magnet_name, attr, strength)
elif attr in MULTIPOLE_ATTRS:
self._set_effective_element_strength(magnet_name, attr, strength)
else:
direct_variables[f"loaded_sequence['{magnet_name}'].{attr}"] = strength
if direct_variables:
self.set_variables(**direct_variables)
[docs]
def get_magnet_strengths(self, names: list[str]) -> dict[str, float]:
"""Get effective magnet strengths, including any dknl/dksl perturbations."""
return {name: self._get_effective_element_strength(*name.rsplit(".", 1)) for name in names}
[docs]
def get_base_magnet_strengths(self, names: list[str]) -> dict[str, float]:
"""Get underlying magnet strengths without any dknl/dksl perturbation."""
return {name: self._get_base_element_strength(*name.rsplit(".", 1)) for name in names}
def _resolve_relative_error(
self,
family_config: dict[str, Any],
element_name: str,
rel_error: float | None,
) -> float | None:
"""Resolve the relative error for one element from global or family settings."""
if rel_error is not None:
return rel_error
relative_error_table = family_config.get("relative_error_table")
if isinstance(relative_error_table, dict):
for prefix, rel_value in relative_error_table.items():
if element_name.startswith(str(prefix)):
return float(rel_value)
default_rel_std = family_config.get("default_rel_std")
if default_rel_std is not None:
return float(default_rel_std)
if relative_error_table is not None:
return None
raise ValueError(
f"Relative error not specified for family with kind {family_config['kind']}"
)
def _set_multipole_perturbation(
self,
element_name: str,
attr: str,
info: MultipoleInfo,
integrated_delta: float,
target_strength: float,
) -> None:
"""Apply one multipole perturbation.
``integrated_delta`` is supplied for subclasses that expose integrated
``dk*l`` knobs. The base interface writes the requested absolute
per-metre ``target_strength`` through the normal element-strength path.
"""
del info, integrated_delta
self._set_effective_element_strength(element_name, attr, target_strength)
[docs]
def apply_magnet_perturbations(
self,
rel_error: float | None = None,
seed: int = 42,
magnet_type: str | list[str] = "all",
) -> tuple[dict[str, float], dict[str, float]]:
"""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.
Args:
rel_error: 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: Seed of the random generator.
magnet_type: ``"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.
"""
if magnet_type == "all":
requested = ["d", "q", "s"]
else:
requested = magnet_type if isinstance(magnet_type, list) else list(magnet_type)
if not requested:
return {}, {}
family_overrides = self.accelerator.get_perturbation_families()
family_configs = [
_PERTURBATION_BASE_SPECS[family] | family_overrides[family]
for family in ("d", "q", "s")
if family in requested and family in family_overrides
]
if not family_configs:
return {}, {}
rng = np.random.default_rng(seed)
magnet_strengths: dict[str, float] = {}
true_strengths: dict[str, float] = {}
for elm in self.mad.loaded_sequence:
for family_config in family_configs:
if elm.kind not in family_config["kind"]:
continue
pattern = family_config.get("pattern")
if pattern and not re.match(str(pattern), str(elm.name)):
continue
element_rel_error = self._resolve_relative_error(
family_config=family_config,
element_name=str(elm.name),
rel_error=rel_error,
)
if element_rel_error is None:
continue
attr = str(family_config["attr"])
strength_before = float(elm[attr])
if strength_before == 0.0:
continue
delta = float(rng.normal(0, abs(strength_before * element_rel_error)))
strength_after = strength_before + delta
info = MULTIPOLE_ATTRS.get(attr)
if info is not None:
# ``_set_effective_element_strength`` writes the *integrated*
# perturbation (delta * length) into dknl, and the ``dk*l`` knob
# name is itself integrated, so record the integrated value. This
# keeps the returned dict consistent with what
# ``get_magnet_strengths`` reads back for the same knob (which
# returns dknl[i] directly).
length = float(elm.l)
knob_name = f"{elm.name}.{info.dk_suffix}"
integrated_delta = delta * length
self._set_multipole_perturbation(
str(elm.name),
attr,
info,
integrated_delta,
strength_after,
)
magnet_strengths[knob_name] = integrated_delta
else:
elm[attr] = strength_after
magnet_strengths[f"{elm.name}.{attr}"] = strength_after
true_strengths[str(elm.name)] = strength_after
break
return magnet_strengths, true_strengths
[docs]
def set_madx_variables(self, **kwargs) -> None:
"""
Set multiple MADX variables.
Args:
**kwargs: Variable names and their values
"""
kwargs = {f"MADX['{key}']": value for key, value in kwargs.items()}
self.set_variables(**kwargs)
[docs]
def get_variables(self, *names: str) -> tuple[float, ...]:
"""
Get MAD variable values.
Args:
names: Variable names
Returns:
Variable values
"""
return self.mad.recv_vars(*names, shallow_copy=True)
[docs]
def check_madng_succeded(self, fail_message: str) -> None:
"""Check if the last MAD-NG command succeeded, raise error if not."""
result = self.mad.send(f"{self.py_name}:send('success')").recv()
if result != "success":
raise RuntimeError(f"{fail_message}: {result}")
[docs]
def close(self) -> None:
"""Close the MAD-NG interface."""
if self.mad is not None:
logger.debug("Closing MAD interface")
self.mad.close()
def _info_required(self) -> int:
# If the logging level is info, we want info = 2, if it's debug, we want info = 5 at least
if logger.isEnabledFor(logging.DEBUG):
return 7
if logger.isEnabledFor(logging.INFO):
return 2
return 0
[docs]
def match_tunes(
self,
target_qx: float,
target_qy: float,
qx_knob: str | None = None,
qy_knob: str | None = None,
deltap: float | None = None,
pt: float | None = None,
) -> dict[str, float]:
"""Match tunes using tune variables provided by the accelerator.
Args:
target_qx: Target horizontal tune (fractional or full)
target_qy: Target vertical tune (fractional or full)
qx_knob: MAD variable name for horizontal tune knob
qy_knob: MAD variable name for vertical tune knob (both knobs default to
``accelerator.tune_variables`` unless both are given)
deltap: Momentum deviation ``dp/p`` at which to match. Mutually
exclusive with *pt*.
pt: MAD-NG native longitudinal momentum at which to match. Mutually
exclusive with *deltap*; omit both to match on momentum.
"""
if qx_knob is None or qy_knob is None:
qx_knob, qy_knob = self.accelerator.tune_variables
twiss_kwargs = self._normalise_twiss_kwargs("match_tunes", {"deltap": deltap, "pt": pt})
# Check if we have been given the total tunes rather than the fractional
qx_int, qy_int = self.accelerator.tune_integers
if target_qx >= 1:
qx_int = 0
if target_qy >= 1:
qy_int = 0
# Numbers go through the binary pipe (bit-exact), never formatted into the Lua code.
self.mad.send(MATCH_TUNES_SCRIPT.read_text())
self.mad["match_knobs"] = [qx_knob, qy_knob]
self.mad["match_X0"] = [float(v) for v in twiss_kwargs.get("X0", [0.0] * 6)]
self.mad["match_deltap"] = float(twiss_kwargs.get("deltap", 0.0))
self.mad["match_q"] = [float(qx_int + target_qx), float(qy_int + target_qy)]
self.mad.send(
f"match_tunes(match_knobs, match_X0, match_deltap, match_q, {self._info_required()})"
)
return {
qx_knob: self.mad[f"MADX['{qx_knob}']"],
qy_knob: self.mad[f"MADX['{qy_knob}']"],
}
def _check_mad_response(self, expected: str, error_msg: str) -> None:
"""Check that the response from MAD-NG matches the expected value."""
try:
result = self.mad.recv()
except Exception as exc:
raise RuntimeError(error_msg) from exc
if result != expected:
raise RuntimeError(f"Unexpected response from MAD-NG: {result}. {error_msg}")
def _clear_disabled_elements(self) -> None:
self.mad.send("loaded_sequence:deselect(MAD.element.flags.disabled)")
def _enable_only_named_elements(self, names: list[str], element_class: str) -> None:
"""Disable every element of ``element_class`` except ``names``."""
self.mad.send(f"""
local disabled_flag = MAD.element.flags.disabled
loaded_sequence:select(disabled_flag, nil, {{class={element_class}}})
loaded_sequence:deselect(disabled_flag, nil, {self.py_name}:recv())
{self.py_name}:send("Complete")
""")
self.mad.send(names)
self._check_mad_response("Complete", "Error applying orbit-correction element filter")
def _run_orbit_correction(self, twiss_name: str) -> None:
self.mad.send(rf"""
local correct, option in MAD
io.write("*** orbit correction using off momentum twiss\n")
local tws_offmom = twiss {{ sequence=loaded_sequence, deltap=machine_deltap }}
local fmt = option.numfmt ; option.numfmt = "% -.16e"
local tbl = correct {{ sequence=loaded_sequence, model=tws_offmom, target={twiss_name}, method="svd", info=1, plane=correction_plane }}
if correct_file then
tbl:write(correct_file)
end
option.numfmt = fmt
{self.py_name}:send("Complete")
""")
self._check_mad_response("Complete", "Error during MAD-NG orbit correction")
[docs]
def install_ac_dipole(
self,
nat_tunes: tuple[float, float],
drv_tunes: tuple[float, float],
deltap: float = 0.0,
) -> None:
"""
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.
Args:
nat_tunes: Natural tunes (qx, qy)
drv_tunes: Driven tunes (qx_drv, qy_drv)
deltap: Relative momentum deviation for the marker beta functions.
"""
install_point = self.accelerator.ac_dipole_name
logger.debug(
f"Installing AC dipole at {install_point} with natural tunes {nat_tunes} "
f"and driven tunes {drv_tunes}"
)
# Get beta functions at AC marker location
self.mad.send(f"""
acd_location = loaded_sequence:upos("{install_point}")
{self.py_name}:send(acd_location, true)
""")
acd_location = self.mad.recv()
if acd_location is None:
raise ValueError(
f"Could not find position for AC dipole installation point: {install_point}"
)
# Install AC kickers
self.mad.send(f"""
local marker in MAD.element
-- Make the ACD thin with a marker just to get the beta functions at the correct location
loaded_sequence:replace({{marker '__custom_marker__' {{at = acd_location}}}}, "{install_point}")
""")
self.mad.send(f"""
local hackicker, vackicker in MAD.element
! Do a twiss and replace the ac_bet values for the kickers
local tws = twiss{{sequence=loaded_sequence, deltap={deltap:.16e}}}
local betx = tws['__custom_marker__'].beta11
local bety = tws['__custom_marker__'].beta22
loaded_sequence:install{{
hackicker "hackicker" {{
at = acd_location,
nat_q = {nat_tunes[0]:.15e},
drv_q = {drv_tunes[0]:.15e},
ac_bet = betx,
}},
vackicker "vackicker" {{
at = acd_location,
nat_q = {nat_tunes[1]:.15e},
drv_q = {drv_tunes[1]:.15e},
ac_bet = bety,
}}
}}
loaded_sequence:remove('__custom_marker__') -- Clean up the temporary marker
""")
logger.debug(f"AC dipole installed: at {install_point}, {acd_location:.6f} m")
[docs]
def install_ac_kickers(
self, kicks: tuple[float, float, float, float], freqs: tuple[float, float]
) -> tuple[str, ...]:
"""Install the ``AC_KICKERS`` at the thin AC-dipole element (see :meth:`insert_acd_markers`).
Args:
kicks: Initial volts ``(a_x, b_x, a_y, b_y)``.
freqs: Horizontal and vertical drive tunes.
Returns:
The kicker element names, ``AC_KICKERS``.
Raises:
RuntimeError: If the AC-dipole element is not thin.
"""
install_ac_kickers(self.mad, self.accelerator.ac_dipole_name, kicks, freqs)
return AC_KICKERS
def __enter__(self) -> Self:
"""Enter context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
"""Exit context manager and close MAD interface."""
self.close()
[docs]
class AcceleratorErrorsMadInterface(AcceleratorMadInterface):
"""MAD interface variant that applies accelerator-specific startup errors."""
def __init__(self, accelerator: Accelerator, **mad_kwargs):
super().__init__(accelerator=accelerator, **mad_kwargs)
self.accelerator.apply_accelerator_specific_errors(self)