accelmo 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. accelmo/__init__.py +8 -0
  2. accelmo/analysis/__init__.py +21 -0
  3. accelmo/analysis/degeneracy_checker.py +308 -0
  4. accelmo/backend/__init__.py +26 -0
  5. accelmo/backend/madng/__init__.py +5 -0
  6. accelmo/backend/madng/accelerator_hooks.py +171 -0
  7. accelmo/backend/madng/engines.py +535 -0
  8. accelmo/backend/madng/interface.py +600 -0
  9. accelmo/backend/madng/machine_state.py +62 -0
  10. accelmo/backend/madng/mad_scripts/run_closed_twiss_init.mad +399 -0
  11. accelmo/backend/madng/scripts.py +367 -0
  12. accelmo/backend/protocol.py +274 -0
  13. accelmo/backend/xtrack/__init__.py +1 -0
  14. accelmo/backend/xtrack/engines.py +366 -0
  15. accelmo/backend/xtrack/model.py +292 -0
  16. accelmo/config.py +169 -0
  17. accelmo/fitting/__init__.py +4 -0
  18. accelmo/fitting/bpm_gains.py +54 -0
  19. accelmo/fitting/config.py +44 -0
  20. accelmo/fitting/lifecycle.py +40 -0
  21. accelmo/fitting/lm_loop.py +212 -0
  22. accelmo/fitting/pool.py +75 -0
  23. accelmo/fitting/priors.py +58 -0
  24. accelmo/fitting/protocol.py +265 -0
  25. accelmo/fitting/reduction.py +65 -0
  26. accelmo/fitting/results.py +36 -0
  27. accelmo/fitting/setup.py +239 -0
  28. accelmo/fitting/shared_reference.py +102 -0
  29. accelmo/fitting/uncertainty.py +115 -0
  30. accelmo/fitting/weights.py +13 -0
  31. accelmo/fitting/worker.py +250 -0
  32. accelmo/machine/__init__.py +1 -0
  33. accelmo/machine/accelerators/__init__.py +27 -0
  34. accelmo/machine/accelerators/base.py +276 -0
  35. accelmo/machine/accelerators/fcc.py +82 -0
  36. accelmo/machine/accelerators/lhc.py +188 -0
  37. accelmo/machine/accelerators/magnet_grouping.py +149 -0
  38. accelmo/machine/accelerators/psb.py +202 -0
  39. accelmo/machine/accelerators/selection.py +109 -0
  40. accelmo/machine/accelerators/sps.py +125 -0
  41. accelmo/machine/knob_names.py +14 -0
  42. accelmo/machine/machine_state.py +65 -0
  43. accelmo/machine/patterns.py +96 -0
  44. accelmo/momentum_reference.py +271 -0
  45. accelmo/monitor/__init__.py +21 -0
  46. accelmo/monitor/__main__.py +52 -0
  47. accelmo/monitor/app.py +338 -0
  48. accelmo/monitor/cache.py +240 -0
  49. accelmo/monitor/panels.py +261 -0
  50. accelmo/monitor/source.py +52 -0
  51. accelmo/monitor/view.py +39 -0
  52. accelmo/optimisers/__init__.py +18 -0
  53. accelmo/optimisers/adam.py +136 -0
  54. accelmo/optimisers/base.py +84 -0
  55. accelmo/optimisers/lbfgs.py +208 -0
  56. accelmo/optimisers/levenberg_marquardt.py +253 -0
  57. accelmo/poco/__init__.py +34 -0
  58. accelmo/poco/calibrated.py +328 -0
  59. accelmo/poco/calibration.py +234 -0
  60. accelmo/poco/closed_orbit.py +335 -0
  61. accelmo/poco/fitter.py +410 -0
  62. accelmo/poco/workers/__init__.py +1 -0
  63. accelmo/poco/workers/calibrated.py +200 -0
  64. accelmo/poco/workers/closed_orbit.py +501 -0
  65. accelmo/poco/workers/closed_twiss.py +174 -0
  66. accelmo/runlog/__init__.py +25 -0
  67. accelmo/runlog/reader.py +127 -0
  68. accelmo/runlog/writer.py +150 -0
  69. accelmo/tracking/__init__.py +59 -0
  70. accelmo/tracking/config/__init__.py +29 -0
  71. accelmo/tracking/config/helpers.py +43 -0
  72. accelmo/tracking/config/models.py +66 -0
  73. accelmo/tracking/config/tracking.py +535 -0
  74. accelmo/tracking/data_manager.py +476 -0
  75. accelmo/tracking/dispatch/__init__.py +1 -0
  76. accelmo/tracking/dispatch/payloads.py +210 -0
  77. accelmo/tracking/dispatch/setup.py +212 -0
  78. accelmo/tracking/dispatch/turn_planner.py +196 -0
  79. accelmo/tracking/fitter.py +698 -0
  80. accelmo/tracking/ic_iteration.py +110 -0
  81. accelmo/tracking/lm_problem.py +252 -0
  82. accelmo/tracking/ranges.py +112 -0
  83. accelmo/tracking/session.py +301 -0
  84. accelmo/tracking/sgd/__init__.py +1 -0
  85. accelmo/tracking/sgd/checkpointing.py +229 -0
  86. accelmo/tracking/sgd/loop.py +327 -0
  87. accelmo/tracking/sgd/scheduler.py +70 -0
  88. accelmo/tracking/uncertainty.py +160 -0
  89. accelmo/tracking/worker.py +661 -0
  90. accelmo-0.0.1.dist-info/METADATA +208 -0
  91. accelmo-0.0.1.dist-info/RECORD +95 -0
  92. accelmo-0.0.1.dist-info/WHEEL +5 -0
  93. accelmo-0.0.1.dist-info/entry_points.txt +2 -0
  94. accelmo-0.0.1.dist-info/licenses/LICENSE +21 -0
  95. accelmo-0.0.1.dist-info/top_level.txt +1 -0
accelmo/config.py ADDED
@@ -0,0 +1,169 @@
1
+ """Settings of the gradient-descent optimiser, the worker processes and the tracking fit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from dataclasses import dataclass, field
7
+
8
+ #: Optimisers :class:`OptimiserConfig` can name.
9
+ OPTIMISER_TYPES = ("adam", "lbfgs")
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class OptimiserConfig:
14
+ """Configuration for gradient descent optimiser algorithms.
15
+
16
+ Controls learning rates, convergence criteria, and optimiser type
17
+ for the gradient descent training process.
18
+ """
19
+
20
+ max_epochs: int
21
+ warmup_epochs: int
22
+ warmup_lr_start: float
23
+ max_lr: float
24
+ min_lr: float
25
+ optimiser_type: str = field(default="adam") # one of OPTIMISER_TYPES
26
+
27
+ # Smoothing factor of the moving average of the relative loss change the stopping rule uses.
28
+ loss_change_alpha: float = field(default=0.2)
29
+ # Stop once the smoothed relative loss change falls below this, after at least
30
+ # loss_change_min_epoch_fraction * max_epochs epochs. 0 disables the rule.
31
+ loss_change_tolerance: float = field(default=1e-6)
32
+ loss_change_min_epoch_fraction: float = field(default=0.2)
33
+
34
+ # Fit in stages of this many epochs (``max_epochs`` is then their total): the
35
+ # learning-rate schedule (warmup, then decay over the rest of the stage) restarts at
36
+ # each stage and the best loss and stopping averages reset. The stopping rules are
37
+ # off, so a stage always runs its epochs and the next starts at a multiple of this.
38
+ stage_epochs: int | None = field(default=None)
39
+
40
+ # L-BFGS-specific parameters (ignored for adam)
41
+ lbfgs_history_size: int = field(default=10)
42
+ lbfgs_max_step_norm: float | None = field(default=1.0)
43
+ lbfgs_powell_damping: float = field(default=0.2)
44
+
45
+ # Adam-specific parameters (ignored for lbfgs)
46
+ adam_weight_decay: float = field(default=0.0)
47
+ # None keeps each optimiser's own default. Lower it when the gradients are far
48
+ # below the default, or eps rather than the gradient scale sets the step size.
49
+ adam_eps: float | None = field(default=None)
50
+
51
+ def __post_init__(self):
52
+ if self.optimiser_type not in OPTIMISER_TYPES:
53
+ raise ValueError(
54
+ f"Unknown optimiser type {self.optimiser_type!r}; choose from {OPTIMISER_TYPES}"
55
+ )
56
+
57
+ @property
58
+ def decay_epochs(self) -> int:
59
+ """Epochs of learning-rate decay after the warmup, per stage."""
60
+ return (self.stage_epochs or self.max_epochs) - self.warmup_epochs
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class WorkerRuntime:
65
+ """How the worker processes run: how many, their log level and BLAS threads."""
66
+
67
+ num_workers: int
68
+
69
+ # Logging level for worker processes (separate from main process)
70
+ logging_level: int = field(default=logging.WARNING)
71
+
72
+ # BLAS/LAPACK threads per worker process. Every worker does dense linear algebra
73
+ # (e.g. the Gauss-Newton Hessian) while the other workers do the same, so the
74
+ # library default (one thread per core, per worker) oversubscribes the machine:
75
+ # 16 closed-orbit workers took 3.4x longer per Hessian and pushed the load
76
+ # average to ~290 on a 64-core host. 1 (default) keeps one thread per worker;
77
+ # None leaves the library default.
78
+ blas_threads: int | None = field(default=1)
79
+
80
+ def __post_init__(self):
81
+ if self.num_workers < 1:
82
+ raise ValueError(f"WorkerRuntime.num_workers must be >= 1, got {self.num_workers}")
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class TrackingDataConfig:
87
+ """Which tracking data the fit uses and how its turns are batched."""
88
+
89
+ # Batches each worker's turns are split into. Kicker and ACD-sinusoid fits use 1
90
+ # whatever is set here: each worker holds a single track.
91
+ num_batches: int
92
+
93
+ # Fraction of the post-validation-split training data to use and
94
+ # distribute among the workers. 1.0 (default) uses every available training
95
+ # turn; smaller values keep that fraction of each file's turns (per-file
96
+ # stratified sampling). Must be in (0, 1].
97
+ data_fraction: float = field(default=1.0)
98
+
99
+ # Fraction of the available turns held out per file as a disjoint validation
100
+ # set used only to measure generalisation. These turns are removed from
101
+ # training, so the validation loss is out-of-sample. `data_fraction` is applied to the remaining training
102
+ # turns. Must be in [0, 1); 0.0 disables held-out validation.
103
+ validation_fraction: float = field(default=0.1)
104
+
105
+ # Whether to include momenta (px, py) in loss function
106
+ # When False, only positions (x, y) are used for optimisation
107
+ optimise_momenta: bool = field(default=True)
108
+
109
+ def __post_init__(self):
110
+ if not 0.0 < self.data_fraction <= 1.0:
111
+ raise ValueError(
112
+ f"TrackingDataConfig.data_fraction must be in (0, 1], got {self.data_fraction}"
113
+ )
114
+ if not 0.0 <= self.validation_fraction < 1.0:
115
+ raise ValueError(
116
+ "TrackingDataConfig.validation_fraction must be in [0, 1), "
117
+ f"got {self.validation_fraction}"
118
+ )
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class TrackingParameters:
123
+ """What a tracking fit fits besides the magnet knobs, and every prior width."""
124
+
125
+ # Fit one gain per BPM and plane on the positions, reading = (1 + g) * position, with a
126
+ # Gaussian prior of this width. None fits no gains.
127
+ bpm_gain_sigma: float | None = field(default=None)
128
+
129
+ # LM only: zero-centred Gaussian prior widths, as POCO's knob_sigmas: keyed by knob
130
+ # name or terminal attribute (e.g. dk1l); a BPM gain named here overrides bpm_gain_sigma.
131
+ knob_sigmas: dict[str, float] | None = field(default=None)
132
+
133
+ # LM only: also fit every particle's start x, px, y, py.
134
+ fit_start_coords: bool = field(default=False)
135
+
136
+ # LM only: the starts are functions of the BPM gains, s(g) = s_ref + S (g - g_ref),
137
+ # given by the initial-conditions callback as a StartGainMap; the gains' gradient and
138
+ # Gauss-Newton blocks include the path through the starts (docs/start_gain_chain_rule.md).
139
+ starts_follow_gains: bool = field(default=False)
140
+
141
+ # LM only: planes ("x", "y") whose mean BPM gain is held at 0, for a common scale the data leave free.
142
+ bpm_gain_zero_mean_planes: tuple[str, ...] = field(default=())
143
+
144
+ @property
145
+ def start_derivatives(self) -> bool:
146
+ """Whether the workers return the start-coordinate derivative blocks."""
147
+ return self.fit_start_coords or self.starts_follow_gains
148
+
149
+ def __post_init__(self):
150
+ if unknown := set(self.bpm_gain_zero_mean_planes) - {"x", "y"}:
151
+ raise ValueError(f"bpm_gain_zero_mean_planes takes 'x' and 'y', got {sorted(unknown)}")
152
+ if self.bpm_gain_zero_mean_planes and self.bpm_gain_sigma is None:
153
+ raise ValueError("bpm_gain_zero_mean_planes needs fitted gains (bpm_gain_sigma)")
154
+
155
+
156
+ # Global schema constant for data files (this is appropriate as a global)
157
+ FILE_COLUMNS: tuple[str, ...] = (
158
+ "name",
159
+ "turn",
160
+ "bunch_number",
161
+ "x",
162
+ "px",
163
+ "y",
164
+ "py",
165
+ "var_x",
166
+ "var_y",
167
+ "var_px",
168
+ "var_py",
169
+ )
@@ -0,0 +1,4 @@
1
+ """What both fitting engines share: machine setup, worker protocol and pool, run lifecycle, reduction, weights, uncertainties and results.
2
+
3
+ Nothing here imports :mod:`accelmo.tracking` or :mod:`accelmo.poco`.
4
+ """
@@ -0,0 +1,54 @@
1
+ """BPM gains, shared by the closed-orbit (poco) and tracking fits.
2
+
3
+ A gain ``g`` scales what a BPM reports: ``reading = (1 + g) * position``. Only
4
+ positions are read by a BPM; momenta are never scaled. Gains travel in the knob
5
+ dict next to the magnet knobs as ``bpmgain.<x|y>.<BPM>``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+
12
+ PREFIX = "bpmgain"
13
+ PLANES = ("x", "y")
14
+
15
+
16
+ def bpm_gain_name(plane: str, bpm: str) -> str:
17
+ """Fit-parameter name of the gain of ``bpm`` in ``plane``."""
18
+ return f"{PREFIX}.{plane}.{bpm}"
19
+
20
+
21
+ def bpm_gain_names(bpms: list[str] | tuple[str, ...]) -> list[str]:
22
+ """Every x gain, then every y gain, in ``bpms`` order."""
23
+ return [bpm_gain_name(plane, bpm) for plane in PLANES for bpm in bpms]
24
+
25
+
26
+ def is_bpm_gain(name: str) -> bool:
27
+ """True if ``name`` is a BPM gain parameter."""
28
+ return name.startswith(f"{PREFIX}.")
29
+
30
+
31
+ def without_bpm_gains(knobs: dict[str, float]) -> dict[str, float]:
32
+ """``knobs`` without the BPM gains."""
33
+ return {k: v for k, v in knobs.items() if not is_bpm_gain(k)}
34
+
35
+
36
+ def only_bpm_gains(knobs: dict[str, float]) -> dict[str, float]:
37
+ """Only the BPM gains of ``knobs``."""
38
+ return {k: v for k, v in knobs.items() if is_bpm_gain(k)}
39
+
40
+
41
+ def bpm_gains(knobs: dict[str, float], plane: str, bpms: list[str] | tuple[str, ...]) -> np.ndarray:
42
+ """The ``plane`` gain of each of ``bpms`` from ``knobs``; 0 where a gain is absent."""
43
+ return np.array([knobs.get(bpm_gain_name(plane, bpm), 0.0) for bpm in bpms])
44
+
45
+
46
+ def bpm_reading(position: np.ndarray | float, gains: np.ndarray) -> np.ndarray:
47
+ """What a BPM with ``gains`` reports for ``position`` (gains broadcast on the last axis)."""
48
+ return (1.0 + gains) * position
49
+
50
+
51
+ def point_gain_index(point_names: list[str], gain_bpms: tuple[str, ...]) -> np.ndarray:
52
+ """Index of each observation point's BPM in ``gain_bpms``; -1 for points with no gain."""
53
+ index = {bpm: i for i, bpm in enumerate(gain_bpms)}
54
+ return np.array([index.get(name, -1) for name in point_names], dtype=np.int64)
@@ -0,0 +1,44 @@
1
+ """Configuration shared by every fitter: the lattice range and the output settings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ @dataclass
11
+ class SequenceConfig:
12
+ """Configuration for the sequence segment used during optimisation.
13
+
14
+ The fields define the magnet range to expose to MAD-NG and any BPMs that
15
+ should be ignored. Where measurement data starts (the BPM each recorded turn
16
+ begins at) is a property of the measurement, not the sequence, so it lives on
17
+ :class:`MeasurementDetails`.
18
+ """
19
+
20
+ magnet_range: str = "$start/$end"
21
+ bad_bpms: list[str] | None = None
22
+
23
+
24
+ @dataclass
25
+ class OutputConfig:
26
+ """Output and logging behaviour for optimisation runs.
27
+
28
+ Attributes:
29
+ write_run_log: Whether to write a run log (see :mod:`accelmo.runlog`).
30
+ include_uncertainty: Whether to compute uncertainties. Disabling this
31
+ skips worker-side Hessian estimation for faster execution.
32
+ run_log_root: Directory under which each fit writes its run log.
33
+ run_metadata: Free-form, JSON-serialisable description stored with the run
34
+ log, e.g. what is needed to rebuild the model for replaying it.
35
+ mad_logfile: Optional MAD log file path.
36
+ python_logfile: Optional Python worker log file path.
37
+ """
38
+
39
+ write_run_log: bool = True
40
+ include_uncertainty: bool = True
41
+ run_log_root: Path = field(default_factory=lambda: Path("runs"))
42
+ run_metadata: dict[str, Any] = field(default_factory=dict)
43
+ mad_logfile: Path | None = None
44
+ python_logfile: Path | None = None
@@ -0,0 +1,40 @@
1
+ """The run/interrupt/cleanup shape every fitter shares."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import TYPE_CHECKING, TypeVar
7
+
8
+ if TYPE_CHECKING:
9
+ from collections.abc import Callable
10
+
11
+ from accelmo.runlog import RunLog
12
+
13
+ LOGGER = logging.getLogger(__name__)
14
+
15
+ T = TypeVar("T")
16
+
17
+
18
+ def run_with_workers(
19
+ body: Callable[[], T],
20
+ *,
21
+ fallback: Callable[[], T],
22
+ stop_workers: Callable[[], None],
23
+ run_log: RunLog | None = None,
24
+ ) -> T:
25
+ """Run ``body``; on Ctrl-C return ``fallback()`` (the best result so far) instead.
26
+
27
+ The workers are stopped and the run log closed however the run ends;
28
+ any other exception propagates once they are.
29
+ """
30
+ try:
31
+ return body()
32
+ except KeyboardInterrupt:
33
+ LOGGER.warning(
34
+ "KeyboardInterrupt: stopping the optimisation early with the best result so far."
35
+ )
36
+ return fallback()
37
+ finally:
38
+ stop_workers()
39
+ if run_log is not None:
40
+ run_log.close()
@@ -0,0 +1,212 @@
1
+ """The Levenberg-Marquardt iteration shared by every closed-orbit / closed-twiss fitter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from dataclasses import dataclass
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ import numpy as np
11
+
12
+ from accelmo.fitting.results import FitDiagnostics
13
+ from accelmo.optimisers.levenberg_marquardt import (
14
+ LevenbergMarquardtOptimiser,
15
+ LevenbergMarquardtUpdate,
16
+ )
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Sequence
20
+
21
+ from accelmo.optimisers.levenberg_marquardt import LevenbergMarquardtConfig
22
+ from accelmo.runlog import RunLog
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ @dataclass
28
+ class LMPoint:
29
+ """The objective at one point: loss, gradient and Gauss-Newton Hessian.
30
+
31
+ ``failed`` marks a point where the closed orbit was lost. ``extra`` is whatever
32
+ the evaluation wants handed back to ``on_accept``.
33
+ """
34
+
35
+ loss: float
36
+ grad: np.ndarray
37
+ hessian: np.ndarray
38
+ failed: bool = False
39
+ extra: Any = None
40
+
41
+
42
+ class LMProblem:
43
+ """What :func:`run_levenberg_marquardt` asks of a fit; subclasses override the hooks they use."""
44
+
45
+ #: Score each trial point by :meth:`trial_loss` first and evaluate it in full only if it
46
+ #: improves on the best loss, so a rejected step costs a cheap loss evaluation.
47
+ loss_only_trials = False
48
+
49
+ def evaluate(self, params: np.ndarray, iteration: int) -> LMPoint:
50
+ """The full objective at ``params``."""
51
+ raise NotImplementedError
52
+
53
+ def trial_loss(self, params: np.ndarray) -> float | None:
54
+ """The loss alone at ``params``, ``None`` when the orbit is lost."""
55
+ raise NotImplementedError
56
+
57
+ def on_accept(self, params: np.ndarray, point: LMPoint) -> None:
58
+ """Sees every accepted point."""
59
+
60
+ def after_step(self, params: np.ndarray, optimiser: LevenbergMarquardtOptimiser) -> None:
61
+ """Runs once the next point is chosen."""
62
+
63
+ def refresh(self, params: np.ndarray) -> bool:
64
+ """Runs at every newly accepted point; True if it changed the objective.
65
+
66
+ E.g. the tracking start conditions were rebuilt from the fitted model. The old losses
67
+ then no longer compare: the optimiser forgets its best point and the same point is
68
+ evaluated again before the next step is taken.
69
+ """
70
+ return False
71
+
72
+
73
+ def run_levenberg_marquardt(
74
+ params: np.ndarray,
75
+ problem: LMProblem,
76
+ config: LevenbergMarquardtConfig,
77
+ *,
78
+ run_log: RunLog | None = None,
79
+ param_names: Sequence[str] | None = None,
80
+ ) -> tuple[LevenbergMarquardtOptimiser, FitDiagnostics]:
81
+ """Minimise with Levenberg-Marquardt steps ``(H + lam·diag H) delta = -g``.
82
+
83
+ A rejected step is not a no-op: the optimiser retries from its best point with
84
+ more damping, so the next point still needs evaluating. Only the terminal
85
+ reasons (no curvature to retry from, or damping driven to the ceiling) end the
86
+ solve early.
87
+
88
+ With ``run_log``, every accepted iteration's loss is logged, and its parameters
89
+ too when ``param_names`` names them.
90
+
91
+ Returns the optimiser, whose ``best_params`` are the solution, and how the fit ended.
92
+ """
93
+ optimiser = LevenbergMarquardtOptimiser(config, initial_params=params)
94
+ run_start = time.time()
95
+ last_update = None
96
+ completed_iterations = 0
97
+ accepted_evaluations = 0
98
+ just_refreshed = False
99
+ record_params = run_log is not None and param_names is not None
100
+ if record_params:
101
+ run_log.begin(_named(param_names, params))
102
+
103
+ for iteration in range(config.max_iterations):
104
+ completed_iterations = iteration + 1
105
+ update, point = _next_update(problem, optimiser, params, iteration)
106
+ last_update = update
107
+ accepted_params = params
108
+ if update.accepted:
109
+ assert point is not None # loss-only trials are never accepted
110
+ accepted_evaluations += 1
111
+ problem.on_accept(params, point)
112
+ params = update.next_params
113
+
114
+ if update.accepted:
115
+ if not just_refreshed and problem.refresh(accepted_params):
116
+ optimiser.reset_objective(accepted_params)
117
+ params, just_refreshed = accepted_params, True
118
+ continue
119
+ just_refreshed = False
120
+
121
+ if update.converged and not update.accepted:
122
+ logger.warning(
123
+ "Levenberg-Marquardt stopped at iter %d (%s, lam=%.1e)",
124
+ iteration,
125
+ update.reason,
126
+ update.damping,
127
+ )
128
+ break
129
+ problem.after_step(params, optimiser)
130
+ if not update.accepted:
131
+ _log_unaccepted(iteration, update, optimiser.best.loss)
132
+ continue
133
+
134
+ _log_iteration(iteration, update.loss, update.grad_norm, update.damping, run_start)
135
+ if run_log is not None:
136
+ run_log.log(
137
+ iteration, loss=update.loss, grad_norm=update.grad_norm, lm_lambda=update.damping
138
+ )
139
+ if record_params:
140
+ run_log.record_knobs(iteration, _named(param_names, accepted_params))
141
+ if update.converged:
142
+ logger.info("Levenberg-Marquardt converged (%s) at iter %d", update.reason, iteration)
143
+ break
144
+
145
+ diagnostics = FitDiagnostics(
146
+ converged=bool(last_update is not None and last_update.converged),
147
+ reason=None if last_update is None else last_update.reason,
148
+ iterations=completed_iterations,
149
+ best_loss=float(optimiser.best.loss),
150
+ gradient_norm=None if last_update is None else float(last_update.grad_norm),
151
+ damping=None if last_update is None else float(last_update.damping),
152
+ accepted_evaluations=accepted_evaluations,
153
+ )
154
+ if run_log is not None:
155
+ run_log.finish(
156
+ reason=diagnostics.reason,
157
+ iterations=diagnostics.iterations,
158
+ best_loss=diagnostics.best_loss,
159
+ )
160
+ return optimiser, diagnostics
161
+
162
+
163
+ def _next_update(
164
+ problem: LMProblem, optimiser: LevenbergMarquardtOptimiser, params: np.ndarray, iteration: int
165
+ ) -> tuple[LevenbergMarquardtUpdate, LMPoint | None]:
166
+ """The optimiser's verdict on ``params`` and the full point it was given, if one was evaluated."""
167
+ if problem.loss_only_trials and optimiser.best_hessian is not None:
168
+ loss = problem.trial_loss(params)
169
+ n = len(params)
170
+ if loss is None:
171
+ update = optimiser.update(
172
+ params, float("nan"), np.zeros(n), np.zeros((n, n)), failed=True
173
+ )
174
+ return update, None
175
+ if not loss < optimiser.best.loss:
176
+ update = optimiser.update(params, loss, np.zeros(n), np.zeros((n, n)), failed=False)
177
+ return update, None
178
+ point = problem.evaluate(params, iteration)
179
+ return optimiser.update(params, point.loss, point.grad, point.hessian, point.failed), point
180
+
181
+
182
+ def _log_unaccepted(iteration: int, update: LevenbergMarquardtUpdate, best_loss: float) -> None:
183
+ if update.reason == "failed":
184
+ logger.warning(
185
+ "Iter %d: closed orbit lost; retrying from best (lam=%.1e)", iteration, update.damping
186
+ )
187
+ else:
188
+ logger.info(
189
+ "Iter %d: step rejected (loss %.6e >= best %.6e); retrying from best (lam=%.1e)",
190
+ iteration,
191
+ update.loss,
192
+ best_loss,
193
+ update.damping,
194
+ )
195
+
196
+
197
+ def _named(names: Sequence[str], params: np.ndarray) -> dict[str, float]:
198
+ return dict(zip(names, (float(v) for v in params), strict=True))
199
+
200
+
201
+ def _log_iteration(
202
+ iteration: int, loss: float, grad_norm: float, lam: float, run_start: float
203
+ ) -> None:
204
+ """Log one accepted iteration to the console."""
205
+ logger.info(
206
+ "LM iter %d: loss=%.3e, |g|=%.3e, lam=%.1e, tt=%.1fs",
207
+ iteration,
208
+ loss,
209
+ grad_norm,
210
+ lam,
211
+ time.time() - run_start,
212
+ )
@@ -0,0 +1,75 @@
1
+ """A pool of worker processes and the parent-side state kept for each one."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import logging
7
+ import multiprocessing as mp
8
+ from dataclasses import dataclass, field
9
+ from typing import TYPE_CHECKING, Generic, TypeVar
10
+
11
+ from accelmo.fitting.protocol import STOP, WorkerChannels
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Callable
15
+ from multiprocessing.connection import Connection
16
+
17
+ LOGGER = logging.getLogger(__name__)
18
+
19
+ #: What the fitter keeps about each worker (tracking: its runtime metadata).
20
+ MetadataT = TypeVar("MetadataT")
21
+
22
+
23
+ @dataclass
24
+ class WorkerPool(Generic[MetadataT]):
25
+ """Worker processes, their pipes and, for tracking workers, their metadata.
26
+
27
+ ``metadata`` and ``particle_counts`` are parallel to ``workers`` when filled;
28
+ pools whose workers need neither (closed-twiss) leave them empty.
29
+ """
30
+
31
+ conns: list[Connection] = field(default_factory=list)
32
+ workers: list[mp.Process] = field(default_factory=list)
33
+ metadata: list[MetadataT] = field(default_factory=list)
34
+ particle_counts: list[int] = field(default_factory=list)
35
+
36
+ def __len__(self) -> int:
37
+ return len(self.workers)
38
+
39
+ def spawn(
40
+ self, worker_class: Callable[..., mp.Process], worker_id: int, *args: object
41
+ ) -> Connection:
42
+ """Start ``worker_class(child_conn, worker_id, *args)`` and return the parent pipe end."""
43
+ parent, child = mp.Pipe()
44
+ worker = worker_class(child, worker_id, *args)
45
+ worker.start()
46
+ self.conns.append(parent)
47
+ self.workers.append(worker)
48
+ return parent
49
+
50
+ @property
51
+ def channels(self) -> WorkerChannels:
52
+ """Channels over every worker in the pool."""
53
+ if not self.workers:
54
+ raise RuntimeError("Worker pool is empty")
55
+ return WorkerChannels(self.conns, self.workers)
56
+
57
+ def stop(self) -> None:
58
+ """Send :data:`~accelmo.fitting.protocol.STOP`, join (forcing stragglers) and close the pipes."""
59
+ for conn in self.conns:
60
+ with contextlib.suppress(OSError, EOFError):
61
+ conn.send(STOP)
62
+ for worker in self.workers:
63
+ worker.join(timeout=5.0)
64
+ if worker.is_alive():
65
+ LOGGER.warning("Worker %s did not terminate, forcing...", worker.name)
66
+ worker.terminate()
67
+ worker.join()
68
+ for conn in self.conns:
69
+ conn.close()
70
+
71
+ def kill(self) -> None:
72
+ """Terminate every worker without waiting for it to respond."""
73
+ for worker in self.workers:
74
+ worker.terminate()
75
+ worker.join()
@@ -0,0 +1,58 @@
1
+ """Gaussian priors shared by the tracking and closed-orbit LM fits."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ import numpy as np
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Mapping, Sequence
11
+
12
+ #: Width of the prior that holds a zero-mean gain group's mean at 0 (a near-exact constraint).
13
+ ZERO_MEAN_SIGMA = 1e-5
14
+
15
+
16
+ def knob_sigma_array(knob_names: Sequence[str], knob_sigmas: Mapping[str, float]) -> np.ndarray:
17
+ """Prior width of each of ``knob_names`` (0 = free), by name, else by terminal attribute.
18
+
19
+ ``knob_sigmas`` keys are case-insensitive: a knob name or a terminal attribute such as
20
+ ``dk1l`` that applies to every knob ending in it.
21
+ """
22
+ sigmas = {name.lower(): float(sigma) for name, sigma in knob_sigmas.items()}
23
+ if any(sigma <= 0 for sigma in sigmas.values()):
24
+ raise ValueError("knob_sigmas must be > 0")
25
+ names = [name.lower() for name in knob_names]
26
+ attributes = [name.rpartition(".")[2] for name in names]
27
+ if unknown := sorted(set(sigmas) - set(names) - set(attributes)):
28
+ raise ValueError(f"knob_sigmas names knobs that are not optimised: {unknown[:5]}")
29
+ return np.array(
30
+ [sigmas.get(n, sigmas.get(a, 0.0)) for n, a in zip(names, attributes, strict=True)]
31
+ )
32
+
33
+
34
+ def inverse_variances(sigmas: np.ndarray) -> np.ndarray:
35
+ """``1/σ²`` of each prior width; 0 where ``σ`` is 0 (no prior)."""
36
+ sigmas = np.asarray(sigmas, dtype=float)
37
+ return np.divide(1.0, sigmas**2, out=np.zeros_like(sigmas), where=sigmas > 0)
38
+
39
+
40
+ def add_quadratic_prior(
41
+ loss: float, grad: np.ndarray, hessian: np.ndarray, params: np.ndarray, prior: np.ndarray
42
+ ) -> tuple[float, np.ndarray, np.ndarray]:
43
+ """``loss``, ``grad`` and ``hessian`` plus those of ``params^T prior params``."""
44
+ return (
45
+ loss + float(params @ prior @ params),
46
+ grad + 2.0 * prior @ params,
47
+ hessian + 2.0 * prior,
48
+ )
49
+
50
+
51
+ def quadratic_prior(ridge: np.ndarray, zero_mean: list[np.ndarray], weight: float) -> np.ndarray:
52
+ """Quadratic prior ``p^T P p``: ``diag(ridge)`` plus ``weight * mean²`` of each index group in ``zero_mean``."""
53
+ prior = np.diag(np.asarray(ridge, dtype=float))
54
+ for group in zero_mean:
55
+ a = np.zeros(len(prior))
56
+ a[group] = 1.0 / len(group)
57
+ prior += weight * np.outer(a, a)
58
+ return prior