accelmo 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.
Files changed (95) hide show
  1. accelmo/__init__.py +8 -0
  2. accelmo/analysis/__init__.py +21 -0
  3. accelmo/analysis/degeneracy_checker.py +308 -0
  4. accelmo/backend/__init__.py +26 -0
  5. accelmo/backend/madng/__init__.py +5 -0
  6. accelmo/backend/madng/accelerator_hooks.py +171 -0
  7. accelmo/backend/madng/engines.py +535 -0
  8. accelmo/backend/madng/interface.py +600 -0
  9. accelmo/backend/madng/machine_state.py +62 -0
  10. accelmo/backend/madng/mad_scripts/run_closed_twiss_init.mad +399 -0
  11. accelmo/backend/madng/scripts.py +367 -0
  12. accelmo/backend/protocol.py +274 -0
  13. accelmo/backend/xtrack/__init__.py +1 -0
  14. accelmo/backend/xtrack/engines.py +366 -0
  15. accelmo/backend/xtrack/model.py +292 -0
  16. accelmo/config.py +169 -0
  17. accelmo/fitting/__init__.py +4 -0
  18. accelmo/fitting/bpm_gains.py +54 -0
  19. accelmo/fitting/config.py +44 -0
  20. accelmo/fitting/lifecycle.py +40 -0
  21. accelmo/fitting/lm_loop.py +212 -0
  22. accelmo/fitting/pool.py +75 -0
  23. accelmo/fitting/priors.py +58 -0
  24. accelmo/fitting/protocol.py +265 -0
  25. accelmo/fitting/reduction.py +65 -0
  26. accelmo/fitting/results.py +36 -0
  27. accelmo/fitting/setup.py +239 -0
  28. accelmo/fitting/shared_reference.py +102 -0
  29. accelmo/fitting/uncertainty.py +115 -0
  30. accelmo/fitting/weights.py +13 -0
  31. accelmo/fitting/worker.py +250 -0
  32. accelmo/machine/__init__.py +1 -0
  33. accelmo/machine/accelerators/__init__.py +27 -0
  34. accelmo/machine/accelerators/base.py +276 -0
  35. accelmo/machine/accelerators/fcc.py +82 -0
  36. accelmo/machine/accelerators/lhc.py +188 -0
  37. accelmo/machine/accelerators/magnet_grouping.py +149 -0
  38. accelmo/machine/accelerators/psb.py +202 -0
  39. accelmo/machine/accelerators/selection.py +109 -0
  40. accelmo/machine/accelerators/sps.py +125 -0
  41. accelmo/machine/knob_names.py +14 -0
  42. accelmo/machine/machine_state.py +65 -0
  43. accelmo/machine/patterns.py +96 -0
  44. accelmo/momentum_reference.py +271 -0
  45. accelmo/monitor/__init__.py +21 -0
  46. accelmo/monitor/__main__.py +52 -0
  47. accelmo/monitor/app.py +338 -0
  48. accelmo/monitor/cache.py +240 -0
  49. accelmo/monitor/panels.py +261 -0
  50. accelmo/monitor/source.py +52 -0
  51. accelmo/monitor/view.py +39 -0
  52. accelmo/optimisers/__init__.py +18 -0
  53. accelmo/optimisers/adam.py +136 -0
  54. accelmo/optimisers/base.py +84 -0
  55. accelmo/optimisers/lbfgs.py +208 -0
  56. accelmo/optimisers/levenberg_marquardt.py +253 -0
  57. accelmo/poco/__init__.py +34 -0
  58. accelmo/poco/calibrated.py +328 -0
  59. accelmo/poco/calibration.py +234 -0
  60. accelmo/poco/closed_orbit.py +335 -0
  61. accelmo/poco/fitter.py +410 -0
  62. accelmo/poco/workers/__init__.py +1 -0
  63. accelmo/poco/workers/calibrated.py +200 -0
  64. accelmo/poco/workers/closed_orbit.py +501 -0
  65. accelmo/poco/workers/closed_twiss.py +174 -0
  66. accelmo/runlog/__init__.py +25 -0
  67. accelmo/runlog/reader.py +127 -0
  68. accelmo/runlog/writer.py +150 -0
  69. accelmo/tracking/__init__.py +59 -0
  70. accelmo/tracking/config/__init__.py +29 -0
  71. accelmo/tracking/config/helpers.py +43 -0
  72. accelmo/tracking/config/models.py +66 -0
  73. accelmo/tracking/config/tracking.py +535 -0
  74. accelmo/tracking/data_manager.py +476 -0
  75. accelmo/tracking/dispatch/__init__.py +1 -0
  76. accelmo/tracking/dispatch/payloads.py +210 -0
  77. accelmo/tracking/dispatch/setup.py +212 -0
  78. accelmo/tracking/dispatch/turn_planner.py +196 -0
  79. accelmo/tracking/fitter.py +698 -0
  80. accelmo/tracking/ic_iteration.py +110 -0
  81. accelmo/tracking/lm_problem.py +252 -0
  82. accelmo/tracking/ranges.py +112 -0
  83. accelmo/tracking/session.py +301 -0
  84. accelmo/tracking/sgd/__init__.py +1 -0
  85. accelmo/tracking/sgd/checkpointing.py +229 -0
  86. accelmo/tracking/sgd/loop.py +327 -0
  87. accelmo/tracking/sgd/scheduler.py +70 -0
  88. accelmo/tracking/uncertainty.py +160 -0
  89. accelmo/tracking/worker.py +661 -0
  90. accelmo-0.0.1.dist-info/METADATA +208 -0
  91. accelmo-0.0.1.dist-info/RECORD +95 -0
  92. accelmo-0.0.1.dist-info/WHEEL +5 -0
  93. accelmo-0.0.1.dist-info/entry_points.txt +2 -0
  94. accelmo-0.0.1.dist-info/licenses/LICENSE +21 -0
  95. accelmo-0.0.1.dist-info/top_level.txt +1 -0
accelmo/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Public interface for the accelmo package.
2
+
3
+ The package bundles configuration helpers, optimiser implementations, and
4
+ simulation orchestrators for magnet knob tuning studies.
5
+ """
6
+
7
+ # The top-level package intentionally does not re-export a large symbol surface.
8
+ __all__ = []
@@ -0,0 +1,21 @@
1
+ """Analysis utilities that inspect a fit without changing the optimisation.
2
+
3
+ Currently this exposes the degeneracy checker, which examines the Gauss-Newton
4
+ normal matrix ``A = JᵀWJ`` to reveal knob combinations the measurement cannot
5
+ constrain - the flat directions that make an optimiser wander instead of
6
+ converging to a unique minimum.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from accelmo.analysis.degeneracy_checker import (
12
+ DegeneracyReport,
13
+ DegenerateDirection,
14
+ analyse_degeneracy,
15
+ )
16
+
17
+ __all__ = [
18
+ "DegeneracyReport",
19
+ "DegenerateDirection",
20
+ "analyse_degeneracy",
21
+ ]
@@ -0,0 +1,308 @@
1
+ """Detect degenerate (unconstrained) knob directions before optimising.
2
+
3
+ Background
4
+ ----------
5
+ A weighted least-squares fit ``min_x Σ w r(x)²`` is well-posed only if the
6
+ measurement constrains every knob combination. Otherwise the Gauss-Newton normal
7
+ matrix ``A = JᵀWJ`` (``J`` the residual Jacobian, ``W`` the inverse-variance
8
+ weights) is rank-deficient or ill-conditioned, with near-zero eigenvalues whose
9
+ eigenvectors are knob combinations the data cannot constrain. An optimiser started
10
+ on such a problem has no unique minimum: the knobs drift along the flat direction
11
+ with little change in loss.
12
+
13
+ ``A`` is the matrix already accumulated for parameter uncertainties
14
+ (:func:`accelmo.fitting.uncertainty.hessian_uncertainties`). Its eigenspectrum at
15
+ the initial knobs identifies a degenerate fit, and the knob combinations
16
+ responsible, before optimisation, so the user can regularise, remove knobs or add
17
+ independent data.
18
+
19
+ Unit scaling
20
+ ------------
21
+ The raw ``A`` mixes knobs of different physical scale (dipole ``k0``, quad ``k1``,
22
+ ``pt``), so its condition number reflects unit disparity as well as degeneracy. By
23
+ default the analysis uses the symmetrically scaled matrix
24
+ ``Ã = D^{-1/2} A D^{-1/2}`` with ``D = diag(A)``. It is dimensionless with unit
25
+ diagonal for every constrained knob, so a small eigenvalue indicates an
26
+ unconstrained *combination* rather than a small-valued knob. Knobs with zero
27
+ sensitivity (``diag(A) == 0``) are reported separately as fully unconstrained.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from dataclasses import dataclass, field
33
+
34
+ import numpy as np
35
+
36
+ from accelmo.fitting.uncertainty import hessian_uncertainties
37
+
38
+ # Default relative tolerance for calling a (scaled) eigenvalue "null". Scaled
39
+ # eigenvalues are O(1) for well-constrained directions, so this compares against
40
+ # the largest eigenvalue rather than an absolute floor.
41
+ DEFAULT_REL_TOL = 1e-8
42
+
43
+ # Below this fraction of the largest self-sensitivity, a knob's diagonal entry is
44
+ # treated as a structural zero (no sensitivity at all). This is deliberately tiny:
45
+ # it exists only to catch genuinely dead columns (and numerical fuzz on them), not
46
+ # to demote knobs that are merely far less sensitive than the strongest one - unit
47
+ # disparity between real knobs is handled by the symmetric scaling instead.
48
+ DEFAULT_ZERO_SENSITIVITY_REL = 1e-15
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class DegenerateDirection:
53
+ """One near-null direction of the normal matrix - an unconstrained combination.
54
+
55
+ Attributes:
56
+ eigenvalue: Scaled eigenvalue (``≈ 0`` for a perfectly flat direction).
57
+ relative_eigenvalue: ``eigenvalue / largest eigenvalue``; the size of this
58
+ direction's curvature relative to the best-constrained direction.
59
+ components: Combination coefficients in knob space, one per knob, unit-norm.
60
+ The knobs trade off along ``Σ components[i] * knob[i]``.
61
+ contributions: ``(knob_name, coefficient)`` pairs for the knobs that
62
+ dominate this direction, largest ``|coefficient|`` first.
63
+ """
64
+
65
+ eigenvalue: float
66
+ relative_eigenvalue: float
67
+ components: np.ndarray
68
+ contributions: list[tuple[str, float]] = field(default_factory=list)
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class DegeneracyReport:
73
+ """Result of :func:`analyse_degeneracy`.
74
+
75
+ Attributes:
76
+ knob_names: Knob ordering matching every per-knob array below.
77
+ scaled: Whether the eigen-analysis used the unit-scaled matrix.
78
+ eigenvalues: Eigenvalues of the (scaled) normal matrix, descending.
79
+ eigenvectors: Corresponding eigenvectors as columns, in knob space and
80
+ aligned with ``eigenvalues``.
81
+ condition_number: ``λ_max / λ_min`` over the positive eigenvalues; ``inf``
82
+ when any direction is exactly flat.
83
+ numerical_rank: Number of eigenvalues above ``rel_tol * λ_max``.
84
+ n_degenerate: ``len(knob_names) - numerical_rank`` - the number of
85
+ unconstrained knob combinations.
86
+ degenerate_directions: The near-null directions, weakest first.
87
+ zero_sensitivity_knobs: Knobs whose data sensitivity is (numerically) zero.
88
+ uncertainties: Physical 1σ uncertainty per knob from the *raw* matrix.
89
+ rel_tol: Relative tolerance used for the rank decision.
90
+ """
91
+
92
+ knob_names: list[str]
93
+ scaled: bool
94
+ eigenvalues: np.ndarray
95
+ eigenvectors: np.ndarray
96
+ condition_number: float
97
+ numerical_rank: int
98
+ n_degenerate: int
99
+ degenerate_directions: list[DegenerateDirection]
100
+ zero_sensitivity_knobs: list[str]
101
+ uncertainties: dict[str, float]
102
+ rel_tol: float
103
+
104
+ @property
105
+ def is_degenerate(self) -> bool:
106
+ """True when at least one knob combination is unconstrained by the data."""
107
+ return self.n_degenerate > 0
108
+
109
+ def worst_constrained_knobs(self, count: int = 10) -> list[tuple[str, float]]:
110
+ """Knobs with the largest physical uncertainty, worst first."""
111
+ ordered = sorted(self.uncertainties.items(), key=lambda kv: kv[1], reverse=True)
112
+ return ordered[:count]
113
+
114
+ def summary(self, *, max_directions: int = 10, max_knobs: int = 8) -> str:
115
+ """Human-readable overview suitable for logging before an optimisation."""
116
+ lines: list[str] = []
117
+ verdict = "DEGENERATE" if self.is_degenerate else "well-posed"
118
+ lines.append(
119
+ f"Degeneracy check ({'scaled' if self.scaled else 'raw'}): {verdict} - "
120
+ f"{self.numerical_rank}/{len(self.knob_names)} knob directions constrained, "
121
+ f"{self.n_degenerate} unconstrained."
122
+ )
123
+ cond = self.condition_number
124
+ cond_str = "inf" if not np.isfinite(cond) else f"{cond:.3e}"
125
+ lines.append(f" condition number = {cond_str} (rel_tol = {self.rel_tol:.1e})")
126
+
127
+ if self.zero_sensitivity_knobs:
128
+ preview = ", ".join(self.zero_sensitivity_knobs[:max_knobs])
129
+ extra = len(self.zero_sensitivity_knobs) - max_knobs
130
+ if extra > 0:
131
+ preview += f", ... (+{extra} more)"
132
+ lines.append(f" zero-sensitivity knobs (data cannot see them): {preview}")
133
+
134
+ if self.degenerate_directions:
135
+ lines.append(" unconstrained knob combinations (weakest first):")
136
+ for i, direction in enumerate(self.degenerate_directions[:max_directions]):
137
+ terms = ", ".join(
138
+ f"{coeff:+.2f}*{name}"
139
+ for name, coeff in direction.contributions[:max_knobs]
140
+ )
141
+ lines.append(
142
+ f" [{i}] rel_eig={direction.relative_eigenvalue:.2e}: {terms}"
143
+ )
144
+ hidden = len(self.degenerate_directions) - max_directions
145
+ if hidden > 0:
146
+ lines.append(f" ... (+{hidden} more directions)")
147
+
148
+ worst = self.worst_constrained_knobs(max_knobs)
149
+ if worst:
150
+ worst_str = ", ".join(f"{name}={sigma:.2e}" for name, sigma in worst)
151
+ lines.append(f" largest 1σ uncertainties: {worst_str}")
152
+ return "\n".join(lines)
153
+
154
+
155
+ def _extract_contributions(
156
+ components: np.ndarray,
157
+ knob_names: list[str],
158
+ *,
159
+ contribution_threshold: float,
160
+ ) -> list[tuple[str, float]]:
161
+ """Return dominant ``(knob, coefficient)`` pairs of a unit-norm direction."""
162
+ magnitudes = np.abs(components)
163
+ peak = float(magnitudes.max()) if magnitudes.size else 0.0
164
+ if peak == 0.0:
165
+ return []
166
+ cutoff = contribution_threshold * peak
167
+ order = np.argsort(magnitudes)[::-1]
168
+ return [
169
+ (knob_names[i], float(components[i]))
170
+ for i in order
171
+ if magnitudes[i] >= cutoff
172
+ ]
173
+
174
+
175
+ def analyse_degeneracy(
176
+ normal_matrix: np.ndarray,
177
+ knob_names: list[str],
178
+ *,
179
+ scale: bool = True,
180
+ rel_tol: float = DEFAULT_REL_TOL,
181
+ contribution_threshold: float = 0.1,
182
+ zero_sensitivity_rel: float = DEFAULT_ZERO_SENSITIVITY_REL,
183
+ ) -> DegeneracyReport:
184
+ """Diagnose unconstrained knob directions from a Gauss-Newton normal matrix.
185
+
186
+ Args:
187
+ normal_matrix: The weighted normal matrix ``A = JᵀWJ`` (symmetric, positive
188
+ semi-definite), as accumulated by the tracking workers. Evaluate it at
189
+ the *initial* knobs to diagnose the problem before optimising.
190
+ knob_names: Names of the knobs, in the row/column order of ``normal_matrix``.
191
+ scale: If True (default), analyse the dimensionless symmetrically scaled
192
+ matrix ``D^{-1/2} A D^{-1/2}`` so the verdict reflects
193
+ collinearity rather than unit disparity between knobs.
194
+ rel_tol: A direction is "unconstrained" when its eigenvalue is below
195
+ ``rel_tol * λ_max``.
196
+ contribution_threshold: A knob is listed as contributing to a degenerate
197
+ direction when ``|coefficient| >= contribution_threshold * max|coeff|``.
198
+ zero_sensitivity_rel: A knob is treated as having zero sensitivity when its
199
+ diagonal entry is below ``zero_sensitivity_rel * max(diag)``.
200
+
201
+ Returns:
202
+ A :class:`DegeneracyReport`.
203
+
204
+ Raises:
205
+ ValueError: If ``normal_matrix`` is not square or ``knob_names`` does not
206
+ match its dimension.
207
+ """
208
+ matrix = np.asarray(normal_matrix, dtype=np.float64)
209
+ if matrix.ndim != 2 or matrix.shape[0] != matrix.shape[1]:
210
+ raise ValueError(f"normal_matrix must be square, got shape {matrix.shape}")
211
+ n = matrix.shape[0]
212
+ if len(knob_names) != n:
213
+ raise ValueError(
214
+ f"knob_names has {len(knob_names)} entries but normal_matrix is {n}x{n}"
215
+ )
216
+ if not np.all(np.isfinite(matrix)):
217
+ raise ValueError("normal_matrix contains non-finite entries (NaN or inf)")
218
+ knob_names = list(knob_names)
219
+
220
+ sym = 0.5 * (matrix + matrix.T)
221
+
222
+ # Physical 1σ uncertainties come from the *raw* matrix (real parameter units).
223
+ uncertainty_values = hessian_uncertainties(sym)
224
+ uncertainties = dict(zip(knob_names, (float(u) for u in uncertainty_values)))
225
+
226
+ diag = np.diag(sym)
227
+ diag_max = float(diag.max()) if n else 0.0
228
+ zero_sens_mask = diag <= (zero_sensitivity_rel * diag_max if diag_max > 0.0 else 0.0)
229
+ zero_sensitivity_knobs = [knob_names[i] for i in np.nonzero(zero_sens_mask)[0]]
230
+
231
+ if scale:
232
+ # Symmetric scaling: unit diagonal for every knob with sensitivity, and an
233
+ # all-zero row/column (hence an exact zero eigenvalue with a unit-vector
234
+ # eigenvector) for every zero-sensitivity knob.
235
+ inv_sqrt = np.zeros(n, dtype=np.float64)
236
+ good = ~zero_sens_mask
237
+ inv_sqrt[good] = 1.0 / np.sqrt(diag[good])
238
+ work = sym * np.outer(inv_sqrt, inv_sqrt)
239
+ else:
240
+ work = sym
241
+
242
+ eigenvalues, eigenvectors = np.linalg.eigh(work)
243
+ # eigh returns ascending; reorder to descending for readability.
244
+ order = np.argsort(eigenvalues)[::-1]
245
+ eigenvalues = eigenvalues[order]
246
+ eigenvectors = eigenvectors[:, order]
247
+
248
+ lambda_max = float(eigenvalues[0]) if n else 0.0
249
+ # Numerical noise can push tiny eigenvalues slightly negative; clamp for reporting.
250
+ clamped = np.clip(eigenvalues, 0.0, None)
251
+ threshold = rel_tol * lambda_max if lambda_max > 0.0 else 0.0
252
+ constrained_mask = clamped > threshold
253
+ numerical_rank = int(np.count_nonzero(constrained_mask))
254
+ n_degenerate = n - numerical_rank
255
+
256
+ positive = clamped[clamped > threshold]
257
+ if positive.size and positive.min() > 0.0 and numerical_rank == n:
258
+ condition_number = float(lambda_max / positive.min())
259
+ else:
260
+ # At least one flat/near-flat direction: treat as singular.
261
+ condition_number = float("inf")
262
+
263
+ degenerate_directions: list[DegenerateDirection] = []
264
+ for idx in range(n):
265
+ if constrained_mask[idx]:
266
+ continue
267
+ components = eigenvectors[:, idx]
268
+ # Normalise sign so the dominant component is positive (stable presentation).
269
+ peak_idx = int(np.argmax(np.abs(components)))
270
+ if components[peak_idx] < 0:
271
+ components = -components
272
+ contributions = _extract_contributions(
273
+ components, knob_names, contribution_threshold=contribution_threshold
274
+ )
275
+ degenerate_directions.append(
276
+ DegenerateDirection(
277
+ eigenvalue=float(eigenvalues[idx]),
278
+ relative_eigenvalue=(
279
+ float(clamped[idx] / lambda_max) if lambda_max > 0.0 else 0.0
280
+ ),
281
+ components=components.copy(),
282
+ contributions=contributions,
283
+ )
284
+ )
285
+ # Weakest (most degenerate) direction first.
286
+ degenerate_directions.sort(key=lambda d: d.relative_eigenvalue)
287
+
288
+ return DegeneracyReport(
289
+ knob_names=knob_names,
290
+ scaled=scale,
291
+ eigenvalues=eigenvalues,
292
+ eigenvectors=eigenvectors,
293
+ condition_number=condition_number,
294
+ numerical_rank=numerical_rank,
295
+ n_degenerate=n_degenerate,
296
+ degenerate_directions=degenerate_directions,
297
+ zero_sensitivity_knobs=zero_sensitivity_knobs,
298
+ uncertainties=uncertainties,
299
+ rel_tol=rel_tol,
300
+ )
301
+
302
+
303
+ __all__ = [
304
+ "DEFAULT_REL_TOL",
305
+ "DegeneracyReport",
306
+ "DegenerateDirection",
307
+ "analyse_degeneracy",
308
+ ]
@@ -0,0 +1,26 @@
1
+ """Model backends: MAD-NG (``madng``) and xtrack (``xtrack``). See :mod:`accelmo.backend.protocol`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib import import_module
6
+ from typing import TYPE_CHECKING, cast
7
+
8
+ if TYPE_CHECKING:
9
+ from accelmo.backend.protocol import Backend
10
+
11
+ BACKENDS = ("madng", "xtrack")
12
+
13
+
14
+ def get_backend(name: str) -> Backend:
15
+ """The backend module ``accelmo.backend.<name>.engines``."""
16
+ if name not in BACKENDS:
17
+ raise ValueError(f"Unknown backend {name!r}; valid: {BACKENDS}")
18
+ try:
19
+ return cast("Backend", import_module(f"accelmo.backend.{name}.engines"))
20
+ except ModuleNotFoundError as err:
21
+ if name == "xtrack" and err.name in {"xtrack", "xtrack_tools"}:
22
+ raise ImportError(
23
+ "The xtrack backend needs xtrack (with tpsa) and xtrack_tools, which are not "
24
+ "installed by accelmo."
25
+ ) from err
26
+ raise
@@ -0,0 +1,5 @@
1
+ """MAD-NG backend: everything that imports ``pymadng`` or ``pymadng_utils.mad`` or sends Lua."""
2
+
3
+ from .interface import MadInterface
4
+
5
+ __all__ = ["MadInterface"]
@@ -0,0 +1,171 @@
1
+ """MAD-NG side of the accelerator definitions: Lua run around knob creation, per-kind track methods."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import textwrap
6
+ from typing import TYPE_CHECKING
7
+
8
+ from pymadng_utils.mad.ac_kickers import AC_KICKERS
9
+
10
+ from accelmo.machine.accelerators import LHC, PSB
11
+ from accelmo.machine.accelerators.magnet_grouping import normalise_lhcbend_magnets
12
+
13
+ if TYPE_CHECKING:
14
+ from accelmo.backend.madng.interface import MadInterface
15
+ from accelmo.machine.accelerators import Accelerator, KnobSpec
16
+
17
+ TILT_SEED = 1e-9 # Should discuss this with Laurent.
18
+ # Every offset is zeroed (not just the selected one) so the deferred table never reads nil.
19
+ _MISALIGN_PREPARATION = (
20
+ "e.dx = e.dx or 0\ne.dy = e.dy or 0\ne.ds = e.ds or 0\n"
21
+ "e.misalign = MAD.typeid.deferred{dx =\\->e.dx, dy =\\->e.dy, ds =\\->e.ds}"
22
+ )
23
+ _KNOB_PREPARATION = {
24
+ "dx": _MISALIGN_PREPARATION,
25
+ "dy": _MISALIGN_PREPARATION,
26
+ "ds": _MISALIGN_PREPARATION,
27
+ # MAD-NG drops a rotation whose scalar angle is zero (mad_dynmap.cpp:345),
28
+ # silently zeroing the knob's Jacobian column. Seeding above ``minang``
29
+ # (1e-10 rad) keeps the derivative; the knob inherits the seed as its value.
30
+ "tilt": f"e.tilt = (e.tilt or 0) + {TILT_SEED:.15e}",
31
+ }
32
+ #: Per-kind track ``method`` overrides that keep the method=6 accuracy.
33
+ _TRACK_METHODS: dict[type, dict[str, int]] = {LHC: {"sextupole": 4}}
34
+ _PSB_GROUP_SUFFIXES = {
35
+ "k1": "dk1l",
36
+ "k0s": "dk0sl",
37
+ "k1s": "dk1sl",
38
+ "dx": "dx",
39
+ "dy": "dy",
40
+ "ds": "ds",
41
+ "tilt": "tilt",
42
+ }
43
+
44
+
45
+ def track_methods(accelerator: Accelerator) -> dict[str, int]:
46
+ """Per-element-kind MAD-NG track ``method`` overrides for ``accelerator``."""
47
+ for kind, methods in _TRACK_METHODS.items():
48
+ if isinstance(accelerator, kind):
49
+ return methods
50
+ return {}
51
+
52
+
53
+ def prepare_knob_creation(
54
+ iface: MadInterface, accelerator: Accelerator, specs: list[KnobSpec]
55
+ ) -> None:
56
+ """Install PSB AC kickers, run each attribute's ``_KNOB_PREPARATION``, read LHC bend lengths."""
57
+ if isinstance(accelerator, PSB) and accelerator.acd_drive_tunes is not None:
58
+ iface.install_ac_kickers((0.0, 0.0, 0.0, 0.0), accelerator.acd_drive_tunes[0])
59
+ grouped: dict[tuple[str, str], list[str]] = {}
60
+ for spec in specs:
61
+ body = _KNOB_PREPARATION.get(spec.attribute)
62
+ if body is not None:
63
+ grouped.setdefault((spec.kind, body), []).append(spec.pattern)
64
+ for (element_kind, body), patterns in grouped.items():
65
+ _prepare_matching_elements(iface, element_kind, tuple(dict.fromkeys(patterns)), body)
66
+ if (
67
+ isinstance(accelerator, LHC)
68
+ and accelerator.optimises("bend", "k0")
69
+ and accelerator.normalise_bends
70
+ ):
71
+ _normalise_lhc_bends(iface, accelerator)
72
+
73
+
74
+ def _prepare_matching_elements(
75
+ iface: MadInterface, element_kind: str, patterns: tuple[str, ...], body: str
76
+ ) -> None:
77
+ """Run Lua ``body`` once per element of ``element_kind`` matching ``patterns`` (seen as ``e``)."""
78
+ iface.mad.send(f"""
79
+ local element_kind = {iface.py_name}:recv()
80
+ local patterns = {iface.py_name}:recv()
81
+ for i, e in loaded_sequence:siter(magnet_range) do
82
+ if e.kind == element_kind then
83
+ for _, pattern in ipairs(patterns) do
84
+ if string.match(e.name, pattern) then
85
+ {textwrap.indent(body, " " * 24)}
86
+ break
87
+ end
88
+ end
89
+ end
90
+ end
91
+ """)
92
+ iface.mad.send(element_kind).send(patterns)
93
+
94
+
95
+ def _normalise_lhc_bends(iface: MadInterface, accelerator: LHC) -> None:
96
+ iface.mad.send(f"""
97
+ bend_dict = {{}}
98
+ bend_lengths = {{}}
99
+ for i, e in loaded_sequence:siter(magnet_range) do
100
+ if (e.kind == "sbend" or e.kind == "rbend") and e.k0 ~= 0 then
101
+ bend_dict[e.name .. ".dk0l"] = e.k0
102
+ bend_lengths[e.name .. ".dk0l"] = e.l
103
+ end
104
+ end
105
+ {iface.py_name}:send(bend_dict, true)
106
+ {iface.py_name}:send(bend_lengths, true)
107
+ bend_dict = {iface.py_name}:recv()
108
+ """)
109
+ true_strengths_dict: dict[str, float] = iface.mad.recv()
110
+ accelerator.bend_lengths = iface.mad.recv()
111
+ iface.mad.send(normalise_lhcbend_magnets(true_strengths_dict, accelerator.bend_lengths))
112
+
113
+
114
+ def knob_expansion_block(accelerator: Accelerator) -> str:
115
+ """Lua run after knob creation that may edit ``knob_names`` / ``spos_list``.
116
+
117
+ PSB with several ACD files: each kicker's volt (a or b) becomes one knob per file.
118
+ """
119
+ if not isinstance(accelerator, PSB) or accelerator.acd_files == 1:
120
+ return ""
121
+ names = ", ".join(f"'{name}.volt'" for name in AC_KICKERS)
122
+ return f"""
123
+ for _, k in ipairs {{{names}}} do
124
+ for idx, name in ipairs(knob_names) do
125
+ if name == k then
126
+ table.remove(knob_names, idx)
127
+ local spos = table.remove(spos_list, idx)
128
+ for f = 0, {accelerator.acd_files - 1} do
129
+ loaded_sequence[k .. '_f' .. f] = loaded_sequence[k]
130
+ table.insert(knob_names, k .. '_f' .. f)
131
+ table.insert(spos_list, spos)
132
+ end
133
+ break
134
+ end
135
+ end
136
+ end
137
+ """
138
+
139
+
140
+ def mad_attr_spec(accelerator: Accelerator, kind: str, attribute: str) -> dict[str, str]:
141
+ """Lua ``name_expr`` / ``sign_expr`` / ``mad_value`` overrides for one element attribute."""
142
+ if isinstance(accelerator, PSB):
143
+ return _psb_attr_spec(accelerator, kind, attribute)
144
+ if isinstance(accelerator, LHC):
145
+ if not accelerator.normalise_bends or kind != "sbend" or attribute != "k0":
146
+ return {}
147
+ return {
148
+ "name_expr": 'string.gsub(e.name, "(MB%.)([ABCD])([0-9]+[LR][1-8]%.B[12])", "%1%3") .. ".dk0l"',
149
+ "mad_value": "bend_dict[k_str_name]",
150
+ }
151
+ return {}
152
+
153
+
154
+ def _psb_attr_spec(accelerator: PSB, kind: str, attribute: str) -> dict[str, str]:
155
+ """Share the two QFO knobs in each cell when native grouping is enabled."""
156
+ if not accelerator.group_quadrupoles_by_cell or kind != "quadrupole":
157
+ return {}
158
+ suffix = _PSB_GROUP_SUFFIXES.get(attribute)
159
+ if suffix is None:
160
+ return {}
161
+ if attribute == "tilt" and accelerator.differential_cell_tilt:
162
+ return {
163
+ "name_expr": (
164
+ '(string.gsub((string.gsub(e.name, "^BR%.QFO(%d+)%d$", "BR.QCELL%1")), '
165
+ '"^BR%.QDE(%d+)$", "BR.QCELL%1")) .. ".tilt"'
166
+ ),
167
+ "sign_expr": '(e.name:match("^BR%.QDE") and -1 or 1)',
168
+ }
169
+ return {
170
+ "name_expr": (f'string.gsub(e.name, "^(BR%.QFO)(%d+)(%d)$", "%1CELL%2") .. ".{suffix}"')
171
+ }