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.
- accelmo/__init__.py +8 -0
- accelmo/analysis/__init__.py +21 -0
- accelmo/analysis/degeneracy_checker.py +308 -0
- accelmo/backend/__init__.py +26 -0
- accelmo/backend/madng/__init__.py +5 -0
- accelmo/backend/madng/accelerator_hooks.py +171 -0
- accelmo/backend/madng/engines.py +535 -0
- accelmo/backend/madng/interface.py +600 -0
- accelmo/backend/madng/machine_state.py +62 -0
- accelmo/backend/madng/mad_scripts/run_closed_twiss_init.mad +399 -0
- accelmo/backend/madng/scripts.py +367 -0
- accelmo/backend/protocol.py +274 -0
- accelmo/backend/xtrack/__init__.py +1 -0
- accelmo/backend/xtrack/engines.py +366 -0
- accelmo/backend/xtrack/model.py +292 -0
- accelmo/config.py +169 -0
- accelmo/fitting/__init__.py +4 -0
- accelmo/fitting/bpm_gains.py +54 -0
- accelmo/fitting/config.py +44 -0
- accelmo/fitting/lifecycle.py +40 -0
- accelmo/fitting/lm_loop.py +212 -0
- accelmo/fitting/pool.py +75 -0
- accelmo/fitting/priors.py +58 -0
- accelmo/fitting/protocol.py +265 -0
- accelmo/fitting/reduction.py +65 -0
- accelmo/fitting/results.py +36 -0
- accelmo/fitting/setup.py +239 -0
- accelmo/fitting/shared_reference.py +102 -0
- accelmo/fitting/uncertainty.py +115 -0
- accelmo/fitting/weights.py +13 -0
- accelmo/fitting/worker.py +250 -0
- accelmo/machine/__init__.py +1 -0
- accelmo/machine/accelerators/__init__.py +27 -0
- accelmo/machine/accelerators/base.py +276 -0
- accelmo/machine/accelerators/fcc.py +82 -0
- accelmo/machine/accelerators/lhc.py +188 -0
- accelmo/machine/accelerators/magnet_grouping.py +149 -0
- accelmo/machine/accelerators/psb.py +202 -0
- accelmo/machine/accelerators/selection.py +109 -0
- accelmo/machine/accelerators/sps.py +125 -0
- accelmo/machine/knob_names.py +14 -0
- accelmo/machine/machine_state.py +65 -0
- accelmo/machine/patterns.py +96 -0
- accelmo/momentum_reference.py +271 -0
- accelmo/monitor/__init__.py +21 -0
- accelmo/monitor/__main__.py +52 -0
- accelmo/monitor/app.py +338 -0
- accelmo/monitor/cache.py +240 -0
- accelmo/monitor/panels.py +261 -0
- accelmo/monitor/source.py +52 -0
- accelmo/monitor/view.py +39 -0
- accelmo/optimisers/__init__.py +18 -0
- accelmo/optimisers/adam.py +136 -0
- accelmo/optimisers/base.py +84 -0
- accelmo/optimisers/lbfgs.py +208 -0
- accelmo/optimisers/levenberg_marquardt.py +253 -0
- accelmo/poco/__init__.py +34 -0
- accelmo/poco/calibrated.py +328 -0
- accelmo/poco/calibration.py +234 -0
- accelmo/poco/closed_orbit.py +335 -0
- accelmo/poco/fitter.py +410 -0
- accelmo/poco/workers/__init__.py +1 -0
- accelmo/poco/workers/calibrated.py +200 -0
- accelmo/poco/workers/closed_orbit.py +501 -0
- accelmo/poco/workers/closed_twiss.py +174 -0
- accelmo/runlog/__init__.py +25 -0
- accelmo/runlog/reader.py +127 -0
- accelmo/runlog/writer.py +150 -0
- accelmo/tracking/__init__.py +59 -0
- accelmo/tracking/config/__init__.py +29 -0
- accelmo/tracking/config/helpers.py +43 -0
- accelmo/tracking/config/models.py +66 -0
- accelmo/tracking/config/tracking.py +535 -0
- accelmo/tracking/data_manager.py +476 -0
- accelmo/tracking/dispatch/__init__.py +1 -0
- accelmo/tracking/dispatch/payloads.py +210 -0
- accelmo/tracking/dispatch/setup.py +212 -0
- accelmo/tracking/dispatch/turn_planner.py +196 -0
- accelmo/tracking/fitter.py +698 -0
- accelmo/tracking/ic_iteration.py +110 -0
- accelmo/tracking/lm_problem.py +252 -0
- accelmo/tracking/ranges.py +112 -0
- accelmo/tracking/session.py +301 -0
- accelmo/tracking/sgd/__init__.py +1 -0
- accelmo/tracking/sgd/checkpointing.py +229 -0
- accelmo/tracking/sgd/loop.py +327 -0
- accelmo/tracking/sgd/scheduler.py +70 -0
- accelmo/tracking/uncertainty.py +160 -0
- accelmo/tracking/worker.py +661 -0
- accelmo-0.0.1.dist-info/METADATA +208 -0
- accelmo-0.0.1.dist-info/RECORD +95 -0
- accelmo-0.0.1.dist-info/WHEEL +5 -0
- accelmo-0.0.1.dist-info/entry_points.txt +2 -0
- accelmo-0.0.1.dist-info/licenses/LICENSE +21 -0
- accelmo-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
"""Helpers for loading or generating MAD-NG tracking scripts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
mad_dir = Path(__file__).absolute().parent
|
|
9
|
+
MAD_SCRIPTS_DIR = mad_dir / "mad_scripts"
|
|
10
|
+
|
|
11
|
+
CLOSED_TWISS_INIT = MAD_SCRIPTS_DIR / "run_closed_twiss_init.mad"
|
|
12
|
+
|
|
13
|
+
TRACKING_OBSERVABLES = ("x", "y", "px", "py")
|
|
14
|
+
LOGGER = logging.getLogger(__name__)
|
|
15
|
+
TAB = "\t"
|
|
16
|
+
PYTHON_IN_MAD = "python"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def dump_debug_script(
|
|
20
|
+
script_name: str,
|
|
21
|
+
text: str,
|
|
22
|
+
*,
|
|
23
|
+
debug: bool,
|
|
24
|
+
mad_logfile: Path | None = None,
|
|
25
|
+
worker_id: int | None = None,
|
|
26
|
+
) -> Path | None:
|
|
27
|
+
"""Write a generated MAD script to disk when debug mode is enabled."""
|
|
28
|
+
if not debug:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
base_dir = (
|
|
32
|
+
mad_logfile.parent / "generated_mad_scripts"
|
|
33
|
+
if mad_logfile is not None
|
|
34
|
+
else Path.cwd() / "generated_mad_scripts"
|
|
35
|
+
)
|
|
36
|
+
base_dir.mkdir(parents=True, exist_ok=True)
|
|
37
|
+
suffix = f"_worker_{worker_id}" if worker_id is not None else ""
|
|
38
|
+
output_path = base_dir / f"{script_name}{suffix}.mad"
|
|
39
|
+
output_path.write_text(text)
|
|
40
|
+
LOGGER.debug("Wrote generated MAD script to %s", output_path)
|
|
41
|
+
return output_path
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _validate_observables(observables: tuple[str, ...]) -> tuple[str, ...]:
|
|
45
|
+
invalid = set(observables) - set(TRACKING_OBSERVABLES)
|
|
46
|
+
if invalid:
|
|
47
|
+
raise ValueError(f"Unsupported tracking observables: {sorted(invalid)}")
|
|
48
|
+
if not observables:
|
|
49
|
+
raise ValueError("At least one observable is required")
|
|
50
|
+
return observables
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _join_lines(lines: list[str]) -> str:
|
|
54
|
+
"""Join script lines while keeping the assembly logic easy to read."""
|
|
55
|
+
return "\n".join(lines)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _indent(level: int, text: str) -> str:
|
|
59
|
+
"""Indent one generated Lua line with tabs."""
|
|
60
|
+
return f"{TAB * level}{text}"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _per_observable(observables: tuple[str, ...], template: str, *, level: int = 0) -> list[str]:
|
|
64
|
+
"""Render ``template`` once per observable as indented Lua lines.
|
|
65
|
+
|
|
66
|
+
``template`` is a normal ``str.format`` template using ``{o}`` for the
|
|
67
|
+
observable name, e.g. ``"{o}[i]:zeros()"``.
|
|
68
|
+
"""
|
|
69
|
+
return [_indent(level, template.format(o=observable)) for observable in observables]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _table_definitions(observables: tuple[str, ...], *, include_derivatives: bool = True) -> str:
|
|
73
|
+
lines = _per_observable(observables, "{o} = table.new(batch_size, 0)")
|
|
74
|
+
if include_derivatives:
|
|
75
|
+
lines += _per_observable(observables, "d{o}_dk = table.new(batch_size, 0)")
|
|
76
|
+
lines += _per_observable(observables, "d{o}_dc0 = table.new(batch_size, 0)")
|
|
77
|
+
return _join_lines(lines)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _allocation_block(observables: tuple[str, ...], *, include_derivatives: bool = True) -> str:
|
|
81
|
+
lines = _per_observable(observables, "{o}[i] = vector(nbpms * n_run_turns)", level=1)
|
|
82
|
+
if include_derivatives:
|
|
83
|
+
lines += _per_observable(
|
|
84
|
+
observables, "d{o}_dk[i] = matrix(nbpms * n_run_turns, matrix_size)", level=1
|
|
85
|
+
)
|
|
86
|
+
lines += _per_observable(
|
|
87
|
+
observables, "d{o}_dc0[i] = matrix(4, nbpms * n_run_turns)", level=1
|
|
88
|
+
)
|
|
89
|
+
return _join_lines(lines)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _save_scalar_block(observables: tuple[str, ...]) -> str:
|
|
93
|
+
return _join_lines(
|
|
94
|
+
_per_observable(observables, "{o}[i]:seti(observe_count, mflw[i].{o}:get0())", level=3)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _save_knob_derivative_block(observables: tuple[str, ...]) -> str:
|
|
99
|
+
return _join_lines(
|
|
100
|
+
_per_observable(
|
|
101
|
+
observables,
|
|
102
|
+
"_C.mad_tpsa_getv(mflw[i].{o}, 7, num_knobs, d{o}_dk[i]._dat + row)",
|
|
103
|
+
level=4,
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _save_energy_derivative_block(observables: tuple[str, ...]) -> str:
|
|
109
|
+
return _join_lines(
|
|
110
|
+
_per_observable(
|
|
111
|
+
observables,
|
|
112
|
+
"d{o}_dk[i]._dat[row + num_knobs] = mflw[i].{o}:get(7)",
|
|
113
|
+
level=4,
|
|
114
|
+
)
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _save_start_derivative_block(observables: tuple[str, ...]) -> str:
|
|
119
|
+
"""Store d(observable)/d(x0, px0, y0, py0), TPSA monomials 2 to 5."""
|
|
120
|
+
lines = []
|
|
121
|
+
for row in range(1, 5):
|
|
122
|
+
lines += _per_observable(
|
|
123
|
+
observables,
|
|
124
|
+
f"d{{o}}_dc0[i]:set({row}, observe_count, mflw[i].{{o}}:get({row + 1}))",
|
|
125
|
+
level=4,
|
|
126
|
+
)
|
|
127
|
+
return _join_lines(lines)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _reset_block(observables: tuple[str, ...]) -> str:
|
|
131
|
+
# derivative matrices are fully overwritten each track (preflight checks the count)
|
|
132
|
+
return _join_lines(_per_observable(observables, "{o}[i]:zeros()", level=2))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _send_block(
|
|
136
|
+
observables: tuple[str, ...],
|
|
137
|
+
*,
|
|
138
|
+
include_derivatives: bool = True,
|
|
139
|
+
include_start_derivatives: bool = False,
|
|
140
|
+
) -> str:
|
|
141
|
+
lines = _per_observable(observables, f"{PYTHON_IN_MAD}:send({{o}}, true)")
|
|
142
|
+
if include_derivatives:
|
|
143
|
+
lines += _per_observable(observables, f"{PYTHON_IN_MAD}:send(d{{o}}_dk, true)")
|
|
144
|
+
if include_start_derivatives:
|
|
145
|
+
lines += _per_observable(observables, f"{PYTHON_IN_MAD}:send(d{{o}}_dc0, true)")
|
|
146
|
+
return _join_lines(lines)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _track_call(*, x0: str, atexit: str, level: int = 0) -> str:
|
|
150
|
+
"""Render a MAD ``track{...}`` call with the standard tracking arguments.
|
|
151
|
+
|
|
152
|
+
Only ``x0`` and the ``atexit`` callback differ between the tracking,
|
|
153
|
+
preflight, validation and Hessian scripts; ``level`` indents the whole call
|
|
154
|
+
for use inside a ``for`` loop.
|
|
155
|
+
"""
|
|
156
|
+
fields = [
|
|
157
|
+
"sequence=loaded_sequence",
|
|
158
|
+
f"X0={x0}",
|
|
159
|
+
"nturn=n_run_turns",
|
|
160
|
+
"save=false",
|
|
161
|
+
f"atexit={atexit}",
|
|
162
|
+
"range=tracking_range",
|
|
163
|
+
"dir=sdir",
|
|
164
|
+
"aperture={kind='circle', 100}",
|
|
165
|
+
"method=6",
|
|
166
|
+
]
|
|
167
|
+
return _join_lines(
|
|
168
|
+
[
|
|
169
|
+
_indent(level, "local _, mflw = track {"),
|
|
170
|
+
*(_indent(level + 1, f"{field},") for field in fields),
|
|
171
|
+
_indent(level, "}"),
|
|
172
|
+
]
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _observation_gate_definition() -> str:
|
|
177
|
+
"""Return the MAD predicate shared by every observation callback.
|
|
178
|
+
|
|
179
|
+
An element is an observation point on its exit slice (``slc == -4``) when it is
|
|
180
|
+
flagged observed. Defining it once keeps ``save_data``, the validation saver and
|
|
181
|
+
the preflight counter on exactly the same gate, so the preflight count can never
|
|
182
|
+
drift from what the real tracking callbacks store.
|
|
183
|
+
"""
|
|
184
|
+
return "function is_observation_point(elm, slc)\nreturn slc == -4 and elm:is_observed()\nend"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def build_track_speedup_script(track_methods: dict[str, int]) -> str:
|
|
188
|
+
"""Remove zero-field magnets without knob parameters and set per-kind track methods.
|
|
189
|
+
|
|
190
|
+
Run after machine state and TPSA knobs are installed: knob values are TPSA, so an
|
|
191
|
+
element carrying a knob is never removed. The gaps are tracked as implicit drifts.
|
|
192
|
+
"""
|
|
193
|
+
methods = ", ".join(f"{kind}={method}" for kind, method in track_methods.items())
|
|
194
|
+
return f"""! Generated track speed-up script
|
|
195
|
+
local KINDS = {{quadrupole=true, sextupole=true, octupole=true, decapole=true, dodecapole=true,
|
|
196
|
+
hkicker=true, vkicker=true, kicker=true, tkicker=true, solenoid=true, rfcavity=true}}
|
|
197
|
+
local ATTR = {{"k0", "k0s", "k1", "k1s", "k2", "k2s", "k3", "k3s", "k4", "k4s", "k5", "k5s",
|
|
198
|
+
"kick", "hkick", "vkick", "ks", "ksi", "volt", "angle", "knl", "ksl", "dknl", "dksl",
|
|
199
|
+
"dx", "dy", "ds", "dtheta", "dphi", "dpsi", "tilt"}}
|
|
200
|
+
local function zero(v)
|
|
201
|
+
local t = type(v)
|
|
202
|
+
if t == "nil" or t == "boolean" then return not v end
|
|
203
|
+
if t == "number" then return v == 0 end
|
|
204
|
+
if t == "table" then
|
|
205
|
+
for i = 1, #v do if not zero(v[i]) then return false end end
|
|
206
|
+
return true
|
|
207
|
+
end
|
|
208
|
+
return false
|
|
209
|
+
end
|
|
210
|
+
local function is_off(e, i)
|
|
211
|
+
if not (KINDS[e.kind] and e.is_thick and e.l > 0) or e.misalign or loaded_sequence:align(i) then
|
|
212
|
+
return false
|
|
213
|
+
end
|
|
214
|
+
for _, a in ipairs(ATTR) do if not zero(e[a]) then return false end end
|
|
215
|
+
return true
|
|
216
|
+
end
|
|
217
|
+
-- remove needs increasing indexes: drop the (by-name) cycle around it
|
|
218
|
+
local cycle_ref = loaded_sequence.__cycle
|
|
219
|
+
loaded_sequence:cycle(nil)
|
|
220
|
+
loaded_sequence:remove {{select=is_off}}
|
|
221
|
+
loaded_sequence:cycle(cycle_ref)
|
|
222
|
+
local methods = {{{methods}}}
|
|
223
|
+
loaded_sequence:foreach(\\e => e.method = methods[e.kind] end, {{select=\\e -> methods[e.kind] ~= nil}})
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def build_tracking_init_script(
|
|
228
|
+
observables: tuple[str, ...], *, start_on_first_turn: bool = False
|
|
229
|
+
) -> str:
|
|
230
|
+
"""Build the tracking initialisation script for the requested observables."""
|
|
231
|
+
observables = _validate_observables(observables)
|
|
232
|
+
initial_observe_count = "1" if start_on_first_turn else "nbpms + 1"
|
|
233
|
+
|
|
234
|
+
return f"""! Generated tracking init script
|
|
235
|
+
num_knobs = #knob_names
|
|
236
|
+
local matrix_size = optimise_energy and (num_knobs + 1) or num_knobs
|
|
237
|
+
local _C in MAD
|
|
238
|
+
|
|
239
|
+
{_table_definitions(observables)}
|
|
240
|
+
|
|
241
|
+
for i=1,batch_size do
|
|
242
|
+
{_allocation_block(observables)}
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
{_observation_gate_definition()}
|
|
246
|
+
|
|
247
|
+
observe_count = {initial_observe_count}
|
|
248
|
+
-- Only the uncertainty propagation needs the start-coordinate derivatives.
|
|
249
|
+
save_start_derivatives = false
|
|
250
|
+
function save_data(elm, mflw, _, slc)
|
|
251
|
+
if is_observation_point(elm, slc) then
|
|
252
|
+
local row = (observe_count - 1) * matrix_size
|
|
253
|
+
for i=1,batch_size do
|
|
254
|
+
{_save_scalar_block(observables)}
|
|
255
|
+
|
|
256
|
+
if num_knobs > 0 then
|
|
257
|
+
{_save_knob_derivative_block(observables)}
|
|
258
|
+
end
|
|
259
|
+
|
|
260
|
+
if optimise_energy then
|
|
261
|
+
{_save_energy_derivative_block(observables)}
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
if save_start_derivatives then
|
|
265
|
+
{_save_start_derivative_block(observables)}
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
observe_count = observe_count + 1
|
|
269
|
+
end
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
function reset_before_tracking()
|
|
273
|
+
observe_count = 1
|
|
274
|
+
for i=1,batch_size do
|
|
275
|
+
{_reset_block(observables)}
|
|
276
|
+
end
|
|
277
|
+
end
|
|
278
|
+
"""
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def build_tracking_script(
|
|
282
|
+
observables: tuple[str, ...], *, include_start_derivatives: bool = False
|
|
283
|
+
) -> str:
|
|
284
|
+
"""Build the tracking script for the requested observables.
|
|
285
|
+
|
|
286
|
+
``include_start_derivatives`` also sends ``d{o}_dc0``; the caller must set
|
|
287
|
+
``save_start_derivatives = true`` in MAD first.
|
|
288
|
+
"""
|
|
289
|
+
observables = _validate_observables(observables)
|
|
290
|
+
return f"""! Generated tracking script
|
|
291
|
+
reset_before_tracking()
|
|
292
|
+
{_track_call(x0="da_x0_c[batch]", atexit="save_data")}
|
|
293
|
+
|
|
294
|
+
local n_lost = 0
|
|
295
|
+
for i=1,batch_size do
|
|
296
|
+
if mflw[i] and mflw[i].status == 'lost' then n_lost = n_lost + 1 end
|
|
297
|
+
end
|
|
298
|
+
{PYTHON_IN_MAD}:send({{n_lost=n_lost, n_total=batch_size}}, true)
|
|
299
|
+
{_send_block(observables, include_start_derivatives=include_start_derivatives)}
|
|
300
|
+
"""
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def build_tracking_preflight_script() -> str:
|
|
304
|
+
"""Build the single-particle preflight script.
|
|
305
|
+
|
|
306
|
+
Tracks one particle through the configured range/turns with a counting
|
|
307
|
+
``atexit`` and reports how many BPM points were observed. The worker compares
|
|
308
|
+
this against the allocated result-vector size (``nbpms * n_run_turns``) once,
|
|
309
|
+
before the optimisation loop, so an observe/range misconfiguration fails with a
|
|
310
|
+
clear message here instead of as an opaque ``seti`` index-out-of-bounds deep in
|
|
311
|
+
a tracking run. Observable-independent: only the observation geometry matters.
|
|
312
|
+
"""
|
|
313
|
+
return f"""! Generated tracking preflight script
|
|
314
|
+
local observed = 0
|
|
315
|
+
local function preflight_counter(elm, mflw, _, slc)
|
|
316
|
+
if is_observation_point(elm, slc) then observed = observed + 1 end
|
|
317
|
+
end
|
|
318
|
+
{_track_call(x0="da_x0_c[1][1]", atexit="preflight_counter")}
|
|
319
|
+
{PYTHON_IN_MAD}:send({{
|
|
320
|
+
observed=observed,
|
|
321
|
+
expected=nbpms * n_run_turns,
|
|
322
|
+
lost=(mflw[1] and mflw[1].status == 'lost') or false,
|
|
323
|
+
}}, true)
|
|
324
|
+
"""
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def build_validation_init_script(observables: tuple[str, ...]) -> str:
|
|
328
|
+
"""Build the validation initialisation script without derivative storage."""
|
|
329
|
+
observables = _validate_observables(observables)
|
|
330
|
+
|
|
331
|
+
return f"""! Generated validation init script
|
|
332
|
+
{_table_definitions(observables, include_derivatives=False)}
|
|
333
|
+
|
|
334
|
+
for i=1,batch_size do
|
|
335
|
+
{_allocation_block(observables, include_derivatives=False)}
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
{_observation_gate_definition()}
|
|
339
|
+
|
|
340
|
+
observe_count = nbpms + 1
|
|
341
|
+
function save_val_data(elm, mflw, _, slc)
|
|
342
|
+
if is_observation_point(elm, slc) then
|
|
343
|
+
for i=1,batch_size do
|
|
344
|
+
{_save_scalar_block(observables)}
|
|
345
|
+
end
|
|
346
|
+
observe_count = observe_count + 1
|
|
347
|
+
end
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
function reset_before_validation()
|
|
351
|
+
observe_count = 1
|
|
352
|
+
for i=1,batch_size do
|
|
353
|
+
{_reset_block(observables)}
|
|
354
|
+
end
|
|
355
|
+
end
|
|
356
|
+
"""
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def build_validation_script(observables: tuple[str, ...]) -> str:
|
|
360
|
+
"""Build the validation tracking script without derivative returns."""
|
|
361
|
+
observables = _validate_observables(observables)
|
|
362
|
+
return f"""! Generated validation script
|
|
363
|
+
reset_before_validation()
|
|
364
|
+
{_track_call(x0="da_x0_c[batch]", atexit="save_val_data")}
|
|
365
|
+
|
|
366
|
+
{_send_block(observables, include_derivatives=False)}
|
|
367
|
+
"""
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""What the workers and the parent need from a model backend.
|
|
2
|
+
|
|
3
|
+
A backend module (``accelmo.backend.<name>``) provides :class:`TrackingEngine` and
|
|
4
|
+
:class:`ClosedOrbitEngine` implementations plus the parent-side :func:`open_model` and
|
|
5
|
+
:func:`closed_orbit_table`; :func:`accelmo.backend.get_backend` picks it from
|
|
6
|
+
``Accelerator.backend``. Only automatic differentiation computes derivatives.
|
|
7
|
+
MAD-NG is the production backend, xtrack the reference for other codes; the contract
|
|
8
|
+
and the acceptance tests are in ``docs/backends.rst``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import TYPE_CHECKING, Protocol
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
import pandas as pd
|
|
22
|
+
|
|
23
|
+
from accelmo.fitting.worker import WorkerConfig
|
|
24
|
+
from accelmo.machine.accelerators import Accelerator
|
|
25
|
+
from accelmo.machine.machine_state import MachineState
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class TrackGeometry:
|
|
30
|
+
"""The model segment one tracking worker observes and tracks, fixed when its engine is built."""
|
|
31
|
+
|
|
32
|
+
start_bpm: str
|
|
33
|
+
end_bpm: str
|
|
34
|
+
#: Marker supplying the start coordinates (kicker, AC dipole); the full ring is tracked.
|
|
35
|
+
initial_condition_marker: str | None = None
|
|
36
|
+
sdir: int = 1
|
|
37
|
+
cycle_marker: str | None = None
|
|
38
|
+
anchor_mode: str | None = None
|
|
39
|
+
anchor_sources: tuple[str, ...] = ()
|
|
40
|
+
#: Turns tracked from each start.
|
|
41
|
+
n_turns: int = 1
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def init_point(self) -> str:
|
|
45
|
+
"""Where the start coordinates are read: the marker, else the first BPM in tracking order."""
|
|
46
|
+
if self.initial_condition_marker is not None:
|
|
47
|
+
return self.initial_condition_marker
|
|
48
|
+
return self.start_bpm if self.sdir > 0 else self.end_bpm
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def bpm_range(self) -> str:
|
|
52
|
+
"""Observed BPM range ``first/last``."""
|
|
53
|
+
return f"{self.start_bpm}/{self.end_bpm}"
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def tracking_range(self) -> str | None:
|
|
57
|
+
"""Tracked range in tracking order; ``None`` tracks the full cycled sequence.
|
|
58
|
+
|
|
59
|
+
A marker start tracks the whole ring every turn, since a named range would treat
|
|
60
|
+
elements outside it as drifts.
|
|
61
|
+
"""
|
|
62
|
+
if self.initial_condition_marker is not None:
|
|
63
|
+
return None
|
|
64
|
+
if self.sdir < 0:
|
|
65
|
+
return f"{self.end_bpm}/{self.start_bpm}"
|
|
66
|
+
return self.bpm_range
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def cycle_target(self) -> str:
|
|
70
|
+
"""Element the sequence is cycled to before tracking.
|
|
71
|
+
|
|
72
|
+
The initial-condition marker or where the measured turn increment starts: the
|
|
73
|
+
tracking end for a backward range, where the start coordinates are taken.
|
|
74
|
+
Validation workers cycle identically or they track a different path.
|
|
75
|
+
"""
|
|
76
|
+
init_bpm = self.start_bpm if self.sdir > 0 else self.end_bpm
|
|
77
|
+
return self.cycle_marker or self.initial_condition_marker or init_bpm
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class TrackRequest:
|
|
82
|
+
"""What one tracking worker tracks.
|
|
83
|
+
|
|
84
|
+
``turn_offset`` is the start turn minus the file's first turn (AC-kicker phase) and
|
|
85
|
+
``file_index`` the measurement file of every particle.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
geometry: TrackGeometry
|
|
89
|
+
observables: tuple[str, ...]
|
|
90
|
+
batch_size: int
|
|
91
|
+
num_batches: int
|
|
92
|
+
validation: bool
|
|
93
|
+
file_index: int
|
|
94
|
+
turn_offset: int
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class TrackResult:
|
|
99
|
+
"""One tracked batch.
|
|
100
|
+
|
|
101
|
+
``obs[o]`` is ``(P, N)``; ``d_dk[o]`` is ``(P, K, N)`` with ``K`` the knobs (then
|
|
102
|
+
``pt`` when the energy is fitted); ``d_dc0[o]`` is ``(P, 4, N)``, the derivatives by
|
|
103
|
+
the start x, px, y, py. Validation engines fill ``obs`` only.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
obs: dict[str, np.ndarray]
|
|
107
|
+
d_dk: dict[str, np.ndarray] | None = None
|
|
108
|
+
d_dc0: dict[str, np.ndarray] | None = None
|
|
109
|
+
n_lost: int = 0
|
|
110
|
+
n_total: int = 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
@dataclass
|
|
114
|
+
class ClosedSolution:
|
|
115
|
+
"""Closed orbit (and optics) at the BPMs in model order.
|
|
116
|
+
|
|
117
|
+
``values`` is ``(n_observables, n_bpms)`` and ``jacobian`` ``(n_observables, n_bpms,
|
|
118
|
+
n_knobs)`` (``None`` from a ``jacobian=False`` solve), rows in the requested observable order.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
names: list[str]
|
|
122
|
+
values: np.ndarray
|
|
123
|
+
jacobian: np.ndarray | None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class TrackingEngine(Protocol):
|
|
127
|
+
"""Tracks batches of particles with knob (and start-coordinate) derivatives.
|
|
128
|
+
|
|
129
|
+
``knob_names`` are the fitted knobs, ``pt`` last when the energy is fitted.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
knob_names: list[str]
|
|
133
|
+
nbpms: int
|
|
134
|
+
|
|
135
|
+
def __init__(
|
|
136
|
+
self,
|
|
137
|
+
config: WorkerConfig,
|
|
138
|
+
plan: TrackRequest,
|
|
139
|
+
init_knobs: Mapping[str, float],
|
|
140
|
+
*,
|
|
141
|
+
worker_id: int,
|
|
142
|
+
logfile: Path | None = None,
|
|
143
|
+
) -> None:
|
|
144
|
+
"""Load the model for ``config`` and prepare to track ``plan`` from ``init_knobs``."""
|
|
145
|
+
|
|
146
|
+
def set_knobs(self, knobs: Mapping[str, float]) -> None:
|
|
147
|
+
"""Set the fitted knobs (and ``pt`` when the energy is fitted) to ``knobs``."""
|
|
148
|
+
|
|
149
|
+
def load_particles(
|
|
150
|
+
self, init_coords: list[list[list[float]]], init_pts: list[list[float]]
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Set the start coordinates and ``pt`` offsets, both indexed ``[batch][particle]``."""
|
|
153
|
+
|
|
154
|
+
def set_pts(self, pt: float, first_batch: int, last_batch: int) -> None:
|
|
155
|
+
"""Set ``pt`` of every particle in batches ``first..last`` (0-based) to ``pt`` plus its own offset."""
|
|
156
|
+
|
|
157
|
+
def set_start_coords(
|
|
158
|
+
self, x: np.ndarray, px: np.ndarray, y: np.ndarray, py: np.ndarray
|
|
159
|
+
) -> None:
|
|
160
|
+
"""Replace the start ``x, px, y, py`` of every particle, in batch order; ``pt`` is kept."""
|
|
161
|
+
|
|
162
|
+
def preflight(self) -> dict[str, int | bool]:
|
|
163
|
+
"""One-particle dry run: ``{"observed", "expected", "lost"}``."""
|
|
164
|
+
|
|
165
|
+
def track(self, batch: int, *, start_derivatives: bool) -> TrackResult:
|
|
166
|
+
"""Track batch ``batch`` (0-based); ``start_derivatives`` also fills ``d_dc0``."""
|
|
167
|
+
|
|
168
|
+
def close(self) -> None:
|
|
169
|
+
"""Release the model."""
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class ClosedOrbitEngine(Protocol):
|
|
173
|
+
"""Solves the closed orbit (and twiss) with knob derivatives."""
|
|
174
|
+
|
|
175
|
+
knob_names: list[str]
|
|
176
|
+
#: ``pt`` is fitted too: its derivative is the Jacobian column after the knobs.
|
|
177
|
+
fit_pt: bool
|
|
178
|
+
|
|
179
|
+
def __init__(
|
|
180
|
+
self,
|
|
181
|
+
config: WorkerConfig,
|
|
182
|
+
init_knobs: Mapping[str, float],
|
|
183
|
+
*,
|
|
184
|
+
optics_names: Sequence[str],
|
|
185
|
+
orbit_coords: Sequence[str],
|
|
186
|
+
worker_id: int,
|
|
187
|
+
logfile: Path | None = None,
|
|
188
|
+
extra_knobs: Sequence[str] | None = None,
|
|
189
|
+
) -> None:
|
|
190
|
+
"""Load the model; ``solve`` returns ``optics_names`` and ``orbit_coords`` rows.
|
|
191
|
+
|
|
192
|
+
``extra_knobs`` (calibration fits; ``madng`` only) are zero-valued knobs after the magnet
|
|
193
|
+
knobs, and ``pt`` is then never fitted.
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
def set_knobs(self, knobs: Mapping[str, float]) -> None:
|
|
197
|
+
"""Set the fitted knobs to ``knobs``."""
|
|
198
|
+
|
|
199
|
+
def get_vars(self, names: Sequence[str]) -> dict[str, float]:
|
|
200
|
+
"""Current values of the global variables ``names`` (machine state, e.g. corrector kicks)."""
|
|
201
|
+
|
|
202
|
+
def set_vars(self, values: Mapping[str, float]) -> None:
|
|
203
|
+
"""Set global variables or element attributes (a machine state)."""
|
|
204
|
+
|
|
205
|
+
def set_pt(self, pt: float) -> None:
|
|
206
|
+
"""Set the momentum offset ``pt`` of the closed-orbit search."""
|
|
207
|
+
|
|
208
|
+
def set_warm_start(self, key: str) -> None:
|
|
209
|
+
"""Start the next closed-orbit search from the last orbit solved under ``key``."""
|
|
210
|
+
|
|
211
|
+
def solve(self, observables: Sequence[str], *, jacobian: bool = True) -> ClosedSolution | None:
|
|
212
|
+
"""``None`` when the closed orbit is lost.
|
|
213
|
+
|
|
214
|
+
``jacobian=False`` (loss-only evaluation, orbit observables only) leaves
|
|
215
|
+
``ClosedSolution.jacobian`` ``None`` and may skip the derivatives entirely.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def close(self) -> None:
|
|
219
|
+
"""Release the model."""
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Model(Protocol):
|
|
223
|
+
"""Parent-side model: knob discovery and BPM lists (no derivatives)."""
|
|
224
|
+
|
|
225
|
+
knob_names: list[str]
|
|
226
|
+
all_bpms: list[str]
|
|
227
|
+
bpms_in_range: list[str]
|
|
228
|
+
|
|
229
|
+
def cycle_to_start(self, marker: str) -> None:
|
|
230
|
+
"""Make ``marker`` the first element of the sequence."""
|
|
231
|
+
|
|
232
|
+
def recount_bpms(self) -> None:
|
|
233
|
+
"""Refresh ``all_bpms`` and ``bpms_in_range`` after a cycle."""
|
|
234
|
+
|
|
235
|
+
def apply_initial_model_values(self, values: Mapping[str, float]) -> None:
|
|
236
|
+
"""Set knobs and fixed strengths to ``values`` before the fit starts."""
|
|
237
|
+
|
|
238
|
+
def knob_values(self) -> np.ndarray:
|
|
239
|
+
"""Current values of ``knob_names``, in that order."""
|
|
240
|
+
|
|
241
|
+
def close(self) -> None:
|
|
242
|
+
"""Release the model."""
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class Backend(Protocol):
|
|
246
|
+
"""The module ``accelmo.backend.<name>``."""
|
|
247
|
+
|
|
248
|
+
TrackingEngine: type[TrackingEngine]
|
|
249
|
+
ClosedOrbitEngine: type[ClosedOrbitEngine]
|
|
250
|
+
|
|
251
|
+
def open_model(
|
|
252
|
+
self,
|
|
253
|
+
accelerator: Accelerator,
|
|
254
|
+
*,
|
|
255
|
+
magnet_range: str,
|
|
256
|
+
machine_state: MachineState | None = None,
|
|
257
|
+
b2_errors: Path | None = None,
|
|
258
|
+
bad_bpms: list[str] | None = None,
|
|
259
|
+
debug: bool = False,
|
|
260
|
+
mad_logfile: Path | None = None,
|
|
261
|
+
anchor_mode: str | None = None,
|
|
262
|
+
anchor_markers: Sequence[str] = (),
|
|
263
|
+
) -> Model:
|
|
264
|
+
"""Load ``accelerator``, create its knobs over ``magnet_range`` and return the model."""
|
|
265
|
+
|
|
266
|
+
def closed_orbit_table(
|
|
267
|
+
self,
|
|
268
|
+
accelerator: Accelerator,
|
|
269
|
+
magnet_strengths: Mapping[str, float] | None,
|
|
270
|
+
pt: float,
|
|
271
|
+
machine_state: MachineState | None,
|
|
272
|
+
columns: Sequence[str],
|
|
273
|
+
) -> pd.DataFrame:
|
|
274
|
+
"""Closed-orbit ``columns`` at the BPMs for these strengths, ``pt`` and state."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""xtrack TPSA backend: everything that imports xtrack."""
|