Skip to main content

kallo_core/
scan.rs

1//! Spectral scanning: print densities to output colour.
2//!
3//! The last non-physical step. Phase 0 turned a print density straight into a
4//! channel value; this turns it into a spectrum, then into a colour:
5//!
6//! ```text
7//! D_cmy ──► R(λ) = 10^(-Σ d·dye - base) ──► R(λ)·L(λ) ──► XYZ ──► linear RGB
8//! ```
9//!
10//! The observer is the CIE 1931 2° fit from `kallo-spectral`; the illuminant
11//! is equal-energy and the dyes are the same placeholder bands as the print. All
12//! three are labelled where they are defined, and all three are replaceable
13//! without touching this arithmetic.
14
15use kallo_spectral::Spectrum;
16use kallo_spectral::sensor::cie1931_xyz;
17
18use crate::model::{ScanModel, inverse3, table, tables};
19use crate::spectral::{GRID_LEN, GRID_START_NM, GRID_STEP_NM};
20
21/// A dye's absorption band, as a Gaussian.
22#[derive(Debug, Clone, Copy)]
23struct Band {
24    peak_nm: f64,
25    width_nm: f64,
26}
27
28/// The image dyes in the paper: cyan, magenta, yellow, at the usual primaries.
29const PAPER_DYES: [Band; 3] = [
30    Band {
31        peak_nm: 650.0,
32        width_nm: 55.0,
33    },
34    Band {
35        peak_nm: 550.0,
36        width_nm: 50.0,
37    },
38    Band {
39        peak_nm: 450.0,
40        width_nm: 55.0,
41    },
42];
43
44/// Base density of unexposed paper: a little light is always lost.
45const PAPER_BASE_DENSITY: f64 = 0.06;
46
47/// Density range covered by the grey-balance table.
48const NEUTRAL_MAX_DENSITY: f64 = 3.0;
49/// Entries in the grey-balance table.
50const NEUTRAL_STEPS: usize = 32;
51/// Entries in [`ScanContext::neutral_rgb`], the density levels 0 to
52/// `NEUTRAL_MAX_DENSITY` inclusive.
53pub(crate) const NEUTRAL_ENTRIES: usize = NEUTRAL_STEPS + 1;
54
55/// CIE standard illuminant D50 on the internal grid, 5 nm steps.
56///
57/// ISO 3664 specifies D50 for judging reflection prints, which is what this
58/// model scans. Values are the CIE SPD, normalised only by the white-point
59/// division in `scan`.
60const D50_SPD: [f64; 71] = [
61    24.49, 27.18, 29.87, 39.59, 49.31, 52.91, 56.51, 58.27, 60.03, 58.93, 57.82, 66.32, 74.83,
62    81.04, 87.25, 88.93, 90.61, 90.99, 91.37, 93.24, 95.11, 93.54, 91.96, 93.84, 95.72, 96.17,
63    96.61, 96.87, 97.13, 99.61, 102.10, 101.43, 100.75, 101.54, 102.32, 101.16, 100.00, 98.87,
64    97.73, 98.33, 98.92, 96.21, 93.50, 95.59, 97.69, 98.48, 99.27, 99.16, 99.04, 97.38, 95.72,
65    97.29, 98.86, 97.26, 95.67, 96.93, 98.19, 100.60, 103.00, 101.07, 99.13, 93.26, 87.38, 89.49,
66    91.60, 92.25, 92.89, 84.87, 76.85, 81.68, 86.51,
67];
68
69/// XYZ (D65) to linear sRGB, the standard matrix.
70const XYZ_TO_SRGB: [[f64; 3]; 3] = [
71    [3.240_454_2, -1.537_138_5, -0.498_531_4],
72    [-0.969_266_0, 1.876_010_8, 0.041_556_0],
73    [0.055_643_4, -0.204_025_9, 1.057_225_2],
74];
75
76/// The spectral model of the scan.
77#[derive(Debug, Clone)]
78pub struct ScanContext {
79    grid: Spectrum,
80    dye: [Spectrum; 3],
81    illuminant: Spectrum,
82    cmf: [Spectrum; 3],
83    /// XYZ of paper white, used to normalise so that white prints at 1.0.
84    white_xyz: [f64; 3],
85    /// RGB of paper white after the matrix, so white divides out to 1.0.
86    white_rgb: [f64; 3],
87    /// RGB of a neutral density at evenly spaced levels. Used for grey balance,
88    /// for the same reason the print needs one: overlapping dyes do not cancel.
89    neutral_rgb: Vec<[f64; 3]>,
90}
91
92impl ScanContext {
93    /// Build the context on the internal grid.
94    ///
95    /// # Panics
96    ///
97    /// Cannot panic: the grid is a valid constant.
98    #[must_use]
99    pub fn new() -> Self {
100        let grid = Spectrum::uniform(GRID_START_NM, GRID_STEP_NM, GRID_LEN)
101            .expect("the internal grid is a valid constant");
102
103        let dye: [Spectrum; 3] = PAPER_DYES.map(|band| gaussian(&grid, band));
104        // D50: the viewing condition ISO 3664 specifies for reflection prints.
105        let illuminant = Spectrum::new(
106            crate::spectral::GRID_START_NM,
107            crate::spectral::GRID_STEP_NM,
108            D50_SPD.to_vec(),
109        )
110        .expect("the D50 table matches the internal grid");
111
112        let cmf: [Spectrum; 3] = std::array::from_fn(|axis| {
113            let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
114            for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
115                let wavelength = GRID_START_NM + GRID_STEP_NM * index as f64;
116                *value = cie1931_xyz(wavelength)[axis].max(0.0);
117            }
118            spectrum
119        });
120
121        let mut context = Self {
122            grid,
123            dye,
124            illuminant,
125            cmf,
126            white_xyz: [1.0; 3],
127            white_rgb: [1.0; 3],
128            neutral_rgb: Vec::new(),
129        };
130
131        context.recompute();
132        context
133    }
134
135    /// Apply the XYZ-to-RGB matrix without normalisation.
136    fn matrix(&self, xyz: [f64; 3]) -> [f64; 3] {
137        let mut rgb = [0.0_f64; 3];
138        for (row, value) in XYZ_TO_SRGB.iter().zip(rgb.iter_mut()) {
139            *value = row[0] * xyz[0] + row[1] * xyz[1] + row[2] * xyz[2];
140        }
141        rgb
142    }
143
144    fn normalised_xyz(&self, density_cmy: [f64; 3]) -> [f64; 3] {
145        let xyz = self.xyz(density_cmy);
146        std::array::from_fn(|axis| xyz[axis] / self.white_xyz[axis].max(1e-12))
147    }
148
149    /// Grey balance, interpolated on the neutral axis.
150    fn balance(&self, rgb: [f64; 3], mean_density: f64) -> [f64; 3] {
151        if self.neutral_rgb.is_empty() {
152            return rgb;
153        }
154        let position = (mean_density / NEUTRAL_MAX_DENSITY * NEUTRAL_STEPS as f64)
155            .clamp(0.0, NEUTRAL_STEPS as f64);
156        let low = position.floor() as usize;
157        let high = (low + 1).min(NEUTRAL_STEPS);
158        let fraction = position - low as f64;
159
160        let neutral: [f64; 3] = std::array::from_fn(|axis| {
161            self.neutral_rgb[low][axis] * (1.0 - fraction) + self.neutral_rgb[high][axis] * fraction
162        });
163        let target = (neutral[0].max(1e-12) * neutral[1].max(1e-12) * neutral[2].max(1e-12)).cbrt();
164        std::array::from_fn(|axis| rgb[axis] * target / neutral[axis].max(1e-12))
165    }
166
167    /// Replace the placeholder image dyes with measured spectra.
168    ///
169    /// Build the context the renderer uses: the paper's dyes are measured.
170    ///
171    /// # Panics
172    ///
173    /// Cannot panic: the tables are compile-time constants on the internal grid.
174    #[must_use]
175    pub fn measured() -> Self {
176        Self::measured_with(&crate::measured::PAPER_DYES)
177    }
178
179    /// As [`Self::measured`], on the dyes of a particular paper.
180    #[must_use]
181    pub fn measured_with(dyes: &[[f64; GRID_LEN]; 3]) -> Self {
182        Self::new().with_dyes(dyes.map(|table| crate::measured::spectrum(&table)))
183    }
184
185    /// White, the neutral-axis table and every derived quantity are recomputed,
186    /// because all three depend on the dyes.
187    #[must_use]
188    pub fn with_dyes(mut self, dye: [Spectrum; 3]) -> Self {
189        self.dye = dye.map(|spectrum| spectrum.resampled(&self.grid));
190        self.recompute();
191        self
192    }
193
194    /// Recompute everything that depends on the dye spectra.
195    fn recompute(&mut self) {
196        self.white_xyz = self.xyz([0.0; 3]);
197        self.white_rgb = self.matrix([1.0; 3]);
198        self.neutral_rgb = (0..=NEUTRAL_STEPS)
199            .map(|index| {
200                let density = NEUTRAL_MAX_DENSITY * index as f64 / NEUTRAL_STEPS as f64;
201                let rgb = self.matrix(self.normalised_xyz([density; 3]));
202                std::array::from_fn(|axis| rgb[axis] / self.white_rgb[axis].max(1e-12))
203            })
204            .collect();
205    }
206
207    /// The wavelength grid.
208    #[must_use]
209    pub fn grid(&self) -> &Spectrum {
210        &self.grid
211    }
212
213    /// The paper's image dyes.
214    #[must_use]
215    pub fn dye(&self) -> &[Spectrum; 3] {
216        &self.dye
217    }
218
219    /// The viewing illuminant.
220    #[must_use]
221    pub fn illuminant(&self) -> &Spectrum {
222        &self.illuminant
223    }
224
225    /// The colour matching functions, one per axis.
226    #[must_use]
227    pub fn cmf(&self) -> &[Spectrum; 3] {
228        &self.cmf
229    }
230
231    /// XYZ of paper white.
232    #[must_use]
233    pub fn white_xyz(&self) -> [f64; 3] {
234        self.white_xyz
235    }
236
237    /// RGB of paper white.
238    #[must_use]
239    pub fn white_rgb(&self) -> [f64; 3] {
240        self.white_rgb
241    }
242
243    /// RGB along the neutral axis, evenly spaced in density from zero to the
244    /// span [`Self::model`] reports as `neutral_max_density`.
245    #[must_use]
246    pub fn neutral_rgb(&self) -> &[[f64; 3]] {
247        &self.neutral_rgb
248    }
249
250    /// The constants this context integrates with, flattened for another backend.
251    ///
252    /// `None` when a table is not on the model's grid, which [`Self::new`] rules
253    /// out but [`Self::with_dyes`] does not have to.
254    #[must_use]
255    pub fn model(&self) -> Option<ScanModel> {
256        let inverse = inverse3(self.analytical_matrix());
257        Some(ScanModel {
258            analytical: inverse.unwrap_or([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
259            clamped: inverse.is_some(),
260            dye: tables(&self.dye)?,
261            illuminant: table(&self.illuminant)?,
262            cmf: tables(&self.cmf)?,
263            matrix: XYZ_TO_SRGB,
264            white_xyz: self.white_xyz,
265            white_rgb: self.white_rgb,
266            neutral: self.neutral_rgb.as_slice().try_into().ok()?,
267            neutral_max_density: NEUTRAL_MAX_DENSITY,
268            base_density: PAPER_BASE_DENSITY,
269        })
270    }
271
272    /// Solve for the per-dye analytical densities behind a set of status densities.
273    ///
274    /// The characteristic curves report **status** densities: each channel is
275    /// measured through a filter and contains contributions from all three dyes.
276    /// The dye curves describe **analytical** absorption: one shape per dye,
277    /// peak-normalised. Feeding status densities straight into the dye shapes
278    /// double-counts the overlap, which is why a neutral print went black.
279    ///
280    /// The mixing matrix samples the dye curves at the status filter peaks
281    /// (650/550/450 nm). Real status filters are broad; sampling their peaks is
282    /// the documented approximation.
283    fn analytical_matrix(&self) -> [[f64; 3]; 3] {
284        let probes = [650.0, 550.0, 450.0];
285        let mut matrix = [[0.0_f64; 3]; 3];
286        for (row, wavelength) in probes.iter().enumerate() {
287            for (column, dye) in self.dye.iter().enumerate() {
288                matrix[row][column] = dye.interpolate(*wavelength);
289            }
290        }
291        matrix
292    }
293
294    fn analytical(&self, status: [f64; 3]) -> [f64; 3] {
295        solve3(self.analytical_matrix(), status)
296            .map(|values| values.map(|value| value.max(0.0)))
297            .unwrap_or(status)
298    }
299
300    fn reflectance(&self, status_density: [f64; 3]) -> Spectrum {
301        let density_cmy = self.analytical(status_density);
302        let step = self.grid.step_nm();
303        let mut reflectance = self.grid.clone();
304        for (index, value) in reflectance.values_mut().iter_mut().enumerate() {
305            let mut density = PAPER_BASE_DENSITY;
306            for (value, dye) in density_cmy.iter().zip(&self.dye) {
307                density += value * dye.values()[index];
308            }
309            *value = (-density * std::f64::consts::LOG2_10).exp2();
310        }
311        let _ = step;
312        reflectance
313    }
314
315    fn xyz(&self, density_cmy: [f64; 3]) -> [f64; 3] {
316        let reflectance = self.reflectance(density_cmy);
317        let step = self.grid.step_nm();
318        let mut xyz = [0.0_f64; 3];
319        for (index, reflectance_value) in reflectance.values().iter().enumerate() {
320            let light = reflectance_value * self.illuminant.values()[index];
321            for (value, cmf) in xyz.iter_mut().zip(&self.cmf) {
322                *value += light * cmf.values()[index];
323            }
324        }
325        for value in &mut xyz {
326            *value *= step;
327        }
328        xyz
329    }
330
331    /// Linear-light RGB for a set of print densities.
332    ///
333    /// White is normalised to 1.0 per channel and the result is clamped to
334    /// `[0, 1]`; the paper cannot reflect more than it receives.
335    #[must_use]
336    pub fn scan(&self, density_cmy: [f64; 3]) -> [f64; 3] {
337        let rgb = self.matrix(self.normalised_xyz(density_cmy));
338        let white_relative: [f64; 3] =
339            std::array::from_fn(|axis| rgb[axis] / self.white_rgb[axis].max(1e-12));
340        let mean = (density_cmy[0] + density_cmy[1] + density_cmy[2]) / 3.0;
341        let balanced = self.balance(white_relative, mean);
342        balanced.map(|value| value.clamp(0.0, 1.0))
343    }
344}
345
346impl Default for ScanContext {
347    fn default() -> Self {
348        Self::new()
349    }
350}
351
352/// Gaussian elimination with partial pivoting for the 3x3 unmixing solve.
353pub(crate) fn solve3(mut matrix: [[f64; 3]; 3], mut rhs: [f64; 3]) -> Option<[f64; 3]> {
354    for column in 0..3 {
355        let pivot = (column..3)
356            .max_by(|&a, &b| matrix[a][column].abs().total_cmp(&matrix[b][column].abs()))?;
357        if matrix[pivot][column].abs() < 1e-9 {
358            return None;
359        }
360        matrix.swap(column, pivot);
361        rhs.swap(column, pivot);
362        let pivot_row = matrix[column];
363        let pivot_value = pivot_row[column];
364        for row in (column + 1)..3 {
365            let factor = matrix[row][column] / pivot_value;
366            for (cell, value) in pivot_row.iter().enumerate().skip(column) {
367                matrix[row][cell] -= factor * value;
368            }
369            rhs[row] -= factor * rhs[column];
370        }
371    }
372    let mut solution = [0.0; 3];
373    for row in (0..3).rev() {
374        let mut sum = rhs[row];
375        for (column, value) in solution.iter().enumerate().skip(row + 1) {
376            sum -= matrix[row][column] * value;
377        }
378        solution[row] = sum / matrix[row][row];
379    }
380    Some(solution)
381}
382
383fn gaussian(grid: &Spectrum, band: Band) -> Spectrum {
384    let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
385    for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
386        let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
387        let z = (wavelength - band.peak_nm) / band.width_nm;
388        *value = (-0.5 * z * z).exp();
389    }
390    spectrum
391}
392
393#[cfg(test)]
394mod tests {
395    use super::*;
396
397    #[test]
398    fn paper_white_maps_to_one() {
399        let context = ScanContext::new();
400        let rgb = context.scan([0.0; 3]);
401        for channel in rgb {
402            assert!((channel - 1.0).abs() < 0.01, "white scans at {channel}");
403        }
404    }
405
406    #[test]
407    fn measured_dyes_replace_the_placeholders() {
408        let baseline = ScanContext::new().scan([1.0, 0.6, 0.3]);
409        let grid = ScanContext::new().grid().clone();
410        let narrow: [Spectrum; 3] = [450.0, 550.0, 650.0].map(|peak| {
411            let mut spectrum = Spectrum::filled(grid.clone(), 0.0);
412            for (index, value) in spectrum.values_mut().iter_mut().enumerate() {
413                let wavelength = grid.start_nm() + grid.step_nm() * index as f64;
414                *value = (-0.5 * ((wavelength - peak) / 12.0).powi(2)).exp();
415            }
416            spectrum
417        });
418        let replaced = ScanContext::new().with_dyes(narrow).scan([1.0, 0.6, 0.3]);
419        let difference: f64 = baseline
420            .iter()
421            .zip(&replaced)
422            .map(|(a, b)| (a - b).abs())
423            .sum();
424        assert!(difference > 1e-3, "replacing the dyes changed nothing");
425    }
426
427    #[test]
428    fn neutral_densities_scan_neutral() {
429        let context = ScanContext::new();
430        for step in 1..=10 {
431            let density = 0.15 * f64::from(step);
432            let rgb = context.scan([density; 3]);
433            let spread = rgb.iter().copied().fold(f64::NEG_INFINITY, f64::max)
434                - rgb.iter().copied().fold(f64::INFINITY, f64::min);
435            assert!(spread < 0.02, "grey {density} drifts by {spread}: {rgb:?}");
436        }
437    }
438
439    #[test]
440    fn more_density_means_darker() {
441        let context = ScanContext::new();
442        let light = context.scan([0.2; 3]);
443        let dark = context.scan([1.5; 3]);
444        for channel in 0..3 {
445            assert!(dark[channel] < light[channel]);
446        }
447    }
448}