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
@@ -0,0 +1,600 @@
1
+ """The MAD-NG session of accelmo: :class:`MadInterface`.
2
+
3
+ Loads the sequence and beam, observes and thins the BPMs, applies the machine state and,
4
+ with ``create_knobs=True``, creates the fit knobs selected by the accelerator.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import re
11
+ from typing import TYPE_CHECKING
12
+
13
+ import numpy as np
14
+ import tfs
15
+ from pymadng_utils.mad.accelerator_mad_interface import (
16
+ MAX_MULTIPOLE,
17
+ MULTIPOLE_ATTRS,
18
+ MultipoleInfo,
19
+ )
20
+ from pymadng_utils.mad.knob_mad_interface import KnobMadInterface
21
+
22
+ from accelmo.machine.accelerators import LHC
23
+ from accelmo.machine.knob_names import is_magnet_strength_name
24
+ from accelmo.machine.machine_state import MachineState, resolve_machine_state
25
+
26
+ from .accelerator_hooks import knob_expansion_block, mad_attr_spec, prepare_knob_creation
27
+ from .machine_state import set_vars
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Iterable
31
+ from pathlib import Path
32
+
33
+ from accelmo.machine.accelerators import Accelerator
34
+
35
+ BPM_PATTERN = "^BPM"
36
+ LOGGER = logging.getLogger(__name__)
37
+
38
+ _INDEXED_MULTIPOLE_RE = re.compile(r"^(knl|ksl)\[(\d+)\]$")
39
+
40
+
41
+ def indexed_multipole_attr_info(attr: str) -> MultipoleInfo | None:
42
+ """Return multipole metadata for indexed MAD attrs such as ``knl[3]`` or ``ksl[3]``."""
43
+ match = _INDEXED_MULTIPOLE_RE.fullmatch(attr)
44
+ if match is None:
45
+ return None
46
+
47
+ base_table, index_str = match.groups()
48
+ index = int(index_str)
49
+ if index < 1 or index > MAX_MULTIPOLE:
50
+ return None
51
+
52
+ order = index - 1
53
+ base_attr = f"k{order}" if base_table == "knl" else f"k{order}s"
54
+ return MULTIPOLE_ATTRS[base_attr]
55
+
56
+
57
+ def _ensure_cycleable_start_element(
58
+ iface: MadInterface,
59
+ start_bpm: str,
60
+ observed_bpms: list[str],
61
+ ) -> None:
62
+ """Replace a non-BPM start element with a same-name marker for MAD cycling."""
63
+ if start_bpm in observed_bpms:
64
+ return
65
+ iface.mad.send(f"""
66
+ correct_elm = MADX['{start_bpm}']
67
+ local new_elm = MAD.element.marker ('{start_bpm}') {{ at=loaded_sequence:upos(correct_elm) }}
68
+ local replaced = loaded_sequence:replace({{new_elm}}, '{start_bpm}')
69
+ MADX['{start_bpm}'] = new_elm
70
+ {iface.py_name}:send(replaced and #replaced or 0)
71
+ correct_elm = nil
72
+ """)
73
+ if iface.mad.recv() != 1:
74
+ raise ValueError(f"Failed to replace start element {start_bpm} with a marker")
75
+ LOGGER.info("Replaced non-BPM start element with cycle marker: %s", start_bpm)
76
+
77
+
78
+ def _unique_names(names: Iterable[str]) -> list[str]:
79
+ """Return names deduplicated in first-seen order."""
80
+ return list(dict.fromkeys(names))
81
+
82
+
83
+ def _absolute_name_from_dk_knob(knob_name: str) -> str | None:
84
+ """Map a dknl/dksl perturbation knob name back to its absolute strength attribute."""
85
+ for abs_attr, mp in MULTIPOLE_ATTRS.items():
86
+ if not mp.is_delta and knob_name.endswith(f".{mp.dk_suffix}"):
87
+ return knob_name[: -(len(mp.dk_suffix) + 1)] + f".{abs_attr}"
88
+ return None
89
+
90
+
91
+ def _deferred_table_helpers() -> str:
92
+ """Lua helpers that defer dknl/dksl tables without resetting current values."""
93
+ values = ",\n ".join(f"old[{idx}] or 0.0" for idx in range(1, MAX_MULTIPOLE + 1))
94
+ return "".join(
95
+ f"""
96
+ local function make_{table}_deferred_knob(e)
97
+ if not MAD.typeid.is_deferred(loaded_sequence[e.name].{table}) then
98
+ local old = loaded_sequence[e.name].{table} or {{}}
99
+ loaded_sequence[e.name].{table} = MAD.typeid.deferred {{
100
+ {values},
101
+ }}
102
+ end
103
+ end"""
104
+ for table in ("dknl", "dksl")
105
+ )
106
+
107
+
108
+ def read_b2_error_table(path: Path | str) -> dict[str, float]:
109
+ """Read an OMC3-style ``.errors`` table as an element-name to K1L mapping."""
110
+ table = tfs.read(path, index="NAME")
111
+ return {str(name): float(value) for name, value in table["K1L"].items()} # ty: ignore[missing-attribute]
112
+
113
+
114
+ def apply_b2_errors_to_sequence(
115
+ mad,
116
+ py_name: str,
117
+ b2_errors: Path | None,
118
+ machine_state: MachineState | None,
119
+ ) -> None:
120
+ """Route a b2 dipole error table into the loaded sequence's dknl[2] slots.
121
+
122
+ Works on any MAD interface whose sequence is bound to the ``loaded_sequence``
123
+ global (the reconstruction ``ACDipoleMadDriver`` and the optimisation
124
+ ``MadInterface`` both qualify). The b2 K1L is added to the quadrupole
125
+ perturbation slot (dknl[2]), leaving the dipole slot dknl[1] untouched. b2
126
+ errors shift the machine tunes, so a machine state holding the tune knobs is required
127
+ to restore them.
128
+ """
129
+ if b2_errors is None:
130
+ return
131
+ if machine_state is None:
132
+ raise ValueError(
133
+ "The tune knobs in the machine state are designed to compensate for the known b2 errors."
134
+ "Therefore it makes no sense to apply b2 errors without also applying a machine state."
135
+ )
136
+
137
+ b2_table = read_b2_error_table(b2_errors)
138
+ if not b2_table:
139
+ LOGGER.warning("No entries found in b2 error table %s", b2_errors)
140
+ return
141
+
142
+ zeros = ", ".join(["0.0"] * MAX_MULTIPOLE)
143
+ mad.send(
144
+ f"""
145
+ local b2_errors = {py_name}:recv()
146
+ local applied = {{}}
147
+ local missing = {{}}
148
+
149
+ for name, k1l in pairs(b2_errors) do
150
+ local element = loaded_sequence[name]
151
+ if element == nil then
152
+ table.insert(missing, name)
153
+ elseif k1l ~= 0 then
154
+ -- Route the b2 K1L into the dknl perturbation table, leaving the
155
+ -- dipole slot dknl[1] at 0 and adding the quadrupole error to dknl[2].
156
+ if not MAD.typeid.is_deferred(element.dknl) then
157
+ element.dknl = MAD.typeid.deferred {{{zeros}}}
158
+ end
159
+ element.dknl[2] = (element.dknl[2] or 0.0) + k1l
160
+ applied[name] = element.dknl[2]
161
+ end
162
+ end
163
+
164
+ {py_name}:send(applied, true)
165
+ {py_name}:send(missing, true)
166
+ """
167
+ )
168
+ mad.send(b2_table)
169
+ applied = mad.recv()
170
+ missing = mad.recv()
171
+
172
+ if missing:
173
+ preview = ", ".join(sorted(str(name) for name in missing[:8]))
174
+ raise ValueError(
175
+ f"B2 error table {b2_errors} contains elements not present in the loaded "
176
+ f"sequence: {preview}"
177
+ )
178
+
179
+ LOGGER.info("Applied %d b2 dipole error entries from %s", len(applied), b2_errors)
180
+
181
+
182
+ class MadInterface(KnobMadInterface):
183
+ """MAD-NG session: sequence, beam, observed thin BPMs, machine state and (optionally) fit knobs.
184
+
185
+ ``create_knobs=True`` creates the knobs selected by the accelerator's ``errors`` and
186
+ ``misalignments`` (accelerator hooks in :mod:`accelmo.backend.madng.accelerator_hooks`)
187
+ and then applies ``initial_model_values``.
188
+ """
189
+
190
+ accelerator: Accelerator
191
+
192
+ def __init__(
193
+ self,
194
+ accelerator: Accelerator,
195
+ *,
196
+ magnet_range: str = "$start/$end",
197
+ bpm_range: str | None = None,
198
+ bad_bpms: list[str] | None = None,
199
+ machine_state: MachineState | None = None,
200
+ b2_errors: Path | None = None,
201
+ create_knobs: bool = False,
202
+ initial_model_values: dict[str, float] | None = None,
203
+ py_name: str = "py",
204
+ debug: bool = False,
205
+ mad_logfile: Path | None = None,
206
+ discard_mad_output: bool = False,
207
+ tracking_anchor_mode: str | None = None,
208
+ tracking_anchor_markers: list[str] | None = None,
209
+ observe_anchor_markers: bool = True,
210
+ ):
211
+ stdout, redirect_stderr = self._resolve_mad_stdout(mad_logfile, discard_mad_output)
212
+
213
+ super().__init__(
214
+ accelerator=accelerator,
215
+ stdout=stdout,
216
+ redirect_stderr=redirect_stderr,
217
+ py_name=py_name,
218
+ debug=debug,
219
+ )
220
+
221
+ self.accelerator = accelerator
222
+ self.magnet_range = magnet_range
223
+ self.bpm_range = bpm_range if bpm_range is not None else magnet_range
224
+ self.knob_names: list[str] = []
225
+ self.knob_name_set: set[str] = set()
226
+ self.elem_spos: list[float] = []
227
+
228
+ # Set MAD variables for ranges and patterns
229
+ self.mad["magnet_range"] = self.magnet_range
230
+ self.mad["bpm_range"] = self.bpm_range
231
+
232
+ anchor_markers = self.prepare_tracking_anchors(
233
+ mode=tracking_anchor_mode,
234
+ marker_names=tracking_anchor_markers,
235
+ )
236
+
237
+ self.observe_bpms(bad_bpms=bad_bpms, unobserve_first=True)
238
+ if observe_anchor_markers:
239
+ for marker in anchor_markers:
240
+ self.observe_element(marker)
241
+ self.recount_bpms()
242
+ self.make_all_monitors_thin(list(set(self.all_bpms) - set(anchor_markers)))
243
+
244
+ self._apply_b2_errors(b2_errors, machine_state)
245
+
246
+ if machine_state is not None:
247
+ self._set_machine_state(machine_state)
248
+ else:
249
+ LOGGER.info("Skipping machine state (not provided)")
250
+
251
+ if create_knobs:
252
+ if accelerator.has_any_optimisation():
253
+ self._make_adj_knobs()
254
+ else:
255
+ LOGGER.warning("create_knobs=True but the accelerator selects no knobs")
256
+ self.apply_initial_model_values(initial_model_values)
257
+
258
+ def observe_bpms(
259
+ self,
260
+ bpm_pattern: str | None = None,
261
+ bad_bpms: list[str] | None = None,
262
+ unobserve_first: bool = True,
263
+ ) -> None:
264
+ """Observe the BPMs matching ``bpm_pattern`` (default: the accelerator's)."""
265
+ if bpm_pattern is None:
266
+ bpm_pattern = self.accelerator.bpm_pattern
267
+ super().observe_bpms(bpm_pattern, bad_bpms, unobserve_first)
268
+
269
+ def get_bpm_list(self, bpm_range: str) -> tuple[list[str], list[str]]:
270
+ """Observed BPM names in the whole sequence and in ``bpm_range``."""
271
+ get_bpms_mad = f"""
272
+ local all_bpms = {{}}
273
+ local bpm_in_range = {{}}
274
+ for _, elm in loaded_sequence:iter() do
275
+ if elm:is_observed() then
276
+ table.insert(all_bpms, elm.name)
277
+ end
278
+ end
279
+ for _, elm in loaded_sequence:iter("{bpm_range}") do
280
+ if elm:is_observed() then
281
+ table.insert(bpm_in_range, elm.name)
282
+ end
283
+ end
284
+ {self.py_name}:send(all_bpms, true)
285
+ {self.py_name}:send(bpm_in_range, true)
286
+ """
287
+ self.mad.send(get_bpms_mad)
288
+ all_bpms = self.mad.receive()
289
+ bpms_in_range = self.mad.receive()
290
+
291
+ # Remove duplicate if the first and last BPM are the same physical element.
292
+ if all_bpms[0] == all_bpms[-1] and len(all_bpms) > 1:
293
+ all_bpms = all_bpms[:-1]
294
+ bpms_in_range = [bpm for bpm in all_bpms if bpm in bpms_in_range]
295
+ return all_bpms, bpms_in_range
296
+
297
+ def prepare_tracking_anchors(
298
+ self,
299
+ *,
300
+ mode: str | None,
301
+ marker_names: list[str] | None,
302
+ ) -> list[str]:
303
+ """Prepare marker-anchored tracking modes through one monitor-anchor path.
304
+
305
+ Returns the observed anchor markers the caller must keep through the BPM
306
+ observation filter (the ACD before/after monitors; none for kicker mode).
307
+ """
308
+ anchor_markers = _unique_names(marker_names or [])
309
+ if mode == "acd":
310
+ acd_before, acd_after = self.insert_acd_markers()
311
+ LOGGER.info("Installed ACD markers: before=%s, after=%s", acd_before, acd_after)
312
+ anchor_markers = _unique_names([*anchor_markers, acd_before, acd_after])
313
+ elif mode == "kicker":
314
+ if not anchor_markers:
315
+ raise ValueError("Kicker tracking anchor mode requires a marker name")
316
+ for source_name in anchor_markers:
317
+ self.make_element_thin(
318
+ source_name,
319
+ marker_name=f"{source_name}_centre",
320
+ observe_after=False,
321
+ )
322
+ anchor_markers = []
323
+ elif mode is not None:
324
+ raise ValueError(f"Unsupported tracking anchor mode: {mode!r}")
325
+ return anchor_markers
326
+
327
+ def cycle_to_start(self, start_marker: str) -> None:
328
+ """Cycle the loaded sequence so it begins at ``start_marker``.
329
+
330
+ Cycling is never done implicitly during construction; callers (e.g. a
331
+ worker that must track a range as one contiguous segment) request it
332
+ explicitly. A non-BPM start element is first replaced with a same-name
333
+ marker so MAD can cycle to it.
334
+ """
335
+ _ensure_cycleable_start_element(self, start_marker, self.all_bpms)
336
+ self.cycle_sequence(marker_name=start_marker)
337
+ LOGGER.info("Cycled sequence to start at: %s", start_marker)
338
+
339
+ @staticmethod
340
+ def _resolve_mad_stdout(
341
+ mad_logfile: Path | None, discard_mad_output: bool
342
+ ) -> tuple[Path | str | None, bool]:
343
+ """Return (stdout, redirect_stderr) for the MAD process."""
344
+ if mad_logfile is not None:
345
+ if discard_mad_output:
346
+ LOGGER.warning(
347
+ "MAD logfile specified, but discard_mad_output is True. MAD output will be logged."
348
+ )
349
+ LOGGER.info(f"MAD logfile set to: {mad_logfile.absolute()}")
350
+ return mad_logfile, True
351
+ if discard_mad_output:
352
+ return "/dev/null", True
353
+ return None, False
354
+
355
+ def _apply_b2_errors(self, b2_errors: Path | None, machine_state: MachineState | None) -> None:
356
+ """Route a b2 dipole error table into this interface's loaded sequence."""
357
+ if b2_errors is not None and not isinstance(self.accelerator, LHC):
358
+ raise ValueError("b2_errors are only supported for LHC MAD interfaces.")
359
+ apply_b2_errors_to_sequence(self.mad, self.py_name, b2_errors, machine_state)
360
+
361
+ @property
362
+ def nbpms(self) -> int:
363
+ """Number of observed BPMs in ``bpm_range``."""
364
+ return len(self.bpms_in_range)
365
+
366
+ def recount_bpms(self) -> None:
367
+ """Refresh ``all_bpms`` and ``bpms_in_range`` (after a cycle)."""
368
+ self.all_bpms, self.bpms_in_range = self.get_bpm_list(self.bpm_range)
369
+ LOGGER.info("Counted %d BPMs in range %s", len(self.bpms_in_range), self.bpm_range)
370
+
371
+ def make_all_monitors_thin(self, monitors: list[str], observe_after: bool = True) -> None:
372
+ """Replace monitor elements with thin observation markers."""
373
+ self.make_elements_thin(monitors, observe_after=observe_after, require_kind="monitor")
374
+ LOGGER.info("Replaced %d monitor BPMs with thin observation markers", len(monitors))
375
+
376
+ def _set_machine_state(self, machine_state: MachineState) -> None:
377
+ """Put the model in *machine_state* (see :mod:`accelmo.machine.machine_state`)."""
378
+ state = resolve_machine_state(machine_state)
379
+ set_vars(self.mad, state)
380
+ LOGGER.info("Set %d machine-state entries", len(state))
381
+
382
+ def apply_initial_model_values(self, values: dict[str, float] | None) -> None:
383
+ """Apply a full initial machine-state map without changing the trainable set."""
384
+ if not values:
385
+ return
386
+
387
+ unknown = [
388
+ name
389
+ for name in values
390
+ if name != "pt" and not is_magnet_strength_name(name) and name not in self.knob_name_set
391
+ ]
392
+ if unknown:
393
+ raise ValueError(
394
+ "Unknown initial model value names: "
395
+ + ", ".join(sorted(unknown)[:10])
396
+ + ("..." if len(unknown) > 10 else "")
397
+ )
398
+
399
+ if "pt" in values:
400
+ self.mad["loaded_sequence['pt']"] = float(values["pt"])
401
+
402
+ knob_values = {
403
+ name: float(value) for name, value in values.items() if name in self.knob_name_set
404
+ }
405
+ if knob_values:
406
+ self.update_knob_values(knob_values)
407
+
408
+ magnet_values = {
409
+ name: float(value)
410
+ for name, value in values.items()
411
+ if name != "pt" and name not in self.knob_name_set and is_magnet_strength_name(name)
412
+ }
413
+ if magnet_values:
414
+ self.set_magnet_strengths(magnet_values)
415
+
416
+ def _build_attr_block(self, attr_conditions: list[tuple[str, str, str]]) -> str:
417
+ """
418
+ Build the MAD-NG Lua block that assigns a deferred knob variable to each matched element.
419
+
420
+ Each entry in attr_conditions is (kind, attr, lua_condition). For multipole
421
+ attrs (k1, k1s, dk1l, …) the knob routes through dknl/dksl so the base
422
+ strength is never mutated. For direct attrs (kick, dx, …) the element
423
+ attribute itself becomes a deferred variable.
424
+ """
425
+ lines: list[str] = []
426
+
427
+ for kind, attr, condition in attr_conditions:
428
+ spec = mad_attr_spec(self.accelerator, kind, attr)
429
+ mp = MULTIPOLE_ATTRS.get(attr) or indexed_multipole_attr_info(attr)
430
+
431
+ # The knob variable name in MAD (e.g. "MQXA.1R1.dk1l")
432
+ default_name_expr = (
433
+ f'e.name .. ".{mp.dk_suffix}"' if mp is not None else f'e.name .. ".{attr}"'
434
+ )
435
+ name_expr = spec.get("name_expr", default_name_expr)
436
+ mad_value = spec.get("mad_value", f"e.{attr}")
437
+
438
+ tmpl = [
439
+ f"if {condition} then",
440
+ f" local k_str_name = {name_expr}",
441
+ ]
442
+ if mp is not None:
443
+ tmpl += [
444
+ f" make_{mp.dk_table}_deferred_knob(e)",
445
+ (
446
+ f" loaded_sequence[k_str_name] = loaded_sequence[k_str_name] "
447
+ f"or loaded_sequence[e.name].{mp.dk_table}[{mp.index}] or 0.0"
448
+ ),
449
+ f" loaded_sequence[e.name].{mp.dk_table}[{mp.index}] = \\->loaded_sequence[k_str_name]",
450
+ ]
451
+ elif "sign_expr" in spec:
452
+ # Shared knob with a per-element sign: element value = sign * knob.
453
+ tmpl += [
454
+ f" local k_sign = {spec['sign_expr']}",
455
+ f" loaded_sequence[k_str_name] = loaded_sequence[k_str_name] or k_sign * {mad_value}",
456
+ f" loaded_sequence[e.name].{attr} = \\->k_sign * loaded_sequence[k_str_name]",
457
+ ]
458
+ else:
459
+ tmpl += [
460
+ f" loaded_sequence[k_str_name] = loaded_sequence[k_str_name] or {mad_value}",
461
+ f" loaded_sequence[e.name].{attr} = \\->loaded_sequence[k_str_name]",
462
+ ]
463
+ tmpl.append(f" store_knobs(k_str_name, {mad_value}, '{attr}', s)")
464
+ tmpl.append("end")
465
+ lines.extend(f" {line}" for line in tmpl)
466
+
467
+ return "\n".join(lines) if lines else " -- no attributes selected"
468
+
469
+ def get_absolute_knob_values(self, knob_names: list[str]) -> dict[str, float]:
470
+ """Return underlying absolute strengths for optimisation knob names.
471
+
472
+ For ``*.dk0l/*.dk1l/*.dk2l`` (and skew equivalents) this returns the base
473
+ element strength before any perturbation. For direct knobs it returns the
474
+ current value from the sequence.
475
+ """
476
+ absolute_names = [_absolute_name_from_dk_knob(knob) or knob for knob in knob_names]
477
+ return self.get_base_magnet_strengths(absolute_names)
478
+
479
+ def _make_adj_knobs(self) -> None:
480
+ """Create deferred-strength knobs in MAD for all elements matching the knob specs."""
481
+ specs = self.accelerator.get_knob_specs()
482
+ prepare_knob_creation(self, self.accelerator, specs)
483
+
484
+ attr_block = ""
485
+ if specs:
486
+ attr_conditions = [
487
+ (
488
+ kind,
489
+ attr,
490
+ f'(e.kind == "{kind}" {"and e." + nonzero_attr + " ~=0 " if nonzero_attr else ""}and e.name:match("{pattern}"))',
491
+ )
492
+ for kind, attr, pattern, nonzero_attr, _label in specs
493
+ ]
494
+ attr_block = f"""
495
+ local function store_knobs(k_str_name, mad_value, attr, spos)
496
+ if not used[k_str_name] then
497
+ used[k_str_name] = #knob_names + 1 ! deduplicate (e.g. shared PSB QFO knobs)
498
+ counts[k_str_name] = 1
499
+ table.insert(knob_names, k_str_name)
500
+ table.insert(spos_list, spos)
501
+ else
502
+ local count = counts[k_str_name] + 1
503
+ local index = used[k_str_name]
504
+ spos_list[index] = (spos_list[index] * (count - 1) + spos) / count
505
+ counts[k_str_name] = count
506
+ end
507
+ end
508
+ {_deferred_table_helpers()}
509
+ for i, e, s, ds in loaded_sequence:siter(magnet_range) do
510
+ {self._build_attr_block(attr_conditions)}
511
+ end
512
+ """
513
+
514
+ energy_block = ""
515
+ if self.accelerator.optimise_energy:
516
+ energy_block = """
517
+ loaded_sequence['pt'] = loaded_sequence['pt'] or 1e-6
518
+ table.insert(knob_names, "pt")
519
+ """
520
+
521
+ self.mad.send(f"""
522
+ local knob_names = {{}}
523
+ local spos_list = {{}}
524
+ local used = {{}}
525
+ local counts = {{}}
526
+ {attr_block}
527
+ {knob_expansion_block(self.accelerator)}
528
+ {energy_block}
529
+ {self.py_name}:send(knob_names, true)
530
+ {self.py_name}:send(spos_list, true)
531
+ """)
532
+ knob_names_all: list[str] = self.mad.recv()
533
+ elem_spos_all: list[float] = self.mad.recv()
534
+
535
+ # Optionally restrict to a user-specified subset of knobs
536
+ if self.accelerator.custom_knobs_to_optimise is not None:
537
+ keep = set(self.accelerator.custom_knobs_to_optimise)
538
+ pairs = [(k, s) for k, s in zip(knob_names_all, elem_spos_all) if k in keep]
539
+ knob_names_all, elem_spos_all = (list(x) for x in zip(*pairs)) if pairs else ([], [])
540
+ LOGGER.info(
541
+ f"Filtered to {len(knob_names_all)} knobs based on custom_knobs_to_optimise"
542
+ )
543
+
544
+ self.knob_names = knob_names_all
545
+ self.elem_spos = elem_spos_all
546
+ self.knob_name_set = set(self.knob_names)
547
+ self.mad["knob_names"] = self.knob_names
548
+
549
+ if self.elem_spos:
550
+ LOGGER.info(
551
+ f"Created {len(self.knob_names)} knobs from {self.elem_spos[0]} to {self.elem_spos[-1]}"
552
+ )
553
+ LOGGER.debug(f"Knob names: {self.knob_names}")
554
+ else:
555
+ LOGGER.info("No knobs created")
556
+
557
+ def _set_multipole_perturbation(
558
+ self,
559
+ element_name: str,
560
+ attr: str,
561
+ info: MultipoleInfo,
562
+ integrated_delta: float,
563
+ target_strength: float,
564
+ ) -> None:
565
+ """Apply a perturbation through an existing optimisation knob when possible."""
566
+ knob_name = f"{element_name}.{info.dk_suffix}"
567
+ if self.accelerator.has_any_optimisation() and knob_name in self.knob_name_set:
568
+ self.mad[f"loaded_sequence['{knob_name}']"] = integrated_delta
569
+ return
570
+
571
+ super()._set_multipole_perturbation(
572
+ element_name,
573
+ attr,
574
+ info,
575
+ integrated_delta,
576
+ target_strength,
577
+ )
578
+
579
+ def knob_values(self) -> np.ndarray:
580
+ """Retrieve the current values of all knobs from the MAD-NG session."""
581
+ var_names = [f"loaded_sequence['{k}']" for k in self.knob_names]
582
+ values = self.mad.recv_vars(*var_names)
583
+ # recv_vars returns a scalar when only one variable is requested
584
+ if len(self.knob_names) == 1:
585
+ values = [values]
586
+ return np.array(values, dtype=float)
587
+
588
+ def update_knob_values(self, knob_values: dict[str, float]) -> None:
589
+ """Update knob values in the MAD-NG session."""
590
+ unknown = [n for n in knob_values if n not in self.knob_name_set]
591
+ if unknown:
592
+ raise ValueError(
593
+ "Unknown knob names supplied to update_knob_values: "
594
+ + ", ".join(unknown[:10])
595
+ + ("..." if len(unknown) > 10 else "")
596
+ )
597
+ commands = [f"loaded_sequence['{n}'] = {v}" for n, v in knob_values.items()]
598
+ if commands:
599
+ self.mad.send("\n".join(commands))
600
+ LOGGER.info(f"Updated {len(commands)} knobs from {len(knob_values)} provided")
@@ -0,0 +1,62 @@
1
+ """Read and assign machine-state globals (see :mod:`accelmo.machine.machine_state`) in a MAD-NG session."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ if TYPE_CHECKING:
8
+ from collections.abc import Mapping
9
+
10
+ from pymadng import MAD
11
+
12
+
13
+ def _key(name: str) -> str:
14
+ """Lua expression for the ``MADX.__var`` key of *name*: MAD-NG stores a dotted variable (``k_hcor_qf2a.56``) with ``.`` as ``_``,
15
+ although ``MADX['k_hcor_qf2a.56']`` maps it on access (a raw ``__var`` lookup does not)."""
16
+ return repr(name.replace(".", "_"))
17
+
18
+
19
+ def check_state_names(mad: MAD, py_name: str, names: list[str]) -> None:
20
+ """Raise ``ValueError`` for a name that is neither a MAD-X variable nor an element attribute.
21
+
22
+ Indexing ``MADX`` with an unknown name silently creates it as zero, so existence is tested first.
23
+ """
24
+ for name in names:
25
+ element, _, attribute = name.rpartition(".")
26
+ mad.send(
27
+ f"{py_name}:send(MADX.__var[{_key(name)}] ~= nil or "
28
+ f"('{element}' ~= '' and loaded_sequence[('{element}'):upper()] ~= nil and loaded_sequence[('{element}'):upper()]['{attribute}'] ~= nil))"
29
+ )
30
+ if not mad.recv():
31
+ raise ValueError(
32
+ f"machine_state names {name!r}, which is neither a MAD-X variable nor an element attribute"
33
+ )
34
+
35
+
36
+ def get_vars(mad: MAD, py_name: str, names: list[str]) -> dict[str, float]:
37
+ """The current value of each name (checked first, see :func:`check_state_names`)."""
38
+ check_state_names(mad, py_name, names)
39
+ values = {}
40
+ for name in names:
41
+ element, _, attribute = name.rpartition(".")
42
+ mad.send(
43
+ f"{py_name}:send(MADX.__var[{_key(name)}] ~= nil and MADX['{name}'] or loaded_sequence[('{element}'):upper()]['{attribute}'])"
44
+ )
45
+ values[name] = float(mad.recv())
46
+ return values
47
+
48
+
49
+ def set_vars(mad: MAD, state: Mapping[str, float]) -> None:
50
+ """Set every name of *state*: an existing variable, else an element attribute, else a new variable."""
51
+ if state:
52
+ mad.send("\n".join(_assignment(name, value) for name, value in state.items()))
53
+
54
+
55
+ def _assignment(name: str, value: float) -> str:
56
+ element, _, attribute = name.rpartition(".")
57
+ target = f"loaded_sequence[('{element}'):upper()]"
58
+ return (
59
+ f"if MADX.__var[{_key(name)}] ~= nil then MADX['{name}'] = {value!r} "
60
+ f"elseif '{element}' ~= '' and {target} ~= nil and {target}['{attribute}'] ~= nil then {target}['{attribute}'] = {value!r} "
61
+ f"else MADX['{name}'] = {value!r} end"
62
+ )