Skip to main content

qualia_core_db/audio/qac/profiles/
numerical_bridge.rs

1//! Bidirectional typed bridges between QAC v1 container profiles (`audio::qac::profiles`)
2//! and the continuum / spatial DSP numerical engines (`audio::qac::numerical`, `etalon_sim`).
3
4use super::elastic::{
5    CauchyStress6 as ProfileCauchyStress6, ElasticStressChunkView, ElasticStressVelocityRecord,
6    ELASTIC_VALID_DISPLACEMENT, ELASTIC_VALID_STRESS, ELASTIC_VALID_VELOCITY,
7};
8use super::pressure_velocity::{
9    PressureVelocityChunkView, PressureVelocityRecord, PV_VALID_ENERGY, PV_VALID_INTENSITY,
10    PV_VALID_PRESSURE, PV_VALID_VELOCITY,
11};
12use super::types::ProfileError;
13use crate::audio::qac::numerical::{
14    elastic_virieux::{
15        CauchyStress6 as NumericalCauchyStress6,
16        ElasticStressVelocityRecord as NumericalElasticRecord, ESV_VALID_DISPLACEMENT,
17        ESV_VALID_STRESS, ESV_VALID_VELOCITY,
18    },
19    fdtd_fluid::{
20        collocate_fluid_cell, FluidFdtdConfig, FluidFdtdState,
21        PressureVelocityRecord as NumericalPvRecord, PV_VALID_ENERGY_DENSITY,
22        PV_VALID_INTENSITY as NUM_PV_VALID_INTENSITY, PV_VALID_POSITION,
23        PV_VALID_PRESSURE as NUM_PV_VALID_PRESSURE, PV_VALID_VELOCITY as NUM_PV_VALID_VELOCITY,
24    },
25    NumericalError,
26};
27
28/// Translates profile Mode `0x0000` validity bits (`PV_VALID_*`) to numerical continuum bits.
29pub const fn profile_pv_mask_to_numerical(profile_mask: u32) -> u32 {
30    let mut out = PV_VALID_POSITION;
31    if (profile_mask & PV_VALID_PRESSURE) != 0 {
32        out |= NUM_PV_VALID_PRESSURE;
33    }
34    if (profile_mask & PV_VALID_VELOCITY) != 0 {
35        out |= NUM_PV_VALID_VELOCITY;
36    }
37    if (profile_mask & PV_VALID_ENERGY) != 0 {
38        out |= PV_VALID_ENERGY_DENSITY;
39    }
40    if (profile_mask & PV_VALID_INTENSITY) != 0 {
41        out |= NUM_PV_VALID_INTENSITY;
42    }
43    out
44}
45
46/// Translates numerical Mode `0x0000` validity bits back to storage profile `PV_VALID_*` bits.
47pub const fn numerical_pv_mask_to_profile(num_mask: u32) -> u32 {
48    let mut out = 0u32;
49    if (num_mask & NUM_PV_VALID_PRESSURE) != 0 {
50        out |= PV_VALID_PRESSURE;
51    }
52    if (num_mask & NUM_PV_VALID_VELOCITY) != 0 {
53        out |= PV_VALID_VELOCITY;
54    }
55    if (num_mask & PV_VALID_ENERGY_DENSITY) != 0 {
56        out |= PV_VALID_ENERGY;
57    }
58    if (num_mask & NUM_PV_VALID_INTENSITY) != 0 {
59        out |= PV_VALID_INTENSITY;
60    }
61    out
62}
63
64impl From<&PressureVelocityRecord> for NumericalPvRecord {
65    fn from(r: &PressureVelocityRecord) -> Self {
66        Self {
67            position_m: r.position_m,
68            pressure_pa: r.pressure_pa,
69            particle_velocity_m_s: r.particle_velocity_m_s,
70            energy_density_j_m3: r.energy_density_j_m3,
71            intensity_w_m2: r.intensity_w_m2,
72            material_ref: r.material_ref,
73            validity_bits: profile_pv_mask_to_numerical(r.validity_bits),
74        }
75    }
76}
77
78impl From<&NumericalPvRecord> for PressureVelocityRecord {
79    fn from(r: &NumericalPvRecord) -> Self {
80        Self {
81            position_m: r.position_m,
82            pressure_pa: r.pressure_pa,
83            particle_velocity_m_s: r.particle_velocity_m_s,
84            energy_density_j_m3: r.energy_density_j_m3,
85            intensity_w_m2: r.intensity_w_m2,
86            material_ref: r.material_ref,
87            validity_bits: numerical_pv_mask_to_profile(r.validity_bits),
88        }
89    }
90}
91
92impl From<ProfileCauchyStress6> for NumericalCauchyStress6 {
93    fn from(s: ProfileCauchyStress6) -> Self {
94        Self::new([s.xx, s.yy, s.zz, s.xy, s.yz, s.xz])
95    }
96}
97
98impl From<NumericalCauchyStress6> for ProfileCauchyStress6 {
99    fn from(s: NumericalCauchyStress6) -> Self {
100        Self::from_wire_f32([
101            s.components[0] as f32,
102            s.components[1] as f32,
103            s.components[2] as f32,
104            s.components[3] as f32,
105            s.components[4] as f32,
106            s.components[5] as f32,
107        ])
108    }
109}
110
111impl From<&ElasticStressVelocityRecord> for NumericalElasticRecord {
112    fn from(r: &ElasticStressVelocityRecord) -> Self {
113        let mut mask = 0u32;
114        if (r.validity_bits & ELASTIC_VALID_VELOCITY) != 0 {
115            mask |= ESV_VALID_VELOCITY;
116        }
117        if (r.validity_bits & ELASTIC_VALID_STRESS) != 0 {
118            mask |= ESV_VALID_STRESS;
119        }
120        if (r.validity_bits & ELASTIC_VALID_DISPLACEMENT) != 0 {
121            mask |= ESV_VALID_DISPLACEMENT;
122        }
123        Self {
124            velocity_m_s: r.velocity_m_s,
125            material_ref: r.material_ref,
126            stress_xx_yy_zz_xy_yz_xz_pa: r.stress_xx_yy_zz_xy_yz_xz_pa,
127            displacement_m: r.displacement_m,
128            validity_bits: mask,
129        }
130    }
131}
132
133impl From<&NumericalElasticRecord> for ElasticStressVelocityRecord {
134    fn from(r: &NumericalElasticRecord) -> Self {
135        let mut mask = 0u32;
136        if (r.validity_bits & ESV_VALID_VELOCITY) != 0 {
137            mask |= ELASTIC_VALID_VELOCITY;
138        }
139        if (r.validity_bits & ESV_VALID_STRESS) != 0 {
140            mask |= ELASTIC_VALID_STRESS;
141        }
142        if (r.validity_bits & ESV_VALID_DISPLACEMENT) != 0 {
143            mask |= ELASTIC_VALID_DISPLACEMENT;
144        }
145        Self {
146            velocity_m_s: r.velocity_m_s,
147            material_ref: r.material_ref,
148            stress_xx_yy_zz_xy_yz_xz_pa: r.stress_xx_yy_zz_xy_yz_xz_pa,
149            displacement_m: r.displacement_m,
150            validity_bits: mask,
151        }
152    }
153}
154
155/// Decodes an admitted `0x0000` profile chunk directly into validated `numerical` solver records.
156pub fn chunk_to_numerical_pv_records(
157    chunk: &PressureVelocityChunkView<'_>,
158) -> Result<Vec<NumericalPvRecord>, ProfileError> {
159    let mut out = Vec::with_capacity(chunk.len());
160    for i in 0..chunk.len() {
161        let rec = chunk.get(i)?;
162        out.push(NumericalPvRecord::from(&rec));
163    }
164    Ok(out)
165}
166
167/// Decodes an admitted `0x0001` profile chunk directly into validated `numerical` Virieux records.
168pub fn chunk_to_numerical_elastic_records(
169    chunk: &ElasticStressChunkView<'_>,
170) -> Result<Vec<NumericalElasticRecord>, ProfileError> {
171    let mut out = Vec::with_capacity(chunk.len());
172    for i in 0..chunk.len() {
173        let rec = chunk.get(i)?;
174        out.push(NumericalElasticRecord::from(&rec));
175    }
176    Ok(out)
177}
178
179/// Exports collocated `FluidFdtdState` fields as verified Mode `0x0000` storage profile records
180/// using staggered spatial/temporal interpolation via [`collocate_fluid_cell`].
181pub fn export_fdtd_cell_records(
182    cfg: &FluidFdtdConfig,
183    state: &FluidFdtdState,
184) -> Result<Vec<PressureVelocityRecord>, NumericalError> {
185    cfg.validate()?;
186    let [nx, ny, nz] = cfg.dims;
187    let total = cfg.cell_count();
188    if state.p.len() != total {
189        return Err(NumericalError::BufferLengthMismatch {
190            buffer: "FluidFdtdState.p",
191            expected: total,
192            actual: state.p.len(),
193        });
194    }
195    let mut out = Vec::with_capacity(total);
196    for x in 0..nx {
197        for y in 0..ny {
198            for z in 0..nz {
199                let (p, col_v, energy, intensity) = collocate_fluid_cell(
200                    cfg,
201                    &state.p,
202                    (&state.prev_vx, &state.prev_vy, &state.prev_vz),
203                    (&state.vx, &state.vy, &state.vz),
204                    [x, y, z],
205                )?;
206                let pos = [
207                    x as f32 * cfg.spacing_m[0] as f32,
208                    y as f32 * cfg.spacing_m[1] as f32,
209                    z as f32 * cfg.spacing_m[2] as f32,
210                ];
211                let nrec = NumericalPvRecord {
212                    position_m: pos,
213                    pressure_pa: p as f32,
214                    particle_velocity_m_s: [col_v[0] as f32, col_v[1] as f32, col_v[2] as f32],
215                    energy_density_j_m3: energy as f32,
216                    intensity_w_m2: [intensity[0] as f32, intensity[1] as f32, intensity[2] as f32],
217                    material_ref: cfg.medium.material_ref,
218                    validity_bits: PV_VALID_POSITION
219                        | NUM_PV_VALID_PRESSURE
220                        | NUM_PV_VALID_VELOCITY
221                        | PV_VALID_ENERGY_DENSITY
222                        | NUM_PV_VALID_INTENSITY,
223                };
224                nrec.validate()?;
225                out.push(PressureVelocityRecord::from(&nrec));
226            }
227        }
228    }
229    Ok(out)
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use super::super::envelope::{AdmittedEnvelope, AdmittedEntryKind};
236    use crate::audio::qac::metadata::SignalRegistry;
237    use crate::q42::field_semantics::DomainRegistry;
238
239    #[test]
240    fn gap_023_signal_registry_delegates_domain_schemas_and_s201_keys() {
241        let reg = SignalRegistry;
242        assert_eq!(reg.descriptor_target_schema(4), Some(200));
243        assert_eq!(reg.descriptor_target_schema(5), Some(201));
244        assert_eq!(reg.descriptor_target_schema(6), Some(202));
245        for schema in [200u16, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210] {
246            assert!(reg.rules(schema, 1).is_some(), "missing schema {schema}");
247        }
248        let s201 = super::super::registry::QacProfileRegistry.rules(201, 1).unwrap();
249        assert!(s201.iter().any(|r| r.key == 16 && r.type_tag == 4));
250        assert!(s201.iter().any(|r| r.key == 17 && r.type_tag == 6));
251    }
252
253    #[test]
254    fn gap_026_pv_and_elastic_profile_numerical_roundtrip_and_entry_summary() {
255        let pv = PressureVelocityRecord {
256            position_m: [0.1, 0.2, 0.3],
257            pressure_pa: 2.5,
258            particle_velocity_m_s: [0.005, -0.001, 0.0],
259            energy_density_j_m3: 0.04,
260            intensity_w_m2: [0.0125, -0.0025, 0.0],
261            material_ref: 7,
262            validity_bits: PV_VALID_PRESSURE | PV_VALID_VELOCITY | PV_VALID_ENERGY | PV_VALID_INTENSITY,
263        };
264        let npv = NumericalPvRecord::from(&pv);
265        assert_eq!(npv.pressure_pa, pv.pressure_pa);
266        assert_eq!(npv.material_ref, 7);
267        assert_ne!(npv.validity_bits & PV_VALID_POSITION, 0);
268        let back = PressureVelocityRecord::from(&npv);
269        assert_eq!(back, pv);
270
271        let es = ElasticStressVelocityRecord {
272            velocity_m_s: [0.1, 0.2, 0.3],
273            material_ref: 3,
274            stress_xx_yy_zz_xy_yz_xz_pa: [10.0, 20.0, 30.0, 1.0, 2.0, 3.0],
275            displacement_m: [0.001, 0.002, 0.003],
276            validity_bits: ELASTIC_VALID_VELOCITY | ELASTIC_VALID_STRESS | ELASTIC_VALID_DISPLACEMENT,
277        };
278        let nes = NumericalElasticRecord::from(&es);
279        assert_eq!(ElasticStressVelocityRecord::from(&nes), es);
280        assert_eq!(AdmittedEntryKind::ModalResonance.is_signal_waveform_entry(), false);
281        assert_eq!(AdmittedEntryKind::PcmPreservation.is_signal_waveform_entry(), true);
282    }
283
284    #[test]
285    fn gap_024_and_026_fdtd_step_export_qac_roundtrip_and_summary_admission() {
286        use super::super::pressure_velocity::{
287            read_pressure_velocity_qac, write_pressure_velocity_qac, FluidMediumModel,
288            StaggeringOffsetsPV,
289        };
290        use super::super::types::{
291            ClockSpec, FrameSpec, ProfileLimits, ProvenanceSpec, RationalRate,
292        };
293        use crate::audio::qac::numerical::fdtd_fluid::{
294            step_fluid_fdtd_in_place, FluidBoundaryCondition, FluidMedium,
295        };
296
297        let cfg = FluidFdtdConfig {
298            dims: [4, 4, 4],
299            spacing_m: [0.05, 0.05, 0.05],
300            dt_s: 2.0e-5,
301            medium: FluidMedium::new(1.2041, 142_000.0, 0.0, 0).expect("air"),
302            boundary: FluidBoundaryCondition::Rigid,
303        };
304        let mut state = FluidFdtdState::new(&cfg).expect("state");
305        state.p[(1 * 4 + 1) * 4 + 1] = 10.0;
306        step_fluid_fdtd_in_place(&cfg, &mut state).expect("step");
307
308        let exported = export_fdtd_cell_records(&cfg, &state).expect("export");
309        assert_eq!(exported.len(), 64);
310        assert!(exported.iter().any(|r| r.pressure_pa.abs() > 0.0));
311
312        let medium_model = FluidMediumModel::FluidLinear {
313            density_kg_m3: cfg.medium.density_kg_m3,
314            bulk_modulus_pa: cfg.medium.bulk_modulus_pa,
315            temperature_k: None,
316            ambient_pressure_pa: None,
317            flow_m_s: None,
318            matter_digest: None,
319            material_table_digest: None,
320            material_table_epoch: None,
321            material_ids: Vec::new(),
322        };
323        let clk = ClockSpec {
324            scale: 0,
325            epoch_seconds: 1_700_000_000,
326            epoch_nanoseconds: 0,
327            ticks_per_second: RationalRate::new(48_000, 1).expect("hz"),
328        };
329        let prov = ProvenanceSpec {
330            role: 0,
331            source_digests: &[],
332            algorithm: Some("urn:qac:test-fdtd-bridge"),
333            algorithm_version: Some("1"),
334            instrument_uri: None,
335            authority_receipt_digest: None,
336            lineage: None,
337        };
338        let qac = write_pressure_velocity_qac(
339            &exported,
340            &medium_model,
341            &StaggeringOffsetsPV::collocated(),
342            &clk,
343            RationalRate::new(50_000, 1).expect("rate"),
344            &FrameSpec::local_default(),
345            &prov,
346            None,
347            ProfileLimits::default(),
348        )
349        .expect("write_pressure_velocity_qac");
350
351        let env = AdmittedEnvelope::open_alloc(&qac, ProfileLimits::default()).expect("admit");
352        let summary = env.inspect_entry_summary(1).expect("summary");
353        assert_eq!(summary.kind, AdmittedEntryKind::PressureVelocity);
354        assert_eq!(summary.kind.as_str(), "pressure-velocity");
355        assert!(!summary.kind.is_signal_waveform_entry());
356
357        let view = read_pressure_velocity_qac(&qac, 1, ProfileLimits::default()).expect("read");
358        let back = chunk_to_numerical_pv_records(&view.records).expect("convert back");
359        assert_eq!(back.len(), 64);
360        assert_eq!(back[0].pressure_pa, exported[0].pressure_pa);
361    }
362}