Skip to main content

fpm_rs/model/
image_plane_fpm.rs

1use ndarray::{ArrayView2, ArrayViewMut2};
2use num_complex::Complex64;
3use serde::{Deserialize, Deserializer, Serialize};
4
5use crate::{
6    Result,
7    array_layout::{StandardView2, checked_len_2d},
8    error::Error,
9    experiment::{
10        AcquisitionPlan, Illumination, KVector, MultiplexingMatrix, Optics, ResolvedIllumination,
11    },
12};
13
14use super::{CropIndices, FourierCrop, FourierOffset, Pupil, Sampling};
15
16/// Selects an explicit reconstruction grid or an automatic sizing strategy.
17///
18/// Automatic shapes preserve the low-resolution aspect ratio, so the recovered
19/// object has the same pixel size in both axes. [`Self::Smooth`] and
20/// [`Self::PowerOfTwo`] round the shared reduced-aspect-ratio multiplier rather
21/// than each dimension independently.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum ReconstructionShape {
24    /// Use the supplied concrete `(height, width)` after validating it.
25    Exact((usize, usize)),
26    /// Use the smallest grid containing every Fourier crop and interpolation
27    /// stencil.
28    Minimum,
29    /// Round the minimum shared multiplier up to a value whose prime factors
30    /// are limited to 2, 3, 5, and 7.
31    Smooth,
32    /// Round the minimum shared multiplier up to a power of two.
33    PowerOfTwo,
34}
35
36#[derive(Clone, Copy, Debug)]
37struct GridShift {
38    integer: isize,
39    offset: f64,
40    lower: isize,
41    upper: isize,
42}
43
44#[derive(Clone, Copy, Debug)]
45pub(crate) struct CropDisplacementBounds {
46    minimum_row: isize,
47    maximum_row: isize,
48    minimum_column: isize,
49    maximum_column: isize,
50}
51
52/// Algorithm-facing image-plane FPM model. It contains no LED or camera geometry.
53///
54/// Source-indexed vectors, crops, and optional subpixel offsets describe individual
55/// illuminations. Acquisition-frame-indexed gains, background, and multiplexing describe
56/// measured frames. Shapes are `(height, width)` and stored arrays own their data.
57#[derive(Clone, Debug, Serialize)]
58pub struct ImagePlaneModel {
59    /// One transverse wave vector per illumination source.
60    pub(crate) k_vectors: Vec<KVector>,
61    pub(crate) pupil: Pupil,
62    pub(crate) crop_indices: CropIndices,
63    /// Fractional `(row, column)` Fourier-grid offsets relative to each crop.
64    #[serde(default)]
65    pub(crate) subpixel_offsets: Option<Vec<FourierOffset>>,
66    pub(crate) sampling: Sampling,
67    pub(crate) image_shape: (usize, usize),
68    pub(crate) reconstruction_shape: (usize, usize),
69    pub(crate) frame_gains: Option<Vec<f64>>,
70    pub(crate) background: Option<Vec<f64>>,
71    /// Optional measured-frame rows of `(source_index, incoherent_weight)`.
72    pub(crate) multiplexing_matrix: Option<MultiplexingMatrix>,
73}
74
75impl<'de> Deserialize<'de> for ImagePlaneModel {
76    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
77    where
78        D: Deserializer<'de>,
79    {
80        use serde::de::Error as _;
81
82        #[derive(Deserialize)]
83        #[serde(deny_unknown_fields)]
84        struct Representation {
85            k_vectors: Vec<KVector>,
86            pupil: Pupil,
87            crop_indices: CropIndices,
88            #[serde(default)]
89            subpixel_offsets: Option<Vec<FourierOffset>>,
90            sampling: Sampling,
91            image_shape: (usize, usize),
92            reconstruction_shape: (usize, usize),
93            frame_gains: Option<Vec<f64>>,
94            background: Option<Vec<f64>>,
95            multiplexing_matrix: Option<MultiplexingMatrix>,
96        }
97
98        let representation = Representation::deserialize(deserializer)?;
99        let model = Self {
100            k_vectors: representation.k_vectors,
101            pupil: representation.pupil,
102            crop_indices: representation.crop_indices,
103            subpixel_offsets: representation.subpixel_offsets,
104            sampling: representation.sampling,
105            image_shape: representation.image_shape,
106            reconstruction_shape: representation.reconstruction_shape,
107            frame_gains: representation.frame_gains,
108            background: representation.background,
109            multiplexing_matrix: representation.multiplexing_matrix,
110        };
111        model.validate().map_err(D::Error::custom)?;
112        Ok(model)
113    }
114}
115
116impl ImagePlaneModel {
117    /// Saves this validated compiled kernel as float-roundtrip JSON.
118    /// Intended for external dataset converters; overwrites the destination and
119    /// synchronizes file contents. Does not create parent directories or access the network.
120    pub fn save_json(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
121        self.validate()?;
122        let file = std::fs::File::create(path)?;
123        serde_json::to_writer_pretty(&file, self)?;
124        file.sync_all()?;
125        Ok(())
126    }
127    /// Loads and validates a compiled kernel JSON entirely from local files.
128    /// Preserves explicit sampling metadata, source weights, crops and fixed pupil.
129    pub fn load_json(path: impl AsRef<std::path::Path>) -> Result<Self> {
130        let model: Self =
131            serde_json::from_reader(std::io::BufReader::new(std::fs::File::open(path)?))?;
132        model.validate()?;
133        Ok(model)
134    }
135
136    /// Builds and validates a non-multiplexed model from explicitly compiled components.
137    ///
138    /// `k_vectors` and `crop_indices` must have equal non-zero source counts. `pupil`
139    /// and each crop must have `image_shape`; `sampling` and `reconstruction_shape`
140    /// must be mutually consistent.
141    pub fn new(
142        k_vectors: Vec<KVector>,
143        pupil: Pupil,
144        crop_indices: CropIndices,
145        sampling: Sampling,
146        image_shape: (usize, usize),
147        reconstruction_shape: (usize, usize),
148    ) -> Result<Self> {
149        let model = Self {
150            k_vectors,
151            pupil,
152            crop_indices,
153            subpixel_offsets: None,
154            sampling,
155            image_shape,
156            reconstruction_shape,
157            frame_gains: None,
158            background: None,
159            multiplexing_matrix: None,
160        };
161        model.validate()?;
162        Ok(model)
163    }
164
165    /// Compiles an experiment using an explicit or automatically selected
166    /// reconstruction shape.
167    pub fn from_experiment(
168        optics: &Optics,
169        illumination: &Illumination,
170        image_shape: (usize, usize),
171        reconstruction_shape: ReconstructionShape,
172    ) -> Result<Self> {
173        optics.validate()?;
174        let resolved = illumination.resolve(optics)?;
175        Self::compile(optics, &resolved, image_shape, reconstruction_shape)
176    }
177
178    /// Resolves an explicit shape or suggests an automatic reconstruction grid
179    /// from the actual illumination wave vectors.
180    pub fn suggest_reconstruction_shape(
181        optics: &Optics,
182        illumination: &Illumination,
183        image_shape: (usize, usize),
184        reconstruction_shape: ReconstructionShape,
185    ) -> Result<(usize, usize)> {
186        optics.validate()?;
187        let resolved = illumination.resolve(optics)?;
188        let bounds = Self::crop_displacement_bounds(optics, image_shape, resolved.k_vectors())?;
189        Self::resolve_reconstruction_shape(image_shape, reconstruction_shape, &[bounds])
190    }
191
192    /// Compiles already resolved illumination into algorithm-facing numerical state.
193    ///
194    /// Geometry positions and poses are intentionally not retained. Sparse frame
195    /// weights are multiplied by stable source powers during compilation.
196    pub fn compile(
197        optics: &Optics,
198        illumination: &ResolvedIllumination,
199        image_shape: (usize, usize),
200        reconstruction_shape: ReconstructionShape,
201    ) -> Result<Self> {
202        optics.validate()?;
203        let k_vectors = illumination.k_vectors().to_vec();
204        let bounds = Self::crop_displacement_bounds(optics, image_shape, &k_vectors)?;
205        let reconstruction_shape =
206            Self::resolve_reconstruction_shape(image_shape, reconstruction_shape, &[bounds])?;
207        let scale = reconstruction_shape.1 as f64 / image_shape.1 as f64;
208        let low_res_pixel_size = optics.object_pixel_size();
209        let mut sampling = Sampling::new(
210            low_res_pixel_size,
211            low_res_pixel_size / scale,
212            std::f64::consts::TAU / (image_shape.1 as f64 * low_res_pixel_size),
213            std::f64::consts::TAU / (image_shape.0 as f64 * low_res_pixel_size),
214        )?;
215        sampling.wavelength = Some(optics.wavelength_vacuum_m);
216        let maximum_illumination_na = k_vectors
217            .iter()
218            .map(|vector| {
219                vector.kx.hypot(vector.ky) * optics.wavelength_vacuum_m / std::f64::consts::TAU
220            })
221            .fold(0.0, f64::max);
222        sampling.synthetic_na = Some(optics.objective_na + maximum_illumination_na);
223        let pupil = Pupil::circular(image_shape, &sampling, optics)?;
224        let mut offsets = Vec::with_capacity(k_vectors.len());
225        let crops = k_vectors
226            .iter()
227            .map(|vector| {
228                let (crop, offset) =
229                    Self::crop_for_k_vector(vector, &sampling, image_shape, reconstruction_shape)?;
230                offsets.push(offset);
231                Ok(crop)
232            })
233            .collect::<Result<Vec<_>>>()?;
234        let mut model = Self::new(
235            k_vectors,
236            pupil,
237            CropIndices::new(crops),
238            sampling,
239            image_shape,
240            reconstruction_shape,
241        )?;
242        model.frame_gains = Some(illumination.frame_gains());
243        let matrix = illumination.compiled_multiplexing_matrix();
244        let identity = matrix.len() == model.source_count()
245            && matrix
246                .iter()
247                .enumerate()
248                .all(|(source, row)| row.as_slice() == [(source, 1.0)]);
249        model.multiplexing_matrix = (!identity).then_some(matrix);
250        model.subpixel_offsets = Some(offsets);
251        model.validate()?;
252        Ok(model)
253    }
254
255    pub(crate) fn crop_displacement_bounds(
256        optics: &Optics,
257        image_shape: (usize, usize),
258        k_vectors: &[KVector],
259    ) -> Result<CropDisplacementBounds> {
260        optics.validate()?;
261        validate_image_shape(image_shape)?;
262        if k_vectors.is_empty() {
263            return Err(Error::InvalidModel(
264                "illumination must contain at least one frame".into(),
265            ));
266        }
267        let low_res_pixel_size = optics.object_pixel_size();
268        let dkx = std::f64::consts::TAU / (image_shape.1 as f64 * low_res_pixel_size);
269        let dky = std::f64::consts::TAU / (image_shape.0 as f64 * low_res_pixel_size);
270        let mut bounds = CropDisplacementBounds {
271            minimum_row: isize::MAX,
272            maximum_row: isize::MIN,
273            minimum_column: isize::MAX,
274            maximum_column: isize::MIN,
275        };
276        for vector in k_vectors {
277            let row = checked_grid_shift(vector.ky / dky)?;
278            let column = checked_grid_shift(vector.kx / dkx)?;
279            bounds.minimum_row = bounds.minimum_row.min(row.lower);
280            bounds.maximum_row = bounds.maximum_row.max(row.upper);
281            bounds.minimum_column = bounds.minimum_column.min(column.lower);
282            bounds.maximum_column = bounds.maximum_column.max(column.upper);
283        }
284        Ok(bounds)
285    }
286
287    pub(crate) fn resolve_reconstruction_shape(
288        image_shape: (usize, usize),
289        reconstruction_shape: ReconstructionShape,
290        bounds: &[CropDisplacementBounds],
291    ) -> Result<(usize, usize)> {
292        validate_image_shape(image_shape)?;
293        if bounds.is_empty() {
294            return Err(Error::InvalidModel(
295                "at least one set of illumination crop bounds is required".into(),
296            ));
297        }
298        match reconstruction_shape {
299            ReconstructionShape::Exact(shape) => {
300                validate_reconstruction_aspect(image_shape, shape)?;
301                if !shape_contains_bounds(image_shape, shape, bounds)? {
302                    return Err(Error::InvalidShape(format!(
303                        "reconstruction shape {shape:?} does not contain every illumination crop and subpixel interpolation stencil"
304                    )));
305                }
306                Ok(shape)
307            }
308            policy => {
309                let divisor = greatest_common_divisor(image_shape.0, image_shape.1);
310                let aspect_height = image_shape.0 / divisor;
311                let aspect_width = image_shape.1 / divisor;
312                let maximum_multiplier =
313                    (isize::MAX as usize / aspect_height).min(isize::MAX as usize / aspect_width);
314                let minimum_multiplier = minimum_fitting_multiplier(
315                    image_shape,
316                    (aspect_height, aspect_width),
317                    divisor,
318                    maximum_multiplier,
319                    bounds,
320                )?;
321                let multiplier = match policy {
322                    ReconstructionShape::Minimum => minimum_multiplier,
323                    ReconstructionShape::Smooth => next_smooth_multiplier(minimum_multiplier)
324                        .filter(|&value| value <= maximum_multiplier)
325                        .ok_or_else(|| {
326                            Error::InvalidShape(
327                                "no supported 2/3/5/7-smooth reconstruction multiplier exists"
328                                    .into(),
329                            )
330                        })?,
331                    ReconstructionShape::PowerOfTwo => minimum_multiplier
332                        .checked_next_power_of_two()
333                        .filter(|&value| value <= maximum_multiplier)
334                        .ok_or_else(|| {
335                            Error::InvalidShape(
336                                "no supported power-of-two reconstruction multiplier exists".into(),
337                            )
338                        })?,
339                    ReconstructionShape::Exact(shape) => {
340                        return Err(Error::InvalidShape(format!(
341                            "unexpected exact reconstruction shape {shape:?} during automatic sizing"
342                        )));
343                    }
344                };
345                candidate_shape((aspect_height, aspect_width), multiplier)
346            }
347        }
348    }
349
350    /// Returns the number of individual illumination sources.
351    pub fn source_count(&self) -> usize {
352        self.k_vectors.len()
353    }
354
355    /// Returns the acquisition-frame count, which can differ when sources are multiplexed.
356    pub fn frame_count(&self) -> usize {
357        self.multiplexing_matrix
358            .as_ref()
359            .map_or_else(|| self.source_count(), Vec::len)
360    }
361
362    /// Returns whether acquisition frames contain incoherent combinations of sources.
363    pub fn is_multiplexed(&self) -> bool {
364        self.multiplexing_matrix
365            .as_ref()
366            .is_some_and(|matrix| matrix.iter().any(|row| row.len() > 1))
367    }
368
369    /// Borrows transverse wave vectors in source order, in radians per metre.
370    pub fn k_vectors(&self) -> &[KVector] {
371        &self.k_vectors
372    }
373
374    /// Borrows the low-resolution complex pupil and binary support.
375    pub fn pupil(&self) -> &Pupil {
376        &self.pupil
377    }
378
379    /// Mutably borrows the pupil; callers must preserve its shape and support invariants.
380    pub fn pupil_mut(&mut self) -> &mut Pupil {
381        &mut self.pupil
382    }
383
384    /// Borrows integer Fourier crops in individual source order.
385    pub fn crop_indices(&self) -> &CropIndices {
386        &self.crop_indices
387    }
388
389    /// Borrows optional fractional `(row, column)` offsets in source order.
390    pub fn subpixel_offsets(&self) -> Option<&[FourierOffset]> {
391        self.subpixel_offsets.as_deref()
392    }
393
394    /// Borrows real- and Fourier-space sampling metadata.
395    pub const fn sampling(&self) -> &Sampling {
396        &self.sampling
397    }
398
399    /// Returns low-resolution detector shape as `(height, width)`.
400    pub const fn image_shape(&self) -> (usize, usize) {
401        self.image_shape
402    }
403
404    /// Returns high-resolution object shape as `(height, width)`.
405    pub const fn reconstruction_shape(&self) -> (usize, usize) {
406        self.reconstruction_shape
407    }
408
409    /// Borrows optional non-negative multiplicative gains in acquisition-frame order.
410    pub fn frame_gains(&self) -> Option<&[f64]> {
411        self.frame_gains.as_deref()
412    }
413
414    /// Borrows optional non-negative optical intensity background.
415    ///
416    /// Length is one low-resolution frame (broadcast) or a complete row-major
417    /// `(frame, row, column)` stack.
418    pub fn background(&self) -> Option<&[f64]> {
419        self.background.as_deref()
420    }
421
422    /// Borrows optional acquisition-frame rows of non-negative source weights.
423    pub fn multiplexing_matrix(&self) -> Option<&MultiplexingMatrix> {
424        self.multiplexing_matrix.as_ref()
425    }
426
427    /// Replaces gains, requiring one finite non-negative value per acquisition frame.
428    pub fn with_frame_gains(mut self, values: Option<Vec<f64>>) -> Result<Self> {
429        self.frame_gains = values;
430        self.validate()?;
431        Ok(self)
432    }
433
434    /// Refreshes only source powers, sparse acquisition weights, and frame gains.
435    ///
436    /// Physical positions, propagation vectors, Fourier crops, subpixel offsets,
437    /// pupil samples, sampling metadata, and reconstruction shapes are retained.
438    /// This is the intensity-only update boundary used by physical illumination
439    /// calibration.
440    pub fn update_intensity_calibration(
441        &mut self,
442        source_power: &[f64],
443        acquisition: &AcquisitionPlan,
444    ) -> Result<()> {
445        if source_power.len() != self.source_count()
446            || source_power
447                .iter()
448                .any(|value| !value.is_finite() || *value < 0.0)
449        {
450            return Err(Error::InvalidParameter {
451                name: "source_power",
452                reason: format!(
453                    "must contain {} finite non-negative values",
454                    self.source_count()
455                ),
456            });
457        }
458        if acquisition.frame_count() != self.frame_count() {
459            return Err(Error::InvalidParameter {
460                name: "acquisition",
461                reason: format!(
462                    "frame count {} differs from compiled frame count {}",
463                    acquisition.frame_count(),
464                    self.frame_count()
465                ),
466            });
467        }
468        let mut matrix = Vec::with_capacity(acquisition.frame_count());
469        let mut gains = Vec::with_capacity(acquisition.frame_count());
470        for frame in acquisition.frames() {
471            let mut row = Vec::with_capacity(frame.contributions.len());
472            for contribution in &frame.contributions {
473                let power = source_power.get(contribution.source).ok_or_else(|| {
474                    Error::InvalidParameter {
475                        name: "acquisition",
476                        reason: format!(
477                            "source index {} is outside {} compiled sources",
478                            contribution.source,
479                            self.source_count()
480                        ),
481                    }
482                })?;
483                let weight = contribution.intensity_weight * power;
484                if !weight.is_finite() || weight < 0.0 {
485                    return Err(Error::InvalidParameter {
486                        name: "acquisition",
487                        reason: "compiled source weights must be finite and non-negative".into(),
488                    });
489                }
490                if weight != 0.0 {
491                    row.push((contribution.source, weight));
492                }
493            }
494            if row.is_empty() {
495                return Err(Error::InvalidParameter {
496                    name: "acquisition",
497                    reason: "every calibrated frame must retain positive source weight".into(),
498                });
499            }
500            matrix.push(row);
501            gains.push(frame.gain);
502        }
503        let identity = matrix.len() == self.source_count()
504            && matrix
505                .iter()
506                .enumerate()
507                .all(|(source, row)| row.as_slice() == [(source, 1.0)]);
508        let previous_matrix =
509            std::mem::replace(&mut self.multiplexing_matrix, (!identity).then_some(matrix));
510        let previous_gains = self.frame_gains.replace(gains);
511        if let Err(error) = self.validate() {
512            self.multiplexing_matrix = previous_matrix;
513            self.frame_gains = previous_gains;
514            return Err(error);
515        }
516        Ok(())
517    }
518
519    /// Recompiles illumination-dependent geometry into the existing numerical grid.
520    ///
521    /// The low- and high-resolution shapes, optical sampling, pupil values,
522    /// background, and other static model state are retained. A geometry that
523    /// would move a crop outside the existing reconstruction grid is rejected.
524    pub fn update_illumination_geometry(
525        &mut self,
526        optics: &Optics,
527        illumination: &Illumination,
528    ) -> Result<()> {
529        let resolved = illumination.resolve(optics)?;
530        if resolved.source_count() != self.source_count()
531            || resolved.frame_count() != self.frame_count()
532        {
533            return Err(Error::InvalidModel(
534                "calibrated illumination must preserve source and frame counts".into(),
535            ));
536        }
537        let k_vectors = resolved.k_vectors().to_vec();
538        let mut offsets = Vec::with_capacity(k_vectors.len());
539        let crops = k_vectors
540            .iter()
541            .map(|vector| {
542                let (crop, offset) = Self::crop_for_k_vector(
543                    vector,
544                    &self.sampling,
545                    self.image_shape,
546                    self.reconstruction_shape,
547                )?;
548                offsets.push(offset);
549                Ok(crop)
550            })
551            .collect::<Result<Vec<_>>>()?;
552
553        let previous_vectors = std::mem::replace(&mut self.k_vectors, k_vectors);
554        let previous_crops = std::mem::replace(&mut self.crop_indices, CropIndices::new(crops));
555        let previous_offsets = self.subpixel_offsets.replace(offsets);
556        let previous_synthetic_na = self.sampling.synthetic_na;
557        self.sampling.synthetic_na = Some(
558            optics.objective_na
559                + self
560                    .k_vectors
561                    .iter()
562                    .map(|vector| {
563                        vector.kx.hypot(vector.ky) * optics.wavelength_vacuum_m
564                            / std::f64::consts::TAU
565                    })
566                    .fold(0.0, f64::max),
567        );
568        if let Err(error) =
569            self.update_intensity_calibration(resolved.source_power(), illumination.acquisition())
570        {
571            self.k_vectors = previous_vectors;
572            self.crop_indices = previous_crops;
573            self.subpixel_offsets = previous_offsets;
574            self.sampling.synthetic_na = previous_synthetic_na;
575            return Err(error);
576        }
577        self.validate()
578    }
579
580    /// Replaces the source wave vectors while preserving the compiled crops.
581    ///
582    /// This is intended for calibrated models whose replacement vectors use
583    /// the same Fourier sampling and source ordering. The full model invariant
584    /// set is revalidated before the replacement is committed.
585    pub fn replace_k_vectors(&mut self, values: Vec<KVector>) -> Result<()> {
586        let previous = std::mem::replace(&mut self.k_vectors, values);
587        if let Err(error) = self.validate() {
588            self.k_vectors = previous;
589            return Err(error);
590        }
591        Ok(())
592    }
593
594    /// Replaces optical intensity background with a broadcast frame, full stack, or `None`.
595    pub fn with_background(mut self, values: Option<Vec<f64>>) -> Result<Self> {
596        self.background = values;
597        self.validate()?;
598        Ok(self)
599    }
600
601    /// Sets compiled sparse acquisition with one non-empty non-negative row per frame.
602    pub fn with_multiplexing(mut self, matrix: MultiplexingMatrix) -> Result<Self> {
603        self.multiplexing_matrix = Some(matrix);
604        self.validate()?;
605        Ok(self)
606    }
607
608    /// Sets one finite fractional Fourier-grid offset per individual source.
609    pub fn with_subpixel_offsets(mut self, offsets: Vec<FourierOffset>) -> Result<Self> {
610        self.subpixel_offsets = Some(offsets);
611        self.validate()?;
612        Ok(self)
613    }
614
615    /// Returns a source's fractional Fourier-grid offset, or zero when absent.
616    pub fn source_offset(&self, source: usize) -> Result<FourierOffset> {
617        self.crop_indices.get(source)?;
618        match &self.subpixel_offsets {
619            None => Ok(FourierOffset::default()),
620            Some(offsets) => offsets.get(source).copied().ok_or_else(|| {
621                Error::InvalidModel("subpixel offset count does not match source count".into())
622            }),
623        }
624    }
625
626    /// Extracts one source patch from a standard-layout high-resolution object spectrum.
627    ///
628    /// `destination` has `image_shape.0 * image_shape.1` row-major complex values.
629    /// Fractional offsets use bilinear Fourier-grid interpolation.
630    pub fn extract_patch(
631        &self,
632        object_spectrum: ArrayView2<'_, Complex64>,
633        source: usize,
634        destination: &mut [Complex64],
635    ) -> Result<()> {
636        let object_spectrum = StandardView2::try_from(object_spectrum)?;
637        self.extract_patch_standard(object_spectrum, source, destination)
638    }
639
640    pub(crate) fn extract_patch_standard(
641        &self,
642        object_spectrum: StandardView2<'_, Complex64>,
643        source: usize,
644        destination: &mut [Complex64],
645    ) -> Result<()> {
646        self.extract_patch_at_offset(
647            object_spectrum,
648            source,
649            self.source_offset(source)?,
650            destination,
651        )
652    }
653
654    pub(crate) fn extract_patch_at_offset(
655        &self,
656        object_spectrum: StandardView2<'_, Complex64>,
657        source: usize,
658        offset: FourierOffset,
659        destination: &mut [Complex64],
660    ) -> Result<()> {
661        if object_spectrum.dim() != self.reconstruction_shape {
662            return Err(Error::InvalidShape(format!(
663                "object spectrum shape {:?} does not match {:?}",
664                object_spectrum.dim(),
665                self.reconstruction_shape
666            )));
667        }
668        let crop = self.crop_indices.get(source)?;
669        crop.extract_subpixel_standard(object_spectrum, destination, offset)
670    }
671
672    /// Adds an update into a high-resolution spectrum through the adjoint crop operator.
673    pub fn insert_patch_adjoint(
674        &self,
675        destination: ArrayViewMut2<'_, Complex64>,
676        source: usize,
677        update: &[Complex64],
678        scale: f64,
679    ) -> Result<()> {
680        let destination = crate::array_layout::StandardViewMut2::try_from(destination)?;
681        self.insert_patch_adjoint_standard(destination, source, update, scale)
682    }
683
684    pub(crate) fn insert_patch_adjoint_standard(
685        &self,
686        destination: crate::array_layout::StandardViewMut2<'_, Complex64>,
687        source: usize,
688        update: &[Complex64],
689        scale: f64,
690    ) -> Result<()> {
691        self.insert_patch_adjoint_at_offset(
692            destination,
693            source,
694            update,
695            scale,
696            self.source_offset(source)?,
697        )
698    }
699
700    pub(crate) fn insert_patch_adjoint_at_offset(
701        &self,
702        mut destination: crate::array_layout::StandardViewMut2<'_, Complex64>,
703        source: usize,
704        update: &[Complex64],
705        scale: f64,
706        offset: FourierOffset,
707    ) -> Result<()> {
708        if destination.dim() != self.reconstruction_shape {
709            return Err(Error::InvalidShape(format!(
710                "object spectrum shape {:?} does not match {:?}",
711                destination.dim(),
712                self.reconstruction_shape
713            )));
714        }
715        let crop = self.crop_indices.get(source)?;
716        crop.insert_subpixel_adjoint_slice(
717            destination.as_slice_mut(),
718            self.reconstruction_shape,
719            update,
720            scale,
721            offset,
722        )
723    }
724
725    pub(crate) fn insert_patch_adjoint_slice_at_offset(
726        &self,
727        destination: &mut [Complex64],
728        source: usize,
729        update: &[Complex64],
730        scale: f64,
731        offset: FourierOffset,
732    ) -> Result<()> {
733        let crop = self.crop_indices.get(source)?;
734        crop.insert_subpixel_adjoint_slice(
735            destination,
736            self.reconstruction_shape,
737            update,
738            scale,
739            offset,
740        )
741    }
742
743    /// Checks that `source` exists and the interpolation stencil for `offset` is in bounds.
744    pub fn validate_source_offset(&self, source: usize, offset: FourierOffset) -> Result<()> {
745        self.crop_indices
746            .get(source)?
747            .validate_subpixel_inside(self.reconstruction_shape, offset)
748    }
749
750    pub(crate) fn crop_for_k_vector(
751        vector: &KVector,
752        sampling: &Sampling,
753        image_shape: (usize, usize),
754        reconstruction_shape: (usize, usize),
755    ) -> Result<(FourierCrop, FourierOffset)> {
756        let continuous_row = vector.ky / sampling.dky;
757        let continuous_column = vector.kx / sampling.dkx;
758        let row_shift = checked_grid_shift(continuous_row)?;
759        let column_shift = checked_grid_shift(continuous_column)?;
760        let reconstruction_center_row = isize::try_from(reconstruction_shape.0 / 2)
761            .map_err(|_| Error::InvalidShape("reconstruction height is too large".into()))?;
762        let reconstruction_center_column = isize::try_from(reconstruction_shape.1 / 2)
763            .map_err(|_| Error::InvalidShape("reconstruction width is too large".into()))?;
764        let image_half_height = isize::try_from(image_shape.0 / 2)
765            .map_err(|_| Error::InvalidShape("image height is too large".into()))?;
766        let image_half_width = isize::try_from(image_shape.1 / 2)
767            .map_err(|_| Error::InvalidShape("image width is too large".into()))?;
768        let start_row = reconstruction_center_row
769            .checked_sub(image_half_height)
770            .and_then(|value| value.checked_add(row_shift.integer));
771        let start_column = reconstruction_center_column
772            .checked_sub(image_half_width)
773            .and_then(|value| value.checked_add(column_shift.integer));
774        let (Some(start_row), Some(start_column)) = (start_row, start_column) else {
775            return Err(Error::InvalidModel(format!(
776                "illumination vector {vector:?} overflows the reconstruction grid"
777            )));
778        };
779        if start_row < 0 || start_column < 0 {
780            return Err(Error::InvalidModel(format!(
781                "illumination vector {vector:?} produces a crop outside the reconstruction grid"
782            )));
783        }
784        let crop = FourierCrop::new(
785            usize::try_from(start_row).map_err(|_| {
786                Error::InvalidModel("crop row cannot be represented as an index".into())
787            })?,
788            usize::try_from(start_column).map_err(|_| {
789                Error::InvalidModel("crop column cannot be represented as an index".into())
790            })?,
791            image_shape.0,
792            image_shape.1,
793        );
794        let offset = FourierOffset::new(row_shift.offset, column_shift.offset);
795        crop.validate_subpixel_inside(reconstruction_shape, offset)?;
796        Ok((crop, offset))
797    }
798
799    /// Returns a frame's positive gain, defaulting to `1.0` when gains are absent.
800    pub fn frame_gain(&self, frame: usize) -> Result<f64> {
801        if frame >= self.frame_count() {
802            return Err(Error::FrameOutOfRange {
803                index: frame,
804                frames: self.frame_count(),
805            });
806        }
807        Ok(self
808            .frame_gains
809            .as_ref()
810            .map_or(1.0, |values| values[frame]))
811    }
812
813    /// Returns background intensity for a frame and row-major pixel index.
814    ///
815    /// Returns zero when background is absent and handles broadcast backgrounds.
816    pub fn background_value(&self, frame: usize, pixel: usize) -> Result<f64> {
817        if frame >= self.frame_count() {
818            return Err(Error::FrameOutOfRange {
819                index: frame,
820                frames: self.frame_count(),
821            });
822        }
823        let image_len = checked_len_2d(self.image_shape)?;
824        if pixel >= image_len {
825            return Err(Error::InvalidParameter {
826                name: "pixel",
827                reason: format!("index {pixel} is outside an image with {image_len} pixels"),
828            });
829        }
830        Ok(self.background.as_ref().map_or(0.0, |values| {
831            values[if values.len() == image_len {
832                pixel
833            } else {
834                frame * image_len + pixel
835            }]
836        }))
837    }
838
839    /// Validates source/crop counts, shapes, pupil, sampling, vectors, interpolation
840    /// bounds, gains, background, and optional multiplexing rows.
841    pub fn validate(&self) -> Result<()> {
842        self.sampling.validate()?;
843        if self.k_vectors.is_empty() || self.source_count() != self.crop_indices.len() {
844            return Err(Error::InvalidModel(format!(
845                "{} source k-vectors and {} crops; counts must be equal and non-zero",
846                self.source_count(),
847                self.crop_indices.len()
848            )));
849        }
850        if self
851            .k_vectors
852            .iter()
853            .any(|vector| !vector.kx.is_finite() || !vector.ky.is_finite())
854        {
855            return Err(Error::InvalidModel(
856                "k-vectors must contain finite values".into(),
857            ));
858        }
859        if self.pupil.shape() != self.image_shape {
860            return Err(Error::InvalidModel(format!(
861                "pupil shape {:?} does not match image shape {:?}",
862                self.pupil.shape(),
863                self.image_shape
864            )));
865        }
866        if self.pupil.support.len() != self.pupil.values.len()
867            || self
868                .pupil
869                .values
870                .as_slice()
871                .iter()
872                .any(|value| !value.re.is_finite() || !value.im.is_finite())
873        {
874            return Err(Error::InvalidModel(
875                "pupil support or numeric values are invalid".into(),
876            ));
877        }
878        if self.reconstruction_shape.0 < self.image_shape.0
879            || self.reconstruction_shape.1 < self.image_shape.1
880        {
881            return Err(Error::InvalidModel(
882                "reconstruction shape must contain a low-resolution crop".into(),
883            ));
884        }
885        for crop in &self.crop_indices.crops {
886            if (crop.height, crop.width) != self.image_shape {
887                return Err(Error::InvalidModel(format!(
888                    "crop shape {:?} does not match image shape {:?}",
889                    (crop.height, crop.width),
890                    self.image_shape
891                )));
892            }
893            crop.validate_inside(self.reconstruction_shape)?;
894        }
895        if let Some(offsets) = &self.subpixel_offsets {
896            if offsets.len() != self.source_count() {
897                return Err(Error::InvalidModel(
898                    "subpixel offset count does not match source count".into(),
899                ));
900            }
901            for (crop, &offset) in self.crop_indices.crops.iter().zip(offsets) {
902                crop.validate_subpixel_inside(self.reconstruction_shape, offset)?;
903            }
904        }
905        if let Some(values) = &self.frame_gains {
906            if values.len() != self.frame_count() {
907                return Err(Error::InvalidModel(
908                    "frame gain count does not match frame count".into(),
909                ));
910            }
911            if values
912                .iter()
913                .any(|value| !value.is_finite() || *value < 0.0)
914            {
915                return Err(Error::InvalidModel(
916                    "frame gains must be finite and non-negative".into(),
917                ));
918            }
919        }
920        let image_len = checked_len_2d(self.image_shape)?;
921        let stack_len =
922            image_len
923                .checked_mul(self.frame_count())
924                .ok_or_else(|| Error::ShapeOverflow {
925                    shape: vec![self.frame_count(), self.image_shape.0, self.image_shape.1],
926                })?;
927        if self
928            .background
929            .as_ref()
930            .is_some_and(|values| values.len() != image_len && values.len() != stack_len)
931        {
932            return Err(Error::InvalidModel(
933                "background must be one image or one image per frame".into(),
934            ));
935        }
936        if self
937            .background
938            .as_ref()
939            .is_some_and(|values| values.iter().any(|value| !value.is_finite()))
940        {
941            return Err(Error::InvalidModel(
942                "background values must be finite".into(),
943            ));
944        }
945        if let Some(matrix) = &self.multiplexing_matrix {
946            if matrix.is_empty() {
947                return Err(Error::InvalidModel(
948                    "multiplexing matrix must contain at least one measured frame".into(),
949                ));
950            }
951            for (row_index, row) in matrix.iter().enumerate() {
952                let mut seen = vec![false; self.source_count()];
953                let invalid = row.is_empty()
954                    || row.iter().any(|&(source, weight)| {
955                        let duplicate = source < self.source_count() && seen[source];
956                        if source < self.source_count() {
957                            seen[source] = true;
958                        }
959                        source >= self.source_count()
960                            || !weight.is_finite()
961                            || weight < 0.0
962                            || duplicate
963                    });
964                if invalid {
965                    return Err(Error::InvalidModel(format!(
966                        "multiplexing row {row_index} is empty or contains a duplicate/invalid source or weight"
967                    )));
968                }
969            }
970        }
971        Ok(())
972    }
973}
974
975fn checked_grid_shift(value: f64) -> Result<GridShift> {
976    if !value.is_finite() {
977        return Err(Error::InvalidModel(
978            "illumination shift must be finite".into(),
979        ));
980    }
981    let rounded = value.round();
982    if rounded < isize::MIN as f64 || rounded > isize::MAX as f64 {
983        return Err(Error::InvalidModel(
984            "illumination shift is outside the supported index range".into(),
985        ));
986    }
987    let integer = rounded as isize;
988    let offset = value - rounded;
989    let nearest_offset = offset.round();
990    let (lower, upper) = if (offset - nearest_offset).abs() <= 1e-12 {
991        let displacement = integer
992            .checked_add(nearest_offset as isize)
993            .ok_or_else(|| {
994                Error::InvalidModel(
995                    "illumination shift is outside the supported index range".into(),
996                )
997            })?;
998        (displacement, displacement)
999    } else if offset > 0.0 {
1000        (
1001            integer,
1002            integer.checked_add(1).ok_or_else(|| {
1003                Error::InvalidModel(
1004                    "illumination shift is outside the supported index range".into(),
1005                )
1006            })?,
1007        )
1008    } else {
1009        (
1010            integer.checked_sub(1).ok_or_else(|| {
1011                Error::InvalidModel(
1012                    "illumination shift is outside the supported index range".into(),
1013                )
1014            })?,
1015            integer,
1016        )
1017    };
1018    Ok(GridShift {
1019        integer,
1020        offset,
1021        lower,
1022        upper,
1023    })
1024}
1025
1026fn validate_image_shape(image_shape: (usize, usize)) -> Result<()> {
1027    if image_shape.0 == 0 || image_shape.1 == 0 {
1028        return Err(Error::InvalidShape(format!(
1029            "image shape {image_shape:?} must be non-zero"
1030        )));
1031    }
1032    if image_shape.0 > isize::MAX as usize || image_shape.1 > isize::MAX as usize {
1033        return Err(Error::InvalidShape(
1034            "image shape is outside the supported index range".into(),
1035        ));
1036    }
1037    Ok(())
1038}
1039
1040fn validate_reconstruction_aspect(
1041    image_shape: (usize, usize),
1042    reconstruction_shape: (usize, usize),
1043) -> Result<()> {
1044    if reconstruction_shape.0 < image_shape.0 || reconstruction_shape.1 < image_shape.1 {
1045        return Err(Error::InvalidShape(format!(
1046            "image shape {image_shape:?} must fit reconstruction shape {reconstruction_shape:?}"
1047        )));
1048    }
1049    if reconstruction_shape.0 > isize::MAX as usize || reconstruction_shape.1 > isize::MAX as usize
1050    {
1051        return Err(Error::InvalidShape(
1052            "reconstruction shape is outside the supported index range".into(),
1053        ));
1054    }
1055    let left = reconstruction_shape.0 as u128 * image_shape.1 as u128;
1056    let right = reconstruction_shape.1 as u128 * image_shape.0 as u128;
1057    if left != right {
1058        return Err(Error::InvalidShape(
1059            "reconstruction must use the same scale factor in both dimensions".into(),
1060        ));
1061    }
1062    Ok(())
1063}
1064
1065fn shape_contains_bounds(
1066    image_shape: (usize, usize),
1067    reconstruction_shape: (usize, usize),
1068    bounds: &[CropDisplacementBounds],
1069) -> Result<bool> {
1070    validate_reconstruction_aspect(image_shape, reconstruction_shape)?;
1071    for bound in bounds {
1072        if !axis_contains_bounds(
1073            image_shape.0,
1074            reconstruction_shape.0,
1075            bound.minimum_row,
1076            bound.maximum_row,
1077        )? || !axis_contains_bounds(
1078            image_shape.1,
1079            reconstruction_shape.1,
1080            bound.minimum_column,
1081            bound.maximum_column,
1082        )? {
1083            return Ok(false);
1084        }
1085    }
1086    Ok(true)
1087}
1088
1089fn axis_contains_bounds(
1090    image_length: usize,
1091    reconstruction_length: usize,
1092    minimum_displacement: isize,
1093    maximum_displacement: isize,
1094) -> Result<bool> {
1095    let centre = i128::try_from(reconstruction_length / 2)
1096        .map_err(|_| Error::InvalidShape("reconstruction dimension is too large".into()))?;
1097    let image_half = i128::try_from(image_length / 2)
1098        .map_err(|_| Error::InvalidShape("image dimension is too large".into()))?;
1099    let base = centre.checked_sub(image_half).ok_or_else(|| {
1100        Error::InvalidShape("reconstruction crop origin overflows the index range".into())
1101    })?;
1102    let lower = base
1103        .checked_add(minimum_displacement as i128)
1104        .ok_or_else(|| {
1105            Error::InvalidShape("reconstruction crop origin overflows the index range".into())
1106        })?;
1107    let upper = base
1108        .checked_add((image_length - 1) as i128)
1109        .and_then(|value| value.checked_add(maximum_displacement as i128))
1110        .ok_or_else(|| {
1111            Error::InvalidShape("reconstruction crop extent overflows the index range".into())
1112        })?;
1113    Ok(lower >= 0 && upper < reconstruction_length as i128)
1114}
1115
1116fn minimum_fitting_multiplier(
1117    image_shape: (usize, usize),
1118    aspect: (usize, usize),
1119    initial_multiplier: usize,
1120    maximum_multiplier: usize,
1121    bounds: &[CropDisplacementBounds],
1122) -> Result<usize> {
1123    let fits = |multiplier| -> Result<bool> {
1124        let shape = candidate_shape(aspect, multiplier)?;
1125        shape_contains_bounds(image_shape, shape, bounds)
1126    };
1127    if fits(initial_multiplier)? {
1128        return Ok(initial_multiplier);
1129    }
1130    let mut lower = initial_multiplier;
1131    let mut upper = initial_multiplier;
1132    loop {
1133        let doubled = upper.checked_mul(2).unwrap_or(maximum_multiplier);
1134        upper = doubled.min(maximum_multiplier);
1135        if upper == lower {
1136            return Err(Error::InvalidShape(
1137                "illumination crops require a reconstruction shape outside the supported index range"
1138                    .into(),
1139            ));
1140        }
1141        if fits(upper)? {
1142            break;
1143        }
1144        lower = upper;
1145    }
1146    while lower + 1 < upper {
1147        let middle = lower + (upper - lower) / 2;
1148        if fits(middle)? {
1149            upper = middle;
1150        } else {
1151            lower = middle;
1152        }
1153    }
1154    Ok(upper)
1155}
1156
1157fn candidate_shape(aspect: (usize, usize), multiplier: usize) -> Result<(usize, usize)> {
1158    let height = aspect.0.checked_mul(multiplier).ok_or_else(|| {
1159        Error::InvalidShape("reconstruction height overflows the supported range".into())
1160    })?;
1161    let width = aspect.1.checked_mul(multiplier).ok_or_else(|| {
1162        Error::InvalidShape("reconstruction width overflows the supported range".into())
1163    })?;
1164    Ok((height, width))
1165}
1166
1167fn greatest_common_divisor(mut left: usize, mut right: usize) -> usize {
1168    while right != 0 {
1169        let remainder = left % right;
1170        left = right;
1171        right = remainder;
1172    }
1173    left
1174}
1175
1176fn next_smooth_multiplier(minimum: usize) -> Option<usize> {
1177    fn visit(value: usize, prime_index: usize, minimum: usize, best: &mut Option<usize>) {
1178        if value >= minimum {
1179            if best.is_none_or(|current| value < current) {
1180                *best = Some(value);
1181            }
1182            return;
1183        }
1184        const PRIMES: [usize; 4] = [2, 3, 5, 7];
1185        for (index, &prime) in PRIMES.iter().enumerate().skip(prime_index) {
1186            let Some(next) = value.checked_mul(prime) else {
1187                continue;
1188            };
1189            if best.is_none_or(|current| next < current) {
1190                visit(next, index, minimum, best);
1191            }
1192        }
1193    }
1194
1195    let mut best = None;
1196    visit(1, 0, minimum, &mut best);
1197    best
1198}