accelmo 0.0.1__tar.gz → 0.0.2__tar.gz
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-0.0.1/src/accelmo.egg-info → accelmo-0.0.2}/PKG-INFO +2 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/pyproject.toml +2 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/analysis/degeneracy_checker.py +5 -16
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/engines.py +52 -45
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/interface.py +14 -14
- accelmo-0.0.2/src/accelmo/backend/madng/mad_scripts/particle_maps.mad +12 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/mad_scripts/run_closed_twiss_init.mad +3 -0
- accelmo-0.0.2/src/accelmo/backend/madng/mad_scripts/scale_globals.mad +6 -0
- accelmo-0.0.2/src/accelmo/backend/madng/mad_scripts/second_order.mad +61 -0
- accelmo-0.0.2/src/accelmo/backend/madng/mad_scripts/second_order_rebuild.mad +19 -0
- accelmo-0.0.2/src/accelmo/backend/madng/mad_scripts/track_batch.mad +15 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/scripts.py +37 -43
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/protocol.py +21 -0
- accelmo-0.0.2/src/accelmo/backend/xtrack/closed_orbit.py +198 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/xtrack/engines.py +34 -66
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/xtrack/model.py +48 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/config.py +14 -2
- accelmo-0.0.2/src/accelmo/dashboard/__init__.py +5 -0
- accelmo-0.0.2/src/accelmo/dashboard/fit.py +447 -0
- accelmo-0.0.2/src/accelmo/dashboard/plot.py +108 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/lm_loop.py +31 -18
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/pool.py +2 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/protocol.py +36 -10
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/results.py +14 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/setup.py +2 -2
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/shared_reference.py +11 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/worker.py +5 -33
- accelmo-0.0.2/src/accelmo/fitting/worker_logging.py +62 -0
- accelmo-0.0.2/src/accelmo/logs.py +41 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/base.py +2 -2
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/magnet_grouping.py +1 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/app.py +3 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/view.py +25 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/optimisers/adam.py +2 -2
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/calibrated.py +7 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/closed_orbit.py +10 -6
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/fitter.py +88 -23
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/workers/closed_orbit.py +44 -6
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/workers/closed_twiss.py +16 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/runlog/__init__.py +2 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/runlog/reader.py +13 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/runlog/writer.py +5 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/data_manager.py +6 -6
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/dispatch/turn_planner.py +3 -3
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/fitter.py +238 -61
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/ic_iteration.py +3 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/ranges.py +3 -3
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/session.py +65 -11
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/sgd/checkpointing.py +1 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/sgd/loop.py +25 -36
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/sgd/scheduler.py +0 -6
- accelmo-0.0.2/src/accelmo/tracking/uncertainty.py +314 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/worker.py +102 -20
- {accelmo-0.0.1 → accelmo-0.0.2/src/accelmo.egg-info}/PKG-INFO +2 -1
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo.egg-info/SOURCES.txt +12 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo.egg-info/requires.txt +1 -0
- accelmo-0.0.2/tests/test_logs.py +40 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/tests/test_package_layers.py +2 -0
- accelmo-0.0.1/src/accelmo/tracking/uncertainty.py +0 -160
- {accelmo-0.0.1 → accelmo-0.0.2}/LICENSE +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/README.md +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/setup.cfg +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/analysis/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/accelerator_hooks.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/machine_state.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/xtrack/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/bpm_gains.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/config.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/lifecycle.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/priors.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/reduction.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/uncertainty.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/fitting/weights.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/fcc.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/lhc.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/psb.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/selection.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/accelerators/sps.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/knob_names.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/machine_state.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/machine/patterns.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/momentum_reference.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/__main__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/cache.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/panels.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/monitor/source.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/optimisers/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/optimisers/base.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/optimisers/lbfgs.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/optimisers/levenberg_marquardt.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/calibration.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/workers/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/poco/workers/calibrated.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/config/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/config/helpers.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/config/models.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/config/tracking.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/dispatch/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/dispatch/payloads.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/dispatch/setup.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/lm_problem.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/tracking/sgd/__init__.py +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo.egg-info/dependency_links.txt +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo.egg-info/entry_points.txt +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo.egg-info/top_level.txt +0 -0
- {accelmo-0.0.1 → accelmo-0.0.2}/tests/test_calibration.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: accelmo
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.2
|
|
4
4
|
Summary: Accelerator Effective Lattice Modelling and Optimisation
|
|
5
5
|
Author: Joshua Gray
|
|
6
6
|
License: MIT
|
|
@@ -17,6 +17,7 @@ Requires-Dist: pymadng-utils>=0.0.2
|
|
|
17
17
|
Requires-Dist: matplotlib
|
|
18
18
|
Requires-Dist: uncertainties
|
|
19
19
|
Requires-Dist: scipy>=1.17.1
|
|
20
|
+
Requires-Dist: rich
|
|
20
21
|
Provides-Extra: test
|
|
21
22
|
Requires-Dist: pytest; extra == "test"
|
|
22
23
|
Requires-Dist: pytest-cov; extra == "test"
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "accelmo"
|
|
7
|
-
version = "0.0.
|
|
7
|
+
version = "0.0.2"
|
|
8
8
|
description = "Accelerator Effective Lattice Modelling and Optimisation"
|
|
9
9
|
authors = [
|
|
10
10
|
{ name = "Joshua Gray" },
|
|
@@ -22,6 +22,7 @@ dependencies = [
|
|
|
22
22
|
"matplotlib",
|
|
23
23
|
"uncertainties",
|
|
24
24
|
"scipy>=1.17.1",
|
|
25
|
+
"rich",
|
|
25
26
|
]
|
|
26
27
|
|
|
27
28
|
[project.urls]
|
|
@@ -135,12 +135,9 @@ class DegeneracyReport:
|
|
|
135
135
|
lines.append(" unconstrained knob combinations (weakest first):")
|
|
136
136
|
for i, direction in enumerate(self.degenerate_directions[:max_directions]):
|
|
137
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}"
|
|
138
|
+
f"{coeff:+.2f}*{name}" for name, coeff in direction.contributions[:max_knobs]
|
|
143
139
|
)
|
|
140
|
+
lines.append(f" [{i}] rel_eig={direction.relative_eigenvalue:.2e}: {terms}")
|
|
144
141
|
hidden = len(self.degenerate_directions) - max_directions
|
|
145
142
|
if hidden > 0:
|
|
146
143
|
lines.append(f" ... (+{hidden} more directions)")
|
|
@@ -165,11 +162,7 @@ def _extract_contributions(
|
|
|
165
162
|
return []
|
|
166
163
|
cutoff = contribution_threshold * peak
|
|
167
164
|
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
|
-
]
|
|
165
|
+
return [(knob_names[i], float(components[i])) for i in order if magnitudes[i] >= cutoff]
|
|
173
166
|
|
|
174
167
|
|
|
175
168
|
def analyse_degeneracy(
|
|
@@ -210,9 +203,7 @@ def analyse_degeneracy(
|
|
|
210
203
|
raise ValueError(f"normal_matrix must be square, got shape {matrix.shape}")
|
|
211
204
|
n = matrix.shape[0]
|
|
212
205
|
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
|
-
)
|
|
206
|
+
raise ValueError(f"knob_names has {len(knob_names)} entries but normal_matrix is {n}x{n}")
|
|
216
207
|
if not np.all(np.isfinite(matrix)):
|
|
217
208
|
raise ValueError("normal_matrix contains non-finite entries (NaN or inf)")
|
|
218
209
|
knob_names = list(knob_names)
|
|
@@ -275,9 +266,7 @@ def analyse_degeneracy(
|
|
|
275
266
|
degenerate_directions.append(
|
|
276
267
|
DegenerateDirection(
|
|
277
268
|
eigenvalue=float(eigenvalues[idx]),
|
|
278
|
-
relative_eigenvalue=(
|
|
279
|
-
float(clamped[idx] / lambda_max) if lambda_max > 0.0 else 0.0
|
|
280
|
-
),
|
|
269
|
+
relative_eigenvalue=(float(clamped[idx] / lambda_max) if lambda_max > 0.0 else 0.0),
|
|
281
270
|
components=components.copy(),
|
|
282
271
|
contributions=contributions,
|
|
283
272
|
)
|
|
@@ -21,16 +21,24 @@ from accelmo.backend.madng.interface import MadInterface
|
|
|
21
21
|
from accelmo.backend.madng.machine_state import get_vars, set_vars
|
|
22
22
|
from accelmo.backend.madng.scripts import (
|
|
23
23
|
CLOSED_TWISS_INIT,
|
|
24
|
+
PARTICLE_MAPS,
|
|
24
25
|
PYTHON_IN_MAD,
|
|
26
|
+
SCALE_GLOBALS,
|
|
27
|
+
SECOND_ORDER,
|
|
28
|
+
SECOND_ORDER_REBUILD,
|
|
29
|
+
SET_KNOBS_PLAIN,
|
|
30
|
+
SET_KNOBS_TPSA,
|
|
31
|
+
TRACK_BATCH,
|
|
25
32
|
build_track_speedup_script,
|
|
26
33
|
build_tracking_init_script,
|
|
27
34
|
build_tracking_preflight_script,
|
|
28
35
|
build_tracking_script,
|
|
29
36
|
build_validation_init_script,
|
|
30
37
|
build_validation_script,
|
|
38
|
+
build_zero_field_removal_script,
|
|
31
39
|
dump_debug_script,
|
|
32
40
|
)
|
|
33
|
-
from accelmo.backend.protocol import ClosedSolution, TrackResult
|
|
41
|
+
from accelmo.backend.protocol import ClosedSolution, SecondOrderBlocks, TrackResult
|
|
34
42
|
|
|
35
43
|
if TYPE_CHECKING:
|
|
36
44
|
from collections.abc import Mapping, Sequence
|
|
@@ -100,16 +108,11 @@ class _MadngSession:
|
|
|
100
108
|
|
|
101
109
|
def set_knobs(self, knobs: Mapping[str, float], *, plain: bool) -> None:
|
|
102
110
|
"""Set this process's knobs; ``plain`` assigns numbers instead of the TPSA constant part."""
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
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))
|
|
111
|
+
names = [name for name in knobs if name != "pt" and name in self._settable]
|
|
112
|
+
if names:
|
|
113
|
+
self.mad["set_names"] = names
|
|
114
|
+
self.mad.send(SET_KNOBS_PLAIN if plain else SET_KNOBS_TPSA)
|
|
115
|
+
self.mad.send(np.array([[knobs[name]] for name in names], dtype=np.float64))
|
|
113
116
|
|
|
114
117
|
def fitted_knobs_without_pt(self) -> list[str]:
|
|
115
118
|
"""``pt`` is applied per particle or pinned on the map, never a sequence knob."""
|
|
@@ -222,27 +225,20 @@ init_coords = python:recv()
|
|
|
222
225
|
init_pts = python:recv()
|
|
223
226
|
""")
|
|
224
227
|
mad.send(init_coords).send(init_pts)
|
|
225
|
-
mad.send(
|
|
226
|
-
|
|
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
|
-
""")
|
|
228
|
+
mad.send(PARTICLE_MAPS.read_text())
|
|
229
|
+
mad.send(TRACK_BATCH.read_text())
|
|
235
230
|
mad.send(self._init_script)
|
|
236
231
|
|
|
237
232
|
def set_pts(self, pt: float, first_batch: int, last_batch: int) -> None:
|
|
238
233
|
"""See :meth:`accelmo.backend.protocol.TrackingEngine.set_pts`."""
|
|
239
234
|
self.session.mad.send(f"""
|
|
235
|
+
local pt = python:recv()
|
|
240
236
|
for b = {first_batch + 1}, {last_batch + 1} do
|
|
241
237
|
for i = 1, batch_size do
|
|
242
|
-
da_x0_c[b][i].pt:set0(
|
|
238
|
+
da_x0_c[b][i].pt:set0(pt + init_pts[b][i])
|
|
243
239
|
end
|
|
244
240
|
end
|
|
245
|
-
""")
|
|
241
|
+
""").send(float(pt))
|
|
246
242
|
|
|
247
243
|
def set_start_coords(
|
|
248
244
|
self, x: np.ndarray, px: np.ndarray, y: np.ndarray, py: np.ndarray
|
|
@@ -300,22 +296,31 @@ end
|
|
|
300
296
|
)
|
|
301
297
|
return TrackResult(obs, d_dk, d_dc0, int(loss_info["n_lost"]), int(loss_info["n_total"]))
|
|
302
298
|
|
|
299
|
+
def begin_second_order(self) -> None:
|
|
300
|
+
"""See :meth:`accelmo.backend.protocol.TrackingEngine.begin_second_order`."""
|
|
301
|
+
self.session.mad.send(SECOND_ORDER_REBUILD.read_text())
|
|
302
|
+
|
|
303
|
+
def second_order(
|
|
304
|
+
self, batch: int, weighted_residuals: dict[str, np.ndarray]
|
|
305
|
+
) -> SecondOrderBlocks:
|
|
306
|
+
"""See :meth:`accelmo.backend.protocol.TrackingEngine.second_order`."""
|
|
307
|
+
mad = self.session.mad
|
|
308
|
+
observables = self.plan.observables
|
|
309
|
+
mad["observables"] = list(observables)
|
|
310
|
+
mad.send(f"batch = {batch + 1}")
|
|
311
|
+
mad.send(SECOND_ORDER.read_text())
|
|
312
|
+
for observable in observables:
|
|
313
|
+
mad.send(np.ascontiguousarray(weighted_residuals[observable], dtype=np.float64))
|
|
314
|
+
knob_knob = np.asarray(mad.recv())
|
|
315
|
+
knob_start = np.asarray(mad.recv()).reshape(-1, len(knob_knob), 4)
|
|
316
|
+
start_start = np.asarray(mad.recv()).reshape(-1, 4, 4)
|
|
317
|
+
return SecondOrderBlocks(knob_knob, knob_start, start_start)
|
|
318
|
+
|
|
303
319
|
def close(self) -> None:
|
|
304
320
|
"""Close the MAD-NG process."""
|
|
305
321
|
self.session.close()
|
|
306
322
|
|
|
307
323
|
|
|
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
324
|
def read_orbit_only(mad: MAD, n_coords: int, n_knobs: int):
|
|
320
325
|
"""BPM names, orbit values and Jacobian after ``compute_closed_orbit``."""
|
|
321
326
|
mad.send("send_orbit_only()")
|
|
@@ -379,7 +384,8 @@ class ClosedOrbitEngine:
|
|
|
379
384
|
]
|
|
380
385
|
mad["optics_columns"] = self._value_columns + self._derivative_columns
|
|
381
386
|
mad["orbit_coords"] = self.orbit_coords
|
|
382
|
-
mad.send(
|
|
387
|
+
mad.send(CLOSED_TWISS_INIT.read_text())
|
|
388
|
+
mad.send(build_zero_field_removal_script())
|
|
383
389
|
self._solver = "compute_closed_twiss()" if self.optics_names else "compute_closed_orbit()"
|
|
384
390
|
#: Knobs are plain numbers (after a ``jacobian=False`` solve) until the next full solve.
|
|
385
391
|
self._plain = False
|
|
@@ -399,7 +405,7 @@ class ClosedOrbitEngine:
|
|
|
399
405
|
|
|
400
406
|
def set_pt(self, pt: float) -> None:
|
|
401
407
|
"""See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.set_pt`."""
|
|
402
|
-
self.session.mad.send(
|
|
408
|
+
self.session.mad.send("x0map.pt:set0(python:recv())").send(float(pt))
|
|
403
409
|
|
|
404
410
|
def set_warm_start(self, key: str) -> None:
|
|
405
411
|
"""See :meth:`accelmo.backend.protocol.ClosedOrbitEngine.set_warm_start`."""
|
|
@@ -478,12 +484,13 @@ class ClosedOrbitEngine:
|
|
|
478
484
|
|
|
479
485
|
def scale_globals(self, scaled: Sequence[tuple[str, float, float, str]]) -> None:
|
|
480
486
|
"""Set each global ``name`` to the deferred ``kick * (gain + knob)``, so it follows the knob."""
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
]
|
|
485
|
-
|
|
486
|
-
|
|
487
|
+
if not scaled:
|
|
488
|
+
return
|
|
489
|
+
mad = self.session.mad
|
|
490
|
+
mad["scale_names"] = [name for name, _, _, _ in scaled]
|
|
491
|
+
mad["scale_knobs"] = [knob for _, _, _, knob in scaled]
|
|
492
|
+
mad.send(SCALE_GLOBALS.read_text())
|
|
493
|
+
mad.send(np.array([[kick, gain] for _, kick, gain, _ in scaled], dtype=np.float64))
|
|
487
494
|
|
|
488
495
|
|
|
489
496
|
def open_model(
|
|
@@ -526,9 +533,9 @@ def closed_orbit_table(
|
|
|
526
533
|
if magnet_strengths:
|
|
527
534
|
iface.update_knob_values(dict(magnet_strengths))
|
|
528
535
|
iface.mad.send(
|
|
529
|
-
f"
|
|
530
|
-
|
|
531
|
-
)
|
|
536
|
+
f"local pt = {iface.py_name}:recv()\n"
|
|
537
|
+
"moref = twiss{sequence=loaded_sequence, observe=1, X0={pt=pt}, coupling=true}"
|
|
538
|
+
).send(float(pt))
|
|
532
539
|
frame = iface.mad.moref.to_df(columns=["name", *columns])
|
|
533
540
|
finally:
|
|
534
541
|
iface.close()
|
|
@@ -72,7 +72,7 @@ correct_elm = nil
|
|
|
72
72
|
""")
|
|
73
73
|
if iface.mad.recv() != 1:
|
|
74
74
|
raise ValueError(f"Failed to replace start element {start_bpm} with a marker")
|
|
75
|
-
LOGGER.
|
|
75
|
+
LOGGER.debug("Replaced non-BPM start element with cycle marker: %s", start_bpm)
|
|
76
76
|
|
|
77
77
|
|
|
78
78
|
def _unique_names(names: Iterable[str]) -> list[str]:
|
|
@@ -176,7 +176,7 @@ end
|
|
|
176
176
|
f"sequence: {preview}"
|
|
177
177
|
)
|
|
178
178
|
|
|
179
|
-
LOGGER.
|
|
179
|
+
LOGGER.debug("Applied %d b2 dipole error entries from %s", len(applied), b2_errors)
|
|
180
180
|
|
|
181
181
|
|
|
182
182
|
class MadInterface(KnobMadInterface):
|
|
@@ -246,7 +246,7 @@ class MadInterface(KnobMadInterface):
|
|
|
246
246
|
if machine_state is not None:
|
|
247
247
|
self._set_machine_state(machine_state)
|
|
248
248
|
else:
|
|
249
|
-
LOGGER.
|
|
249
|
+
LOGGER.debug("Skipping machine state (not provided)")
|
|
250
250
|
|
|
251
251
|
if create_knobs:
|
|
252
252
|
if accelerator.has_any_optimisation():
|
|
@@ -308,7 +308,7 @@ class MadInterface(KnobMadInterface):
|
|
|
308
308
|
anchor_markers = _unique_names(marker_names or [])
|
|
309
309
|
if mode == "acd":
|
|
310
310
|
acd_before, acd_after = self.insert_acd_markers()
|
|
311
|
-
LOGGER.
|
|
311
|
+
LOGGER.debug("Installed ACD markers: before=%s, after=%s", acd_before, acd_after)
|
|
312
312
|
anchor_markers = _unique_names([*anchor_markers, acd_before, acd_after])
|
|
313
313
|
elif mode == "kicker":
|
|
314
314
|
if not anchor_markers:
|
|
@@ -334,7 +334,7 @@ class MadInterface(KnobMadInterface):
|
|
|
334
334
|
"""
|
|
335
335
|
_ensure_cycleable_start_element(self, start_marker, self.all_bpms)
|
|
336
336
|
self.cycle_sequence(marker_name=start_marker)
|
|
337
|
-
LOGGER.
|
|
337
|
+
LOGGER.debug("Cycled sequence to start at: %s", start_marker)
|
|
338
338
|
|
|
339
339
|
@staticmethod
|
|
340
340
|
def _resolve_mad_stdout(
|
|
@@ -346,7 +346,7 @@ class MadInterface(KnobMadInterface):
|
|
|
346
346
|
LOGGER.warning(
|
|
347
347
|
"MAD logfile specified, but discard_mad_output is True. MAD output will be logged."
|
|
348
348
|
)
|
|
349
|
-
LOGGER.
|
|
349
|
+
LOGGER.debug("MAD logfile set to: %s", mad_logfile.absolute())
|
|
350
350
|
return mad_logfile, True
|
|
351
351
|
if discard_mad_output:
|
|
352
352
|
return "/dev/null", True
|
|
@@ -366,18 +366,18 @@ class MadInterface(KnobMadInterface):
|
|
|
366
366
|
def recount_bpms(self) -> None:
|
|
367
367
|
"""Refresh ``all_bpms`` and ``bpms_in_range`` (after a cycle)."""
|
|
368
368
|
self.all_bpms, self.bpms_in_range = self.get_bpm_list(self.bpm_range)
|
|
369
|
-
LOGGER.
|
|
369
|
+
LOGGER.debug("Counted %d BPMs in range %s", len(self.bpms_in_range), self.bpm_range)
|
|
370
370
|
|
|
371
371
|
def make_all_monitors_thin(self, monitors: list[str], observe_after: bool = True) -> None:
|
|
372
372
|
"""Replace monitor elements with thin observation markers."""
|
|
373
373
|
self.make_elements_thin(monitors, observe_after=observe_after, require_kind="monitor")
|
|
374
|
-
LOGGER.
|
|
374
|
+
LOGGER.debug("Replaced %d monitor BPMs with thin observation markers", len(monitors))
|
|
375
375
|
|
|
376
376
|
def _set_machine_state(self, machine_state: MachineState) -> None:
|
|
377
377
|
"""Put the model in *machine_state* (see :mod:`accelmo.machine.machine_state`)."""
|
|
378
378
|
state = resolve_machine_state(machine_state)
|
|
379
379
|
set_vars(self.mad, state)
|
|
380
|
-
LOGGER.
|
|
380
|
+
LOGGER.debug("Set %d machine-state entries", len(state))
|
|
381
381
|
|
|
382
382
|
def apply_initial_model_values(self, values: dict[str, float] | None) -> None:
|
|
383
383
|
"""Apply a full initial machine-state map without changing the trainable set."""
|
|
@@ -537,7 +537,7 @@ local counts = {{}}
|
|
|
537
537
|
keep = set(self.accelerator.custom_knobs_to_optimise)
|
|
538
538
|
pairs = [(k, s) for k, s in zip(knob_names_all, elem_spos_all) if k in keep]
|
|
539
539
|
knob_names_all, elem_spos_all = (list(x) for x in zip(*pairs)) if pairs else ([], [])
|
|
540
|
-
LOGGER.
|
|
540
|
+
LOGGER.debug(
|
|
541
541
|
f"Filtered to {len(knob_names_all)} knobs based on custom_knobs_to_optimise"
|
|
542
542
|
)
|
|
543
543
|
|
|
@@ -547,12 +547,12 @@ local counts = {{}}
|
|
|
547
547
|
self.mad["knob_names"] = self.knob_names
|
|
548
548
|
|
|
549
549
|
if self.elem_spos:
|
|
550
|
-
LOGGER.
|
|
550
|
+
LOGGER.debug(
|
|
551
551
|
f"Created {len(self.knob_names)} knobs from {self.elem_spos[0]} to {self.elem_spos[-1]}"
|
|
552
552
|
)
|
|
553
|
-
LOGGER.debug(
|
|
553
|
+
LOGGER.debug("Knob names: %s", self.knob_names)
|
|
554
554
|
else:
|
|
555
|
-
LOGGER.
|
|
555
|
+
LOGGER.debug("No knobs created")
|
|
556
556
|
|
|
557
557
|
def _set_multipole_perturbation(
|
|
558
558
|
self,
|
|
@@ -597,4 +597,4 @@ local counts = {{}}
|
|
|
597
597
|
commands = [f"loaded_sequence['{n}'] = {v}" for n, v in knob_values.items()]
|
|
598
598
|
if commands:
|
|
599
599
|
self.mad.send("\n".join(commands))
|
|
600
|
-
LOGGER.
|
|
600
|
+
LOGGER.debug("Updated %d knobs from %d provided", len(commands), len(knob_values))
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
-- One DA map per particle of every batch, at the starts in init_coords and init_pts.
|
|
2
|
+
function make_particle_maps()
|
|
3
|
+
da_x0_c = table.new(num_batches, 0)
|
|
4
|
+
for i=1,num_batches do
|
|
5
|
+
da_x0_c[i] = table.new(batch_size, 0)
|
|
6
|
+
for j=1,batch_size do
|
|
7
|
+
da_x0_c[i][j] = da_x0_base:copy()
|
|
8
|
+
da_x0_c[i][j]:set0(init_coords[i][j])
|
|
9
|
+
end
|
|
10
|
+
end
|
|
11
|
+
end
|
|
12
|
+
make_particle_maps()
|
{accelmo-0.0.1 → accelmo-0.0.2}/src/accelmo/backend/madng/mad_scripts/run_closed_twiss_init.mad
RENAMED
|
@@ -48,6 +48,9 @@
|
|
|
48
48
|
local matrix, vector in MAD
|
|
49
49
|
local cofind, track in MAD
|
|
50
50
|
|
|
51
|
+
-- Longer loop unrolling and trace recording: the element loops of track/cofind otherwise abort back to the interpreter.
|
|
52
|
+
require('jit.opt').start('loopunroll=60', 'maxrecord=8000')
|
|
53
|
+
|
|
51
54
|
num_knobs = #knob_names
|
|
52
55
|
! Jacobian buffers keep one (all zero) column when there are no knobs: the only fitted parameter may be the momentum pt, which
|
|
53
56
|
! the worker handles outside MAD, and MAD vectors and matrices need at least one element.
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
-- Each global scale_names[i] follows kick * (gain + knob) with (kick, gain) from the received rows.
|
|
2
|
+
local rows = python:recv()
|
|
3
|
+
for i, name in ipairs(scale_names) do
|
|
4
|
+
local kick, gain, knob = rows:get(i, 1), rows:get(i, 2), scale_knobs[i]
|
|
5
|
+
MADX[name] = \-> kick * (gain + loaded_sequence[knob])
|
|
6
|
+
end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
-- Contract w r with the second derivatives of the observables over one batch.
|
|
2
|
+
-- wr_<o> (particles, points) arrive from Python, one per name in `observables`. One TPSA per
|
|
3
|
+
-- particle accumulates sum_points wr m; only its second-order coefficients leave MAD. A
|
|
4
|
+
-- coefficient is the Hessian entry between two monomial positions: knobs are positions 7..,
|
|
5
|
+
-- the energy pt is position 6 when fitted and the starts are positions 1 to 4.
|
|
6
|
+
local matrix in MAD
|
|
7
|
+
local wr = {}
|
|
8
|
+
for _, o in ipairs(observables) do wr[o] = python:recv() end
|
|
9
|
+
|
|
10
|
+
local acc = table.new(batch_size, 0)
|
|
11
|
+
for i=1,batch_size do acc[i] = da_x0_base.x:same() end
|
|
12
|
+
|
|
13
|
+
observe_count = 1
|
|
14
|
+
local function contract(elm, mflw, _, slc)
|
|
15
|
+
if is_observation_point(elm, slc) then
|
|
16
|
+
for i=1,batch_size do
|
|
17
|
+
local a = acc[i]
|
|
18
|
+
for _, o in ipairs(observables) do
|
|
19
|
+
a:axpbypc(mflw[i][o], 1, wr[o]:get(i, observe_count), 0, a)
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
observe_count = observe_count + 1
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
track_batch(contract, da_x0_c[batch])
|
|
26
|
+
|
|
27
|
+
local n = #knob_names
|
|
28
|
+
local kcols = {}
|
|
29
|
+
for p=1,n do kcols[p] = 6 + p end
|
|
30
|
+
if optimise_energy then kcols[#kcols + 1] = 6 end
|
|
31
|
+
local nk = #kcols
|
|
32
|
+
|
|
33
|
+
-- Hessian entry between monomial positions i and j: twice the coefficient on the diagonal
|
|
34
|
+
local function entry(a, i, j)
|
|
35
|
+
local digits = {}
|
|
36
|
+
for k=1,6 + n do digits[k] = '0' end
|
|
37
|
+
digits[i], digits[j] = '1', '1'
|
|
38
|
+
if i == j then digits[i] = '2' end
|
|
39
|
+
local v = a:get(table.concat(digits))
|
|
40
|
+
return i == j and 2 * v or v
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
local total = acc[1]:copy()
|
|
44
|
+
for i=2,batch_size do total:axpbypc(acc[i], 1, 1, 0, total) end
|
|
45
|
+
local rkk = matrix(nk, nk)
|
|
46
|
+
for p=1,nk do
|
|
47
|
+
for q=p,nk do
|
|
48
|
+
local v = entry(total, kcols[p], kcols[q])
|
|
49
|
+
rkk:set(p, q, v) ; rkk:set(q, p, v)
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
local rks, rss = matrix(batch_size * nk, 4), matrix(batch_size * 4, 4)
|
|
53
|
+
for i=1,batch_size do
|
|
54
|
+
for c=1,4 do
|
|
55
|
+
for p=1,nk do rks:set((i - 1) * nk + p, c, entry(acc[i], kcols[p], c)) end
|
|
56
|
+
for d=1,4 do rss:set((i - 1) * 4 + c, d, entry(acc[i], c, d)) end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
python:send(rkk)
|
|
60
|
+
python:send(rks)
|
|
61
|
+
python:send(rss)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
-- Rebuild the base map, the knob strengths and every particle map at TPSA order 2.
|
|
2
|
+
-- The constant parts (knob values, start coordinates, pt) carry over. The strengths take an
|
|
3
|
+
-- order-2 zero so functions of them keep their second derivatives (parameters are order 1).
|
|
4
|
+
local consts = table.new(num_batches, 0)
|
|
5
|
+
for b=1,num_batches do
|
|
6
|
+
consts[b] = table.new(batch_size, 0)
|
|
7
|
+
for j=1,batch_size do consts[b][j] = da_x0_c[b][j]:get0() end
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
da_x0_base = damap{nv=6, np=#knob_names, mo=2, po=2, pn=knob_names}
|
|
11
|
+
local zero = da_x0_base.x:same()
|
|
12
|
+
for _, param in ipairs(knob_names) do
|
|
13
|
+
loaded_sequence[param] = loaded_sequence[param]:get0() + zero + da_x0_base[param]
|
|
14
|
+
end
|
|
15
|
+
make_particle_maps()
|
|
16
|
+
for b=1,num_batches do
|
|
17
|
+
for j=1,batch_size do da_x0_c[b][j]:set0(consts[b][j]) end
|
|
18
|
+
end
|
|
19
|
+
collectgarbage()
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
-- Track one batch of maps with the standard options and return the final flow.
|
|
2
|
+
function track_batch(atexit_fn, x0)
|
|
3
|
+
local _, mflw = track {
|
|
4
|
+
sequence=loaded_sequence,
|
|
5
|
+
X0=x0,
|
|
6
|
+
nturn=n_run_turns,
|
|
7
|
+
save=false,
|
|
8
|
+
atexit=atexit_fn,
|
|
9
|
+
range=tracking_range,
|
|
10
|
+
dir=sdir,
|
|
11
|
+
aperture={kind='circle', 100},
|
|
12
|
+
method=6,
|
|
13
|
+
}
|
|
14
|
+
return mflw
|
|
15
|
+
end
|
|
@@ -9,6 +9,20 @@ mad_dir = Path(__file__).absolute().parent
|
|
|
9
9
|
MAD_SCRIPTS_DIR = mad_dir / "mad_scripts"
|
|
10
10
|
|
|
11
11
|
CLOSED_TWISS_INIT = MAD_SCRIPTS_DIR / "run_closed_twiss_init.mad"
|
|
12
|
+
PARTICLE_MAPS = MAD_SCRIPTS_DIR / "particle_maps.mad"
|
|
13
|
+
SECOND_ORDER_REBUILD = MAD_SCRIPTS_DIR / "second_order_rebuild.mad"
|
|
14
|
+
SECOND_ORDER = MAD_SCRIPTS_DIR / "second_order.mad"
|
|
15
|
+
TRACK_BATCH = MAD_SCRIPTS_DIR / "track_batch.mad"
|
|
16
|
+
SCALE_GLOBALS = MAD_SCRIPTS_DIR / "scale_globals.mad"
|
|
17
|
+
|
|
18
|
+
#: Set knobs from ``set_names`` and one received vector; ``plain`` assigns numbers, not TPSA constants.
|
|
19
|
+
SET_KNOBS_PLAIN = (
|
|
20
|
+
"local v = python:recv()\nfor i, name in ipairs(set_names) do loaded_sequence[name] = v[i] end"
|
|
21
|
+
)
|
|
22
|
+
SET_KNOBS_TPSA = (
|
|
23
|
+
"local v = python:recv()\n"
|
|
24
|
+
"for i, name in ipairs(set_names) do loaded_sequence[name]:set0(v[i]) end"
|
|
25
|
+
)
|
|
12
26
|
|
|
13
27
|
TRACKING_OBSERVABLES = ("x", "y", "px", "py")
|
|
14
28
|
LOGGER = logging.getLogger(__name__)
|
|
@@ -146,33 +160,6 @@ def _send_block(
|
|
|
146
160
|
return _join_lines(lines)
|
|
147
161
|
|
|
148
162
|
|
|
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
163
|
def _observation_gate_definition() -> str:
|
|
177
164
|
"""Return the MAD predicate shared by every observation callback.
|
|
178
165
|
|
|
@@ -184,19 +171,17 @@ def _observation_gate_definition() -> str:
|
|
|
184
171
|
return "function is_observation_point(elm, slc)\nreturn slc == -4 and elm:is_observed()\nend"
|
|
185
172
|
|
|
186
173
|
|
|
187
|
-
def
|
|
188
|
-
"""
|
|
174
|
+
def build_zero_field_removal_script() -> str:
|
|
175
|
+
"""Lua that removes thick zero-field magnets; the gaps are tracked as implicit drifts.
|
|
189
176
|
|
|
190
|
-
Run after machine state and TPSA knobs are installed
|
|
191
|
-
|
|
177
|
+
Run after machine state and TPSA knobs are installed. An element carrying a knob is never
|
|
178
|
+
removed (its strength is TPSA), nor is one whose strength is a deferred expression, which a
|
|
179
|
+
machine-state variable can still change.
|
|
192
180
|
"""
|
|
193
|
-
|
|
194
|
-
|
|
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",
|
|
181
|
+
return """local KINDS = {quadrupole=true, sextupole=true, octupole=true, decapole=true, dodecapole=true}
|
|
182
|
+
local ATTR = {"k0", "k0s", "k1", "k1s", "k2", "k2s", "k3", "k3s", "k4", "k4s", "k5", "k5s",
|
|
198
183
|
"kick", "hkick", "vkick", "ks", "ksi", "volt", "angle", "knl", "ksl", "dknl", "dksl",
|
|
199
|
-
"dx", "dy", "ds", "dtheta", "dphi", "dpsi", "tilt"}
|
|
184
|
+
"dx", "dy", "ds", "dtheta", "dphi", "dpsi", "tilt"}
|
|
200
185
|
local function zero(v)
|
|
201
186
|
local t = type(v)
|
|
202
187
|
if t == "nil" or t == "boolean" then return not v end
|
|
@@ -211,15 +196,24 @@ local function is_off(e, i)
|
|
|
211
196
|
if not (KINDS[e.kind] and e.is_thick and e.l > 0) or e.misalign or loaded_sequence:align(i) then
|
|
212
197
|
return false
|
|
213
198
|
end
|
|
214
|
-
for _, a in ipairs(ATTR) do
|
|
199
|
+
for _, a in ipairs(ATTR) do
|
|
200
|
+
if type(rawget(e, a)) == "function" or not zero(e[a]) then return false end
|
|
201
|
+
end
|
|
215
202
|
return true
|
|
216
203
|
end
|
|
217
204
|
-- remove needs increasing indexes: drop the (by-name) cycle around it
|
|
218
205
|
local cycle_ref = loaded_sequence.__cycle
|
|
219
206
|
loaded_sequence:cycle(nil)
|
|
220
|
-
loaded_sequence:remove {
|
|
207
|
+
loaded_sequence:remove {select=is_off}
|
|
221
208
|
loaded_sequence:cycle(cycle_ref)
|
|
222
|
-
|
|
209
|
+
"""
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def build_track_speedup_script(track_methods: dict[str, int]) -> str:
|
|
213
|
+
"""Remove zero-field magnets and set per-kind track methods."""
|
|
214
|
+
methods = ", ".join(f"{kind}={method}" for kind, method in track_methods.items())
|
|
215
|
+
return f"""! Generated track speed-up script
|
|
216
|
+
{build_zero_field_removal_script()}local methods = {{{methods}}}
|
|
223
217
|
loaded_sequence:foreach(\\e => e.method = methods[e.kind] end, {{select=\\e -> methods[e.kind] ~= nil}})
|
|
224
218
|
"""
|
|
225
219
|
|
|
@@ -289,7 +283,7 @@ def build_tracking_script(
|
|
|
289
283
|
observables = _validate_observables(observables)
|
|
290
284
|
return f"""! Generated tracking script
|
|
291
285
|
reset_before_tracking()
|
|
292
|
-
|
|
286
|
+
local mflw = track_batch(save_data, da_x0_c[batch])
|
|
293
287
|
|
|
294
288
|
local n_lost = 0
|
|
295
289
|
for i=1,batch_size do
|
|
@@ -315,7 +309,7 @@ local observed = 0
|
|
|
315
309
|
local function preflight_counter(elm, mflw, _, slc)
|
|
316
310
|
if is_observation_point(elm, slc) then observed = observed + 1 end
|
|
317
311
|
end
|
|
318
|
-
|
|
312
|
+
local mflw = track_batch(preflight_counter, da_x0_c[1][1])
|
|
319
313
|
{PYTHON_IN_MAD}:send({{
|
|
320
314
|
observed=observed,
|
|
321
315
|
expected=nbpms * n_run_turns,
|
|
@@ -361,7 +355,7 @@ def build_validation_script(observables: tuple[str, ...]) -> str:
|
|
|
361
355
|
observables = _validate_observables(observables)
|
|
362
356
|
return f"""! Generated validation script
|
|
363
357
|
reset_before_validation()
|
|
364
|
-
|
|
358
|
+
track_batch(save_val_data, da_x0_c[batch])
|
|
365
359
|
|
|
366
360
|
{_send_block(observables, include_derivatives=False)}
|
|
367
361
|
"""
|
|
@@ -94,6 +94,19 @@ class TrackRequest:
|
|
|
94
94
|
turn_offset: int
|
|
95
95
|
|
|
96
96
|
|
|
97
|
+
@dataclass
|
|
98
|
+
class SecondOrderBlocks:
|
|
99
|
+
"""``Σ_points wr ∂²m`` of one batch, with ``wr`` the weighted residuals sent in.
|
|
100
|
+
|
|
101
|
+
``knob_knob`` is ``(K, K)`` over the engine's knobs (``pt`` last when fitted), summed over the
|
|
102
|
+
particles; ``knob_start`` is ``(P, K, 4)`` and ``start_start`` ``(P, 4, 4)`` per particle.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
knob_knob: np.ndarray
|
|
106
|
+
knob_start: np.ndarray
|
|
107
|
+
start_start: np.ndarray
|
|
108
|
+
|
|
109
|
+
|
|
97
110
|
@dataclass
|
|
98
111
|
class TrackResult:
|
|
99
112
|
"""One tracked batch.
|
|
@@ -165,6 +178,14 @@ class TrackingEngine(Protocol):
|
|
|
165
178
|
def track(self, batch: int, *, start_derivatives: bool) -> TrackResult:
|
|
166
179
|
"""Track batch ``batch`` (0-based); ``start_derivatives`` also fills ``d_dc0``."""
|
|
167
180
|
|
|
181
|
+
def begin_second_order(self) -> None:
|
|
182
|
+
"""Switch to second-order derivatives, keeping the knobs, starts and ``pt``; ``track`` still works."""
|
|
183
|
+
|
|
184
|
+
def second_order(
|
|
185
|
+
self, batch: int, weighted_residuals: dict[str, np.ndarray]
|
|
186
|
+
) -> SecondOrderBlocks:
|
|
187
|
+
"""Contract ``weighted_residuals[o]`` ``(P, N)`` with the second derivatives of ``o`` (after ``begin_second_order``)."""
|
|
188
|
+
|
|
168
189
|
def close(self) -> None:
|
|
169
190
|
"""Release the model."""
|
|
170
191
|
|