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,535 @@
1
+ """MAD-NG tracking and closed-orbit engines (see :mod:`accelmo.backend.protocol`).
2
+
3
+ Each engine owns one MAD-NG process. Derivatives come from the knobs installed as TPSA
4
+ parameters on the sequence.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ from typing import TYPE_CHECKING
11
+
12
+ import numpy as np
13
+ from pymadng_utils.mad.ac_kickers import (
14
+ bind_ac_kicker_volts,
15
+ set_ac_kicker_freqs,
16
+ shift_ac_kicker_phase,
17
+ )
18
+
19
+ from accelmo.backend.madng.accelerator_hooks import track_methods
20
+ from accelmo.backend.madng.interface import MadInterface
21
+ from accelmo.backend.madng.machine_state import get_vars, set_vars
22
+ from accelmo.backend.madng.scripts import (
23
+ CLOSED_TWISS_INIT,
24
+ PYTHON_IN_MAD,
25
+ build_track_speedup_script,
26
+ build_tracking_init_script,
27
+ build_tracking_preflight_script,
28
+ build_tracking_script,
29
+ build_validation_init_script,
30
+ build_validation_script,
31
+ dump_debug_script,
32
+ )
33
+ from accelmo.backend.protocol import ClosedSolution, TrackResult
34
+
35
+ if TYPE_CHECKING:
36
+ from collections.abc import Mapping, Sequence
37
+ from pathlib import Path
38
+
39
+ from pymadng import MAD
40
+
41
+ from accelmo.backend.protocol import TrackGeometry, TrackRequest
42
+ from accelmo.fitting.worker import WorkerConfig
43
+ from accelmo.machine.accelerators import Accelerator
44
+ from accelmo.machine.machine_state import MachineState
45
+
46
+ LOGGER = logging.getLogger(__name__)
47
+
48
+
49
+ class _MadngSession:
50
+ """The worker's MAD-NG model: sequence, observed BPMs, knobs, cycled start."""
51
+
52
+ def __init__(
53
+ self,
54
+ config: WorkerConfig,
55
+ init_knobs: Mapping[str, float],
56
+ logfile: Path | None,
57
+ geometry: TrackGeometry | None = None,
58
+ ) -> None:
59
+ """``geometry`` is the tracked segment; without it the whole ring is observed, uncycled."""
60
+ iface = MadInterface(
61
+ accelerator=config.accelerator,
62
+ magnet_range=config.magnet_range,
63
+ bpm_range="$start/$end" if geometry is None else geometry.bpm_range,
64
+ machine_state=config.machine_state,
65
+ b2_errors=config.b2_errors,
66
+ initial_model_values=dict(init_knobs),
67
+ bad_bpms=config.bad_bpms,
68
+ debug=config.debug,
69
+ mad_logfile=logfile,
70
+ py_name=PYTHON_IN_MAD,
71
+ tracking_anchor_mode=None if geometry is None else geometry.anchor_mode,
72
+ tracking_anchor_markers=None if geometry is None else list(geometry.anchor_sources),
73
+ # Tracking workers read the anchor markers from the data; they never observe them.
74
+ observe_anchor_markers=geometry is None,
75
+ create_knobs=True,
76
+ )
77
+ # One contiguous segment from this worker's start.
78
+ if geometry is not None:
79
+ iface.cycle_to_start(geometry.cycle_target)
80
+ self.iface = iface
81
+ self.mad: MAD = iface.mad
82
+ #: Every knob this process created, ``pt`` last when the energy is fitted.
83
+ self.knob_names: list[str] = list(iface.knob_names)
84
+ self._settable = set(self.knob_names)
85
+ missing = self._settable - set(init_knobs)
86
+ if missing:
87
+ raise ValueError(
88
+ f"{len(missing)} MAD knobs have no initial value, e.g. {sorted(missing)[:5]}"
89
+ )
90
+ mad = self.mad
91
+ mad["knob_names"] = self.knob_names
92
+ # Without a tracking range (kicker mode) MAD tracks the full cycled ring and
93
+ # observes every monitor, including the one wrapping past the start marker.
94
+ full_ring = geometry is not None and geometry.tracking_range is None
95
+ self.nbpms = len(iface.all_bpms) if full_ring else iface.nbpms
96
+ mad["nbpms"] = self.nbpms
97
+ mad["sdir"] = 1 if geometry is None else geometry.sdir
98
+ mad.import_module("MAD", "damap", "matrix", "vector")
99
+ mad.import_module("MAD.utility", "tblcat")
100
+
101
+ def set_knobs(self, knobs: Mapping[str, float], *, plain: bool) -> None:
102
+ """Set this process's knobs; ``plain`` assigns numbers instead of the TPSA constant part."""
103
+ template = (
104
+ "loaded_sequence['{}'] = {:.15e}" if plain else "loaded_sequence['{}']:set0({:.15e})"
105
+ )
106
+ commands = [
107
+ template.format(name, value)
108
+ for name, value in knobs.items()
109
+ if name != "pt" and name in self._settable
110
+ ]
111
+ if commands:
112
+ self.mad.send("\n".join(commands))
113
+
114
+ def fitted_knobs_without_pt(self) -> list[str]:
115
+ """``pt`` is applied per particle or pinned on the map, never a sequence knob."""
116
+ names = [name for name in self.mad["knob_names"] if name != "pt"]
117
+ self.mad["knob_names"] = names
118
+ return names
119
+
120
+ def create_base_damap(self, knob_order: int = 1) -> None:
121
+ self.mad.send(
122
+ f"da_x0_base = damap{{nv=6, np=#knob_names, "
123
+ f"mo={knob_order}, po={knob_order}, pn=knob_names}}"
124
+ )
125
+
126
+ def close(self) -> None:
127
+ self.mad.send("shush()")
128
+
129
+
130
+ class TrackingEngine:
131
+ """MAD-NG ``track`` of one batch of TPSA maps, one map per particle."""
132
+
133
+ def __init__(
134
+ self,
135
+ config: WorkerConfig,
136
+ plan: TrackRequest,
137
+ init_knobs: Mapping[str, float],
138
+ *,
139
+ worker_id: int,
140
+ logfile: Path | None = None,
141
+ ) -> None:
142
+ self.plan = plan
143
+ self.worker_id = worker_id
144
+ self.session = _MadngSession(config, init_knobs, logfile, plan.geometry)
145
+ self.knob_names = self.session.knob_names
146
+ self.nbpms = self.session.nbpms
147
+ mad = self.session.mad
148
+ accelerator = config.accelerator
149
+ mad["batch_size"] = plan.batch_size
150
+ mad["num_batches"] = plan.num_batches
151
+ mad["optimise_energy"] = accelerator.optimise_energy
152
+ mad["tracking_range"] = plan.geometry.tracking_range
153
+ mad["n_run_turns"] = plan.geometry.n_turns
154
+ if accelerator.has_ac_kickers:
155
+ freqs = accelerator.ac_kicker_freqs(plan.file_index)
156
+ assert freqs is not None
157
+ set_ac_kicker_freqs(mad, freqs)
158
+ volt_knobs = accelerator.ac_kicker_volt_knobs(plan.file_index)
159
+ if volt_knobs is not None:
160
+ bind_ac_kicker_volts(mad, volt_knobs) # ty: ignore[invalid-argument-type]
161
+ shift_ac_kicker_phase(mad, plan.turn_offset)
162
+ self._install_knob_parameters(accelerator)
163
+ self._build_scripts(config)
164
+ self._save_start = False
165
+
166
+ def _install_knob_parameters(self, accelerator: Accelerator) -> None:
167
+ """Knobs as TPSA parameters; a validation engine tracks numbers only."""
168
+ mad = self.session.mad
169
+ if self.plan.validation:
170
+ mad.send("da_x0_base = damap{nv=6, np=0, mo=1, po=1}")
171
+ return
172
+ self.session.fitted_knobs_without_pt()
173
+ self.session.create_base_damap(knob_order=1)
174
+ mad.send("""
175
+ knob_monomials = {}
176
+ for i,param in ipairs(knob_names) do
177
+ loaded_sequence[param] = loaded_sequence[param] + da_x0_base[param]
178
+ knob_monomials[param] = string.rep("0", 6 + i - 1) .. "1"
179
+ end
180
+ """)
181
+ mad.send(build_track_speedup_script(track_methods(accelerator)))
182
+
183
+ def _build_scripts(self, config: WorkerConfig) -> None:
184
+ observables = self.plan.observables
185
+ if self.plan.validation:
186
+ self._init_script = build_validation_init_script(observables)
187
+ self._track_script = build_validation_script(observables)
188
+ self._start_track_script = self._track_script
189
+ return
190
+ self._init_script = build_tracking_init_script(
191
+ observables,
192
+ start_on_first_turn=self.plan.geometry.initial_condition_marker is not None,
193
+ )
194
+ self._track_script = build_tracking_script(observables)
195
+ self._start_track_script = build_tracking_script(
196
+ observables, include_start_derivatives=True
197
+ )
198
+ for name, text in (
199
+ ("run_track_init", self._init_script),
200
+ ("run_track", self._track_script),
201
+ ("run_track_uncertainty", self._start_track_script),
202
+ ):
203
+ dump_debug_script(
204
+ name,
205
+ text,
206
+ debug=config.debug,
207
+ mad_logfile=config.mad_logfile,
208
+ worker_id=self.worker_id,
209
+ )
210
+
211
+ def set_knobs(self, knobs: Mapping[str, float]) -> None:
212
+ """See :meth:`accelmo.backend.protocol.TrackingEngine.set_knobs`."""
213
+ self.session.set_knobs(knobs, plain=self.plan.validation)
214
+
215
+ def load_particles(
216
+ self, init_coords: list[list[list[float]]], init_pts: list[list[float]]
217
+ ) -> None:
218
+ """One DA map per particle in each batch, at its start coordinates."""
219
+ mad = self.session.mad
220
+ mad.send("""
221
+ init_coords = python:recv()
222
+ init_pts = python:recv()
223
+ """)
224
+ mad.send(init_coords).send(init_pts)
225
+ mad.send("""
226
+ da_x0_c = table.new(num_batches, 0)
227
+ for i=1,num_batches do
228
+ da_x0_c[i] = table.new(batch_size, 0)
229
+ for j=1,batch_size do
230
+ da_x0_c[i][j] = da_x0_base:copy()
231
+ da_x0_c[i][j]:set0(init_coords[i][j])
232
+ end
233
+ end
234
+ """)
235
+ mad.send(self._init_script)
236
+
237
+ def set_pts(self, pt: float, first_batch: int, last_batch: int) -> None:
238
+ """See :meth:`accelmo.backend.protocol.TrackingEngine.set_pts`."""
239
+ self.session.mad.send(f"""
240
+ for b = {first_batch + 1}, {last_batch + 1} do
241
+ for i = 1, batch_size do
242
+ da_x0_c[b][i].pt:set0({pt:.15e} + init_pts[b][i])
243
+ end
244
+ end
245
+ """)
246
+
247
+ def set_start_coords(
248
+ self, x: np.ndarray, px: np.ndarray, y: np.ndarray, py: np.ndarray
249
+ ) -> None:
250
+ """Constant parts of x, px, y, py of every map; ``t``, ``pt`` and the DA coefficients stay."""
251
+ mad = self.session.mad
252
+ # N x 1 column matrices (binary protocol); a single MAD matrix index is linear.
253
+ mad.send("""
254
+ new_x = python:recv()
255
+ new_px = python:recv()
256
+ new_y = python:recv()
257
+ new_py = python:recv()
258
+
259
+ local particle = 0
260
+ for batch=1,num_batches do
261
+ for j=1,#da_x0_c[batch] do
262
+ particle = particle + 1
263
+ da_x0_c[batch][j].x:set0(new_x[particle])
264
+ da_x0_c[batch][j].px:set0(new_px[particle])
265
+ da_x0_c[batch][j].y:set0(new_y[particle])
266
+ da_x0_c[batch][j].py:set0(new_py[particle])
267
+ end
268
+ end
269
+ """)
270
+ for values in (x, px, y, py):
271
+ mad.send(np.asarray(values, dtype=np.float64).reshape(-1, 1))
272
+
273
+ def preflight(self) -> dict[str, int | bool]:
274
+ """See :meth:`accelmo.backend.protocol.TrackingEngine.preflight`."""
275
+ mad = self.session.mad
276
+ mad.send(build_tracking_preflight_script())
277
+ return mad.recv()
278
+
279
+ def _set_save_start(self, enabled: bool) -> None:
280
+ if enabled != self._save_start:
281
+ self.session.mad.send(f"save_start_derivatives = {'true' if enabled else 'false'}")
282
+ self._save_start = enabled
283
+
284
+ def track(self, batch: int, *, start_derivatives: bool) -> TrackResult:
285
+ """See :meth:`accelmo.backend.protocol.TrackingEngine.track`."""
286
+ mad = self.session.mad
287
+ observables = self.plan.observables
288
+ mad.send(f"batch = {batch + 1}")
289
+ if self.plan.validation:
290
+ mad.send(self._track_script)
291
+ return TrackResult({o: np.asarray(mad.recv()).squeeze(-1) for o in observables})
292
+ self._set_save_start(start_derivatives)
293
+ mad.send(self._start_track_script if start_derivatives else self._track_script)
294
+ loss_info: dict = mad.recv()
295
+ obs = {o: np.asarray(mad.recv()).squeeze(-1) for o in observables}
296
+ # MAD stores (points, knobs) rows; the result is (particles, knobs, points).
297
+ d_dk = {o: np.stack(mad.recv(), axis=0).transpose(0, 2, 1) for o in observables}
298
+ d_dc0 = (
299
+ {o: np.stack(mad.recv(), axis=0) for o in observables} if start_derivatives else None
300
+ )
301
+ return TrackResult(obs, d_dk, d_dc0, int(loss_info["n_lost"]), int(loss_info["n_total"]))
302
+
303
+ def close(self) -> None:
304
+ """Close the MAD-NG process."""
305
+ self.session.close()
306
+
307
+
308
+ def _strip_comment_lines(text: str) -> str:
309
+ """Remove full-line comments and blank lines before sending to MAD-NG."""
310
+ kept = []
311
+ for line in text.splitlines():
312
+ stripped = line.strip()
313
+ if not stripped or stripped.startswith(("--", "!")):
314
+ continue
315
+ kept.append(line)
316
+ return "\n".join(kept)
317
+
318
+
319
+ def read_orbit_only(mad: MAD, n_coords: int, n_knobs: int):
320
+ """BPM names, orbit values and Jacobian after ``compute_closed_orbit``."""
321
+ mad.send("send_orbit_only()")
322
+ names = list(mad.recv())
323
+ values = np.empty((n_coords, len(names)))
324
+ jacobian = np.empty((n_coords, len(names), n_knobs))
325
+ columns = max(n_knobs, 1) # MAD keeps one all-zero column when there are no knobs
326
+ for i in range(n_coords):
327
+ values[i] = np.asarray(mad.recv(), dtype=float).ravel()
328
+ jacobian[i] = np.asarray(mad.recv(), dtype=float).reshape(len(names), columns)[:, :n_knobs]
329
+ return names, values, jacobian
330
+
331
+
332
+ def _knob_monomial(index: int, n_knobs: int) -> str:
333
+ """Parameter-monomial suffix selecting d/d(knob ``index``) in a trkopt name.
334
+
335
+ ``gphys.nf_pk`` reads the ``_`` separator as the six phase-space slots, so only the
336
+ parameter part belongs in the suffix.
337
+ """
338
+ return "0" * index + "1" + "0" * (n_knobs - index - 1)
339
+
340
+
341
+ class ClosedOrbitEngine:
342
+ """Parametric closed orbit (``cofind`` + one ``track``) or closed twiss in MAD-NG.
343
+
344
+ Optical functions and their knob derivatives come from twiss's ``trkopt`` columns; the
345
+ orbit coordinates from the saved map (``run_closed_twiss_init.mad``). With ``extra_knobs``
346
+ (calibration fits) those zero-valued knobs follow the magnet knobs and ``pt`` is never fitted.
347
+ """
348
+
349
+ def __init__(
350
+ self,
351
+ config: WorkerConfig,
352
+ init_knobs: Mapping[str, float],
353
+ *,
354
+ optics_names: Sequence[str],
355
+ orbit_coords: Sequence[str],
356
+ worker_id: int,
357
+ logfile: Path | None = None,
358
+ extra_knobs: Sequence[str] | None = None,
359
+ ) -> None:
360
+ del worker_id
361
+ self.session = _MadngSession(config, init_knobs, logfile)
362
+ mad = self.session.mad
363
+ self.optics_names = list(optics_names)
364
+ self.orbit_coords = list(orbit_coords)
365
+ #: ``pt`` is fitted (as a parameter after the knobs) when MAD created it as a knob.
366
+ self.fit_pt = "pt" in self.session.knob_names and extra_knobs is None
367
+ if extra_knobs is not None:
368
+ if extra_knobs:
369
+ mad.send("\n".join(f"loaded_sequence['{knob}'] = 0" for knob in extra_knobs))
370
+ mad["knob_names"] = [n for n in mad["knob_names"] if n != "pt"] + list(extra_knobs)
371
+ #: Parametric knobs in Jacobian column order (magnet knobs, then extra knobs).
372
+ self.knob_names = self.session.fitted_knobs_without_pt()
373
+ self.n_knobs = len(self.knob_names)
374
+ self._value_columns = [f"{name}_" for name in self.optics_names]
375
+ self._derivative_columns = [
376
+ f"{name}_{_knob_monomial(i, self.n_knobs)}"
377
+ for name in self.optics_names
378
+ for i in range(self.n_knobs)
379
+ ]
380
+ mad["optics_columns"] = self._value_columns + self._derivative_columns
381
+ mad["orbit_coords"] = self.orbit_coords
382
+ mad.send(_strip_comment_lines(CLOSED_TWISS_INIT.read_text()))
383
+ self._solver = "compute_closed_twiss()" if self.optics_names else "compute_closed_orbit()"
384
+ #: Knobs are plain numbers (after a ``jacobian=False`` solve) until the next full solve.
385
+ self._plain = False
386
+ self._names: list[str] | None = None
387
+
388
+ def set_knobs(self, knobs: Mapping[str, float]) -> None:
389
+ """See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.set_knobs`."""
390
+ self.session.set_knobs(knobs, plain=self._plain)
391
+
392
+ def get_vars(self, names: Sequence[str]) -> dict[str, float]:
393
+ """See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.get_vars`."""
394
+ return get_vars(self.session.mad, PYTHON_IN_MAD, list(names))
395
+
396
+ def set_vars(self, values: Mapping[str, float]) -> None:
397
+ """See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.set_vars`."""
398
+ set_vars(self.session.mad, values)
399
+
400
+ def set_pt(self, pt: float) -> None:
401
+ """See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.set_pt`."""
402
+ self.session.mad.send(f"x0map.pt:set0({pt:.15e})")
403
+
404
+ def set_warm_start(self, key: str) -> None:
405
+ """See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.set_warm_start`."""
406
+ self.session.mad.send(f"co_key = '{key}'")
407
+
408
+ def _found(self, command: str, what: str) -> bool:
409
+ mad = self.session.mad
410
+ mad.send(command)
411
+ try:
412
+ found = mad.recv()
413
+ except RuntimeError as exc: # MAD raised: an unstable trial point
414
+ LOGGER.warning("MAD error in the %s (%s)", what, exc)
415
+ return False
416
+ return bool(found)
417
+
418
+ def _set_plain(self, *, plain: bool) -> None:
419
+ """Switch the knobs between plain numbers and TPSA parameters (one MAD call per switch)."""
420
+ if plain != self._plain:
421
+ self.session.mad.send("knobs_to_plain()" if plain else "knobs_to_param()")
422
+ self._plain = plain
423
+
424
+ def solve(self, observables: Sequence[str], *, jacobian: bool = True) -> ClosedSolution | None:
425
+ """See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.solve`."""
426
+ if not jacobian:
427
+ return self._solve_plain(observables)
428
+ self._set_plain(plain=False)
429
+ if not self._found(self._solver, "closed-orbit solve"):
430
+ return None
431
+ mad = self.session.mad
432
+ n_knobs = self.n_knobs
433
+ if not self.optics_names:
434
+ names, values, jac = read_orbit_only(mad, len(self.orbit_coords), n_knobs)
435
+ rows = dict(zip(self.orbit_coords, zip(values, jac, strict=True), strict=True))
436
+ else:
437
+ columns = ["name", *self.orbit_coords, *self._value_columns, *self._derivative_columns]
438
+ frame = mad.closed_tbl.to_df(columns=columns)
439
+ names = list(frame["name"])
440
+ n_bpms, n_optics = len(names), len(self.optics_names)
441
+ optics_jacobian = (
442
+ frame[self._derivative_columns]
443
+ .to_numpy(dtype=float)
444
+ .reshape(n_bpms, n_optics, n_knobs)
445
+ .transpose(1, 0, 2)
446
+ )
447
+ rows = {
448
+ name: (frame[column].to_numpy(dtype=float), optics_jacobian[i])
449
+ for i, (name, column) in enumerate(zip(self.optics_names, self._value_columns))
450
+ }
451
+ if self.orbit_coords:
452
+ mad.send("send_orbit_jacobian()")
453
+ for coord in self.orbit_coords:
454
+ jac = np.asarray(mad.recv(), dtype=float).reshape(n_bpms, n_knobs)
455
+ rows[coord] = (frame[coord].to_numpy(dtype=float), jac)
456
+ self._names = names
457
+ return ClosedSolution(
458
+ names,
459
+ np.array([rows[name][0] for name in observables]),
460
+ np.array([rows[name][1] for name in observables]),
461
+ )
462
+
463
+ def _solve_plain(self, observables: Sequence[str]) -> ClosedSolution | None:
464
+ if self.optics_names:
465
+ raise NotImplementedError("loss-only evaluation supports orbit observables only")
466
+ if self._names is None:
467
+ raise RuntimeError("loss-only orbit needs the BPM order from a prior full solve")
468
+ self._set_plain(plain=True)
469
+ if not self._found("compute_orbit_plain()", "loss-only orbit"):
470
+ return None
471
+ mad = self.session.mad
472
+ rows = {coord: np.asarray(mad.recv(), dtype=float).ravel() for coord in self.orbit_coords}
473
+ return ClosedSolution(self._names, np.array([rows[name] for name in observables]), None)
474
+
475
+ def close(self) -> None:
476
+ """Close the MAD-NG process."""
477
+ self.session.close()
478
+
479
+ def scale_globals(self, scaled: Sequence[tuple[str, float, float, str]]) -> None:
480
+ """Set each global ``name`` to the deferred ``kick * (gain + knob)``, so it follows the knob."""
481
+ commands = [
482
+ f"MADX['{name}'] = \\-> {kick:.15e} * ({gain:.15e} + loaded_sequence['{knob}'])"
483
+ for name, kick, gain, knob in scaled
484
+ ]
485
+ if commands:
486
+ self.session.mad.send("\n".join(commands))
487
+
488
+
489
+ def open_model(
490
+ accelerator: Accelerator,
491
+ *,
492
+ magnet_range: str,
493
+ machine_state: MachineState | None = None,
494
+ b2_errors: Path | None = None,
495
+ bad_bpms: list[str] | None = None,
496
+ debug: bool = False,
497
+ mad_logfile: Path | None = None,
498
+ anchor_mode: str | None = None,
499
+ anchor_markers: Sequence[str] = (),
500
+ ) -> MadInterface:
501
+ """Parent-side model: knob discovery and BPM lists."""
502
+ return MadInterface(
503
+ accelerator=accelerator,
504
+ magnet_range=magnet_range,
505
+ machine_state=machine_state,
506
+ b2_errors=b2_errors,
507
+ bad_bpms=bad_bpms,
508
+ debug=debug,
509
+ mad_logfile=mad_logfile,
510
+ tracking_anchor_mode=anchor_mode,
511
+ tracking_anchor_markers=list(anchor_markers),
512
+ create_knobs=True,
513
+ )
514
+
515
+
516
+ def closed_orbit_table(
517
+ accelerator: Accelerator,
518
+ magnet_strengths: Mapping[str, float] | None,
519
+ pt: float,
520
+ machine_state: MachineState | None,
521
+ columns: Sequence[str],
522
+ ):
523
+ """Coupled twiss columns at every observed element, ``pt`` pinned on the initial condition."""
524
+ iface = MadInterface(accelerator, machine_state=machine_state, create_knobs=True)
525
+ try:
526
+ if magnet_strengths:
527
+ iface.update_knob_values(dict(magnet_strengths))
528
+ iface.mad.send(
529
+ f"moref = twiss{{sequence=loaded_sequence, observe=1, "
530
+ f"X0={{pt={float(pt):.15e}}}, coupling=true}}"
531
+ )
532
+ frame = iface.mad.moref.to_df(columns=["name", *columns])
533
+ finally:
534
+ iface.close()
535
+ return frame.set_index("name")[list(columns)]