Skip to main content

qualia_core_db/q42/field_spectrum/
conversion.rs

1use super::*;
2/// Exact SI defining constants, represented in f64 (normal rounding applies).
3pub const VACUUM_SPEED_OF_LIGHT_M_PER_S: f64 = 299_792_458.0;
4pub const PLANCK_JOULE_SECOND: f64 = 6.626_070_15e-34;
5pub const ELECTRON_VOLT_JOULE: f64 = 1.602_176_634e-19;
6const HC: f64 = PLANCK_JOULE_SECOND * VACUUM_SPEED_OF_LIGHT_M_PER_S;
7pub(super) fn positive(value: f64) -> Result<(), Error> {
8    if !value.is_finite() {
9        return Err(Error::NonFinite);
10    }
11    if value <= 0.0 {
12        return Err(Error::NonPositive);
13    }
14    Ok(())
15}
16fn checked_positive(value: f64) -> Result<f64, Error> {
17    if !value.is_finite() || value <= 0.0 {
18        Err(Error::Unrepresentable)
19    } else {
20        Ok(value)
21    }
22}
23fn checked_density(value: f64) -> Result<(), Error> {
24    if !value.is_finite() {
25        return Err(Error::NonFinite);
26    }
27    if value < 0.0 {
28        return Err(Error::NonPositive);
29    }
30    Ok(())
31}
32/// Positive carrier only; static/aperiodic fields must retain absence instead.
33pub fn frequency_hz_to_vacuum_wavelength_m(frequency_hz: f64) -> Result<f64, Error> {
34    positive(frequency_hz)?;
35    checked_positive(VACUUM_SPEED_OF_LIGHT_M_PER_S / frequency_hz)
36}
37pub fn vacuum_wavelength_m_to_frequency_hz(wavelength_m: f64) -> Result<f64, Error> {
38    positive(wavelength_m)?;
39    checked_positive(VACUUM_SPEED_OF_LIGHT_M_PER_S / wavelength_m)
40}
41pub fn frequency_hz_to_photon_energy_j(frequency_hz: f64) -> Result<f64, Error> {
42    positive(frequency_hz)?;
43    checked_positive(PLANCK_JOULE_SECOND * frequency_hz)
44}
45pub fn frequency_hz_to_photon_energy_ev(frequency_hz: f64) -> Result<f64, Error> {
46    positive(frequency_hz)?;
47    checked_positive((PLANCK_JOULE_SECOND / ELECTRON_VOLT_JOULE) * frequency_hz)
48}
49pub fn vacuum_wavelength_m_to_photon_energy_j(wavelength_m: f64) -> Result<f64, Error> {
50    positive(wavelength_m)?;
51    checked_positive(HC / wavelength_m)
52}
53pub fn photon_energy_j_to_frequency_hz(energy_j: f64) -> Result<f64, Error> {
54    positive(energy_j)?;
55    checked_positive(energy_j / PLANCK_JOULE_SECOND)
56}
57pub fn photon_energy_j_to_vacuum_wavelength_m(energy_j: f64) -> Result<f64, Error> {
58    positive(energy_j)?;
59    checked_positive(HC / energy_j)
60}
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub enum AxisOrder {
63    Preserved,
64    Reversed,
65}
66impl AxisOrder {
67    /// Explicit permutation for derived ascending coordinates AND matching data.
68    pub fn source_index(self, target_index: u64, count: u64) -> Result<u64, Error> {
69        if target_index >= count {
70            return Err(Error::Index);
71        }
72        Ok(match self {
73            Self::Preserved => target_index,
74            Self::Reversed => count - 1 - target_index,
75        })
76    }
77}
78/// Nanometres are explicit DERIVED density units; schema132 coordinates stay SI.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum DensityCoordinate {
81    Hertz,
82    VacuumMetre,
83    VacuumNanometre,
84}
85fn coordinate(
86    value: f64,
87    source: DensityCoordinate,
88    target: DensityCoordinate,
89) -> Result<f64, Error> {
90    positive(value)?;
91    use DensityCoordinate::*;
92    match (source, target) {
93        (a, b) if a == b => Ok(value),
94        (Hertz, VacuumMetre) => frequency_hz_to_vacuum_wavelength_m(value),
95        (Hertz, VacuumNanometre) => {
96            checked_positive(frequency_hz_to_vacuum_wavelength_m(value)? * 1e9)
97        }
98        (VacuumMetre, Hertz) => vacuum_wavelength_m_to_frequency_hz(value),
99        (VacuumNanometre, Hertz) => checked_positive((VACUUM_SPEED_OF_LIGHT_M_PER_S * 1e9) / value),
100        (VacuumMetre, VacuumNanometre) => checked_positive(value * 1e9),
101        (VacuumNanometre, VacuumMetre) => checked_positive(value * 1e-9),
102        _ => unreachable!(),
103    }
104}
105fn order(source: DensityCoordinate, target: DensityCoordinate) -> AxisOrder {
106    if (source == DensityCoordinate::Hertz) == (target == DensityCoordinate::Hertz) {
107        AxisOrder::Preserved
108    } else {
109        AxisOrder::Reversed
110    }
111}
112#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct DensityJacobian {
114    pub factor: f64,
115    pub order: AxisOrder,
116}
117impl DensityJacobian {
118    /// Unsigned physical radiance/irradiance only. No clipping or normalization.
119    pub fn apply(self, density: f64) -> Result<f64, Error> {
120        positive(self.factor)?;
121        scale(density, self.factor)
122    }
123}
124/// |d(source coordinate)/d(target coordinate)|, using source units as declared.
125/// This helper is exclusively for point densities. Bin averages must preserve
126/// their integral and divide by the NEW bin width, not reuse a point derivative.
127/// Reflectance and bin integrals are not densities and reject this operation.
128pub fn density_coordinate_jacobian(
129    quantity: Quantity,
130    semantics: SampleSemantics,
131    source: DensityCoordinate,
132    target: DensityCoordinate,
133    at_source: f64,
134) -> Result<DensityJacobian, Error> {
135    if !quantity.is_density() || semantics == SampleSemantics::BinIntegral {
136        return Err(Error::NotDensity);
137    }
138    if semantics == SampleSemantics::BinAverage {
139        return Err(Error::BinAverageNeedsIntegral);
140    }
141    let target_value = coordinate(at_source, source, target)?;
142    let factor = if source == target {
143        1.0
144    } else {
145        checked_positive(at_source / target_value)?
146    };
147    Ok(DensityJacobian {
148        factor,
149        order: order(source, target),
150    })
151}
152fn scale(density: f64, factor: f64) -> Result<f64, Error> {
153    checked_density(density)?;
154    let result = density * factor;
155    if !result.is_finite() || (density != 0.0 && result == 0.0) {
156        return Err(Error::Unrepresentable);
157    }
158    Ok(result)
159}
160/// Explicit per-metre to per-nanometre derived values (factor1e-9).
161/// Linear unit scaling also applies to density bin averages, never to integrals.
162pub fn density_per_metre_to_per_nanometre(
163    quantity: Quantity,
164    semantics: SampleSemantics,
165    value: f64,
166) -> Result<f64, Error> {
167    if !quantity.is_density() || semantics == SampleSemantics::BinIntegral {
168        return Err(Error::NotDensity);
169    }
170    scale(value, 1e-9)
171}
172pub fn density_per_nanometre_to_per_metre(
173    quantity: Quantity,
174    semantics: SampleSemantics,
175    value: f64,
176) -> Result<f64, Error> {
177    if !quantity.is_density() || semantics == SampleSemantics::BinIntegral {
178        return Err(Error::NotDensity);
179    }
180    scale(value, 1e9)
181}
182/// A derived ascending bin with explicit source-to-target order. Original edges
183/// and source values remain untouched. Integral units retain radiance/irradiance.
184#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct ConvertedBin {
186    pub lower: f64,
187    pub upper: f64,
188    pub average: f64,
189    pub integral: f64,
190    pub order: AxisOrder,
191}
192pub fn convert_bin_average(
193    quantity: Quantity,
194    source: DensityCoordinate,
195    target: DensityCoordinate,
196    lower: f64,
197    upper: f64,
198    average: f64,
199) -> Result<ConvertedBin, Error> {
200    if !quantity.is_density() {
201        return Err(Error::NotDensity);
202    }
203    positive(lower)?;
204    positive(upper)?;
205    if lower >= upper {
206        return Err(Error::Coordinate);
207    }
208    let width = checked_positive(upper - lower)?;
209    let integral = scale(average, width)?;
210    let first = coordinate(lower, source, target)?;
211    let last = coordinate(upper, source, target)?;
212    let (lower, upper) = if first < last {
213        (first, last)
214    } else {
215        (last, first)
216    };
217    let target_width = checked_positive(upper - lower)?;
218    let average = if integral == 0.0 {
219        integral
220    } else {
221        checked_positive(integral / target_width)?
222    };
223    Ok(ConvertedBin {
224        lower,
225        upper,
226        average,
227        integral,
228        order: order(source, target),
229    })
230}