Skip to main content

fpm_rs/reconstruction/
opd.rs

1//! Referenced, nondispersive OPD recovery by synthetic-wavelength phase mixing.
2
3use std::f64::consts::TAU;
4
5use ndarray::{Array2, ArrayView2};
6use num_complex::Complex64;
7
8use crate::{Error, Result, array_layout::StandardView2, model::ObjectCoupling};
9
10use super::SpectralReconstructionResult;
11
12/// Fixes each channel's unobservable constant phase before wavelength mixing.
13#[derive(Clone, Debug)]
14pub enum PhaseReference {
15    /// Channel-ordered phase pistons in radians, subtracted from field phases.
16    /// Use zero offsets only for fields that already share a calibrated zero-OPD reference.
17    Offsets(Vec<f64>),
18    /// Estimates pistons by an equal-weight circular phase mean on a constant-OPD region.
19    Region {
20        /// Common-grid mask: nonzero selects reference pixels, intersected with valid data.
21        mask: Array2<u8>,
22        /// Known nondispersive OPD of the reference region, in metres.
23        opd_m: f64,
24    },
25}
26
27/// Owned common-grid OPD and diagnostics in input-channel order.
28///
29/// Invalid pixels have NaN OPD/residual and zero fringe orders; always inspect
30/// `valid_mask`. Residuals test phase consistency, not uniqueness of the recovered
31/// branch: sufficiently large phase noise can still cause an undetected order error.
32#[derive(Clone, Debug)]
33pub struct OpticalPathDifferenceResult {
34    /// Recovered nondispersive transmission OPD in metres, `(row, column)`.
35    pub opd_m: Array2<f64>,
36    /// One for usable pixels inside the requested interval and residual tolerance; zero otherwise.
37    pub valid_mask: Array2<u8>,
38    /// RMS principal wrapped phase mismatch over original channels, in radians.
39    pub phase_residual_rad: Array2<f64>,
40    /// Integer cycles added to each referenced principal phase, one array per channel.
41    pub fringe_orders: Vec<Array2<i64>>,
42    /// Applied constant phase pistons in radians, one per input channel.
43    pub phase_offsets_rad: Vec<f64>,
44    /// Vacuum wavelengths in metres, in input-channel order.
45    pub wavelengths_vacuum_m: Vec<f64>,
46    /// Descending synthetic-difference/original periods used for coarse-to-fine recovery.
47    pub wavelength_ladder_m: Vec<f64>,
48}
49
50/// Combines registered complex fields into one nondispersive OPD map.
51///
52/// For transmission phase `φ_i = wrap(2π d / λ_i)`, subtracting the phase of
53/// the longer wavelength from that of the shorter produces period
54/// `Λ = λ_short λ_long / (λ_long - λ_short)`. The longest such period selects
55/// the coarse branch in an explicit half-open OPD interval. All remaining
56/// shorter difference periods and original wavelengths refine integer orders
57/// by rounding; a final equal-phase-weight least-squares fit uses every original
58/// channel. This is post-reconstruction phase mixing, not optical interference
59/// between colors or a joint intensity/OPD optimizer.
60///
61/// Inputs must have matching spatial registration, resolution, phase reference,
62/// and negligible OPD dispersion. No spatial continuity is required, so jumps
63/// exceeding an original wavelength can be recovered. Noise in a coarse OPD
64/// estimate must remain below half the next ladder period for correct rounding.
65/// This implementation uses an explicit interval instead of spatially unwrapping
66/// the longest synthetic phase and does not use phase-sum synthetic wavelengths.
67///
68/// # Example
69/// ```
70/// use fpm_rs::{Complex64, reconstruction::{PhaseReference, SyntheticWavelengthUnwrapper}};
71/// use ndarray::Array2;
72/// let wavelengths = [500e-9, 550e-9];
73/// let fields: Vec<_> = wavelengths.iter().map(|&wavelength| {
74///     Array2::from_elem((2, 3), Complex64::from_polar(1.0,
75///         std::f64::consts::TAU * 2.1e-6 / wavelength))
76/// }).collect();
77/// let views: Vec<_> = fields.iter().map(|field| field.view()).collect();
78/// let result = SyntheticWavelengthUnwrapper::new((0.0, 4e-6))?
79///     .unwrap_fields(&views, &wavelengths, &PhaseReference::Offsets(vec![0.0; 2]), None)?;
80/// assert!((result.opd_m[(0, 0)] - 2.1e-6).abs() < 1e-18);
81/// # Ok::<(), fpm_rs::Error>(())
82/// ```
83///
84/// # References
85/// S. K. Mirsky and N. T. Shaked,
86/// [“Six-pack holography for dynamic profiling of thick and extended objects by simultaneous three-wavelength phase unwrapping with doubled field of view”](https://doi.org/10.1038/s41598-023-45237-6),
87/// Scientific Reports **13**, article 19293 (2023), synthetic-wavelength and
88/// hierarchical phase-unwrapping sections. Here their phase-difference hierarchy
89/// is applied to already reconstructed FPM fields, without their holographic optics.
90#[derive(Clone, Debug)]
91pub struct SyntheticWavelengthUnwrapper {
92    /// Half-open allowed absolute OPD interval `[minimum, maximum)` in metres.
93    /// Its width must not exceed the longest difference synthetic wavelength.
94    pub opd_range_m: (f64, f64),
95    /// All channel amplitudes must strictly exceed this finite nonnegative value.
96    pub minimum_amplitude: f64,
97    /// Optional maximum RMS phase residual in radians, in `(0, π]`.
98    /// `None` retains all otherwise valid pixels and still reports residuals.
99    pub max_phase_residual_rad: Option<f64>,
100}
101
102#[derive(Clone, Copy)]
103struct Period {
104    wavelength: f64,
105    first: usize,
106    second: Option<usize>,
107}
108
109fn parameter(name: &'static str, reason: impl Into<String>) -> Error {
110    Error::InvalidParameter {
111        name,
112        reason: reason.into(),
113    }
114}
115
116fn wrap(phase: f64) -> f64 {
117    phase.sin().atan2(phase.cos())
118}
119
120impl SyntheticWavelengthUnwrapper {
121    /// Creates a validated interval configuration with no residual cutoff and zero amplitude floor.
122    pub fn new(opd_range_m: (f64, f64)) -> Result<Self> {
123        let value = Self {
124            opd_range_m,
125            minimum_amplitude: 0.0,
126            max_phase_residual_rad: None,
127        };
128        value.validate()?;
129        Ok(value)
130    }
131
132    /// Checks finite ordered bounds, amplitude floor, and optional residual tolerance.
133    pub fn validate(&self) -> Result<()> {
134        let (lower, upper) = self.opd_range_m;
135        if !lower.is_finite()
136            || !upper.is_finite()
137            || upper <= lower
138            || !(upper - lower).is_finite()
139        {
140            return Err(parameter(
141                "opd_range_m",
142                "requires finite increasing bounds with finite width",
143            ));
144        }
145        if !self.minimum_amplitude.is_finite() || self.minimum_amplitude < 0.0 {
146            return Err(parameter(
147                "minimum_amplitude",
148                "must be finite and nonnegative",
149            ));
150        }
151        if self
152            .max_phase_residual_rad
153            .is_some_and(|value| !value.is_finite() || value <= 0.0 || value > std::f64::consts::PI)
154        {
155            return Err(parameter(
156                "max_phase_residual_rad",
157                "must be finite in (0, pi]",
158            ));
159        }
160        Ok(())
161    }
162
163    fn periods(&self, wavelengths: &[f64]) -> Result<Vec<Period>> {
164        self.validate()?;
165        if wavelengths.len() < 2 || wavelengths.iter().any(|&w| !w.is_finite() || w <= 0.0) {
166            return Err(parameter(
167                "wavelengths_vacuum_m",
168                "requires at least two distinct finite positive wavelengths",
169            ));
170        }
171        let mut indices: Vec<_> = (0..wavelengths.len()).collect();
172        indices.sort_by(|&a, &b| wavelengths[a].total_cmp(&wavelengths[b]));
173        let mut periods = Vec::new();
174        for (position, &first) in indices.iter().enumerate() {
175            for &second in &indices[position + 1..] {
176                let difference = wavelengths[second] - wavelengths[first];
177                if difference == 0.0 {
178                    return Err(parameter(
179                        "wavelengths_vacuum_m",
180                        "duplicate wavelengths have no finite beat period",
181                    ));
182                }
183                let wavelength = wavelengths[first] * (wavelengths[second] / difference);
184                if !wavelength.is_finite() || wavelength <= 0.0 {
185                    return Err(parameter(
186                        "wavelengths_vacuum_m",
187                        "synthetic periods must be finite and positive",
188                    ));
189                }
190                periods.push(Period {
191                    wavelength,
192                    first,
193                    second: Some(second),
194                });
195            }
196        }
197        periods.sort_by(|a, b| b.wavelength.total_cmp(&a.wavelength));
198        let longest = periods[0].wavelength;
199        if 64.0 * f64::EPSILON * longest >= wavelengths[indices[0]] / 2.0 {
200            return Err(parameter(
201                "wavelengths_vacuum_m",
202                "longest beat is too ill-conditioned for floating-point fringe-order recovery",
203            ));
204        }
205        let (lower, upper) = self.opd_range_m;
206        if upper - lower > longest {
207            return Err(parameter(
208                "opd_range_m",
209                "width exceeds the longest synthetic wavelength; specify a narrower known branch",
210            ));
211        }
212        // Keep integer orders exactly representable by f64 before converting to i64.
213        if lower.abs().max(upper.abs()) / wavelengths[indices[0]] >= (1_u64 << 52) as f64 {
214            return Err(parameter(
215                "opd_range_m",
216                "bounds exceed exact floating-point fringe-order precision",
217            ));
218        }
219        for &first in &indices {
220            if wavelengths[first] <= longest {
221                periods.push(Period {
222                    wavelength: wavelengths[first],
223                    first,
224                    second: None,
225                });
226            }
227        }
228        periods.sort_by(|a, b| b.wavelength.total_cmp(&a.wavelength));
229        periods.dedup_by(|a, b| a.wavelength == b.wavelength);
230        Ok(periods)
231    }
232
233    /// Recovers OPD from at least two finite C-contiguous fields on one nonempty grid.
234    ///
235    /// `reference` explicitly supplies pistons or a constant-known-OPD reference
236    /// mask. `mask`, when present, is a common-grid uint8 validity mask (zero
237    /// excludes a pixel). Zero/below-floor amplitudes in any channel invalidate
238    /// that pixel. Reference means use only pixels valid in every channel.
239    /// Undefined reference means, numerically ill-conditioned beat periods, and
240    /// malformed shapes/layout/values return errors;
241    /// individual range/residual failures are represented in the returned mask.
242    /// Wavelengths are vacuum wavelengths in metres in the same order as fields.
243    pub fn unwrap_fields(
244        &self,
245        fields: &[ArrayView2<'_, Complex64>],
246        wavelengths_vacuum_m: &[f64],
247        reference: &PhaseReference,
248        mask: Option<ArrayView2<'_, u8>>,
249    ) -> Result<OpticalPathDifferenceResult> {
250        let periods = self.periods(wavelengths_vacuum_m)?;
251        if fields.len() != wavelengths_vacuum_m.len() {
252            return Err(parameter(
253                "fields",
254                "field count must equal wavelength count",
255            ));
256        }
257        let shape = fields[0].dim();
258        if shape.0 == 0 || shape.1 == 0 {
259            return Err(Error::InvalidShape(
260                "OPD field grid must be nonempty".into(),
261            ));
262        }
263        let fields = fields
264            .iter()
265            .map(|field| {
266                if field.dim() != shape {
267                    return Err(Error::InvalidShape(
268                        "all OPD fields must have the same shape".into(),
269                    ));
270                }
271                let view = StandardView2::try_from(*field)?;
272                if view
273                    .as_slice()
274                    .iter()
275                    .any(|v| !v.re.is_finite() || !v.im.is_finite() || !v.norm().is_finite())
276                {
277                    return Err(parameter(
278                        "fields",
279                        "complex fields and amplitudes must be finite",
280                    ));
281                }
282                Ok(view)
283            })
284            .collect::<Result<Vec<_>>>()?;
285        let mask = mask
286            .map(|view| {
287                if view.dim() != shape {
288                    return Err(Error::InvalidShape(
289                        "OPD mask must match the field grid".into(),
290                    ));
291                }
292                StandardView2::try_from(view)
293            })
294            .transpose()?;
295        let count = fields[0].as_slice().len();
296        let usable: Vec<_> = (0..count)
297            .map(|pixel| {
298                mask.as_ref().is_none_or(|v| v.as_slice()[pixel] != 0)
299                    && fields
300                        .iter()
301                        .all(|field| field.as_slice()[pixel].norm() > self.minimum_amplitude)
302            })
303            .collect();
304        if !usable.iter().any(|&v| v) {
305            return Err(parameter(
306                "fields/mask",
307                "no pixels have usable amplitudes in all channels",
308            ));
309        }
310        let offsets = match reference {
311            PhaseReference::Offsets(values) => {
312                if values.len() != fields.len() || values.iter().any(|v| !v.is_finite()) {
313                    return Err(parameter(
314                        "phase_offsets_rad",
315                        "requires one finite piston per channel",
316                    ));
317                }
318                values.iter().map(|&v| wrap(v)).collect::<Vec<_>>()
319            }
320            PhaseReference::Region { mask, opd_m } => {
321                if mask.dim() != shape {
322                    return Err(Error::InvalidShape(
323                        "OPD reference mask must match the field grid".into(),
324                    ));
325                }
326                if !opd_m.is_finite() {
327                    return Err(parameter("reference", "requires a finite reference OPD"));
328                }
329                let mask = StandardView2::try_from(mask.view())?;
330                let selected: Vec<_> = (0..count)
331                    .filter(|&p| usable[p] && mask.as_slice()[p] != 0)
332                    .collect();
333                if selected.is_empty() {
334                    return Err(parameter(
335                        "reference_mask",
336                        "reference region has no valid pixels",
337                    ));
338                }
339                fields
340                    .iter()
341                    .zip(wavelengths_vacuum_m)
342                    .map(|(field, &wavelength)| {
343                        let sum: Complex64 = selected
344                            .iter()
345                            .map(|&p| {
346                                let value = field.as_slice()[p];
347                                value / value.norm()
348                            })
349                            .sum();
350                        if sum.norm() <= 1e-12 * selected.len() as f64 {
351                            return Err(parameter(
352                                "reference_mask",
353                                "circular reference phase mean is undefined",
354                            ));
355                        }
356                        let reference_cycles = opd_m / wavelength;
357                        if !reference_cycles.is_finite()
358                            || reference_cycles.abs() >= (1_u64 << 52) as f64
359                        {
360                            return Err(parameter(
361                                "reference_opd_m",
362                                "exceeds exact floating-point fringe-order precision",
363                            ));
364                        }
365                        Ok(wrap(sum.arg() - TAU * reference_cycles.rem_euclid(1.0)))
366                    })
367                    .collect::<Result<Vec<_>>>()?
368            }
369        };
370        let mut result = OpticalPathDifferenceResult {
371            opd_m: Array2::from_elem(shape, f64::NAN),
372            valid_mask: Array2::zeros(shape),
373            phase_residual_rad: Array2::from_elem(shape, f64::NAN),
374            fringe_orders: (0..fields.len()).map(|_| Array2::zeros(shape)).collect(),
375            phase_offsets_rad: offsets.clone(),
376            wavelengths_vacuum_m: wavelengths_vacuum_m.to_vec(),
377            wavelength_ladder_m: periods.iter().map(|p| p.wavelength).collect(),
378        };
379        let shortest = wavelengths_vacuum_m
380            .iter()
381            .copied()
382            .reduce(f64::min)
383            .unwrap();
384        let fit_weights: Vec<_> = wavelengths_vacuum_m.iter().map(|w| shortest / w).collect();
385        let denominator: f64 = fit_weights.iter().map(|w| w * w).sum();
386        let (lower, upper) = self.opd_range_m;
387        let coarse_boundary_tolerance =
388            64.0 * f64::EPSILON * periods[0].wavelength.max(lower.abs()).max(upper.abs());
389        let boundary_tolerance = 64.0 * f64::EPSILON * shortest.max(lower.abs()).max(upper.abs());
390        let mut phases = vec![0.0; fields.len()];
391        let mut orders = vec![0_i64; fields.len()];
392        for (pixel, &valid) in usable.iter().enumerate() {
393            if !valid {
394                continue;
395            }
396            for ((phase, field), &offset) in phases.iter_mut().zip(&fields).zip(&offsets) {
397                *phase = wrap(field.as_slice()[pixel].arg() - offset);
398            }
399            let phase_for = |period: &Period| {
400                wrap(phases[period.first] - period.second.map_or(0.0, |second| phases[second]))
401            };
402            let longest = periods[0].wavelength;
403            let coarse = phase_for(&periods[0]) / TAU * longest;
404            let remainder = (coarse - lower).rem_euclid(longest);
405            // Roundoff at the lower branch boundary must not send an exact
406            // zero/reference pixel to the next synthetic period.
407            let mut opd = if remainder <= coarse_boundary_tolerance
408                || longest - remainder <= coarse_boundary_tolerance
409            {
410                lower
411            } else {
412                lower + remainder
413            };
414            if opd >= upper {
415                continue;
416            }
417            // Mirsky & Shaked (2023): round the coarse/fine OPD difference
418            // divided by the next period to recover its integer fringe order.
419            for period in &periods[1..] {
420                let fraction = phase_for(period) / TAU;
421                opd = ((opd / period.wavelength - fraction).round() + fraction) * period.wavelength;
422            }
423            for ((order, &phase), &wavelength) in
424                orders.iter_mut().zip(&phases).zip(wavelengths_vacuum_m)
425            {
426                *order = (opd / wavelength - phase / TAU).round() as i64;
427            }
428            opd = shortest
429                * phases
430                    .iter()
431                    .zip(&orders)
432                    .zip(&fit_weights)
433                    .map(|((&phase, &order), &weight)| weight * (phase / TAU + order as f64))
434                    .sum::<f64>()
435                / denominator;
436            if (opd - lower).abs() <= boundary_tolerance {
437                opd = lower;
438            }
439            if (opd - upper).abs() <= boundary_tolerance {
440                opd = upper;
441            }
442            let residual = (phases
443                .iter()
444                .zip(wavelengths_vacuum_m)
445                .map(|(&phase, &wavelength)| {
446                    let value = wrap(TAU * (opd / wavelength).rem_euclid(1.0) - phase);
447                    value * value
448                })
449                .sum::<f64>()
450                / fields.len() as f64)
451                .sqrt();
452            if !opd.is_finite()
453                || opd < lower
454                || opd >= upper
455                || self
456                    .max_phase_residual_rad
457                    .is_some_and(|limit| residual > limit)
458            {
459                continue;
460            }
461            let index = (pixel / shape.1, pixel % shape.1);
462            result.opd_m[index] = opd;
463            result.valid_mask[index] = 1;
464            result.phase_residual_rad[index] = residual;
465            for (array, &order) in result.fringe_orders.iter_mut().zip(&orders) {
466                array[index] = order;
467            }
468        }
469        Ok(result)
470    }
471}
472
473impl SpectralReconstructionResult {
474    /// Mixes independent channel phases into a referenced nondispersive OPD map.
475    /// Uses channel metadata for wavelength ordering. Shared-complex coupling is
476    /// rejected because identical complex phases do not express `2π OPD / λ`.
477    pub fn unwrap_opd(
478        &self,
479        unwrapper: &SyntheticWavelengthUnwrapper,
480        reference: &PhaseReference,
481        mask: Option<ArrayView2<'_, u8>>,
482    ) -> Result<OpticalPathDifferenceResult> {
483        if self.object_coupling != ObjectCoupling::Independent {
484            return Err(parameter(
485                "object_coupling",
486                "OPD phase mixing requires independent wavelength fields",
487            ));
488        }
489        let fields: Vec<_> = self.channels.iter().map(|c| c.object.view()).collect();
490        let wavelengths: Vec<_> = self
491            .channels
492            .iter()
493            .map(|c| c.wavelength_vacuum_m)
494            .collect();
495        unwrapper.unwrap_fields(&fields, &wavelengths, reference, mask)
496    }
497}
498
499/// Independent wavelength reconstruction together with referenced common OPD recovery.
500#[derive(Clone, Debug)]
501pub struct MultiWavelengthReconstructionResult {
502    /// Reconstructed channel fields, pupils, metadata, and intensity-fit trace.
503    pub spectral: SpectralReconstructionResult,
504    /// Phase-mixed nondispersive OPD map and diagnostic arrays.
505    pub opd: OpticalPathDifferenceResult,
506}