1use std::{collections::BTreeSet, sync::Arc};
4
5use ndarray::{Array2, ArrayView2};
6use num_complex::Complex64;
7use serde::{Deserialize, Serialize};
8
9use crate::{
10 Result,
11 backend::{Backend, CpuBackend},
12 error::Error,
13 experiment::{
14 Illumination, SourceGeometry, SpectralAcquisitionPlan, SpectralChannel, SpectralGeometry,
15 },
16};
17
18use super::{ForwardModel, ImagePlaneModel, ReconstructionShape};
19
20#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum ObjectCoupling {
24 #[default]
26 Independent,
27 SharedComplex,
30}
31
32#[derive(Clone, Debug, Serialize, Deserialize)]
34#[serde(deny_unknown_fields)]
35pub struct SpectralModelChannel {
36 pub channel_id: String,
38 pub model: ImagePlaneModel,
40}
41
42#[derive(Clone, Debug, Serialize)]
50pub struct SpectralImagePlaneModel {
51 channels: Vec<SpectralModelChannel>,
52 acquisition: SpectralAcquisitionPlan,
53 object_coupling: ObjectCoupling,
54}
55
56impl<'de> Deserialize<'de> for SpectralImagePlaneModel {
57 fn deserialize<D: serde::Deserializer<'de>>(
58 deserializer: D,
59 ) -> std::result::Result<Self, D::Error> {
60 use serde::de::Error as _;
61 #[derive(Deserialize)]
62 #[serde(deny_unknown_fields)]
63 struct Representation {
64 channels: Vec<SpectralModelChannel>,
65 acquisition: SpectralAcquisitionPlan,
66 object_coupling: ObjectCoupling,
67 }
68 let repr = Representation::deserialize(deserializer)?;
69 let model = Self {
70 channels: repr.channels,
71 acquisition: repr.acquisition,
72 object_coupling: repr.object_coupling,
73 };
74 model.validate().map_err(D::Error::custom)?;
75 Ok(model)
76 }
77}
78
79impl SpectralImagePlaneModel {
80 pub fn from_experiment(
132 channels: &[SpectralChannel],
133 geometry: &SpectralGeometry,
134 acquisition: SpectralAcquisitionPlan,
135 image_shape: (usize, usize),
136 reconstruction_shape: ReconstructionShape,
137 object_coupling: ObjectCoupling,
138 ) -> Result<Self> {
139 if channels.is_empty() {
140 return Err(invalid(
141 "spectral_channels",
142 "at least one channel is required",
143 ));
144 }
145 let geometries = match geometry {
146 SpectralGeometry::Shared(SourceGeometry::KVectors(_)) => {
147 return Err(invalid(
148 "spectral_geometry",
149 "wavelength-specific KVectorList cannot be shared physical geometry",
150 ));
151 }
152 SpectralGeometry::Shared(value) => vec![value; channels.len()],
153 SpectralGeometry::PerChannel(values) if values.len() == channels.len() => {
154 values.iter().collect()
155 }
156 SpectralGeometry::PerChannel(_) => {
157 return Err(invalid(
158 "spectral_geometry",
159 "requires one geometry per channel",
160 ));
161 }
162 };
163 let mut resolved = Vec::with_capacity(channels.len());
164 let mut bounds = Vec::with_capacity(channels.len());
165 let pitch = channels[0].optics.object_pixel_size();
166 for (channel, geometry) in channels.iter().zip(geometries) {
167 channel.optics.validate()?;
168 if !same_pitch(pitch, channel.optics.object_pixel_size()) {
169 return Err(invalid(
170 "object_plane_pixel_pitch_m",
171 "spectral channels require the same detector sampling; resampling is not implemented",
172 ));
173 }
174 let illumination = Illumination::new(
175 geometry.clone(),
176 channel.calibration.clone(),
177 channel.acquisition.clone(),
178 )
179 .resolve(&channel.optics)?;
180 bounds.push(ImagePlaneModel::crop_displacement_bounds(
181 &channel.optics,
182 image_shape,
183 illumination.k_vectors(),
184 )?);
185 resolved.push(illumination);
186 }
187 let common_shape = ImagePlaneModel::resolve_reconstruction_shape(
188 image_shape,
189 reconstruction_shape,
190 &bounds,
191 )?;
192 let kernels = channels
193 .iter()
194 .zip(&resolved)
195 .map(|(channel, illumination)| {
196 Ok(SpectralModelChannel {
197 channel_id: channel.channel_id.clone(),
198 model: ImagePlaneModel::compile(
199 &channel.optics,
200 illumination,
201 image_shape,
202 ReconstructionShape::Exact(common_shape),
203 )?,
204 })
205 })
206 .collect::<Result<Vec<_>>>()?;
207 let model = Self {
208 channels: kernels,
209 acquisition,
210 object_coupling,
211 };
212 model.validate()?;
213 Ok(model)
214 }
215
216 pub fn from_compiled_channels(
220 channels: Vec<SpectralModelChannel>,
221 acquisition: SpectralAcquisitionPlan,
222 object_coupling: ObjectCoupling,
223 ) -> Result<Self> {
224 let model = Self {
225 channels,
226 acquisition,
227 object_coupling,
228 };
229 model.validate()?;
230 Ok(model)
231 }
232
233 pub fn mixing_diagnostics(
250 &self,
251 relative_tolerance: Option<f64>,
252 ) -> Result<super::SpectralMixingDiagnostics> {
253 self.validate()?;
254 let mut matrix = Array2::zeros((self.frame_count(), self.channels.len()));
255 for (row_index, row) in self.acquisition.frames().iter().enumerate() {
256 for contribution in &row.contributions {
257 let kernel = &self.channels[contribution.channel].model;
258 matrix[[row_index, contribution.channel]] += row.gain
259 * contribution.spectral_weight
260 * kernel.frame_gain(contribution.local_frame)?
261 * local_weight_sum(kernel, contribution.local_frame);
262 }
263 }
264 super::mixing::diagnose(
265 self.channels.iter().map(|c| c.channel_id.clone()).collect(),
266 matrix,
267 relative_tolerance,
268 )
269 }
270
271 pub fn channels(&self) -> &[SpectralModelChannel] {
273 &self.channels
274 }
275
276 pub fn acquisition(&self) -> &SpectralAcquisitionPlan {
278 &self.acquisition
279 }
280
281 pub fn object_coupling(&self) -> ObjectCoupling {
283 self.object_coupling
284 }
285
286 pub fn object_count(&self) -> usize {
288 match self.object_coupling {
289 ObjectCoupling::Independent => self.channels.len(),
290 ObjectCoupling::SharedComplex => 1,
291 }
292 }
293
294 pub fn object_index(&self, channel: usize) -> Result<usize> {
296 if channel >= self.channels.len() {
297 return Err(invalid("channel", "channel index is out of range"));
298 }
299 Ok(match self.object_coupling {
300 ObjectCoupling::Independent => channel,
301 ObjectCoupling::SharedComplex => 0,
302 })
303 }
304
305 pub fn image_shape(&self) -> (usize, usize) {
307 self.channels[0].model.image_shape()
308 }
309
310 pub fn reconstruction_shape(&self) -> (usize, usize) {
312 self.channels[0].model.reconstruction_shape()
313 }
314
315 pub fn frame_count(&self) -> usize {
317 self.acquisition.frame_count()
318 }
319
320 pub fn validate(&self) -> Result<()> {
322 let first = self
323 .channels
324 .first()
325 .ok_or_else(|| invalid("spectral_channels", "at least one channel is required"))?;
326 let mut ids = BTreeSet::new();
327 let mut wavelengths = Vec::new();
328 let mut covered = Vec::new();
329 for channel in &self.channels {
330 channel.model.validate()?;
331 if channel.channel_id.trim().is_empty() || !ids.insert(&channel.channel_id) {
332 return Err(invalid(
333 "channel_id",
334 "channel IDs must be non-empty and unique",
335 ));
336 }
337 let wavelength = channel.model.sampling().wavelength.ok_or_else(|| {
338 invalid(
339 "wavelength_vacuum_m",
340 "every channel must retain wavelength metadata",
341 )
342 })?;
343 if !wavelength.is_finite() || wavelength <= 0.0 || wavelengths.contains(&wavelength) {
344 return Err(invalid(
345 "wavelength_vacuum_m",
346 "wavelengths must be finite, positive, and distinct",
347 ));
348 }
349 wavelengths.push(wavelength);
350 if channel.model.image_shape() != first.model.image_shape()
351 || channel.model.reconstruction_shape() != first.model.reconstruction_shape()
352 || !same_pitch(
353 channel.model.sampling().low_res_pixel_size,
354 first.model.sampling().low_res_pixel_size,
355 )
356 {
357 return Err(invalid(
358 "spectral_sampling",
359 "all channel kernels must share detector shape, reconstruction grid, and object-plane pixel pitch",
360 ));
361 }
362 if channel.model.background().is_some() {
363 return Err(invalid(
364 "spectral_background",
365 "background belongs to physical detector rows, not channel kernels",
366 ));
367 }
368 covered.push(vec![false; channel.model.frame_count()]);
369 }
370 for row in self.acquisition.frames() {
371 let mut mode_weight_sum = 0.0;
372 for contribution in &row.contributions {
373 let local = covered
374 .get_mut(contribution.channel)
375 .and_then(|frames| frames.get_mut(contribution.local_frame))
376 .ok_or_else(|| {
377 invalid(
378 "spectral_acquisition",
379 "channel/local_frame reference is out of range",
380 )
381 })?;
382 *local = true;
383 let kernel = &self.channels[contribution.channel].model;
384 mode_weight_sum += contribution.spectral_weight
385 * kernel.frame_gain(contribution.local_frame)?
386 * local_weight_sum(kernel, contribution.local_frame);
387 }
388 if !mode_weight_sum.is_finite()
389 || mode_weight_sum <= 0.0
390 || !(row.gain * mode_weight_sum).is_finite()
391 || row.gain * mode_weight_sum <= 0.0
392 {
393 return Err(invalid(
394 "spectral_weight",
395 "effective source-mode weight sum must be finite and positive",
396 ));
397 }
398 }
399 if covered.iter().flatten().any(|value| !value) {
400 return Err(invalid(
401 "spectral_acquisition",
402 "every channel and local frame must participate in the detector plan",
403 ));
404 }
405 Ok(())
406 }
407
408 pub fn forward_intensity(
416 &self,
417 spectra: &[ArrayView2<'_, Complex64>],
418 frame: usize,
419 ) -> Result<Array2<f64>> {
420 self.validate_spectra(spectra)?;
421 let row = self
422 .acquisition
423 .frames()
424 .get(frame)
425 .ok_or(Error::FrameOutOfRange {
426 index: frame,
427 frames: self.frame_count(),
428 })?;
429 let backend: Arc<dyn Backend> = Arc::new(CpuBackend::new(
430 self.image_shape(),
431 self.reconstruction_shape(),
432 )?);
433 let mut result = Array2::zeros(self.image_shape());
434 for contribution in &row.contributions {
435 let kernel = &self.channels[contribution.channel].model;
436 let forward = ForwardModel::with_backend(kernel, backend.clone())?;
437 let local = forward.forward_intensity(
438 spectra[self.object_index(contribution.channel)?],
439 kernel.pupil(),
440 contribution.local_frame,
441 )?;
442 result.scaled_add(contribution.spectral_weight, &local);
443 }
444 result.mapv_inplace(|intensity| row.gain * intensity + row.background);
445 if result.iter().any(|value| !value.is_finite()) {
446 return Err(Error::Numerical(
447 "spectral prediction contains non-finite intensities".into(),
448 ));
449 }
450 Ok(result)
451 }
452
453 pub(crate) fn validate_spectra(&self, spectra: &[ArrayView2<'_, Complex64>]) -> Result<()> {
454 if spectra.len() != self.object_count() {
455 return Err(invalid(
456 "object_spectra",
457 "spectrum count differs from object coupling",
458 ));
459 }
460 for spectrum in spectra {
461 crate::array_layout::StandardView2::try_from(*spectrum)?;
462 if spectrum.dim() != self.reconstruction_shape() {
463 return Err(Error::InvalidShape(
464 "spectral object spectrum differs from common grid".into(),
465 ));
466 }
467 if spectrum
468 .iter()
469 .any(|value| !value.re.is_finite() || !value.im.is_finite())
470 {
471 return Err(invalid("object_spectra", "complex values must be finite"));
472 }
473 }
474 Ok(())
475 }
476}
477
478pub(crate) fn local_weight_sum(model: &ImagePlaneModel, frame: usize) -> f64 {
479 model.multiplexing_matrix().map_or(1.0, |matrix| {
480 matrix[frame].iter().map(|(_, weight)| *weight).sum()
481 })
482}
483
484fn same_pitch(left: f64, right: f64) -> bool {
485 (left - right).abs() <= 1e-12 * left.abs().max(right.abs())
486}
487
488fn invalid(name: &'static str, reason: impl Into<String>) -> Error {
489 Error::InvalidParameter {
490 name,
491 reason: reason.into(),
492 }
493}