Skip to main content

fpm_rs/experiment/
spectral.rs

1//! Narrowband channels and sparse composition of physical detector exposures.
2
3use std::collections::BTreeMap;
4
5use serde::{Deserialize, Serialize};
6
7use crate::{Result, error::Error};
8
9use super::{AcquisitionPlan, Optics, SourceCalibration, SourceGeometry};
10
11/// One narrowband channel's optics, source powers, and local acquisition rows.
12///
13/// The channel ID is stable metadata; its position in the input list is used by
14/// [`SpectralContribution`]. Geometry is supplied separately by [`SpectralGeometry`].
15#[derive(Clone, Debug, Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct SpectralChannel {
18    /// Non-empty, unique channel identifier.
19    pub channel_id: String,
20    /// Channel-specific optics with an explicit vacuum wavelength in metres.
21    pub optics: Optics,
22    /// Fixed relative source powers, including known spectral response if desired.
23    pub calibration: SourceCalibration,
24    /// Ordinary local acquisition rows; their gains precede the spectral sum.
25    pub acquisition: AcquisitionPlan,
26}
27
28/// Declared geometry sharing across narrowband channels.
29#[derive(Clone, Debug, Serialize, Deserialize)]
30#[serde(tag = "kind", content = "geometry", rename_all = "snake_case")]
31pub enum SpectralGeometry {
32    /// Resolve this physical geometry independently with each channel's optics.
33    /// Direct wavelength-specific k-vectors are rejected in this variant.
34    Shared(SourceGeometry),
35    /// One geometry per channel, in channel order; direct k-vectors are allowed.
36    PerChannel(Vec<SourceGeometry>),
37}
38
39/// A non-negative intensity contribution to a detector exposure.
40#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
41#[serde(deny_unknown_fields)]
42pub struct SpectralContribution {
43    /// Zero-based index in the ordered spectral channel list.
44    pub channel: usize,
45    /// Zero-based acquisition row in that channel's ordinary model.
46    pub local_frame: usize,
47    /// Fixed non-negative intensity multiplier; this is not a field amplitude.
48    pub spectral_weight: f64,
49}
50
51/// One physical detector frame, including fixed calibration after the spectral sum.
52#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
53#[serde(deny_unknown_fields)]
54pub struct SpectralFrame {
55    /// Sparse channel/local-frame contributions, canonicalized by the plan constructor.
56    pub contributions: Vec<SpectralContribution>,
57    /// Finite positive detector gain applied once after summing intensities.
58    pub gain: f64,
59    /// Finite non-negative uniform detector background, in intensity units.
60    pub background: f64,
61}
62
63/// Canonical sparse global acquisition plan for separate or multiplexed exposures.
64///
65/// Rows are in physical acquisition order. Duplicate `(channel, local_frame)`
66/// pairs are summed, zero weights removed, and pairs sorted. Every row must
67/// retain a positive contribution. References are checked during compilation.
68#[derive(Clone, Debug, PartialEq, Serialize)]
69pub struct SpectralAcquisitionPlan {
70    frames: Vec<SpectralFrame>,
71}
72
73impl<'de> Deserialize<'de> for SpectralAcquisitionPlan {
74    fn deserialize<D: serde::Deserializer<'de>>(
75        deserializer: D,
76    ) -> std::result::Result<Self, D::Error> {
77        use serde::de::Error as _;
78        #[derive(Deserialize)]
79        #[serde(deny_unknown_fields)]
80        struct Representation {
81            frames: Vec<SpectralFrame>,
82        }
83        Self::multiplexed(Representation::deserialize(deserializer)?.frames)
84            .map_err(D::Error::custom)
85    }
86}
87
88impl SpectralAcquisitionPlan {
89    /// Creates channel-major separate exposures with unit weights/gains and zero background.
90    /// `frame_counts` must contain a positive local-frame count for every channel.
91    pub fn separate(frame_counts: &[usize]) -> Result<Self> {
92        if frame_counts.is_empty() || frame_counts.contains(&0) {
93            return Err(invalid(
94                "frame_counts",
95                "every channel must have at least one local frame",
96            ));
97        }
98        Self::multiplexed(
99            frame_counts
100                .iter()
101                .enumerate()
102                .flat_map(|(channel, &count)| {
103                    (0..count).map(move |local_frame| SpectralFrame {
104                        contributions: vec![SpectralContribution {
105                            channel,
106                            local_frame,
107                            spectral_weight: 1.0,
108                        }],
109                        gain: 1.0,
110                        background: 0.0,
111                    })
112                })
113                .collect(),
114        )
115    }
116
117    /// Canonicalizes explicitly supplied sparse exposures, preserving global row order.
118    /// Non-finite or negative weights/background and non-positive gains are rejected.
119    pub fn multiplexed(mut frames: Vec<SpectralFrame>) -> Result<Self> {
120        if frames.is_empty() {
121            return Err(invalid(
122                "spectral_acquisition",
123                "at least one detector frame is required",
124            ));
125        }
126        for frame in &mut frames {
127            if !frame.gain.is_finite() || frame.gain <= 0.0 {
128                return Err(invalid(
129                    "spectral_frame_gain",
130                    "must be finite and positive",
131                ));
132            }
133            if !frame.background.is_finite() || frame.background < 0.0 {
134                return Err(invalid(
135                    "spectral_frame_background",
136                    "must be finite and non-negative",
137                ));
138            }
139            let mut pairs = BTreeMap::<(usize, usize), f64>::new();
140            for contribution in &frame.contributions {
141                if !contribution.spectral_weight.is_finite() || contribution.spectral_weight < 0.0 {
142                    return Err(invalid(
143                        "spectral_weight",
144                        "must be finite and non-negative",
145                    ));
146                }
147                *pairs
148                    .entry((contribution.channel, contribution.local_frame))
149                    .or_default() += contribution.spectral_weight;
150            }
151            if pairs.values().any(|weight| !weight.is_finite()) {
152                return Err(invalid(
153                    "spectral_weight",
154                    "summed duplicate weights must be finite",
155                ));
156            }
157            frame.contributions = pairs
158                .into_iter()
159                .filter(|(_, weight)| *weight > 0.0)
160                .map(
161                    |((channel, local_frame), spectral_weight)| SpectralContribution {
162                        channel,
163                        local_frame,
164                        spectral_weight,
165                    },
166                )
167                .collect();
168            if frame.contributions.is_empty() {
169                return Err(invalid(
170                    "spectral_acquisition",
171                    "each detector frame must have a positive contribution",
172                ));
173            }
174        }
175        Ok(Self { frames })
176    }
177
178    /// Borrows canonical detector rows in acquisition order.
179    pub fn frames(&self) -> &[SpectralFrame] {
180        &self.frames
181    }
182
183    /// Returns the number of physical detector exposures.
184    pub fn frame_count(&self) -> usize {
185        self.frames.len()
186    }
187}
188
189pub(crate) fn invalid(name: &'static str, reason: impl Into<String>) -> Error {
190    Error::InvalidParameter {
191        name,
192        reason: reason.into(),
193    }
194}