Skip to main content

qualia_core_db/q42/science_validation/
passivity_conservation.rs

1//! Passivity, energy conservation, and C02-C09 numerical budget verifiers.
2//!
3//! Implements independent first-principles `f64` evaluators for:
4//! - C02-C09 `f64` small closed-form budget: $|y - y_{\text{ref}}| \le 64 \cdot 2^{-52} Q$.
5//! - C02-C09 $N$-term reduction / DFT budget: $16\,\gamma_N \sum_{i=1}^N |t_i|$ with $\gamma_N = \frac{N u}{1 - N u}, u = 2^{-53}$.
6//! - C02-C09 QAC `B32` scalar budget: $|y - y_{\text{ref}}| \le 8\,u_{32} S + 2\times 10^{-6} |y_{\text{ref}}|, u_{32} = 2^{-24}$,
7//!   and vector relative $L_2 \le 5\times 10^{-6}$.
8//! - Electromagnetic Mode 0 (Poynting flux, energy density, static wavelength guard) and Mode 2
9//!   (3D Cartesian Yee CFL bound and exact discrete dispersion relation).
10//! - Acoustic Mode 00 (fluid intensity/energy), Mode 01 (6-component Cauchy elasticity), and
11//!   Mode 03 (impedance reflection/transmission energy conservation $R + T = 1$).
12//! - Multi-port scattering matrix passivity ($\|\mathbf{S}\|_2 \le 1$) and grid-refinement
13//!   observed convergence order $p = \frac{\ln(E_1/E_2)}{\ln(h_1/h_2)} \ge 1.8$.
14
15use crate::q42::science_validation::stokes_mueller::{
16    hermitian_4x4_eigenvalues, scaled_hypot3, Complex64, VACUUM_SPEED_OF_LIGHT_M_PER_S,
17};
18
19/// IEEE-754 `f64` unit roundoff $u = 2^{-53}$ (`0.5 * f64::EPSILON`).
20pub const F64_UNIT_ROUNDOFF: f64 = 0.5 * f64::EPSILON;
21
22/// IEEE-754 `f64` machine epsilon $\varepsilon = 2^{-52}$.
23pub const F64_EPSILON: f64 = f64::EPSILON;
24
25/// IEEE-754 `f32` unit roundoff $u_{32} = 2^{-24}$ (`0.5 * f32::EPSILON as f64`).
26pub const F32_UNIT_ROUNDOFF: f64 = 0.5 * (f32::EPSILON as f64);
27
28/// Exact SI magnetic constant (vacuum permeability) $\mu_0 = 4\pi \times 10^{-7}\text{ H/m}$
29/// consistent with $c_0 = 299\,792\,458\text{ m/s}$ and $Z_0 = \mu_0 c_0$.
30pub const VACUUM_PERMEABILITY_H_PER_M: f64 = 4.0e-7 * core::f64::consts::PI;
31
32/// Characteristic impedance of vacuum $Z_0 = \mu_0 c_0$ ($\Omega$).
33pub const VACUUM_IMPEDANCE_OHM: f64 =
34    VACUUM_PERMEABILITY_H_PER_M * VACUUM_SPEED_OF_LIGHT_M_PER_S;
35
36/// Vacuum electric permittivity $\varepsilon_0 = \frac{1}{\mu_0 c_0^2}$ ($\text{F/m}$).
37pub const VACUUM_PERMITTIVITY_F_PER_M: f64 = 1.0
38    / (VACUUM_PERMEABILITY_H_PER_M
39        * VACUUM_SPEED_OF_LIGHT_M_PER_S
40        * VACUUM_SPEED_OF_LIGHT_M_PER_S);
41
42/// Standard C02 amplitude scaling factors for linear-domain invariance checks.
43pub const C02_AMPLITUDE_SCALES_F64: [f64; 3] = [1.0e-6, 1.0, 1.0e6];
44
45/// Standard C02 QAC `B32` amplitude scaling factors.
46pub const C02_AMPLITUDE_SCALES_B32: [f64; 3] = [1.0e-3, 1.0, 1.0e3];
47
48/// Detailed audit record for a numerical budget comparison.
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct BudgetEvaluation {
51    pub actual: f64,
52    pub reference: f64,
53    pub scale: f64,
54    pub abs_error: f64,
55    pub rel_error: f64,
56    pub budget: f64,
57}
58
59/// Errors emitted by passivity, conservation, and numerical budget verifiers.
60#[derive(Debug, Clone, PartialEq)]
61pub enum ConservationValidationError {
62    /// Non-finite input or reference value encountered.
63    NonFiniteValue { context: &'static str, value: f64 },
64    /// Characteristic scale $Q$ or $S$ is non-positive or non-finite.
65    InvalidCharacteristicScale { scale: f64 },
66    /// Reduction term count $N$ is zero or $N u \ge 1$.
67    InvalidReductionCount { n: usize },
68    /// Scalar error exceeded the C02 numerical budget.
69    BudgetExceeded(BudgetEvaluation),
70    /// Vector relative $L_2$ error exceeded the QAC `B32` threshold ($5\times 10^{-6}$).
71    VectorRelativeL2Exceeded {
72        rel_l2_error: f64,
73        max_allowed: f64,
74        l2_diff: f64,
75        l2_ref: f64,
76    },
77    /// Static/aperiodic field ($f_c \le 0$) cannot be evaluated for wavelength $c/f$.
78    StaticFieldWavelengthForbidden { carrier_hz: f64 },
79    /// Invalid constitutive parameters ($\varepsilon_r \le 0$, $\mu_r \le 0$, or $\sigma < 0$).
80    InvalidConstitutiveParameters {
81        epsilon_r: f64,
82        mu_r: f64,
83        sigma_s_per_m: f64,
84    },
85    /// Invalid fluid or elastic medium parameters ($\rho \le 0$, $K \le 0$, or $\mu < 0$).
86    InvalidMediumParameters {
87        density_kg_per_m3: f64,
88        bulk_modulus_pa: f64,
89        shear_modulus_pa: f64,
90    },
91    /// Multiplying non-collocated pressure and velocity without explicit interpolation is forbidden.
92    NonCollocatedPressureVelocityRejected,
93    /// Conservation law residual $\nabla\cdot\mathbf{F} + \partial u/\partial t + w_{\text{loss}}$ exceeded budget,
94    /// or medium exhibited active energy generation ($w_{\text{loss}} < 0$).
95    PassivityOrConservationViolation {
96        residual: f64,
97        dissipated_power_w_per_m3: f64,
98        budget: f64,
99    },
100    /// Yee or leapfrog timestep violated the 3D Courant-Friedrichs-Lewy (CFL) stability bound.
101    CflStabilityViolation {
102        dt_s: f64,
103        cfl_max_dt_s: f64,
104        courant_ratio: f64,
105    },
106    /// Scattering matrix violated passivity ($\|\mathbf{S}\|_2 > 1 + 64\,\varepsilon$).
107    ScatteringPassivityViolation {
108        max_singular_value_sq: f64,
109        tolerance_sq: f64,
110    },
111    /// Grid refinement failed to achieve the minimum observed convergence order $p \ge 1.8$.
112    ConvergenceOrderBelowMinimum {
113        observed_order: f64,
114        minimum_order: f64,
115        coarse_error: f64,
116        fine_error: f64,
117    },
118}
119
120/// Evaluate the C02-C09 small closed-form `f64` budget:
121/// $|y - y_{\text{ref}}| \le 64 \cdot 2^{-52} Q$.
122pub fn verify_f64_closed_form_budget(
123    actual: f64,
124    reference: f64,
125    scale_q: f64,
126) -> Result<BudgetEvaluation, ConservationValidationError> {
127    if !actual.is_finite() {
128        return Err(ConservationValidationError::NonFiniteValue {
129            context: "actual",
130            value: actual,
131        });
132    }
133    if !reference.is_finite() {
134        return Err(ConservationValidationError::NonFiniteValue {
135            context: "reference",
136            value: reference,
137        });
138    }
139    if !scale_q.is_finite() || scale_q <= 0.0 {
140        return Err(ConservationValidationError::InvalidCharacteristicScale { scale: scale_q });
141    }
142    let abs_error = (actual - reference).abs();
143    let rel_error = if reference == 0.0 {
144        abs_error / scale_q
145    } else {
146        abs_error / reference.abs()
147    };
148    let budget = 64.0 * F64_EPSILON * scale_q;
149    let eval = BudgetEvaluation {
150        actual,
151        reference,
152        scale: scale_q,
153        abs_error,
154        rel_error,
155        budget,
156    };
157    if abs_error > budget {
158        return Err(ConservationValidationError::BudgetExceeded(eval));
159    }
160    Ok(eval)
161}
162
163/// Compute Higham's rounding constant $\gamma_N = \frac{N u}{1 - N u}$ with $u = 2^{-53}$.
164pub fn gamma_n_f64(n: usize) -> Result<f64, ConservationValidationError> {
165    if n == 0 {
166        return Err(ConservationValidationError::InvalidReductionCount { n });
167    }
168    let nu = (n as f64) * F64_UNIT_ROUNDOFF;
169    if !nu.is_finite() || nu >= 1.0 {
170        return Err(ConservationValidationError::InvalidReductionCount { n });
171    }
172    Ok(nu / (1.0 - nu))
173}
174
175/// Evaluate the C02-C09 $N$-term reduction / DFT budget:
176/// $|y - y_{\text{ref}}| \le 16\,\gamma_N \sum_{i=1}^N |t_i|$.
177pub fn verify_n_term_reduction_budget(
178    actual: f64,
179    reference: f64,
180    n_terms: usize,
181    sum_abs_terms: f64,
182) -> Result<BudgetEvaluation, ConservationValidationError> {
183    if !actual.is_finite() || !reference.is_finite() {
184        return Err(ConservationValidationError::NonFiniteValue {
185            context: "reduction_value",
186            value: if !actual.is_finite() { actual } else { reference },
187        });
188    }
189    if !sum_abs_terms.is_finite() || sum_abs_terms <= 0.0 {
190        return Err(ConservationValidationError::InvalidCharacteristicScale {
191            scale: sum_abs_terms,
192        });
193    }
194    let gamma = gamma_n_f64(n_terms)?;
195    let budget = 16.0 * gamma * sum_abs_terms;
196    let abs_error = (actual - reference).abs();
197    let rel_error = if reference == 0.0 {
198        abs_error / sum_abs_terms
199    } else {
200        abs_error / reference.abs()
201    };
202    let eval = BudgetEvaluation {
203        actual,
204        reference,
205        scale: sum_abs_terms,
206        abs_error,
207        rel_error,
208        budget,
209    };
210    if abs_error > budget {
211        return Err(ConservationValidationError::BudgetExceeded(eval));
212    }
213    Ok(eval)
214}
215
216/// Evaluate the C02-C09 QAC `B32` scalar budget:
217/// $|y - y_{\text{ref}}| \le 8\,u_{32} S + 2\times 10^{-6} |y_{\text{ref}}|, \quad u_{32} = 2^{-24}$.
218pub fn verify_b32_scalar_budget(
219    actual: f64,
220    reference: f64,
221    scale_s: f64,
222) -> Result<BudgetEvaluation, ConservationValidationError> {
223    if !actual.is_finite() || !reference.is_finite() {
224        return Err(ConservationValidationError::NonFiniteValue {
225            context: "b32_scalar",
226            value: if !actual.is_finite() { actual } else { reference },
227        });
228    }
229    if !scale_s.is_finite() || scale_s <= 0.0 {
230        return Err(ConservationValidationError::InvalidCharacteristicScale { scale: scale_s });
231    }
232    let budget = 8.0 * F32_UNIT_ROUNDOFF * scale_s + 2.0e-6 * reference.abs();
233    let abs_error = (actual - reference).abs();
234    let rel_error = if reference == 0.0 {
235        abs_error / scale_s
236    } else {
237        abs_error / reference.abs()
238    };
239    let eval = BudgetEvaluation {
240        actual,
241        reference,
242        scale: scale_s,
243        abs_error,
244        rel_error,
245        budget,
246    };
247    if abs_error > budget {
248        return Err(ConservationValidationError::BudgetExceeded(eval));
249    }
250    Ok(eval)
251}
252
253/// Evaluate the C02-C09 QAC `B32` vector budget:
254/// per-component `B32` scalar check plus relative $L_2 \le 5\times 10^{-6}$ when $\|\mathbf{y}_{\text{ref}}\|_2 > 0$.
255pub fn verify_b32_vector_budget(
256    actual: &[f64],
257    reference: &[f64],
258    scale_s: f64,
259) -> Result<f64, ConservationValidationError> {
260    if actual.len() != reference.len() || actual.is_empty() {
261        return Err(ConservationValidationError::InvalidReductionCount { n: actual.len() });
262    }
263    let mut diff_sq = 0.0f64;
264    let mut ref_sq = 0.0f64;
265    for (&a, &r) in actual.iter().zip(reference.iter()) {
266        verify_b32_scalar_budget(a, r, scale_s)?;
267        let d = a - r;
268        diff_sq += d * d;
269        ref_sq += r * r;
270    }
271    let l2_diff = diff_sq.sqrt();
272    let l2_ref = ref_sq.sqrt();
273    let rel_l2 = if l2_ref > 0.0 {
274        l2_diff / l2_ref
275    } else {
276        l2_diff / scale_s
277    };
278    if l2_ref > 0.0 && rel_l2 > 5.0e-6 {
279        return Err(ConservationValidationError::VectorRelativeL2Exceeded {
280            rel_l2_error: rel_l2,
281            max_allowed: 5.0e-6,
282            l2_diff,
283            l2_ref,
284        });
285    }
286    Ok(rel_l2)
287}
288
289/// Instantaneous electromagnetic Mode 0 oracle output (vacuum or isotropic lossless medium).
290#[derive(Debug, Clone, Copy, PartialEq)]
291pub struct EmMode0OracleResult {
292    /// Instantaneous Poynting vector $\mathbf{S} = \mathbf{E} \times \mathbf{H}$ ($\text{W/m}^2$).
293    pub poynting_w_per_m2: [f64; 3],
294    /// Peak-phasor time-averaged Poynting vector $\langle\mathbf{S}\rangle = \frac{1}{2}\mathbf{S}$ ($\text{W/m}^2$).
295    pub peak_phasor_mean_poynting_w_per_m2: [f64; 3],
296    /// Instantaneous electromagnetic energy density $u = \frac{1}{2}(\varepsilon \mathbf{E}^2 + \mu^{-1} \mathbf{B}^2)$ ($\text{J/m}^3$).
297    pub energy_density_j_per_m3: f64,
298}
299
300/// Evaluate the independent C02 Mode 0 instantaneous $\mathbf{E}/\mathbf{B}$ oracle in an
301/// isotropic medium ($\varepsilon_r > 0, \mu_r > 0$).
302pub fn evaluate_em_mode0_instantaneous_oracle(
303    e_v_per_m: [f64; 3],
304    b_tesla: [f64; 3],
305    epsilon_r: f64,
306    mu_r: f64,
307) -> Result<EmMode0OracleResult, ConservationValidationError> {
308    for &v in e_v_per_m.iter().chain(b_tesla.iter()) {
309        if !v.is_finite() {
310            return Err(ConservationValidationError::NonFiniteValue {
311                context: "em_mode0_field",
312                value: v,
313            });
314        }
315    }
316    if !epsilon_r.is_finite() || epsilon_r <= 0.0 || !mu_r.is_finite() || mu_r <= 0.0 {
317        return Err(ConservationValidationError::InvalidConstitutiveParameters {
318            epsilon_r,
319            mu_r,
320            sigma_s_per_m: 0.0,
321        });
322    }
323    let mu = VACUUM_PERMEABILITY_H_PER_M * mu_r;
324    let eps = VACUUM_PERMITTIVITY_F_PER_M * epsilon_r;
325    let ex_b = [
326        e_v_per_m[1] * b_tesla[2] - e_v_per_m[2] * b_tesla[1],
327        e_v_per_m[2] * b_tesla[0] - e_v_per_m[0] * b_tesla[2],
328        e_v_per_m[0] * b_tesla[1] - e_v_per_m[1] * b_tesla[0],
329    ];
330    let poynting = [ex_b[0] / mu, ex_b[1] / mu, ex_b[2] / mu];
331    let peak_mean = [0.5 * poynting[0], 0.5 * poynting[1], 0.5 * poynting[2]];
332    let e_sq = e_v_per_m[0] * e_v_per_m[0]
333        + e_v_per_m[1] * e_v_per_m[1]
334        + e_v_per_m[2] * e_v_per_m[2];
335    let b_sq =
336        b_tesla[0] * b_tesla[0] + b_tesla[1] * b_tesla[1] + b_tesla[2] * b_tesla[2];
337    let u = 0.5 * (eps * e_sq + b_sq / mu);
338
339    Ok(EmMode0OracleResult {
340        poynting_w_per_m2: poynting,
341        peak_phasor_mean_poynting_w_per_m2: peak_mean,
342        energy_density_j_per_m3: u,
343    })
344}
345
346/// Evaluate phase wavelength $\lambda = \frac{c_0}{f \sqrt{\varepsilon_r \mu_r}}$, strictly
347/// rejecting static/aperiodic fields ($f \le 0$) per C02-C02 and Mode 0.
348pub fn evaluate_em_wavelength_m(
349    carrier_hz: f64,
350    epsilon_r: f64,
351    mu_r: f64,
352) -> Result<f64, ConservationValidationError> {
353    if !carrier_hz.is_finite() || carrier_hz <= 0.0 {
354        return Err(ConservationValidationError::StaticFieldWavelengthForbidden { carrier_hz });
355    }
356    if !epsilon_r.is_finite() || epsilon_r <= 0.0 || !mu_r.is_finite() || mu_r <= 0.0 {
357        return Err(ConservationValidationError::InvalidConstitutiveParameters {
358            epsilon_r,
359            mu_r,
360            sigma_s_per_m: 0.0,
361        });
362    }
363    let phase_speed = VACUUM_SPEED_OF_LIGHT_M_PER_S / (epsilon_r * mu_r).sqrt();
364    Ok(phase_speed / carrier_hz)
365}
366
367/// Verify Poynting energy conservation and passivity balance:
368/// $\nabla\cdot\mathbf{S} + \frac{\partial u}{\partial t} = -w_{\text{loss}}$ with $w_{\text{loss}} = \sigma \|\mathbf{E}\|^2 \ge 0$.
369pub fn verify_poynting_conservation_balance(
370    div_s_w_per_m3: f64,
371    du_dt_w_per_m3: f64,
372    ohmic_loss_w_per_m3: f64,
373    power_scale_q: f64,
374) -> Result<f64, ConservationValidationError> {
375    if !div_s_w_per_m3.is_finite()
376        || !du_dt_w_per_m3.is_finite()
377        || !ohmic_loss_w_per_m3.is_finite()
378    {
379        return Err(ConservationValidationError::NonFiniteValue {
380            context: "poynting_balance",
381            value: div_s_w_per_m3 + du_dt_w_per_m3 + ohmic_loss_w_per_m3,
382        });
383    }
384    if !power_scale_q.is_finite() || power_scale_q <= 0.0 {
385        return Err(ConservationValidationError::InvalidCharacteristicScale {
386            scale: power_scale_q,
387        });
388    }
389    let budget = 64.0 * F64_EPSILON * power_scale_q;
390    if ohmic_loss_w_per_m3 < -budget {
391        return Err(
392            ConservationValidationError::PassivityOrConservationViolation {
393                residual: div_s_w_per_m3 + du_dt_w_per_m3 + ohmic_loss_w_per_m3,
394                dissipated_power_w_per_m3: ohmic_loss_w_per_m3,
395                budget,
396            },
397        );
398    }
399    let residual = (div_s_w_per_m3 + du_dt_w_per_m3 + ohmic_loss_w_per_m3).abs();
400    if residual > budget {
401        return Err(
402            ConservationValidationError::PassivityOrConservationViolation {
403                residual,
404                dissipated_power_w_per_m3: ohmic_loss_w_per_m3,
405                budget,
406            },
407        );
408    }
409    Ok(residual)
410}
411
412/// Verify Cartesian 3D Yee CFL stability (C02 Mode 2):
413/// $\Delta t \le \frac{1}{v \sqrt{\Delta x^{-2} + \Delta y^{-2} + \Delta z^{-2}}}$ with $v = \frac{c_0}{\sqrt{\varepsilon_r \mu_r}}$,
414/// and evaluate the exact discrete dispersion RHS $(v\Delta t)^2 \sum_{j=0}^2 \frac{\sin^2(k_j \Delta x_j / 2)}{\Delta x_j^2}$.
415pub fn verify_yee_cfl_and_dispersion(
416    dx_m: [f64; 3],
417    dt_s: f64,
418    epsilon_r: f64,
419    mu_r: f64,
420    wavevector_rad_per_m: [f64; 3],
421) -> Result<(f64, f64), ConservationValidationError> {
422    if !epsilon_r.is_finite() || epsilon_r <= 0.0 || !mu_r.is_finite() || mu_r <= 0.0 {
423        return Err(ConservationValidationError::InvalidConstitutiveParameters {
424            epsilon_r,
425            mu_r,
426            sigma_s_per_m: 0.0,
427        });
428    }
429    for &d in &dx_m {
430        if !d.is_finite() || d <= 0.0 {
431            return Err(ConservationValidationError::InvalidCharacteristicScale { scale: d });
432        }
433    }
434    if !dt_s.is_finite() || dt_s <= 0.0 {
435        return Err(ConservationValidationError::InvalidCharacteristicScale { scale: dt_s });
436    }
437    let v = VACUUM_SPEED_OF_LIGHT_M_PER_S / (epsilon_r * mu_r).sqrt();
438    let inv_h_norm = (1.0 / (dx_m[0] * dx_m[0])
439        + 1.0 / (dx_m[1] * dx_m[1])
440        + 1.0 / (dx_m[2] * dx_m[2]))
441        .sqrt();
442    let cfl_max_dt = 1.0 / (v * inv_h_norm);
443    let courant_ratio = dt_s / cfl_max_dt;
444    if courant_ratio > 1.0 + 64.0 * F64_EPSILON {
445        return Err(ConservationValidationError::CflStabilityViolation {
446            dt_s,
447            cfl_max_dt_s: cfl_max_dt,
448            courant_ratio,
449        });
450    }
451
452    let mut spatial_sum = 0.0f64;
453    for j in 0..3 {
454        let s = (0.5 * wavevector_rad_per_m[j] * dx_m[j]).sin();
455        spatial_sum += (s * s) / (dx_m[j] * dx_m[j]);
456    }
457    let rhs = (v * dt_s) * (v * dt_s) * spatial_sum;
458    let omega_num = (2.0 / dt_s) * rhs.clamp(0.0, 1.0).sqrt().asin();
459    Ok((cfl_max_dt, omega_num))
460}
461
462/// Independent QAC Mode 00 fluid acoustic oracle result.
463#[derive(Debug, Clone, Copy, PartialEq)]
464pub struct QacFluidMode00OracleResult {
465    pub sound_speed_m_per_s: f64,
466    pub characteristic_impedance_rayl: f64,
467    pub instantaneous_intensity_w_per_m2: [f64; 3],
468    pub cycle_mean_intensity_w_per_m2: [f64; 3],
469    pub instantaneous_energy_density_j_per_m3: f64,
470}
471
472/// Evaluate QAC Mode 00 fluid acoustic perturbation oracle (C02 Mode 00):
473/// $c = \sqrt{K/\rho}$, $Z = \sqrt{\rho K}$, $\mathbf{I} = p\mathbf{v}$, $e = \frac{1}{2}\rho\|\mathbf{v}\|^2 + \frac{p^2}{2K}$.
474/// Rejects non-collocated $p$ and $\mathbf{v}$ when `collocated` is false.
475pub fn evaluate_qac_fluid_mode00_oracle(
476    density_kg_per_m3: f64,
477    bulk_modulus_pa: f64,
478    pressure_pa: f64,
479    velocity_m_per_s: [f64; 3],
480    collocated: bool,
481) -> Result<QacFluidMode00OracleResult, ConservationValidationError> {
482    if !collocated {
483        return Err(ConservationValidationError::NonCollocatedPressureVelocityRejected);
484    }
485    if !density_kg_per_m3.is_finite()
486        || density_kg_per_m3 <= 0.0
487        || !bulk_modulus_pa.is_finite()
488        || bulk_modulus_pa <= 0.0
489    {
490        return Err(ConservationValidationError::InvalidMediumParameters {
491            density_kg_per_m3,
492            bulk_modulus_pa,
493            shear_modulus_pa: 0.0,
494        });
495    }
496    if !pressure_pa.is_finite() || velocity_m_per_s.iter().any(|v| !v.is_finite()) {
497        return Err(ConservationValidationError::NonFiniteValue {
498            context: "qac_mode00",
499            value: pressure_pa,
500        });
501    }
502    let c = (bulk_modulus_pa / density_kg_per_m3).sqrt();
503    let z = (density_kg_per_m3 * bulk_modulus_pa).sqrt();
504    let intensity = [
505        pressure_pa * velocity_m_per_s[0],
506        pressure_pa * velocity_m_per_s[1],
507        pressure_pa * velocity_m_per_s[2],
508    ];
509    let mean_intensity = [0.5 * intensity[0], 0.5 * intensity[1], 0.5 * intensity[2]];
510    let v_norm = scaled_hypot3(velocity_m_per_s[0], velocity_m_per_s[1], velocity_m_per_s[2]);
511    let energy = 0.5 * density_kg_per_m3 * (v_norm * v_norm)
512        + 0.5 * (pressure_pa * pressure_pa) / bulk_modulus_pa;
513
514    Ok(QacFluidMode00OracleResult {
515        sound_speed_m_per_s: c,
516        characteristic_impedance_rayl: z,
517        instantaneous_intensity_w_per_m2: intensity,
518        cycle_mean_intensity_w_per_m2: mean_intensity,
519        instantaneous_energy_density_j_per_m3: energy,
520    })
521}
522
523/// Independent QAC Mode 01 isotropic elastic solid oracle result.
524#[derive(Debug, Clone, Copy, PartialEq)]
525pub struct QacElasticMode01OracleResult {
526    pub lame_lambda_pa: f64,
527    pub compressional_speed_cp_m_per_s: f64,
528    pub shear_speed_cs_m_per_s: f64,
529    /// Six-component Cauchy stress $[\sigma_{xx}, \sigma_{yy}, \sigma_{zz}, \sigma_{xy}, \sigma_{yz}, \sigma_{xz}]$ ($\text{Pa}$, tensile-positive).
530    pub stress_xx_yy_zz_xy_yz_xz_pa: [f64; 6],
531    /// Mechanical pressure $p = -\frac{1}{3}(\sigma_{xx} + \sigma_{yy} + \sigma_{zz})$ ($\text{Pa}$).
532    pub mechanical_pressure_pa: f64,
533}
534
535/// Evaluate QAC Mode 01 small-strain isotropic elasticity oracle (C02 Mode 01):
536/// $\lambda = K - \frac{2}{3}\mu$, $c_P = \sqrt{\frac{\lambda + 2\mu}{\rho}}$, $c_S = \sqrt{\frac{\mu}{\rho}}$,
537/// $\boldsymbol{\sigma} = \lambda\operatorname{tr}(\boldsymbol{\varepsilon})\mathbf{I} + 2\mu\boldsymbol{\varepsilon}$,
538/// $p = -\frac{1}{3}\operatorname{tr}(\boldsymbol{\sigma})$.
539pub fn evaluate_qac_elastic_mode01_oracle(
540    density_kg_per_m3: f64,
541    bulk_modulus_pa: f64,
542    shear_modulus_pa: f64,
543    tensor_strain_xx_yy_zz_xy_yz_xz: [f64; 6],
544) -> Result<QacElasticMode01OracleResult, ConservationValidationError> {
545    if !density_kg_per_m3.is_finite()
546        || density_kg_per_m3 <= 0.0
547        || !bulk_modulus_pa.is_finite()
548        || bulk_modulus_pa <= 0.0
549        || !shear_modulus_pa.is_finite()
550        || shear_modulus_pa < 0.0
551    {
552        return Err(ConservationValidationError::InvalidMediumParameters {
553            density_kg_per_m3,
554            bulk_modulus_pa,
555            shear_modulus_pa,
556        });
557    }
558    let lambda = bulk_modulus_pa - (2.0 / 3.0) * shear_modulus_pa;
559    let cp = ((lambda + 2.0 * shear_modulus_pa) / density_kg_per_m3).sqrt();
560    let cs = (shear_modulus_pa / density_kg_per_m3).sqrt();
561    let tr_eps = tensor_strain_xx_yy_zz_xy_yz_xz[0]
562        + tensor_strain_xx_yy_zz_xy_yz_xz[1]
563        + tensor_strain_xx_yy_zz_xy_yz_xz[2];
564    let two_mu = 2.0 * shear_modulus_pa;
565    let stress = [
566        lambda * tr_eps + two_mu * tensor_strain_xx_yy_zz_xy_yz_xz[0],
567        lambda * tr_eps + two_mu * tensor_strain_xx_yy_zz_xy_yz_xz[1],
568        lambda * tr_eps + two_mu * tensor_strain_xx_yy_zz_xy_yz_xz[2],
569        two_mu * tensor_strain_xx_yy_zz_xy_yz_xz[3],
570        two_mu * tensor_strain_xx_yy_zz_xy_yz_xz[4],
571        two_mu * tensor_strain_xx_yy_zz_xy_yz_xz[5],
572    ];
573    let pressure = -(stress[0] + stress[1] + stress[2]) / 3.0;
574    Ok(QacElasticMode01OracleResult {
575        lame_lambda_pa: lambda,
576        compressional_speed_cp_m_per_s: cp,
577        shear_speed_cs_m_per_s: cs,
578        stress_xx_yy_zz_xy_yz_xz_pa: stress,
579        mechanical_pressure_pa: pressure,
580    })
581}
582
583/// Evaluate QAC Mode 03 normal-incidence planar acoustic interface coefficients:
584/// $r = \frac{Z_2 - Z_1}{Z_2 + Z_1}$, $t = \frac{2 Z_2}{Z_2 + Z_1}$,
585/// energy reflectance $R = r^2$, energy transmittance $T = \frac{Z_1}{Z_2} t^2$,
586/// verifying energy conservation $R + T = 1$.
587pub fn evaluate_acoustic_interface_oracle(
588    z1_rayl: f64,
589    z2_rayl: f64,
590) -> Result<(f64, f64, f64, f64), ConservationValidationError> {
591    if !z1_rayl.is_finite() || z1_rayl <= 0.0 || !z2_rayl.is_finite() || z2_rayl <= 0.0 {
592        return Err(ConservationValidationError::InvalidCharacteristicScale {
593            scale: z1_rayl.min(z2_rayl),
594        });
595    }
596    let sum = z1_rayl + z2_rayl;
597    let r = (z2_rayl - z1_rayl) / sum;
598    let t = (2.0 * z2_rayl) / sum;
599    let cap_r = r * r;
600    let cap_t = (z1_rayl / z2_rayl) * (t * t);
601    verify_f64_closed_form_budget(cap_r + cap_t, 1.0, 1.0)?;
602    Ok((r, t, cap_r, cap_t))
603}
604
605/// Verify Acoustic energy flux conservation and passivity:
606/// $\nabla\cdot\mathbf{I} + \frac{\partial e}{\partial t} = -w_{\text{loss}}$ with $w_{\text{loss}} \ge 0$.
607pub fn verify_acoustic_energy_conservation(
608    div_i_w_per_m3: f64,
609    de_dt_w_per_m3: f64,
610    viscous_loss_w_per_m3: f64,
611    scale_s: f64,
612) -> Result<f64, ConservationValidationError> {
613    verify_poynting_conservation_balance(
614        div_i_w_per_m3,
615        de_dt_w_per_m3,
616        viscous_loss_w_per_m3,
617        scale_s,
618    )
619}
620
621/// Verify passivity of a multi-port complex scattering matrix $\mathbf{S}$ (up to $4\times 4$):
622/// $\|\mathbf{S}\|_2 \le 1 + 64\,\varepsilon \iff \lambda_{\max}(\mathbf{S}^\dagger\mathbf{S}) \le (1 + 64\,\varepsilon)^2$.
623pub fn verify_scattering_matrix_passivity(
624    s_matrix: &[[Complex64; 4]; 4],
625    active_ports: usize,
626) -> Result<f64, ConservationValidationError> {
627    if active_ports == 0 || active_ports > 4 {
628        return Err(ConservationValidationError::InvalidReductionCount { n: active_ports });
629    }
630    let mut gram = [[Complex64::ZERO; 4]; 4];
631    for i in 0..active_ports {
632        for j in 0..active_ports {
633            let mut sum = Complex64::ZERO;
634            for k in 0..active_ports {
635                let s_ki = s_matrix[k][i];
636                let s_kj = s_matrix[k][j];
637                if !s_ki.re.is_finite()
638                    || !s_ki.im.is_finite()
639                    || !s_kj.re.is_finite()
640                    || !s_kj.im.is_finite()
641                {
642                    return Err(ConservationValidationError::NonFiniteValue {
643                        context: "scattering_matrix",
644                        value: f64::NAN,
645                    });
646                }
647                sum = sum.add(s_ki.conj().mul(s_kj));
648            }
649            gram[i][j] = sum;
650        }
651    }
652    let eigs = hermitian_4x4_eigenvalues(&gram);
653    let max_eig = eigs[3];
654    let tol_sq = (1.0 + 64.0 * F64_EPSILON) * (1.0 + 64.0 * F64_EPSILON);
655    if max_eig > tol_sq {
656        return Err(ConservationValidationError::ScatteringPassivityViolation {
657            max_singular_value_sq: max_eig,
658            tolerance_sq: tol_sq,
659        });
660    }
661    Ok(max_eig.max(0.0).sqrt())
662}
663
664/// Verify observed grid-refinement convergence order $p = \frac{\ln(E_1 / E_2)}{\ln(h_1 / h_2)} \ge p_{\min}$
665/// across successive grid spacings $h_1 > h_2$ with positive errors $E_1 > E_2 > 0$.
666pub fn verify_grid_convergence_order(
667    h_coarse: f64,
668    error_coarse: f64,
669    h_fine: f64,
670    error_fine: f64,
671    min_order: f64,
672) -> Result<f64, ConservationValidationError> {
673    if !h_coarse.is_finite()
674        || !h_fine.is_finite()
675        || h_coarse <= h_fine
676        || h_fine <= 0.0
677        || !error_coarse.is_finite()
678        || !error_fine.is_finite()
679        || error_coarse <= 0.0
680        || error_fine <= 0.0
681    {
682        return Err(ConservationValidationError::InvalidCharacteristicScale {
683            scale: error_fine,
684        });
685    }
686    let observed_order = (error_coarse / error_fine).ln() / (h_coarse / h_fine).ln();
687    if observed_order < min_order {
688        return Err(ConservationValidationError::ConvergenceOrderBelowMinimum {
689            observed_order,
690            minimum_order: min_order,
691            coarse_error: error_coarse,
692            fine_error: error_fine,
693        });
694    }
695    Ok(observed_order)
696}