Skip to main content

fpm_rs/algorithms/
objective.rs

1//! Optimization objectives used by reconstruction algorithms.
2
3use serde::{Deserialize, Serialize};
4
5use crate::{Result, error::Error};
6
7/// Scalar data-fidelity objective between predicted and measured intensity frames.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
9pub enum LossType {
10    /// Mean squared error between predicted and measured amplitudes.
11    #[default]
12    AmplitudeMse,
13    /// Mean squared error between predicted and measured intensities.
14    IntensityMse,
15    /// Mean Poisson negative log likelihood, omitting measurement-only constants.
16    PoissonNegativeLogLikelihood,
17    /// Huber loss on amplitude residuals with the implementation's fixed unit transition.
18    HuberAmplitude,
19}
20
21/// Computes the selected mean frame loss from equal non-empty intensity slices.
22///
23/// Lengths must match and be non-zero, and values must be finite. Amplitude,
24/// Poisson, and Huber-amplitude losses clamp negative intensities to zero;
25/// intensity MSE uses the supplied values. Invalid lengths or non-finite
26/// values return an error.
27pub fn loss(predicted: &[f64], measured: &[f64], loss_type: LossType) -> Result<f64> {
28    if predicted.len() != measured.len() || predicted.is_empty() {
29        return Err(Error::InvalidShape(format!(
30            "loss inputs have lengths {} and {}",
31            predicted.len(),
32            measured.len()
33        )));
34    }
35    let mut sum = 0.0;
36    for (&predicted, &measured) in predicted.iter().zip(measured) {
37        if !predicted.is_finite() || !measured.is_finite() {
38            return Err(Error::Numerical(
39                "loss input contains a non-finite value".into(),
40            ));
41        }
42        sum += point_loss(predicted, measured, loss_type);
43    }
44    Ok(sum / predicted.len() as f64)
45}
46
47pub(crate) fn point_loss(predicted: f64, measured: f64, loss_type: LossType) -> f64 {
48    match loss_type {
49        LossType::AmplitudeMse => {
50            let residual = predicted.max(0.0).sqrt() - measured.max(0.0).sqrt();
51            residual * residual
52        }
53        LossType::IntensityMse => {
54            let residual = predicted - measured;
55            residual * residual
56        }
57        LossType::PoissonNegativeLogLikelihood => {
58            let mean = predicted.max(1e-12);
59            mean - measured.max(0.0) * mean.ln()
60        }
61        LossType::HuberAmplitude => {
62            let residual = predicted.max(0.0).sqrt() - measured.max(0.0).sqrt();
63            let absolute = residual.abs();
64            if absolute <= 1.0 {
65                0.5 * residual * residual
66            } else {
67                absolute - 0.5
68            }
69        }
70    }
71}