Skip to main content

qualia_core_db/q42/field_spectrum/
axis.rs

1use super::*;
2const fn r(key: u16, type_tag: u8, count: Option<u32>, required: bool) -> FieldRule {
3    FieldRule {
4        key,
5        type_tag,
6        count,
7        required,
8    }
9}
10const RULES: &[FieldRule] = &[
11    r(1, 6, None, true),
12    r(2, 6, None, true),
13    r(3, 6, None, true),
14    r(4, 6, None, true),
15    r(5, 5, None, true),
16    r(6, 6, None, true),
17    r(7, 8, Some(1), false),
18    r(8, 6, None, true),
19    r(9, 5, Some(2), false),
20];
21/// A family registry can expose these rules, then call admit_axis with its true N.
22pub fn schema_rules() -> &'static [FieldRule] {
23    RULES
24}
25/// Must resolve the exact nonzero metadata ID to a SUPPORTED typed response
26/// schema/profile, declared quantity/unit and explicit normalization. Unknown is
27/// never a flat response. This is a registry hook, not a default response model.
28pub trait ResponseValidator {
29    fn validate(&self, id: u32, budget: &mut WorkBudget) -> Result<(), Error>;
30}
31#[derive(Clone, Copy, Debug, Default)]
32pub struct NoResponse;
33impl ResponseValidator for NoResponse {
34    fn validate(&self, _id: u32, _budget: &mut WorkBudget) -> Result<(), Error> {
35        Err(Error::UnsupportedResponse)
36    }
37}
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub enum SigmaInterpretation {
40    None,
41    LegacyDisplay400700nm,
42    LegacyEtalonDisplay380750nm,
43    LogFrequency { minimum_hz: f64, maximum_hz: f64 },
44}
45/// Borrowed physical coordinates; sigma labels do not replace or infer these data.
46#[derive(Clone, Copy, Debug)]
47pub struct AxisView<'a> {
48    block: Block<'a>,
49    coordinates: &'a [u8],
50    kind: AxisKind,
51    semantics: SampleSemantics,
52    quantity: Quantity,
53    sigma: SigmaInterpretation,
54    response_metadata_id: Option<u32>,
55    samples: u64,
56    remaining_work: u64,
57}
58impl<'a> AxisView<'a> {
59    pub fn kind(self) -> AxisKind {
60        self.kind
61    }
62    pub fn semantics(self) -> SampleSemantics {
63        self.semantics
64    }
65    pub fn quantity(self) -> Quantity {
66        self.quantity
67    }
68    pub fn sigma(self) -> SigmaInterpretation {
69        self.sigma
70    }
71    pub fn response_metadata_id(self) -> Option<u32> {
72        self.response_metadata_id
73    }
74    pub fn source_block(self) -> Block<'a> {
75        self.block
76    }
77    pub fn sample_count(self) -> u64 {
78        self.samples
79    }
80    pub fn coordinate_count(self) -> u64 {
81        (self.coordinates.len() / 8) as u64
82    }
83    pub fn coordinates(self) -> Coordinates<'a> {
84        Coordinates {
85            bytes: self.coordinates,
86        }
87    }
88    pub fn coordinate(self, index: u64) -> Result<f64, Error> {
89        if index >= self.coordinate_count() {
90            return Err(Error::Index);
91        }
92        Ok(f64_at(self.coordinates, index as usize * 8))
93    }
94    pub fn remaining_work(self) -> u64 {
95        self.remaining_work
96    }
97    /// Coordinate transforms reverse frequency/wavelength order. This map is
98    /// explicit; originals are never reordered, resampled or overwritten.
99    pub fn conversion_order(self, target: AxisKind) -> AxisOrder {
100        if self.kind == target {
101            AxisOrder::Preserved
102        } else {
103            AxisOrder::Reversed
104        }
105    }
106    pub fn source_coordinate_index_for_ascending(
107        self,
108        target: AxisKind,
109        target_index: u64,
110    ) -> Result<u64, Error> {
111        self.conversion_order(target)
112            .source_index(target_index, self.coordinate_count())
113    }
114    /// Sample values have N elements even when bin edges have N+1.
115    pub fn source_sample_index_for_ascending(
116        self,
117        target: AxisKind,
118        target_index: u64,
119    ) -> Result<u64, Error> {
120        self.conversion_order(target)
121            .source_index(target_index, self.sample_count())
122    }
123    pub fn ascending_derived_coordinate(self, target: AxisKind, index: u64) -> Result<f64, Error> {
124        let source = self.source_coordinate_index_for_ascending(target, index)?;
125        let value = self.coordinate(source)?;
126        match (self.kind, target) {
127            (AxisKind::FrequencyHz, AxisKind::VacuumWavelengthMetres) => {
128                frequency_hz_to_vacuum_wavelength_m(value)
129            }
130            (AxisKind::VacuumWavelengthMetres, AxisKind::FrequencyHz) => {
131                vacuum_wavelength_m_to_frequency_hz(value)
132            }
133            _ => Ok(value),
134        }
135    }
136    /// Legacy display sigma intentionally has no physical frequency conversion.
137    pub fn log_frequency_sigma(self, frequency_hz: f64) -> Result<f64, Error> {
138        if let SigmaInterpretation::LogFrequency {
139            minimum_hz,
140            maximum_hz,
141        } = self.sigma
142        {
143            positive(frequency_hz)?;
144            if frequency_hz < minimum_hz || frequency_hz > maximum_hz {
145                return Err(Error::Sigma);
146            }
147            if frequency_hz == minimum_hz {
148                return Ok(0.0);
149            }
150            if frequency_hz == maximum_hz {
151                return Ok(1.0);
152            }
153            let value = log_ratio(frequency_hz, minimum_hz) / log_ratio(maximum_hz, minimum_hz);
154            if !value.is_finite() || !(0.0..=1.0).contains(&value) {
155                return Err(Error::Sigma);
156            }
157            Ok(value)
158        } else {
159            Err(Error::Sigma)
160        }
161    }
162}
163#[derive(Clone, Debug)]
164pub struct Coordinates<'a> {
165    bytes: &'a [u8],
166}
167impl Iterator for Coordinates<'_> {
168    type Item = f64;
169    fn next(&mut self) -> Option<f64> {
170        if self.bytes.is_empty() {
171            return None;
172        }
173        let value = f64_at(self.bytes, 0);
174        self.bytes = &self.bytes[8..];
175        Some(value)
176    }
177}
178fn log_ratio(high: f64, low: f64) -> f64 {
179    let ratio = high / low;
180    if ratio <= 2.0 {
181        ((high - low) / low).ln_1p()
182    } else {
183        high.ln() - low.ln()
184    }
185}
186pub fn admit_axis<'a>(
187    block: Block<'a>,
188    expected_samples: u64,
189    limits: Limits,
190    response: &impl ResponseValidator,
191) -> Result<AxisView<'a>, Error> {
192    if block.schema_type() != SCHEMA_ID || block.revision() != 1 {
193        return Err(Error::Schema);
194    }
195    let mut budget = WorkBudget {
196        remaining: limits.work,
197    };
198    budget.charge(block.raw_bytes().len() as u64)?;
199    budget.charge(
200        (block.fields().count() as u64)
201            .checked_mul(32)
202            .ok_or(Error::Overflow)?,
203    )?;
204    validate_fields(block, RULES).map_err(Error::Shared)?;
205    if expected_samples == 0 {
206        return Err(Error::Count);
207    }
208    if expected_samples > limits.samples {
209        return Err(Error::Limit);
210    }
211    let kind = match string(required(block, 1)?)? {
212        "frequency_hz" => AxisKind::FrequencyHz,
213        "vacuum_wavelength_m" => AxisKind::VacuumWavelengthMetres,
214        _ => return Err(Error::Axis),
215    };
216    let semantics = match string(required(block, 2)?)? {
217        "point_density" => SampleSemantics::PointDensity,
218        "bin_integral" => SampleSemantics::BinIntegral,
219        "bin_average" => SampleSemantics::BinAverage,
220        _ => return Err(Error::Semantics),
221    };
222    let quantity_name = string(required(block, 3)?)?;
223    let quantity = [
224        Quantity::SpectralRadiance,
225        Quantity::SpectralIrradiance,
226        Quantity::BinIntegratedRadiance,
227        Quantity::BinIntegratedIrradiance,
228        Quantity::DimensionlessReflectance,
229    ]
230    .into_iter()
231    .find(|q| q.name() == quantity_name)
232    .ok_or(Error::QuantityUnit)?;
233    if string(required(block, 4)?)? != quantity.unit(kind) {
234        return Err(Error::QuantityUnit);
235    }
236    match (semantics, quantity) {
237        (
238            SampleSemantics::BinIntegral,
239            Quantity::BinIntegratedRadiance | Quantity::BinIntegratedIrradiance,
240        ) => {}
241        (
242            SampleSemantics::PointDensity | SampleSemantics::BinAverage,
243            Quantity::SpectralRadiance
244            | Quantity::SpectralIrradiance
245            | Quantity::DimensionlessReflectance,
246        ) => {}
247        _ => return Err(Error::QuantityUnit),
248    }
249    if string(required(block, 6)?)? != "explicit" {
250        return Err(Error::Spacing);
251    }
252    let coordinates = required(block, 5)?;
253    let expected = if semantics == SampleSemantics::PointDensity {
254        expected_samples
255    } else {
256        expected_samples.checked_add(1).ok_or(Error::Overflow)?
257    };
258    if u64::from(coordinates.element_count()) != expected {
259        return Err(Error::Count);
260    }
261    let sigma = match string(required(block, 8)?)? {
262        "none" => SigmaInterpretation::None,
263        "legacy_display_400_700nm" => SigmaInterpretation::LegacyDisplay400700nm,
264        "legacy_etalon_display_380_750nm" => SigmaInterpretation::LegacyEtalonDisplay380750nm,
265        "log_frequency_v1" => {
266            let f = required(block, 9)?;
267            if f.flags() & 1 == 0 {
268                return Err(Error::Shared(
269                    super::super::field_semantics::Error::RequiredCritical,
270                ));
271            }
272            let lo = f64_at(f.value(), 0);
273            let hi = f64_at(f.value(), 8);
274            positive(lo)?;
275            positive(hi)?;
276            if lo >= hi {
277                return Err(Error::Sigma);
278            }
279            SigmaInterpretation::LogFrequency {
280                minimum_hz: lo,
281                maximum_hz: hi,
282            }
283        }
284        _ => return Err(Error::Sigma),
285    };
286    if !matches!(sigma, SigmaInterpretation::LogFrequency { .. }) && field(block, 9).is_some() {
287        return Err(Error::Sigma);
288    }
289    let mut prior = 0.0;
290    for value in coordinates.value().chunks_exact(8).map(|b| f64_at(b, 0)) {
291        budget.charge(1)?;
292        positive(value)?;
293        if value <= prior {
294            return Err(Error::Coordinate);
295        }
296        prior = value;
297        if let SigmaInterpretation::LogFrequency {
298            minimum_hz,
299            maximum_hz,
300        } = sigma
301        {
302            let f = if kind == AxisKind::FrequencyHz {
303                value
304            } else {
305                vacuum_wavelength_m_to_frequency_hz(value)?
306            };
307            if f < minimum_hz || f > maximum_hz {
308                return Err(Error::Sigma);
309            }
310        }
311    }
312    let response_metadata_id = if let Some(f) = field(block, 7) {
313        let id = u32::from_le_bytes(f.value().try_into().unwrap());
314        if id == 0 {
315            return Err(Error::UnsupportedResponse);
316        }
317        response.validate(id, &mut budget)?;
318        Some(id)
319    } else {
320        None
321    };
322    Ok(AxisView {
323        block,
324        coordinates: coordinates.value(),
325        kind,
326        semantics,
327        quantity,
328        sigma,
329        response_metadata_id,
330        samples: expected_samples,
331        remaining_work: budget.remaining(),
332    })
333}