pymadng-utils 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pymadng_utils/__init__.py +22 -0
- pymadng_utils/accelerators/__init__.py +16 -0
- pymadng_utils/accelerators/base.py +113 -0
- pymadng_utils/accelerators/fcc.py +108 -0
- pymadng_utils/accelerators/lhc.py +115 -0
- pymadng_utils/accelerators/psb.py +79 -0
- pymadng_utils/config.py +8 -0
- pymadng_utils/io/__init__.py +8 -0
- pymadng_utils/io/utils.py +49 -0
- pymadng_utils/mad/__init__.py +13 -0
- pymadng_utils/mad/ac_kickers.py +87 -0
- pymadng_utils/mad/accelerator_mad_interface.py +1076 -0
- pymadng_utils/mad/knob_mad_interface.py +153 -0
- pymadng_utils/mad/model_creator_mad_interface.py +161 -0
- pymadng_utils/mad_scripts/match_tunes.mad +30 -0
- pymadng_utils/mad_scripts/shush_mad_output.mad +43 -0
- pymadng_utils/madx/__init__.py +13 -0
- pymadng_utils/madx/constants.py +19 -0
- pymadng_utils/madx/make_sequence.py +295 -0
- pymadng_utils/madx/tfs_utils.py +98 -0
- pymadng_utils/model_creator/__init__.py +3 -0
- pymadng_utils/model_creator/constants.py +86 -0
- pymadng_utils/model_creator/create_fcc_model.py +82 -0
- pymadng_utils/model_creator/create_models.py +252 -0
- pymadng_utils/model_creator/madng_utils.py +71 -0
- pymadng_utils/physics.py +94 -0
- pymadng_utils/py.typed +0 -0
- pymadng_utils-0.0.1.dist-info/METADATA +170 -0
- pymadng_utils-0.0.1.dist-info/RECORD +32 -0
- pymadng_utils-0.0.1.dist-info/WHEEL +5 -0
- pymadng_utils-0.0.1.dist-info/licenses/LICENSE +21 -0
- pymadng_utils-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Utilities for working with accelerator descriptors, MAD-NG, MAD-X, and model workflows."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import version
|
|
4
|
+
|
|
5
|
+
from pymadng_utils.accelerators import FCC, LHC, PSB
|
|
6
|
+
from pymadng_utils.mad import (
|
|
7
|
+
AcceleratorErrorsMadInterface,
|
|
8
|
+
AcceleratorMadInterface,
|
|
9
|
+
KnobMadInterface,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
__version__ = version("pymadng-utils")
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"FCC",
|
|
16
|
+
"LHC",
|
|
17
|
+
"PSB",
|
|
18
|
+
"AcceleratorErrorsMadInterface",
|
|
19
|
+
"AcceleratorMadInterface",
|
|
20
|
+
"KnobMadInterface",
|
|
21
|
+
"__version__",
|
|
22
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Accelerator descriptors used by MAD-facing helpers."""
|
|
2
|
+
|
|
3
|
+
from pymadng_utils.accelerators.base import Accelerator
|
|
4
|
+
from pymadng_utils.accelerators.fcc import FCC
|
|
5
|
+
from pymadng_utils.accelerators.lhc import LHC
|
|
6
|
+
from pymadng_utils.accelerators.psb import PSB, PSB_FLAT_BOTTOM_GEV
|
|
7
|
+
from pymadng_utils.physics import PROTON_MASS_GEV
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"FCC",
|
|
11
|
+
"LHC",
|
|
12
|
+
"PROTON_MASS_GEV",
|
|
13
|
+
"PSB",
|
|
14
|
+
"PSB_FLAT_BOTTOM_GEV",
|
|
15
|
+
"Accelerator",
|
|
16
|
+
]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Minimal accelerator definitions for MAD-facing helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from pymadng_utils.physics import beta_from_energy, dp2pt, particle_mass, pt2dp
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Accelerator(ABC):
|
|
13
|
+
"""Machine descriptor consumed by the MAD-NG interfaces.
|
|
14
|
+
|
|
15
|
+
Holds the sequence path, MAD sequence name, beam energy, BPM pattern, tune knobs and
|
|
16
|
+
integer tunes, and the AC-dipole element name.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
#: MAD-X ``rbarc`` option used when loading the sequence (rbend length is the straight chord if True).
|
|
20
|
+
RBARC = False
|
|
21
|
+
#: Set MAD-NG's ``option.nocharge`` before the beam is created.
|
|
22
|
+
NOCHARGE = False
|
|
23
|
+
#: MAD-NG ``sequence.dir``: -1 runs the loaded sequence backwards.
|
|
24
|
+
seq_dir = 1
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
sequence_file: Path | str,
|
|
29
|
+
kinetic_energy: float,
|
|
30
|
+
bpm_pattern: str = "BPM",
|
|
31
|
+
particle: str = "proton",
|
|
32
|
+
**kwargs: Any,
|
|
33
|
+
) -> None:
|
|
34
|
+
if kwargs:
|
|
35
|
+
raise TypeError(f"Unexpected keyword arguments: {list(kwargs)}")
|
|
36
|
+
super().__init__()
|
|
37
|
+
self.sequence_file = Path(sequence_file)
|
|
38
|
+
self.kinetic_energy = float(kinetic_energy)
|
|
39
|
+
self.particle = str(particle)
|
|
40
|
+
self.energy = self.kinetic_energy + particle_mass(self.particle)
|
|
41
|
+
self.beta = beta_from_energy(self.energy, self.particle)
|
|
42
|
+
self.bpm_pattern = str(bpm_pattern)
|
|
43
|
+
|
|
44
|
+
def __repr__(self) -> str:
|
|
45
|
+
"""Return a developer-facing representation of public accelerator state."""
|
|
46
|
+
fields = ", ".join(
|
|
47
|
+
f"{name}={value!r}" for name, value in vars(self).items() if not name.startswith("_")
|
|
48
|
+
)
|
|
49
|
+
return f"{type(self).__name__}({fields})"
|
|
50
|
+
|
|
51
|
+
def __str__(self) -> str:
|
|
52
|
+
"""Return a concise human-readable accelerator summary."""
|
|
53
|
+
return (
|
|
54
|
+
f"{type(self).__name__}(seq_name={self.seq_name}, "
|
|
55
|
+
f"particle={self.particle}, "
|
|
56
|
+
f"kinetic_energy={self.kinetic_energy:g} GeV, "
|
|
57
|
+
f"sequence_file={self.sequence_file})"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def dp2pt(self, dp: float) -> float:
|
|
61
|
+
"""Convert relative momentum deviation ``dp/p`` to MAD-NG ``pt``."""
|
|
62
|
+
return dp2pt(dp, self.beta)
|
|
63
|
+
|
|
64
|
+
def pt2dp(self, pt: float) -> float:
|
|
65
|
+
"""Convert MAD-NG ``pt`` to relative momentum deviation ``dp/p``."""
|
|
66
|
+
return pt2dp(pt, self.beta)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
@abstractmethod
|
|
70
|
+
def seq_name(self) -> str:
|
|
71
|
+
"""Return the sequence name for this accelerator.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
Sequence name to use in MAD
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
@abstractmethod
|
|
79
|
+
def ac_dipole_name(self) -> str:
|
|
80
|
+
"""Return the name of the AC-dipole element."""
|
|
81
|
+
|
|
82
|
+
def acd_marker_name(self, side: str) -> str:
|
|
83
|
+
"""Return a stable row name for the AC-dipole marker state."""
|
|
84
|
+
if side not in {"before", "after"}:
|
|
85
|
+
raise ValueError(f"side must be 'before' or 'after', got {side!r}")
|
|
86
|
+
marker_name = self.ac_dipole_name
|
|
87
|
+
return f"{marker_name}_{side}"
|
|
88
|
+
|
|
89
|
+
def kicker_marker_name(self, kicker_name: str) -> str:
|
|
90
|
+
"""Return the measured initial-condition marker name for kicker tracking."""
|
|
91
|
+
return kicker_name
|
|
92
|
+
|
|
93
|
+
def kicker_cycle_marker_name(self, kicker_name: str) -> str:
|
|
94
|
+
"""Return the unobserved centre marker used to cycle kicker-mode tracking."""
|
|
95
|
+
return f"{kicker_name}_centre"
|
|
96
|
+
|
|
97
|
+
def apply_accelerator_specific_errors(self, mad_iface: Any) -> None:
|
|
98
|
+
"""Apply machine-specific startup errors to a loaded MAD sequence."""
|
|
99
|
+
del mad_iface
|
|
100
|
+
|
|
101
|
+
def get_perturbation_families(self) -> dict[str, dict[str, str | float | dict]]:
|
|
102
|
+
"""Return per-family perturbation metadata keyed by family code d/q/s."""
|
|
103
|
+
return {}
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
@abstractmethod
|
|
107
|
+
def tune_variables(self) -> tuple[str, str]:
|
|
108
|
+
"""Return the MAD-X tune knob names (qx, qy)."""
|
|
109
|
+
|
|
110
|
+
@property
|
|
111
|
+
@abstractmethod
|
|
112
|
+
def tune_integers(self) -> tuple[int, int]:
|
|
113
|
+
"""Return the integer parts of the tunes (qx, qy)."""
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""FCC-ee accelerator implementation (LCC lattice, single ring)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
|
|
7
|
+
from pymadng_utils.accelerators.base import Accelerator
|
|
8
|
+
from pymadng_utils.physics import particle_mass
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
#: Total beam energy per FCC-ee mode, GeV.
|
|
14
|
+
FCC_ENERGY_GEV = {"z": 45.6, "w": 80.0, "h": 120.0, "t": 182.5}
|
|
15
|
+
#: Integer tunes of the LCC_107 Z lattice (166.16, 162.20).
|
|
16
|
+
FCC_Z_TUNE_INTEGERS = (166, 162)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FCC(Accelerator):
|
|
20
|
+
"""FCC-ee (LCC optics) accelerator configuration.
|
|
21
|
+
|
|
22
|
+
The LCC lattices are a single ring (``fccee_p_ring``) with lower-case element
|
|
23
|
+
names: BPMs ``bpm_<quad>``, quadrupoles ``q*``, and paired correctors
|
|
24
|
+
``hcor_<quad>`` / ``vcor_<quad>`` (MAD-X ``kicker`` with ``hkick`` / ``vkick``).
|
|
25
|
+
MAD-NG upper-cases element names when loading the madx, so the Lua patterns here
|
|
26
|
+
are upper case (MAD-X variables stay lower case).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
SEQUENCE_NAME = "fccee_p_ring"
|
|
30
|
+
BPM_PATTERN = "^BPM_.*$"
|
|
31
|
+
CORRECTOR_PATTERN = "^[HV]COR_"
|
|
32
|
+
#: Relative k1 calibration error used for the FCC-ee LOCO studies.
|
|
33
|
+
QUAD_REL_STD = 0.5e-2
|
|
34
|
+
#: The LCC madx is written for MAD-X's default rbarc=true (rbend l is the chord).
|
|
35
|
+
RBARC = True
|
|
36
|
+
#: Ignore the beam charge like MAD-X does (otherwise an electron flips every magnet strength).
|
|
37
|
+
NOCHARGE = True
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
sequence_file: Path | str,
|
|
42
|
+
kinetic_energy: float | None = None,
|
|
43
|
+
bpm_pattern: str = BPM_PATTERN,
|
|
44
|
+
particle: str = "electron",
|
|
45
|
+
mode: str = "z",
|
|
46
|
+
**kwargs,
|
|
47
|
+
):
|
|
48
|
+
"""Initialise the FCC-ee accelerator.
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
sequence_file: Path to the MAD-X sequence file (e.g. ``fccee_z.madx``)
|
|
52
|
+
kinetic_energy: Particle kinetic energy in GeV (default: the mode's beam energy
|
|
53
|
+
minus the particle mass)
|
|
54
|
+
bpm_pattern: Pattern for selecting BPMs
|
|
55
|
+
particle: Type of particle (default "electron"; MAD-NG runs with ``nocharge`` as the madx ignores the charge)
|
|
56
|
+
mode: FCC-ee running mode, one of ``z``, ``w``, ``h``, ``t``
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
ValueError: If an unknown mode is given
|
|
60
|
+
"""
|
|
61
|
+
mode = mode.lower()
|
|
62
|
+
if mode not in FCC_ENERGY_GEV:
|
|
63
|
+
raise ValueError(f"FCC mode must be one of {sorted(FCC_ENERGY_GEV)}, got {mode!r}")
|
|
64
|
+
self.mode = mode
|
|
65
|
+
super().__init__(
|
|
66
|
+
sequence_file=sequence_file,
|
|
67
|
+
kinetic_energy=(
|
|
68
|
+
FCC_ENERGY_GEV[mode] - particle_mass(particle)
|
|
69
|
+
if kinetic_energy is None
|
|
70
|
+
else kinetic_energy
|
|
71
|
+
),
|
|
72
|
+
bpm_pattern=bpm_pattern,
|
|
73
|
+
particle=particle,
|
|
74
|
+
**kwargs,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def seq_name(self) -> str:
|
|
79
|
+
"""Return the sequence name of the FCC-ee ring."""
|
|
80
|
+
return self.SEQUENCE_NAME
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def tune_variables(self) -> tuple[str, str]:
|
|
84
|
+
"""The LCC lattice files define no tune knobs."""
|
|
85
|
+
raise NotImplementedError("The FCC-ee LCC lattice has no tune knobs")
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def tune_integers(self) -> tuple[int, int]:
|
|
89
|
+
"""Return the integer tunes (Z lattice)."""
|
|
90
|
+
if self.mode != "z":
|
|
91
|
+
raise NotImplementedError(
|
|
92
|
+
f"Integer tunes are only known for the Z lattice, not {self.mode!r}"
|
|
93
|
+
)
|
|
94
|
+
return FCC_Z_TUNE_INTEGERS
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def ac_dipole_name(self) -> str:
|
|
98
|
+
"""FCC-ee has no AC dipole."""
|
|
99
|
+
raise NotImplementedError("FCC-ee has no AC-dipole exciter")
|
|
100
|
+
|
|
101
|
+
def get_perturbation_families(self) -> dict[str, dict[str, float | str | dict]]:
|
|
102
|
+
"""Return perturbation-family metadata for FCC-ee magnets."""
|
|
103
|
+
return {
|
|
104
|
+
"q": {
|
|
105
|
+
"default_rel_std": self.QUAD_REL_STD,
|
|
106
|
+
"pattern": r"(?i)^q",
|
|
107
|
+
},
|
|
108
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""LHC-specific accelerator implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import TYPE_CHECKING, ClassVar
|
|
7
|
+
|
|
8
|
+
from pymadng_utils.accelerators.base import Accelerator
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
LOGGER = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LHC(Accelerator):
|
|
17
|
+
"""Large Hadron Collider accelerator configuration.
|
|
18
|
+
|
|
19
|
+
Holds the beam number, sequence direction, BPM pattern, operational tune knobs
|
|
20
|
+
(``dqx_b<beam><suffix>``) and the integer tunes (62, 60).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
BPM_PATTERN = "^BPM.*$"
|
|
24
|
+
QUAD_ERROR_TABLE: ClassVar[dict[str, float]] = {
|
|
25
|
+
"MQ.": 18e-4,
|
|
26
|
+
"MQM": 12e-4,
|
|
27
|
+
"MQY": 8e-4,
|
|
28
|
+
"MQX": 10e-4,
|
|
29
|
+
"MQW": 15e-4,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
beam: int,
|
|
35
|
+
sequence_file: Path | str,
|
|
36
|
+
kinetic_energy: float = 6800.0,
|
|
37
|
+
bpm_pattern: str = BPM_PATTERN,
|
|
38
|
+
particle: str = "proton",
|
|
39
|
+
tune_knobs_suffix: str = "_op",
|
|
40
|
+
seq_dir: int | None = None,
|
|
41
|
+
**kwargs,
|
|
42
|
+
):
|
|
43
|
+
"""Initialise LHC accelerator for a specific beam.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
beam: Beam number (1 or 2)
|
|
47
|
+
sequence_file: Path to sequence file
|
|
48
|
+
kinetic_energy: Particle kinetic energy in GeV (default 6800 GeV for LHC)
|
|
49
|
+
bpm_pattern: Pattern for selecting BPMs
|
|
50
|
+
particle: Type of particle (default "proton")
|
|
51
|
+
tune_knobs_suffix: Suffix of the MAD-X tune knobs ``dqx_b<beam>`` / ``dqy_b<beam>``
|
|
52
|
+
seq_dir: MAD-NG sequence direction. Required for beam 2: -1 for the MAD-X beam-2
|
|
53
|
+
sequence (listed in beam-1 order), 1 for the beam-4 tracking sequence (also
|
|
54
|
+
named ``lhcb2``). Defaults to 1 for beam 1.
|
|
55
|
+
Raises:
|
|
56
|
+
ValueError: If an invalid beam number is provided
|
|
57
|
+
"""
|
|
58
|
+
if beam not in (1, 2):
|
|
59
|
+
raise ValueError(f"LHC beam must be 1 or 2, got {beam}")
|
|
60
|
+
self.beam = beam
|
|
61
|
+
self.tune_knobs_suffix = tune_knobs_suffix
|
|
62
|
+
if seq_dir is None:
|
|
63
|
+
if beam == 2:
|
|
64
|
+
raise ValueError(
|
|
65
|
+
"LHC beam 2 needs seq_dir: -1 (MAD-X beam 2) or 1 (beam-4 tracking)"
|
|
66
|
+
)
|
|
67
|
+
seq_dir = 1
|
|
68
|
+
self.seq_dir = seq_dir
|
|
69
|
+
super().__init__(
|
|
70
|
+
sequence_file=sequence_file,
|
|
71
|
+
kinetic_energy=kinetic_energy,
|
|
72
|
+
bpm_pattern=bpm_pattern,
|
|
73
|
+
particle=particle,
|
|
74
|
+
**kwargs,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def seq_name(self) -> str:
|
|
79
|
+
"""Return the sequence name for this LHC beam."""
|
|
80
|
+
return f"lhcb{self.beam}"
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def tune_variables(self) -> tuple[str, str]:
|
|
84
|
+
"""Return LHC operational tune knob names."""
|
|
85
|
+
return (
|
|
86
|
+
f"dqx_b{self.beam}{self.tune_knobs_suffix}",
|
|
87
|
+
f"dqy_b{self.beam}{self.tune_knobs_suffix}",
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def tune_integers(self) -> tuple[int, int]:
|
|
92
|
+
"""Return LHC integer tunes."""
|
|
93
|
+
return 62, 60
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def ac_dipole_name(self) -> str:
|
|
97
|
+
"""Return the LHC AC-dipole element name."""
|
|
98
|
+
return f"MKQA.6L4.B{self.beam}"
|
|
99
|
+
|
|
100
|
+
def get_perturbation_families(self) -> dict[str, dict[str, float | str | dict]]:
|
|
101
|
+
"""Return perturbation-family metadata for LHC magnets."""
|
|
102
|
+
return {
|
|
103
|
+
"d": {
|
|
104
|
+
"default_rel_std": 1e-4,
|
|
105
|
+
"pattern": r"^MB",
|
|
106
|
+
},
|
|
107
|
+
"q": {
|
|
108
|
+
"relative_error_table": self.QUAD_ERROR_TABLE,
|
|
109
|
+
"pattern": r"^MQ",
|
|
110
|
+
},
|
|
111
|
+
"s": {
|
|
112
|
+
"default_rel_std": 1e-4,
|
|
113
|
+
"pattern": r"^MS",
|
|
114
|
+
},
|
|
115
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""PSB-specific accelerator implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pymadng_utils.accelerators.base import (
|
|
9
|
+
Accelerator,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
PSB_FLAT_BOTTOM_GEV = 0.160
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _infer_psb_ring_number(sequence_path: Path) -> int:
|
|
16
|
+
match = re.search(r"psb(\d+)", sequence_path.name, re.IGNORECASE)
|
|
17
|
+
if match is not None:
|
|
18
|
+
return int(match.group(1))
|
|
19
|
+
raise ValueError(
|
|
20
|
+
f"Could not infer PSB ring number from sequence file name: {sequence_path.name}"
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PSB(Accelerator):
|
|
25
|
+
"""Proton Synchrotron Booster accelerator configuration."""
|
|
26
|
+
|
|
27
|
+
BPM_PATTERN_TEMPLATE = "^BR{ring}%.BPM.*{ring}$"
|
|
28
|
+
SEXTUPOLE_PATTERN = r"^BR%d+%.XNO.*"
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
sequence_file: Path | str,
|
|
33
|
+
ring: int | None = None,
|
|
34
|
+
kinetic_energy: float = PSB_FLAT_BOTTOM_GEV,
|
|
35
|
+
bpm_pattern: str | None = None,
|
|
36
|
+
particle: str = "proton",
|
|
37
|
+
**kwargs,
|
|
38
|
+
) -> None:
|
|
39
|
+
if ring is None:
|
|
40
|
+
ring = _infer_psb_ring_number(Path(sequence_file))
|
|
41
|
+
if ring not in (1, 2, 3, 4):
|
|
42
|
+
raise ValueError(f"PSB ring must be 1, 2, 3, or 4, got {ring}")
|
|
43
|
+
|
|
44
|
+
self.ring = ring
|
|
45
|
+
super().__init__(
|
|
46
|
+
sequence_file=sequence_file,
|
|
47
|
+
kinetic_energy=kinetic_energy,
|
|
48
|
+
bpm_pattern=bpm_pattern or self.BPM_PATTERN_TEMPLATE.format(ring=ring),
|
|
49
|
+
particle=particle,
|
|
50
|
+
**kwargs,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def seq_name(self) -> str:
|
|
55
|
+
"""Return the sequence name for the selected PSB ring."""
|
|
56
|
+
return f"psb{self.ring}"
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def ac_dipole_name(self) -> str:
|
|
60
|
+
"""Return the PSB AC-dipole installation element."""
|
|
61
|
+
return "HACMAP" # marker installed by the model-creation workflow
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def tune_variables(self) -> tuple[str, str]:
|
|
65
|
+
"""Return PSB tune variable names."""
|
|
66
|
+
return "kBRQF", "kBRQD"
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def tune_integers(self) -> tuple[int, int]:
|
|
70
|
+
"""Return PSB integer tunes."""
|
|
71
|
+
return 4, 4
|
|
72
|
+
|
|
73
|
+
@staticmethod
|
|
74
|
+
def infer_monitor_plane(bpm_name: str) -> str:
|
|
75
|
+
"""Return ``"HV"`` (both planes) for a PSB monitor name; raise for other names."""
|
|
76
|
+
name = bpm_name.upper()
|
|
77
|
+
if any(token in name for token in (".BPM", ".BWS", ".BPP", ".BPT")):
|
|
78
|
+
return "HV"
|
|
79
|
+
raise ValueError(f"Unsupported PSB monitor name for plane inference: {bpm_name}")
|
pymadng_utils/config.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utilities for reading and saving knob data.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def read_knobs(file_path: str | Path) -> dict[str, float]:
|
|
14
|
+
"""
|
|
15
|
+
Read knob strengths from a tab-delimited file.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
file_path: File where each line is "knob_name\tstrength"; lines without exactly two
|
|
19
|
+
tab-separated fields are skipped.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
A dictionary mapping knob names to their float strengths.
|
|
23
|
+
"""
|
|
24
|
+
path = Path(file_path)
|
|
25
|
+
logger.info(f"Reading knobs from {path}")
|
|
26
|
+
strengths: dict[str, float] = {}
|
|
27
|
+
with path.open("r") as f:
|
|
28
|
+
for line in f:
|
|
29
|
+
parts = line.strip().split("\t")
|
|
30
|
+
if len(parts) != 2:
|
|
31
|
+
continue
|
|
32
|
+
knob, val = parts
|
|
33
|
+
strengths[knob] = float(val)
|
|
34
|
+
logger.debug(f"Read {len(strengths)} knobs from {path}")
|
|
35
|
+
return strengths
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def save_knobs(knobs: dict[str, float], filepath: Path) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Write knob strengths to a tab-separated file, one "knob_name\tstrength" line per knob.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
knobs: Dictionary of knob names and values
|
|
44
|
+
filepath: Path of the file to write
|
|
45
|
+
"""
|
|
46
|
+
logger.info(f"Saving {len(knobs)} knobs to {filepath}")
|
|
47
|
+
with filepath.open("w") as f:
|
|
48
|
+
for key, val in knobs.items():
|
|
49
|
+
f.write(f"{key}\t{val: .15e}\n")
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""MAD-NG interface utilities."""
|
|
2
|
+
|
|
3
|
+
from .accelerator_mad_interface import (
|
|
4
|
+
AcceleratorErrorsMadInterface,
|
|
5
|
+
AcceleratorMadInterface,
|
|
6
|
+
)
|
|
7
|
+
from .knob_mad_interface import KnobMadInterface
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"AcceleratorErrorsMadInterface",
|
|
11
|
+
"AcceleratorMadInterface",
|
|
12
|
+
"KnobMadInterface",
|
|
13
|
+
]
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Thin flattop AC kickers: install them at the AC-dipole element and drive their knobs.
|
|
2
|
+
|
|
3
|
+
Each plane has two fixed-phase kickers, ``a`` (lag 0, sin) and ``b`` (lag 1/4, cos), so the
|
|
4
|
+
kick ``0.3 / pc (a sin(phi) + b cos(phi))`` with ``phi = 2 pi turn freq`` is linear in the volts
|
|
5
|
+
``a`` and ``b``. ``turn`` is the MAD-NG turn counter.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from pymadng import MAD
|
|
14
|
+
|
|
15
|
+
#: ``(name, plane, lag in turns)`` per kicker; plane 0 = horizontal, 1 = vertical.
|
|
16
|
+
KICKER_SPECS = (
|
|
17
|
+
("hackicker_a", 0, 0.0),
|
|
18
|
+
("hackicker_b", 0, 0.25),
|
|
19
|
+
("vackicker_a", 1, 0.0),
|
|
20
|
+
("vackicker_b", 1, 0.25),
|
|
21
|
+
)
|
|
22
|
+
#: Kicker element names in ``KICKER_SPECS`` order.
|
|
23
|
+
AC_KICKERS = tuple(name for name, _, _ in KICKER_SPECS)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _for_each_kicker(mad: MAD, body: str) -> None:
|
|
27
|
+
"""Run ``body`` in Lua for each kicker, with ``i`` (1-based index) and ``e`` (element) set."""
|
|
28
|
+
names = ", ".join(f"'{name}'" for name in AC_KICKERS)
|
|
29
|
+
mad.send(f"""
|
|
30
|
+
for i, name in ipairs {{{names}}} do
|
|
31
|
+
local e = loaded_sequence[name]
|
|
32
|
+
{body}
|
|
33
|
+
end
|
|
34
|
+
""")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def install_ac_kickers(
|
|
38
|
+
mad: MAD,
|
|
39
|
+
acd_name: str,
|
|
40
|
+
kicks: tuple[float, float, float, float],
|
|
41
|
+
freqs: tuple[float, float],
|
|
42
|
+
) -> None:
|
|
43
|
+
"""Install the kickers at the position of the thin element ``acd_name``, which is kept.
|
|
44
|
+
|
|
45
|
+
``kicks`` = (a_x, b_x, a_y, b_y) are the initial volts; ``freqs`` = (h, v) drive tunes.
|
|
46
|
+
"""
|
|
47
|
+
elements = ",\n".join(
|
|
48
|
+
f" {'hackicker' if plane == 0 else 'vackicker'} '{name}' "
|
|
49
|
+
f"{{at=at, volt=kicks[{i}], freq=freqs[{plane + 1}], lag={lag!r}, ramp=ramp}}"
|
|
50
|
+
for i, (name, plane, lag) in enumerate(KICKER_SPECS, start=1)
|
|
51
|
+
)
|
|
52
|
+
mad.send(f"""
|
|
53
|
+
local hackicker, vackicker in MAD.element
|
|
54
|
+
local kicks, freqs = {mad.py_name}:recv(), {mad.py_name}:recv()
|
|
55
|
+
local acd = loaded_sequence['{acd_name}']
|
|
56
|
+
assert(acd and acd.l == 0, "AC kickers need a thin AC-dipole element")
|
|
57
|
+
local at = loaded_sequence:spos(loaded_sequence:index_of(acd))
|
|
58
|
+
local ramp = {{0, 0, 1e12, 1e12}}
|
|
59
|
+
loaded_sequence:install{{
|
|
60
|
+
{elements}
|
|
61
|
+
}}
|
|
62
|
+
{mad.py_name}:send(true)
|
|
63
|
+
""")
|
|
64
|
+
mad.send([float(v) for v in kicks])
|
|
65
|
+
mad.send([float(v) for v in freqs])
|
|
66
|
+
if not mad.recv():
|
|
67
|
+
raise RuntimeError("Failed to install AC kickers")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def set_ac_kicker_freqs(mad: MAD, freqs: tuple[float, float]) -> None:
|
|
71
|
+
"""Set every kicker's ``freq`` to its plane's drive tune ``freqs`` = (h, v)."""
|
|
72
|
+
values = ", ".join(repr(float(freqs[plane])) for _, plane, _ in KICKER_SPECS)
|
|
73
|
+
_for_each_kicker(mad, f"e.freq = ({{{values}}})[i]")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def bind_ac_kicker_volts(mad: MAD, variables: tuple[str, str, str, str]) -> None:
|
|
77
|
+
"""Make each kicker's ``volt`` follow ``loaded_sequence[variable]`` (deferred)."""
|
|
78
|
+
names = ", ".join(f"'{v}'" for v in variables)
|
|
79
|
+
_for_each_kicker(mad, f"local var = ({{{names}}})[i]; e.volt = \\-> loaded_sequence[var]")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def shift_ac_kicker_phase(mad: MAD, turn_offset: int) -> None:
|
|
83
|
+
"""Make MAD turn ``t`` act as turn ``t + turn_offset``: ``lag = lag0 + turn_offset freq``."""
|
|
84
|
+
lags = ", ".join(repr(lag) for _, _, lag in KICKER_SPECS)
|
|
85
|
+
_for_each_kicker(
|
|
86
|
+
mad, f"local lag = ({{{lags}}})[i]; e.lag = \\s -> lag + {int(turn_offset)} * s.freq"
|
|
87
|
+
)
|