Skip to main content

qualia_core_db/q42/emf_profiles/
records.rs

1use super::*;
2#[derive(Clone, Copy, Debug)]
3pub struct FieldRecord<'a> {
4    pub(super) bytes: &'a [u8],
5}
6impl FieldRecord<'_> {
7    pub fn electric_v_per_m(self) -> [f64; 3] {
8        triple(self.bytes, 0)
9    }
10    pub fn magnetic_tesla(self) -> [f64; 3] {
11        triple(self.bytes, 24)
12    }
13    /// Local metres in ProfileChunk::frame_id(); no transform is applied.
14    pub fn position_m(self) -> [f64; 3] {
15        triple(self.bytes, 48)
16    }
17    pub fn tick(self) -> i64 {
18        u64_at(self.bytes, 72) as i64
19    }
20    pub fn carrier_hz(self) -> Option<f64> {
21        if u32_at(self.bytes, 120) & 1 != 0 {
22            Some(f64_at(self.bytes, 80))
23        } else {
24            None
25        }
26    }
27    pub fn coherence_phase_rad(self) -> Option<f64> {
28        if u32_at(self.bytes, 120) & 2 != 0 {
29            Some(f64_at(self.bytes, 88))
30        } else {
31            None
32        }
33    }
34    /// Stored observation only; no constitutive formula is inferred.
35    pub fn stored_poynting_w_per_m2(self) -> Option<[f64; 3]> {
36        if u32_at(self.bytes, 120) & 4 != 0 {
37            Some(triple(self.bytes, 96))
38        } else {
39            None
40        }
41    }
42    pub fn confidence(self) -> Option<f32> {
43        if u32_at(self.bytes, 120) & 8 != 0 {
44            Some(f32::from_bits(u32_at(self.bytes, 124)))
45        } else {
46            None
47        }
48    }
49}
50#[derive(Clone, Copy, Debug)]
51pub struct RayRecord<'a> {
52    pub(super) bytes: &'a [u8],
53}
54impl RayRecord<'_> {
55    /// Local metres in ProfileChunk::frame_id(); no transform is applied.
56    pub fn position_m(self) -> [f64; 3] {
57        triple(self.bytes, 0)
58    }
59    pub fn direction(self) -> [f64; 3] {
60        triple(self.bytes, 24)
61    }
62    /// Time-averaged I/Q/U/V in ProfileChunk::units(), schema135 convention.
63    pub fn stokes(self) -> [f64; 4] {
64        [
65            f64_at(self.bytes, 48),
66            f64_at(self.bytes, 56),
67            f64_at(self.bytes, 64),
68            f64_at(self.bytes, 72),
69        ]
70    }
71    pub fn carrier_hz(self) -> f64 {
72        f64_at(self.bytes, 80)
73    }
74    pub fn bandwidth_hz(self) -> f64 {
75        f64_at(self.bytes, 88)
76    }
77    pub fn geometric_path_m(self) -> f64 {
78        f64_at(self.bytes, 96)
79    }
80    pub fn divergence_rad(self) -> f64 {
81        f64_at(self.bytes, 112)
82    }
83    pub fn phase_rad(self) -> Option<f64> {
84        if u32_at(self.bytes, 124) & 1 != 0 {
85            Some(f64_at(self.bytes, 104))
86        } else {
87            None
88        }
89    }
90    pub fn material_entry(self) -> u32 {
91        u32_at(self.bytes, 120)
92    }
93}
94#[derive(Clone, Copy, Debug)]
95pub struct SpectrumRecord<'a> {
96    pub(super) bytes: &'a [u8],
97    pub(super) bins: u32,
98}
99impl<'a> SpectrumRecord<'a> {
100    /// Local metres in ProfileChunk::frame_id(); no transform is applied.
101    pub fn position_m(self) -> [f64; 3] {
102        triple(self.bytes, 0)
103    }
104    pub fn tick(self) -> i64 {
105        u64_at(self.bytes, 24) as i64
106    }
107    pub fn axis_metadata_id(self) -> u32 {
108        u32_at(self.bytes, 36)
109    }
110    pub fn material_entry(self) -> u32 {
111        u32_at(self.bytes, 32)
112    }
113    pub fn temperature_kelvin(self) -> Option<f64> {
114        if u32_at(self.bytes, 48) & 1 != 0 {
115            Some(f64_at(self.bytes, 40))
116        } else {
117            None
118        }
119    }
120    pub fn values(self) -> SpectrumValues<'a> {
121        SpectrumValues {
122            bytes: &self.bytes[64..64 + self.bins as usize * 8],
123        }
124    }
125}
126#[derive(Clone, Debug)]
127pub struct SpectrumValues<'a> {
128    bytes: &'a [u8],
129}
130impl Iterator for SpectrumValues<'_> {
131    type Item = f64;
132    fn next(&mut self) -> Option<f64> {
133        if self.bytes.is_empty() {
134            return None;
135        }
136        let v = f64_at(self.bytes, 0);
137        self.bytes = &self.bytes[8..];
138        Some(v)
139    }
140}
141fn check_material_entry(
142    context: &Context<'_, '_>,
143    binding: &bindings::Binding<'_>,
144    material_entry: u32,
145) -> Result<(), Error> {
146    if material_entry == 0 {
147        return Ok(());
148    }
149    let Some(mat_id) = binding.material_id else {
150        return Err(Error::UnsupportedProfile);
151    };
152    let mat_block = context.require_schema(mat_id, 105).map_err(Error::Shared)?;
153    if !schemas::material_binding_contains(mat_block, u64::from(material_entry))? {
154        return Err(Error::Descriptor);
155    }
156    Ok(())
157}
158
159pub(super) fn validate(
160    bytes: &[u8],
161    context: &Context<'_, '_>,
162    binding: &bindings::Binding<'_>,
163    ext: Block<'_>,
164    yee_policy: yee::YeeParsePolicy,
165    valid: bool,
166    tick: i64,
167) -> Result<(), Error> {
168    match binding.canonical_mode {
169        0x0100 => field_record(bytes, valid, tick),
170        0x0101 => ray_record(bytes, context, binding, valid),
171        0x0102 => yee_record(bytes, context, binding, yee_policy, valid),
172        0x0103 => spectrum_record(
173            bytes,
174            context,
175            binding,
176            valid,
177            tick,
178            binding.axis_id,
179            binding.bins,
180            binding
181                .axis
182                .map(|axis| axis.quantity())
183                .ok_or(Error::Descriptor)?,
184        ),
185        0x0104 => mueller_record(bytes, context, binding, valid),
186        0x0105 => iq_record(bytes, context, binding, ext, valid, tick),
187        0x0106 => dose_record(bytes, context, binding, valid, tick),
188        0x0107 => biofield_record(bytes, context, binding, valid, tick),
189        _ => Err(Error::UnsupportedProfile),
190    }
191}
192pub(super) fn field_record(bytes: &[u8], valid: bool, tick: i64) -> Result<(), Error> {
193    if u64_at(bytes, 72) as i64 != tick {
194        return Err(Error::Time);
195    }
196    if !valid {
197        zeros(&bytes[..72])?;
198        zeros(&bytes[80..])?;
199        return Ok(());
200    }
201    finite(bytes, 0, 72)?;
202    finite(bytes, 80, 120)?;
203    let flags = u32_at(bytes, 120);
204    if flags & !15 != 0 {
205        return Err(Error::Flags);
206    }
207    if flags & 1 != 0 {
208        if f64_at(bytes, 80) <= 0.0 {
209            return Err(Error::Value);
210        }
211    } else {
212        zeros(&bytes[80..88])?;
213    }
214    if flags & 2 != 0 {
215        if flags & 1 == 0 {
216            return Err(Error::UnsupportedProfile);
217        }
218    } else {
219        zeros(&bytes[88..96])?;
220    }
221    if flags & 4 == 0 {
222        zeros(&bytes[96..120])?;
223    }
224    if flags & 8 != 0 {
225        let c = f32::from_bits(u32_at(bytes, 124));
226        if !c.is_finite() {
227            return Err(Error::NonFinite);
228        }
229        if !(0.0..=1.0).contains(&c) {
230            return Err(Error::Value);
231        }
232    } else {
233        zeros(&bytes[124..128])?;
234    }
235    Ok(())
236}
237fn ray_record(
238    bytes: &[u8],
239    context: &Context<'_, '_>,
240    binding: &bindings::Binding<'_>,
241    valid: bool,
242) -> Result<(), Error> {
243    if !valid {
244        zeros(bytes)?;
245        return Ok(());
246    }
247    let material_entry = u32_at(bytes, 120);
248    check_material_entry(context, binding, material_entry)?;
249    let flags = u32_at(bytes, 124);
250    if flags & !1 != 0 {
251        return Err(Error::Flags);
252    }
253    finite(bytes, 0, 120)?;
254    if flags & 1 != 0 {
255        if binding.calibration_id.is_none() && binding.evidence_id.is_none() {
256            return Err(Error::UnsupportedProfile);
257        }
258    } else {
259        zeros(&bytes[104..112])?;
260    }
261    let d = triple(bytes, 24);
262    let norm = (d[0] * d[0] + d[1] * d[1]) + d[2] * d[2];
263    if (norm - 1.0).abs() > 1e-12 {
264        return Err(Error::Value);
265    }
266    let i = f64_at(bytes, 48);
267    let magnitude = f64_at(bytes, 56)
268        .hypot(f64_at(bytes, 64))
269        .hypot(f64_at(bytes, 72));
270    if i < 0.0
271        || !magnitude.is_finite()
272        || (magnitude > i && (magnitude - i) / magnitude > 64.0 * f64::EPSILON)
273    {
274        return Err(Error::Value);
275    }
276    if f64_at(bytes, 80) <= 0.0
277        || f64_at(bytes, 88) < 0.0
278        || f64_at(bytes, 96) < 0.0
279        || !(0.0..std::f64::consts::FRAC_PI_2).contains(&f64_at(bytes, 112))
280    {
281        return Err(Error::Value);
282    }
283    Ok(())
284}
285fn spectrum_record(
286    bytes: &[u8],
287    context: &Context<'_, '_>,
288    binding: &bindings::Binding<'_>,
289    valid: bool,
290    tick: i64,
291    axis_id: u32,
292    bins: u32,
293    quantity: spectrum::Quantity,
294) -> Result<(), Error> {
295    if u64_at(bytes, 24) as i64 != tick {
296        return Err(Error::Time);
297    }
298    if u32_at(bytes, 36) != axis_id {
299        return Err(Error::Descriptor);
300    }
301    let flags = u32_at(bytes, 48);
302    if flags & !1 != 0 {
303        return Err(Error::Flags);
304    }
305    zeros(&bytes[52..64])?;
306    let end = 64 + bins as usize * 8;
307    zeros(&bytes[end..])?;
308    if !valid {
309        zeros(&bytes[..24])?;
310        zeros(&bytes[32..36])?;
311        zeros(&bytes[40..52])?;
312        zeros(&bytes[64..end])?;
313        return Ok(());
314    }
315    check_material_entry(context, binding, u32_at(bytes, 32))?;
316    finite(bytes, 0, 24)?;
317    finite(bytes, 40, 48)?;
318    finite(bytes, 64, end)?;
319    if flags & 1 != 0 {
320        if f64_at(bytes, 40) < 0.0 {
321            return Err(Error::Value);
322        }
323    } else {
324        zeros(&bytes[40..48])?;
325    }
326    for at in (64..end).step_by(8) {
327        let v = f64_at(bytes, at);
328        if v < 0.0 || (quantity == spectrum::Quantity::DimensionlessReflectance && v > 1.0) {
329            return Err(Error::Value);
330        }
331    }
332    Ok(())
333}
334fn yee_record(
335    bytes: &[u8],
336    context: &Context<'_, '_>,
337    binding: &bindings::Binding<'_>,
338    policy: yee::YeeParsePolicy,
339    valid: bool,
340) -> Result<(), Error> {
341    let Some(rec) = yee::YeeRecord::parse(bytes, valid, policy)? else {
342        return Ok(());
343    };
344    check_material_entry(context, binding, rec.material_entry)?;
345    if let Some(cid) = binding.constitutive_id {
346        let cb = context.require_schema(cid, 133).map_err(Error::Shared)?;
347        if let Ok(schemas::ConstitutiveKind::Vacuum) =
348            schemas::ConstitutiveKind::parse(text(required(cb, 1)?)?)
349        {
350            if (rec.epsilon_relative - 1.0).abs() > 1.0e-12
351                || (rec.mu_relative - 1.0).abs() > 1.0e-12
352                || rec.conductivity_s_per_m != 0.0
353            {
354                return Err(Error::Value);
355            }
356        }
357    }
358    Ok(())
359}
360fn mueller_record(
361    bytes: &[u8],
362    context: &Context<'_, '_>,
363    binding: &bindings::Binding<'_>,
364    valid: bool,
365) -> Result<(), Error> {
366    let Some(rec) = mueller::MuellerRecord::parse(bytes, valid, true)? else {
367        return Ok(());
368    };
369    check_material_entry(context, binding, rec.material_entry)
370}
371fn iq_record(
372    bytes: &[u8],
373    context: &Context<'_, '_>,
374    binding: &bindings::Binding<'_>,
375    ext: Block<'_>,
376    valid: bool,
377    tick: i64,
378) -> Result<(), Error> {
379    let Some(pkt) = iq::IqPacketView::parse(bytes, valid)? else {
380        return Ok(());
381    };
382    if binding.entry.flags() & 2 != 0 && pkt.header.first_sample_tick != tick {
383        return Err(Error::Time);
384    }
385    let acq_id = binding.acquisition_id.ok_or(Error::Descriptor)?;
386    let cal_id = binding.calibration_id.ok_or(Error::Descriptor)?;
387    let acq = context.require_schema(acq_id, 136).map_err(Error::Shared)?;
388    let cal = context.require_schema(cal_id, 107).map_err(Error::Shared)?;
389    let raw_count_mode = text(required(acq, 5)?)? == "counts";
390    pkt.validate_against_blocks(ext, acq, cal, raw_count_mode)
391}
392fn dose_record(
393    bytes: &[u8],
394    context: &Context<'_, '_>,
395    binding: &bindings::Binding<'_>,
396    valid: bool,
397    tick: i64,
398) -> Result<(), Error> {
399    let Some(rec) = dose_biofield::DoseTransportRecord::parse(bytes, valid)? else {
400        return Ok(());
401    };
402    if binding.entry.flags() & 2 != 0 && rec.tick != tick {
403        return Err(Error::Time);
404    }
405    let cal_id = binding.calibration_id.ok_or(Error::Descriptor)?;
406    let ev_id = binding.evidence_id.ok_or(Error::Descriptor)?;
407    let cal = context.require_schema(cal_id, 107).map_err(Error::Shared)?;
408    let ev = context.require_schema(ev_id, 134).map_err(Error::Shared)?;
409    let (_species, _epistemic) = rec.validate_against_blocks(cal, ev)?;
410    check_material_entry(context, binding, rec.material_entry)
411}
412fn biofield_record(
413    bytes: &[u8],
414    context: &Context<'_, '_>,
415    binding: &bindings::Binding<'_>,
416    valid: bool,
417    tick: i64,
418) -> Result<(), Error> {
419    let Some(rec) = dose_biofield::BiofieldRecord::parse(bytes, valid)? else {
420        return Ok(());
421    };
422    if binding.entry.flags() & 2 != 0 && rec.tick != tick {
423        return Err(Error::Time);
424    }
425    let bio_id = binding.bio_context_id.ok_or(Error::Descriptor)?;
426    let ev_id = binding.evidence_id.ok_or(Error::Descriptor)?;
427    let cal_id = binding.calibration_id.ok_or(Error::Descriptor)?;
428    let bio = context.require_schema(bio_id, 137).map_err(Error::Shared)?;
429    let ev = context.require_schema(ev_id, 134).map_err(Error::Shared)?;
430    let cal = context.require_schema(cal_id, 107).map_err(Error::Shared)?;
431    let consent = context
432        .require_schema(rec.consent_provenance_ref, 4)
433        .map_err(Error::Shared)?;
434    let _epistemic = rec.validate_against_blocks(bio, ev, cal, consent, true)?;
435    Ok(())
436}