accelmo.tracking.fitter

Tracking fitters that recover magnet knob strengths from turn-by-turn data.

TrackingFitter holds the mode-agnostic machinery (data + worker management, the optimisation loop, and Hessian-based uncertainties). The public entry points are its thin subclasses, one per tracking geometry:

  • ArcByArcFitter – arc-by-arc ranges, with the AC dipole optionally accounted for (acd_excited).

  • KickerFitter – forward-only tracking from a kicker marker.

  • ACDMarkerFitter – bidirectional tracking from the AC-dipole markers.

accelmo.tracking.fitter.LM_STALL_TOLERANCE = 1e-06

LM stops after this many accepted steps in a row that each lower the chi² by less than this fraction.

accelmo.tracking.fitter.LM_CHI2_FLOOR = 1e-06

abs(Δχ²) < 1e-12 ends a noise-free fit.

Type:

Below this chi² the stall test is absolute

accelmo.tracking.fitter.LM_ONLY_PARAMETERS = ('knob_sigmas', 'fit_start_coords', 'starts_follow_gains', 'bpm_gain_zero_mean_planes')

TrackingParameters fields only the LM solver fits.

accelmo.tracking.fitter.tracking_lm_config(max_iterations)[source]

The tracking LM solver: stops after several stalled steps, since early steps can be tiny.

Return type:

LevenbergMarquardtConfig

Parameters:

max_iterations (int)

class accelmo.tracking.fitter.FitterOptions(initial_knob_strengths=None, true_strengths=None, debug=False, output_config=OutputConfig(), checkpoint_config=None, initial_conditions_callback=None, loss_callback=None, initial_starts=None, parameters=TrackingParameters())[source]

Bases: object

Optional inputs shared by every tracking fitter.

Variables:
  • initial_knob_strengths – Starting knob values (optimisation space; a deltap becomes pt). Knobs left out keep the model value; fixed strengths outside the fitted knobs are set in every model.

  • true_strengths – Known answer, as a dict or knob file, for diagnostics.

  • debug – Run MAD-NG in debug mode.

  • output_config – Logging, TensorBoard and uncertainty settings.

  • checkpoint_config – Periodic checkpointing and restore.

  • initial_conditions_callback – Epoch-end hook that returns refreshed start coordinates for every worker, or None to keep them.

  • loss_callback – Called after every epoch with its losses.

  • initial_starts – Start (x, px, y, py) per particle in session order, replacing the measured starts before the first evaluation.

  • parameters – BPM gains, start coordinates and prior widths fitted with the knobs.

Parameters:
  • initial_knob_strengths (dict[str, float] | None)

  • true_strengths (Path | dict[str, float] | None)

  • debug (bool)

  • output_config (OutputConfig)

  • checkpoint_config (CheckpointConfig | None)

  • initial_conditions_callback (InitialConditionsCallback | None)

  • loss_callback (LossCallback | None)

  • initial_starts (np.ndarray | None)

  • parameters (TrackingParameters)

initial_knob_strengths: dict[str, float] | None = None
true_strengths: Path | dict[str, float] | None = None
debug: bool = False
output_config: OutputConfig
checkpoint_config: CheckpointConfig | None = None
initial_conditions_callback: InitialConditionsCallback | None = None
loss_callback: Callable[[int, float, float | None, float, float], None] | None = None
initial_starts: Optional[ndarray] = None
parameters: TrackingParameters
class accelmo.tracking.fitter.TrackingFitter(plan, *, accelerator, solver, runtime, tracking_data, sequence_config, measurement_config, bpm_start_points=None, bpm_end_points=None, use_fixed_bpm=False, options=None)[source]

Bases: object

Recovers magnet knob strengths from turn-by-turn tracking, via MAD-NG.

Composes a MachineSetup (model, BPM ranges, starting knobs), the measurement DataManager, a TrackingSession per run and the SGDLoop. It is not constructed directly: the plan comes from one of the public subclasses (ArcByArcFitter, KickerFitter, ACDMarkerFitter, ACDSinusoidFitter). Marker-anchored plans fix their own start points.

All inputs and results are in optimisation space.

Parameters:
worker_plans: dict[int, list[TrackingWorkerConfig]]

Per file, the workers one of its turn batches fans out to.

data_manager: DataManager | None
gain_bpms: tuple[str, ...]
knob_names

magnet knobs, then gains.

Type:

Every fitted parameter, in uncertainty order

knob_sigma

Prior width per fitted parameter (0 = none), from knob_sigmas as POCO resolves it.

lm_config: LevenbergMarquardtConfig | None
loop: SGDLoop | None
diagnostics: FitDiagnostics | None

How the last run ended.

fitted_starts

Start (x, px, y, py) per particle from the last LM run with fit_start_coords.

lm_hessian

LM chi-square Gauss-Newton Hessian at the best point (knobs, then starts), priors included.

session: TrackingSession | None

The workers of the current or last run.

run()[source]

Run the optimisation; knobs and uncertainties are in optimisation space.

Return type:

FitResult

recompute_uncertainties(knobs, hessians=('gauss_newton', 'true'))[source]

Recompute the uncertainties at fixed knobs with each Hessian, in one worker session.

knobs is every optimisation parameter: the fit’s knobs and its gains (extra), or a run log’s knobs at a step. Returns the 1-sigma uncertainties by knob name for each Hessian that ran (a requested true Hessian that cannot run is replaced, see TrackingSession.stop_and_collect_uncertainty()) and logs their ratio.

Return type:

dict[str, dict[str, float]]

Parameters:
  • knobs (dict[str, float])

  • hessians (tuple[str, ...])

start_session(start_knobs=None, *, enable_validation=None)[source]

Start the workers, as run() does, and return their session.

start_knobs defaults to MachineSetup.worker_start_knobs; enable_validation to the tracking plan’s choice. The data are reloaded if a previous run released them. Stop the session (or TrackingSession.terminate() it) when done.

Return type:

TrackingSession

Parameters:
  • start_knobs (dict[str, float] | None)

  • enable_validation (bool | None)

build_initial_normal_matrix(start_knobs=None)[source]

Accumulate the Gauss-Newton normal matrix A = JᵀWJ at the initial knobs (or at start_knobs).

This starts the tracking workers exactly as run() does, then requests the worker-side Hessians without taking a single optimisation step, so the returned matrix describes the problem the optimiser is about to face. Workers are shut down before returning; the fitter can still run() afterwards.

Return type:

tuple[ndarray, list[str]]

Returns:

Tuple of (normal matrix, knob names) with the knob names in the row/column order of the matrix.

Parameters:

start_knobs (dict[str, float] | None)

check_degeneracy(**analyse_kwargs)[source]

Diagnose unconstrained knob directions before optimising.

Builds the normal matrix at the initial knobs and analyses its eigenspectrum. Keyword arguments are forwarded to accelmo.analysis.analyse_degeneracy() (e.g. rel_tol, scale).

Return type:

DegeneracyReport

accelmo.tracking.fitter.initial_conditions_hook(callback, fixed_model_values, push)[source]

An epoch-end hook that pushes callback’s new start coordinates with push.

The optimiser only carries this stage’s knobs, but the workers track through the full model: fixed_model_values (fixed strengths and pt from initial_knob_strengths) are merged into the knobs the callback sees, or it would rebuild initial conditions from the bare model defaults. An empty best_knobs stays empty so the callback can skip early epochs. The best knobs keep the fitted bpmgain.* entries so the callback can correct the readings it reconstructs from; the current knobs carry none.

The hook returns a fragment for the epoch log line: dic is the mean absolute change per component since the previous update and dic0 the mean absolute drift since the first one. They separate an update that is converging (dic falling, dic0 settling), one that never moved the conditions (both zero), and a callback that keeps returning None, which emits no fragment.

Return type:

Callable[[dict[str, float], dict[str, float]], str | None]

Parameters:
  • callback (InitialConditionsCallback)

  • fixed_model_values (dict[str, float])

  • push (Callable[[np.ndarray], None])

class accelmo.tracking.fitter.ArcByArcFitter(accelerator, solver, runtime, tracking_data, sequence_config, measurement_config, bpm_start_points, bpm_end_points, *, acd_excited=False, use_fixed_bpm=True, options=None)[source]

Bases: TrackingFitter

Fit magnet strengths from arc-by-arc BPM ranges.

Tracks the caller’s bpm_start_points x bpm_end_points ranges. With use_fixed_bpm (default) every start pairs with one fixed end and every end with one fixed start, from magnet_range; without it every start pairs with every end in both directions (many more, more correlated ranges). Set acd_excited when the data was AC-dipole excited: the exciter markers are then installed and any range that would straddle the AC dipole is rerouted the long way round the ring. Leave it False for free-oscillation data.

Parameters:
class accelmo.tracking.fitter.KickerFitter(accelerator, solver, runtime, tracking_data, sequence_config, measurement_config, kicker_name, turns_per_track, options=None)[source]

Bases: TrackingFitter

Fit magnet strengths from kicker-excited turn-by-turn data.

Tracks forward-only from the kicker marker, which supplies the tracking initial conditions, for turns_per_track turns; num_workers should be the number of files (one per momentum).

Parameters:
class accelmo.tracking.fitter.ACDMarkerFitter(accelerator, solver, runtime, tracking_data, sequence_config, measurement_config, options=None)[source]

Bases: TrackingFitter

Fit magnet strengths from AC-dipole data, tracked from the exciter markers.

Tracks bidirectionally from the AC-dipole before/after markers (which supply the initial conditions) and observes the whole ring. Use ArcByArcFitter with acd_excited=True instead to track AC-dipole data over ordinary arc ranges.

Parameters:
class accelmo.tracking.fitter.ACDSinusoidFitter(accelerator, solver, runtime, tracking_data, sequence_config, measurement_config, turns_per_track, options=None)[source]

Bases: TrackingFitter

Fit AC-dipole data tracked forward over many turns through the model AC kickers.

The accelerator must install the kickers (PSB acd_drive_tunes); fitting the acd family adds their (a, b) volts as knobs. Each file is cut into back-to-back tracks of turns_per_track turns (see ACDSinusoidTrackingPlan).

Parameters: