Skip to main content

qualia_core_db/q42/emf_profiles/
mod.rs

1//! EMF full-profile codecs, semantic admission rules, and zero-heap envelope writers
2//! covering canonical modes `0x0100..=0x0107` (with compatibility mapping for `0..=7`).
3//! Every measurement/model carrier preserves explicit units, calibration/evidence/provenance
4//! links, frame conventions, and physical realizability checks; unsupported profiles fail closed
5//! without recasting, and dose/biofield storage never emits universal safety verdicts.
6use super::field_envelope::{Block, Entry, Field, StructuralView};
7use super::field_semantics::{
8    self as semantics, field, Context, DomainRegistry, FieldRule, Scratch,
9};
10use super::field_spectrum::{self as spectrum, AxisView, SigmaInterpretation};
11mod acquisition_bridge;
12mod bindings;
13mod chunk;
14mod document;
15mod dose_biofield;
16mod extended_writer;
17mod field_metadata;
18mod field_writer;
19mod frame_transforms;
20mod iq;
21mod mueller;
22mod records;
23mod registry;
24mod schemas;
25mod spatial;
26mod yee;
27pub use acquisition_bridge::*;
28pub use chunk::{admit_chunk, ProfileChunk};
29pub use document::ProfileReader;
30pub use dose_biofield::{
31    absorbed_dose_gy, dipole_potential_infinite_homogeneous, encode_biofield_records,
32    encode_dose_records, equivalent_dose_sv, kev_to_joules, linear_from_mass_attenuation,
33    photon_uncollided_fluence, verify_empirical_join_allowed, BiofieldRecord, DoseTransportRecord,
34    TransportSpecies, BIOFIELD_MODEL_URI, BIOFIELD_PROFILE, BIO_FLAG_CARRIER, BIO_FLAG_POTENTIAL,
35    BIO_FLAG_UNCERTAINTY, DOSE_ALL_VALID_MASK, DOSE_MODEL_URI, DOSE_PROFILE,
36    DOSE_VALID_ABSORBED_GY, DOSE_VALID_EQUIVALENT_SV, DOSE_VALID_FLUENCE, DOSE_VALID_LET,
37    DOSE_VALID_LINEAR_ATTEN, DOSE_VALID_MASS_ATTEN, DOSE_VALID_PHOTON_ENERGY,
38    DOSE_VALID_UNCERTAINTY,
39};
40pub use extended_writer::{
41    write_extended_envelope, AcquisitionSpec, BioContextSpec, CalibrationSpec, ConstitutiveSpec,
42    ExtendedModeSpec, MaterialSpec, ModelEvidenceSpec, SpectralAxisSpec,
43};
44pub use field_writer::{
45    encode_field_samples, field_entry_slot, field_metadata_len, prepare_field_document,
46    FieldChunkInput, FieldClock, FieldDocument, FieldFrame, FieldProvenance, FieldSample,
47    FieldWriteLimits, PreparedField,
48};
49pub use frame_transforms::{det_3x3, invert_3x3, FramePose, Schema106Transform};
50pub use iq::{
51    check_complex_nyquist_band, convert_carrier_sign_conjugate, encode_iq_packet,
52    fft_bins_to_ascending_physical, iq_dft_forward_unscaled, iq_idft_scaled, iq_record_crc32c,
53    iq_record_stride, reconstruct_rf_real_signal, signed_baseband_offset_hz, window_weight,
54    IqHeader, IqPacketView, FLAG_LO_PHASE_KNOWN, IQ_CONVENTION, IQ_MODEL_URI, IQ_PROFILE,
55    MAX_IQ_SAMPLES, STFT_FFT_NORMALIZATION,
56};
57pub use mueller::{
58    apply_mueller, apply_spectral_response, build_log_band_edges, cloude_coherency_matrix,
59    cloude_eigenvalues, convert_density_hz, convert_density_wavelength_to_hz,
60    encode_mueller_records, integrate_spectrum_over_axis, jones_to_mueller, rotate_mueller_passive,
61    validate_band_edges, verify_mueller_physical_realizability, DensityTarget, MuellerRecord,
62    MuellerUnits, SpectralPrecisionProfile, BAND_COUNT_24, BAND_COUNT_28, MUELLER_MODEL_URI,
63    MUELLER_PROFILE,
64};
65pub use records::{FieldRecord, RayRecord, SpectrumRecord, SpectrumValues};
66pub use registry::{canonical_emf_mode, extension_rules, polarization_rules, ProfileRegistry};
67pub use schemas::{
68    acquisition_rules, bio_context_rules, calibration_rules, constitutive_model_rules,
69    coordinate_transform_rules, evaluate_calibration, material_binding_contains,
70    material_binding_rules, model_evidence_rules, validate_acquisition, validate_bio_context,
71    validate_calibration, validate_constitutive_model, validate_coordinate_transform,
72    validate_material_binding, validate_model_evidence, ConstitutiveKind, EpistemicClass,
73    ProfileResponseValidator, SignalKind, TransformKind, WindowKind,
74};
75pub use spatial::{BrickLayout, GridIndexing, GridLayout, GridSpec};
76pub use yee::{
77    encode_yee_records, energy_density_isotropic, energy_density_vacuum_eb,
78    evaluate_instantaneous_phasor, optical_path_delay_seconds, peak_to_rms, poynting_e_cross_h,
79    poynting_from_eb_vacuum, rms_to_peak, rotate_stokes_passive, validate_yee_extension,
80    yee_check_cfl, yee_cfl_max_dt_seconds, yee_discrete_dispersion_omega, yee_step_periodic,
81    yee_total_energy_j, HarmonicSign, JonesVector, PhasorAmplitudeKind, YeeParsePolicy, YeeRecord,
82    SPEED_OF_LIGHT_M_PER_S, VACUUM_IMPEDANCE_OHM, VACUUM_PERMEABILITY_H_PER_M,
83    VACUUM_PERMITTIVITY_F_PER_M, YEE_MODEL_URI, YEE_PROFILE,
84};
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum Error {
87    Shared(semantics::Error),
88    Storage(super::field_envelope::Error),
89    Spectrum(spectrum::Error),
90    UnsupportedProfile,
91    Shape,
92    Descriptor,
93    Frame,
94    Time,
95    Flags,
96    NonFinite,
97    Value,
98    Reserved,
99    Validity,
100    Index,
101    WrongMode,
102    Limit,
103    Overflow,
104}
105#[derive(Clone, Copy, Debug)]
106pub struct Limits {
107    pub shared: semantics::Limits,
108    pub records: u64,
109    pub payload_work: u64,
110}
111impl Default for Limits {
112    fn default() -> Self {
113        Self {
114            shared: semantics::Limits::default(),
115            records: 1_000_000,
116            payload_work: 64 << 20,
117        }
118    }
119}
120pub const VALIDITY_PROFILE: &str = "validity_v1";
121pub const VALIDITY_MODEL_URI: &str = "urn:qualia:emf:validity_v1";
122pub const FIELD_PROFILE: &str = "instantaneous_E_B_v1";
123pub const RAY_PROFILE: &str = "polarimetric_ray_v1";
124pub const SPECTRUM_PROFILE: &str = "sampled_spectrum_v1";
125pub const FIELD_MODEL_URI: &str = "urn:qualia:emf:instantaneous_E_B_v1";
126pub const RAY_MODEL_URI: &str = "urn:qualia:emf:polarimetric_ray_v1";
127pub const SPECTRUM_MODEL_URI: &str = "urn:qualia:emf:sampled_spectrum_v1";
128fn required<'a>(b: Block<'a>, k: u16) -> Result<Field<'a>, Error> {
129    field(b, k).ok_or(Error::Descriptor)
130}
131fn u32_at(b: &[u8], i: usize) -> u32 {
132    u32::from_le_bytes(b[i..i + 4].try_into().unwrap())
133}
134fn u64_at(b: &[u8], i: usize) -> u64 {
135    u64::from_le_bytes(b[i..i + 8].try_into().unwrap())
136}
137fn f64_at(b: &[u8], i: usize) -> f64 {
138    f64::from_bits(u64_at(b, i))
139}
140fn scalar32(b: Block<'_>, k: u16) -> Result<u32, Error> {
141    Ok(u32_at(required(b, k)?.value(), 0))
142}
143fn scalar64(b: Block<'_>, k: u16) -> Result<u64, Error> {
144    Ok(u64_at(required(b, k)?.value(), 0))
145}
146fn text(f: Field<'_>) -> Result<&str, Error> {
147    std::str::from_utf8(f.value()).map_err(|_| Error::Descriptor)
148}
149fn triple(bytes: &[u8], at: usize) -> [f64; 3] {
150    [
151        f64_at(bytes, at),
152        f64_at(bytes, at + 8),
153        f64_at(bytes, at + 16),
154    ]
155}
156fn finite(bytes: &[u8], start: usize, end: usize) -> Result<(), Error> {
157    for at in (start..end).step_by(8) {
158        if !f64_at(bytes, at).is_finite() {
159            return Err(Error::NonFinite);
160        }
161    }
162    Ok(())
163}
164fn zeros(bytes: &[u8]) -> Result<(), Error> {
165    if bytes.iter().any(|&b| b != 0) {
166        Err(Error::Reserved)
167    } else {
168        Ok(())
169    }
170}
171fn shared_error(e: semantics::Error) -> Error {
172    if e == semantics::Error::UnsupportedDomain {
173        Error::UnsupportedProfile
174    } else {
175        Error::Shared(e)
176    }
177}
178#[cfg(test)]
179mod dose_biofield_tests;
180#[cfg(test)]
181mod iq_tests;
182#[cfg(test)]
183mod mueller_tests;
184#[cfg(test)]
185mod schemas_tests;
186#[cfg(test)]
187mod tests;
188#[cfg(test)]
189mod yee_tests;