Skip to main content

fpm_rs/algorithms/
spectral.rs

1//! Object-only amplitude projection for sparse narrowband spectral exposures.
2
3use num_complex::Complex64;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    Result,
8    backend::FftDirection,
9    error::Error,
10    measurements::MeasurementRead,
11    model::fftshift_copy,
12    reconstruction::{
13        Batch, SpectralReconstructionProblem, SpectralReconstructionResult,
14        SpectralReconstructionState, SpectralRunner,
15    },
16};
17
18use super::{
19    AlgorithmIterationMetrics, NoIterationMetrics, StepOutput, StepSummary,
20    objective::{LossType, point_loss},
21};
22
23/// Separate solver contract for compiled narrowband spectral models.
24///
25/// Implementors consume only the compiled spectral model and scalar
26/// [`MeasurementRead`], never physical illumination geometry. Ordinary
27/// [`super::ReconstructionAlgorithm`] implementations are intentionally incompatible.
28pub trait SpectralReconstructionAlgorithm {
29    /// Algorithm-owned metrics reduced in exact global detector schedule order.
30    type IterationMetrics: AlgorithmIterationMetrics;
31
32    /// Validates solver parameters before state initialization.
33    fn validate(&self) -> Result<()> {
34        Ok(())
35    }
36
37    /// Validates algorithm-specific requirements on a spectral problem.
38    fn validate_problem<M: MeasurementRead>(
39        &self,
40        _problem: &SpectralReconstructionProblem<M>,
41    ) -> Result<()> {
42        Ok(())
43    }
44
45    /// Creates default CPU spectral state using mask-aware amplitude initialization.
46    fn initialize<M: MeasurementRead>(
47        &self,
48        problem: &SpectralReconstructionProblem<M>,
49    ) -> Result<SpectralReconstructionState> {
50        SpectralReconstructionState::initialize(problem)
51    }
52
53    /// Updates a batch of physical detector exposures in the supplied order.
54    fn step<M: MeasurementRead>(
55        &mut self,
56        problem: &SpectralReconstructionProblem<M>,
57        state: &mut SpectralReconstructionState,
58        batch: &Batch,
59        iteration: usize,
60    ) -> Result<StepOutput<Self::IterationMetrics>>;
61
62    /// Returns the positive number of complete global schedule passes.
63    fn iterations(&self) -> usize;
64
65    /// Returns a positive batch size; implementations still stream individual frames.
66    fn batch_size(&self) -> usize {
67        1
68    }
69
70    /// Returns canonical JSON stepping options for a stateless checkpointable solver.
71    /// `None` (the default) disables capture/resume for custom implementations.
72    /// Implementors opting in must keep every persistent numerical variable in
73    /// the spectral state and exclude only the total iteration target here.
74    fn checkpoint_configuration(&self) -> Option<String> {
75        None
76    }
77
78    /// Runs with sequential physical detector order and default initialization.
79    fn run<M: MeasurementRead>(
80        self,
81        problem: &SpectralReconstructionProblem<M>,
82    ) -> Result<SpectralReconstructionResult>
83    where
84        Self: Sized,
85    {
86        SpectralRunner::new(self).run(problem)
87    }
88}
89
90/// Object-only alternating projection for separate or multiplexed spectral data.
91///
92/// Every coherent source mode in an exposure is evaluated before any object
93/// update. One mask-aware amplitude ratio from their weighted intensity sum is
94/// applied to all modes. Canonical channel crop adjoints accumulate into the
95/// independent objects or one explicitly shared object. Mode updates use their
96/// effective intensity weight divided by the exposure's total mode weight,
97/// preserving ordinary alternating-projection behavior when there is one
98/// channel. Pupils, source powers, and detector calibration remain fixed.
99///
100/// This generalizes narrowband state decomposition to typed channel/local-frame
101/// composition. It does not implement finite bandwidth or mixed-state coherence.
102///
103/// # References
104///
105/// S. Dong, R. Shiradkar, P. Nanda, and G. Zheng,
106/// [“Spectral multiplexing and coherent-state decomposition in Fourier ptychographic imaging”](https://doi.org/10.1364/BOE.5.001757),
107/// *Biomedical Optics Express* **5**(6), 1757–1767 (2014).
108#[derive(Clone, Debug, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct SpectralAlternatingProjection {
111    /// Positive number of complete physical acquisition passes.
112    pub iterations: usize,
113    /// Finite positive relaxation applied to object corrections.
114    pub object_step: f64,
115    /// Positive number of exposures per step; does not change per-frame update order.
116    pub batch_size: usize,
117    /// Finite positive denominator floor and dark-prediction threshold.
118    pub epsilon: f64,
119    /// Mask-aware diagnostic loss; the update always projects measured amplitude.
120    pub loss_type: LossType,
121}
122
123impl Default for SpectralAlternatingProjection {
124    fn default() -> Self {
125        Self {
126            iterations: 50,
127            object_step: 1.0,
128            batch_size: 1,
129            epsilon: 1e-10,
130            loss_type: LossType::AmplitudeMse,
131        }
132    }
133}
134
135impl SpectralAlternatingProjection {
136    /// Sets the positive number of complete acquisition passes.
137    pub fn iterations(mut self, iterations: usize) -> Self {
138        self.iterations = iterations;
139        self
140    }
141
142    /// Sets a finite positive object relaxation, checked before execution.
143    pub fn object_step(mut self, object_step: f64) -> Self {
144        self.object_step = object_step;
145        self
146    }
147
148    /// Sets positive batching without changing the sequential per-frame updates.
149    pub fn batch_size(mut self, batch_size: usize) -> Self {
150        self.batch_size = batch_size;
151        self
152    }
153}
154
155impl SpectralReconstructionAlgorithm for SpectralAlternatingProjection {
156    type IterationMetrics = NoIterationMetrics;
157
158    fn validate(&self) -> Result<()> {
159        for (name, value) in [("object_step", self.object_step), ("epsilon", self.epsilon)] {
160            if !value.is_finite() || value <= 0.0 {
161                return Err(Error::InvalidParameter {
162                    name,
163                    reason: "must be finite and positive".into(),
164                });
165            }
166        }
167        if self.iterations == 0 {
168            return Err(Error::InvalidParameter {
169                name: "iterations",
170                reason: "must be positive".into(),
171            });
172        }
173        if self.batch_size == 0 {
174            return Err(Error::InvalidParameter {
175                name: "batch_size",
176                reason: "must be positive".into(),
177            });
178        }
179        Ok(())
180    }
181
182    fn step<M: MeasurementRead>(
183        &mut self,
184        problem: &SpectralReconstructionProblem<M>,
185        state: &mut SpectralReconstructionState,
186        batch: &Batch,
187        _iteration: usize,
188    ) -> Result<StepOutput<Self::IterationMetrics>> {
189        let model = &problem.model;
190        let shape = model.image_shape();
191        let mut summary = StepSummary::default();
192        for &frame in &batch.indices {
193            let row = model
194                .acquisition()
195                .frames()
196                .get(frame)
197                .ok_or(Error::FrameOutOfRange {
198                    index: frame,
199                    frames: model.frame_count(),
200                })?;
201            let frame_weight = problem.measurements.frame_weight(frame)?;
202            if frame_weight == 0.0 {
203                summary.push_frame(frame, 0.0, 0.0);
204                continue;
205            }
206            state.evaluate_frame(model, frame)?;
207            let weight_sum: f64 = state.modes.iter().map(|mode| mode.weight).sum();
208            let measured = problem.measurements.frame(frame)?;
209            let mask = problem.measurements.frame_mask(frame)?;
210            let mut loss = 0.0;
211            let mut valid = 0;
212            for pixel in 0..measured.len() {
213                if mask.is_some_and(|values| values[pixel] == 0) {
214                    state.projection[pixel] = Complex64::new(1.0, 0.0);
215                    continue;
216                }
217                valid += 1;
218                let prediction = state.predicted[pixel];
219                loss += point_loss(
220                    state.effective_gain * prediction + row.background,
221                    measured[pixel],
222                    self.loss_type,
223                );
224                let target = ((measured[pixel] - row.background) / state.effective_gain).max(0.0);
225                state.projection[pixel] = if prediction > self.epsilon {
226                    Complex64::new((target / prediction).sqrt(), 0.0)
227                } else {
228                    Complex64::new(0.0, (target / weight_sum).sqrt())
229                };
230            }
231            if valid == 0 {
232                return Err(Error::InvalidMeasurements(format!(
233                    "frame {frame} has no unmasked pixels"
234                )));
235            }
236            summary.push_frame(frame, loss / valid as f64, frame_weight);
237            for mode in &state.modes {
238                let kernel = &model.channels()[mode.channel].model;
239                for pixel in 0..measured.len() {
240                    state.field[pixel] = if mask.is_some_and(|values| values[pixel] == 0) {
241                        mode.field[pixel]
242                    } else if state.predicted[pixel] > self.epsilon {
243                        mode.field[pixel] * state.projection[pixel].re
244                    } else {
245                        Complex64::new(state.projection[pixel].im, 0.0)
246                    };
247                }
248                state.backend.fft2(
249                    &mut state.field,
250                    shape,
251                    FftDirection::Forward,
252                    &mut state.column,
253                )?;
254                fftshift_copy(&state.field, &mut state.centered, shape);
255                for (pixel, pupil) in kernel.pupil().values().iter().enumerate() {
256                    state.update[pixel] = pupil.conj() * (state.centered[pixel] - mode.exit[pixel])
257                        / (pupil.norm_sqr() + self.epsilon);
258                }
259                let object_index = model.object_index(mode.channel)?;
260                kernel.insert_patch_adjoint(
261                    state.spectra[object_index].ndarray_view_mut(),
262                    mode.source,
263                    &state.update,
264                    frame_weight * self.object_step * (mode.weight / weight_sum),
265                )?;
266            }
267            // Keep only this exposure's fields; memory is independent of stack size.
268            state.modes.clear();
269        }
270        Ok(summary.into())
271    }
272
273    fn iterations(&self) -> usize {
274        self.iterations
275    }
276    fn batch_size(&self) -> usize {
277        self.batch_size
278    }
279    fn checkpoint_configuration(&self) -> Option<String> {
280        let mut configuration = self.clone();
281        configuration.iterations = 1;
282        serde_json::to_string(&configuration).ok()
283    }
284}