fpm_rs/algorithms/mod.rs
1//! Iterative reconstruction algorithms for compiled image-plane models.
2//!
3//! Choose a concrete solver such as [`crate::algorithms::AlternatingProjection`],
4//! [`crate::algorithms::AdaptiveAlternatingProjection`],
5//! [`crate::algorithms::Fpie`], [`crate::algorithms::Mpie`], [`crate::algorithms::Epry`],
6//! [`crate::algorithms::Admm`] or [`crate::algorithms::GradientDescent`]. All
7//! implement [`crate::algorithms::ReconstructionAlgorithm`] and consume a validated
8//! [`crate::reconstruction::ReconstructionProblem`]; illumination geometry is compiled
9//! beforehand into the problem's [`crate::model::ImagePlaneModel`].
10//!
11//! [`crate::algorithms::SpectralAlternatingProjection`] reconstructs wavelength fields from a compiled
12//! [`crate::model::SpectralImagePlaneModel`]. [`crate::algorithms::MultiWavelengthGradientDescent`]
13//! instead fits wavelength amplitudes and one shared nondispersive OPD to those
14//! detector measurements, using referenced phase mixing or an explicit OPD start.
15
16mod adaptive_alternating_projection;
17mod admm;
18mod alternating_projection;
19mod common;
20mod epry;
21mod fpie;
22mod gauge;
23mod gradient_descent;
24mod joint_reconstruction;
25mod metrics;
26mod mpie;
27mod multi_wavelength;
28pub mod objective;
29mod regularization;
30mod spectral;
31
32pub use adaptive_alternating_projection::{
33 AdaptiveAlternatingProjection, AdaptiveAlternatingProjectionIterationMetrics,
34};
35pub use admm::{Admm, AdmmIterationMetrics};
36pub use alternating_projection::AlternatingProjection;
37pub use epry::Epry;
38pub use fpie::Fpie;
39pub use gradient_descent::{GradientDescent, GradientDescentIterationMetrics};
40pub use joint_reconstruction::{
41 JointIterationMetrics, JointReconstruction, JointReconstructionResult,
42};
43pub use metrics::{AlgorithmIterationMetrics, NoIterationMetrics, StepOutput, StepSummary};
44pub use mpie::Mpie;
45pub(crate) use multi_wavelength::Gauge;
46pub use multi_wavelength::{MultiWavelengthGradientDescent, MultiWavelengthSolverResult};
47pub use spectral::{SpectralAlternatingProjection, SpectralReconstructionAlgorithm};
48
49use crate::{
50 Result,
51 backend::Backend,
52 callbacks::Callback,
53 measurements::MeasurementRead,
54 reconstruction::{
55 Batch, ReconstructionCheckpoint, ReconstructionProblem, ReconstructionResult,
56 ReconstructionState, RunOptions, Runner,
57 },
58};
59use std::sync::Arc;
60
61/// Contract implemented by iterative image-plane reconstruction solvers.
62///
63/// Implementors validate their configuration, initialize a [`ReconstructionState`],
64/// and update one scheduled [`Batch`] at a time. The trait's convenience methods own
65/// the algorithm, borrow the problem for the duration of the run, and return an owned
66/// [`ReconstructionResult`].
67pub trait ReconstructionAlgorithm {
68 /// Algorithm-specific metrics emitted by each step and appended to the trace.
69 type IterationMetrics: AlgorithmIterationMetrics;
70
71 /// Validates solver parameters independently of a reconstruction problem.
72 fn validate(&self) -> Result<()> {
73 Ok(())
74 }
75
76 /// Validates solver requirements that depend on `problem`.
77 fn validate_problem<M: MeasurementRead>(
78 &self,
79 _problem: &ReconstructionProblem<M>,
80 ) -> Result<()> {
81 Ok(())
82 }
83
84 /// Creates the default CPU-backed state for `problem`.
85 fn initialize<M: MeasurementRead>(
86 &self,
87 problem: &ReconstructionProblem<M>,
88 ) -> Result<ReconstructionState> {
89 ReconstructionState::initialize(problem)
90 }
91
92 /// Creates reconstruction state using the supplied execution `backend`.
93 fn initialize_with_backend<M: MeasurementRead>(
94 &self,
95 problem: &ReconstructionProblem<M>,
96 backend: Arc<dyn Backend>,
97 ) -> Result<ReconstructionState> {
98 ReconstructionState::initialize_with_backend(problem, backend)
99 }
100
101 /// Projects algorithm-owned ambiguities into a stable reported convention.
102 ///
103 /// [`Runner`] calls this after initialization or checkpoint restoration and
104 /// after every completed iteration, before iteration diagnostics and
105 /// callbacks, checkpoints, and final result construction. The default
106 /// implementation leaves state unchanged. Algorithms that jointly recover
107 /// coupled fields can override it without requiring external implementations
108 /// to add a lifecycle method. Implementations must preserve the represented
109 /// forward prediction and make repeated projection numerically idempotent.
110 fn canonicalize_state<M: MeasurementRead>(
111 &self,
112 _problem: &ReconstructionProblem<M>,
113 _state: &mut ReconstructionState,
114 ) -> Result<()> {
115 Ok(())
116 }
117
118 /// Reports whether the algorithm may run inside physical joint calibration.
119 ///
120 /// The default permits wrapping. Stateful methods whose internal variables
121 /// would become invalid when the calibrated forward model is recompiled can
122 /// return `false`; [`JointReconstruction`] then rejects them during
123 /// validation.
124 fn supports_joint_reconstruction(&self) -> bool {
125 true
126 }
127
128 /// Updates `state` for one scheduled batch in zero-based `iteration`.
129 fn step<M: MeasurementRead>(
130 &mut self,
131 problem: &ReconstructionProblem<M>,
132 state: &mut ReconstructionState,
133 batch: &Batch,
134 iteration: usize,
135 ) -> Result<StepOutput<Self::IterationMetrics>>;
136
137 /// Returns the requested number of complete schedule passes.
138 fn iterations(&self) -> usize;
139
140 /// Returns the number of measured frames combined into one step.
141 fn batch_size(&self) -> usize {
142 1
143 }
144
145 /// Runs the algorithm with default sequential scheduling and no callbacks.
146 fn run<M: MeasurementRead>(
147 self,
148 problem: &ReconstructionProblem<M>,
149 ) -> Result<ReconstructionResult>
150 where
151 Self: Sized,
152 {
153 let options = RunOptions {
154 max_iterations: self.iterations(),
155 batch_size: self.batch_size(),
156 ..RunOptions::default()
157 };
158 Runner::new(self, options).run(problem)
159 }
160
161 /// Runs the algorithm and invokes `callbacks` at their declared hooks.
162 fn run_with_callbacks<M: MeasurementRead>(
163 self,
164 problem: &ReconstructionProblem<M>,
165 callbacks: Vec<Box<dyn Callback>>,
166 ) -> Result<ReconstructionResult>
167 where
168 Self: Sized,
169 {
170 let options = RunOptions {
171 max_iterations: self.iterations(),
172 batch_size: self.batch_size(),
173 ..RunOptions::default()
174 };
175 Runner::new(self, options)
176 .with_callbacks(callbacks)
177 .run(problem)
178 }
179
180 /// Resumes a run from a checkpoint after validating it against `problem`.
181 fn run_from_checkpoint<M: MeasurementRead>(
182 self,
183 problem: &ReconstructionProblem<M>,
184 checkpoint: ReconstructionCheckpoint,
185 ) -> Result<ReconstructionResult>
186 where
187 Self: Sized,
188 {
189 let options = RunOptions {
190 max_iterations: self.iterations(),
191 batch_size: self.batch_size(),
192 ..RunOptions::default()
193 };
194 Runner::new(self, options)
195 .resume_from(checkpoint)
196 .run(problem)
197 }
198}