1use 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
23pub trait SpectralReconstructionAlgorithm {
29 type IterationMetrics: AlgorithmIterationMetrics;
31
32 fn validate(&self) -> Result<()> {
34 Ok(())
35 }
36
37 fn validate_problem<M: MeasurementRead>(
39 &self,
40 _problem: &SpectralReconstructionProblem<M>,
41 ) -> Result<()> {
42 Ok(())
43 }
44
45 fn initialize<M: MeasurementRead>(
47 &self,
48 problem: &SpectralReconstructionProblem<M>,
49 ) -> Result<SpectralReconstructionState> {
50 SpectralReconstructionState::initialize(problem)
51 }
52
53 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 fn iterations(&self) -> usize;
64
65 fn batch_size(&self) -> usize {
67 1
68 }
69
70 fn checkpoint_configuration(&self) -> Option<String> {
75 None
76 }
77
78 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#[derive(Clone, Debug, Serialize, Deserialize)]
109#[serde(deny_unknown_fields)]
110pub struct SpectralAlternatingProjection {
111 pub iterations: usize,
113 pub object_step: f64,
115 pub batch_size: usize,
117 pub epsilon: f64,
119 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 pub fn iterations(mut self, iterations: usize) -> Self {
138 self.iterations = iterations;
139 self
140 }
141
142 pub fn object_step(mut self, object_step: f64) -> Self {
144 self.object_step = object_step;
145 self
146 }
147
148 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 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}