Skip to main content

qualia_core_db/q42/material_coupling/
acoustic_coupling.rs

1//! Acoustic & continuum elastic material coupling (QAC Schema 200, Modes 0x0000/0x0001/0x0103,
2//! `.m64` constituent LUT & strata records, and C02-C06 namespace separation).
3
4use std::f64::consts::PI;
5
6use super::constitutive::ActiveHamiltonRotation;
7use crate::q42::m64_matter::{M64StrataColumnRecord, Q42ConstituentLutEntry};
8
9/// Errors arising during acoustic or elastic medium admission, wave evaluation, or namespace resolution.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub enum AcousticCouplingError {
12    NonFiniteParameter,
13    InvalidDensity { rho_kg_per_m3: f64 },
14    InvalidBulkModulus { bulk_modulus_pa: f64 },
15    InvalidShearModulus { shear_modulus_pa: f64 },
16    SolidRequiresPositiveShearModulus,
17    FluidRequiresZeroShearModulus { shear_modulus_pa: f64 },
18    EmfMaterialZeroUnbound,
19    EmfVacuumCannotPropagateMechanicalWave,
20    QacUniformMediumNotDeclared,
21    MaterialEntryOutOfBounds { index: u32, len: usize },
22    InvalidIncidenceAngle { theta_rad: f64 },
23    InvalidAttenuationExponent { y: f64 },
24    InvalidFrequency { omega_rad_s: f64 },
25    NonPositiveDefiniteOrthotropicStiffness,
26}
27
28/// Explicit medium classification for QAC Schema 200 (`Medium`).
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum MediumKind {
31    /// Inviscid or acoustic fluid ($\mu = 0$ exactly).
32    Fluid,
33    /// Isotropic linear elastic solid ($\mu > 0$; negative Lamé $\lambda$ permitted if $K > 0, \mu > 0$).
34    IsotropicSolid,
35}
36
37/// Validated fluid or isotropic elastic continuum medium (QAC Schema 200).
38#[derive(Clone, Copy, Debug, PartialEq)]
39pub struct ContinuumMedium {
40    pub kind: MediumKind,
41    /// Mass density $\rho > 0$ in $\text{kg}\cdot\text{m}^{-3}$.
42    pub density_kg_per_m3: f64,
43    /// Adiabatic bulk modulus $K > 0$ in $\text{Pa}$.
44    pub bulk_modulus_pa: f64,
45    /// Shear modulus $\mu \ge 0$ in $\text{Pa}$ ($\mu = 0$ for `Fluid`, $\mu > 0$ for `IsotropicSolid`).
46    pub shear_modulus_pa: f64,
47    /// Ambient static pressure $p_0$ in $\text{Pa}$.
48    pub ambient_pressure_pa: f64,
49    /// Stationary background flow velocity $\mathbf{v}_0$ in $\text{m}\cdot\text{s}^{-1}$ (zero for initial stationary solvers).
50    pub flow_velocity_m_per_s: [f64; 3],
51}
52
53impl ContinuumMedium {
54    /// Admit a fluid medium ($\rho > 0, K > 0, \mu = 0$). Rejects $\rho \le 0$ (vacuum is never $\rho = 0$).
55    pub fn new_fluid(
56        density_kg_per_m3: f64,
57        bulk_modulus_pa: f64,
58        ambient_pressure_pa: f64,
59    ) -> Result<Self, AcousticCouplingError> {
60        let m = Self {
61            kind: MediumKind::Fluid,
62            density_kg_per_m3,
63            bulk_modulus_pa,
64            shear_modulus_pa: 0.0,
65            ambient_pressure_pa,
66            flow_velocity_m_per_s: [0.0; 3],
67        };
68        m.validate()?;
69        Ok(m)
70    }
71
72    /// Admit an isotropic elastic solid medium ($\rho > 0, K > 0, \mu > 0$).
73    /// Note per C02-C06: negative Lamé $\lambda = K - \frac{2}{3}\mu$ is admissible when $K > 0$ and $\mu > 0$.
74    pub fn new_isotropic_solid(
75        density_kg_per_m3: f64,
76        bulk_modulus_pa: f64,
77        shear_modulus_pa: f64,
78        ambient_pressure_pa: f64,
79    ) -> Result<Self, AcousticCouplingError> {
80        let m = Self {
81            kind: MediumKind::IsotropicSolid,
82            density_kg_per_m3,
83            bulk_modulus_pa,
84            shear_modulus_pa,
85            ambient_pressure_pa,
86            flow_velocity_m_per_s: [0.0; 3],
87        };
88        m.validate()?;
89        Ok(m)
90    }
91
92    /// Construct from an `.m64` `Q42ConstituentLutEntry`.
93    /// Converts Young's modulus $E$ ($\text{MPa}$) and Poisson's ratio $\nu$ (or $c_P$ for fluids when $\nu = 0.50$).
94    pub fn from_m64_lut_entry(entry: &Q42ConstituentLutEntry) -> Result<Self, AcousticCouplingError> {
95        let rho = entry.bulk_density_kg_m3 as f64;
96        if rho <= 0.0 {
97            return Err(AcousticCouplingError::InvalidDensity { rho_kg_per_m3: rho });
98        }
99        let nu = (entry.poissons_ratio_x100 as f64) * 0.01;
100        let e_pa = (entry.youngs_modulus_mpa as f64) * 1e6;
101        if entry.poissons_ratio_x100 >= 50 || e_pa == 0.0 {
102            // Fluid limit: derive bulk modulus from acoustic P-wave velocity if E is not a solid Young's modulus
103            let cp = entry.acoustic_p_wave_m_s as f64;
104            let k_pa = if cp > 0.0 { rho * cp * cp } else { e_pa };
105            Self::new_fluid(rho, k_pa, 101_325.0)
106        } else {
107            let k_pa = e_pa / (3.0 * (1.0 - 2.0 * nu));
108            let mu_pa = e_pa / (2.0 * (1.0 + nu));
109            Self::new_isotropic_solid(rho, k_pa, mu_pa, 101_325.0)
110        }
111    }
112
113    /// Construct an equivalent fluid/poroelastic P-wave medium from an `.m64` `M64StrataColumnRecord`
114    /// and its referenced LUT grain density.
115    pub fn from_m64_strata_record(
116        strata: &M64StrataColumnRecord,
117        bulk_density_kg_per_m3: f64,
118    ) -> Result<Self, AcousticCouplingError> {
119        let cp = strata.acoustic_p_wave_m_s as f64;
120        let mu_pa = (strata.bulk_shear_strength_kpa as f64) * 1e3;
121        let p_mod = bulk_density_kg_per_m3 * cp * cp;
122        let k_pa = p_mod - (4.0 / 3.0) * mu_pa;
123        if mu_pa > 0.0 {
124            Self::new_isotropic_solid(bulk_density_kg_per_m3, k_pa, mu_pa, 101_325.0)
125        } else {
126            Self::new_fluid(bulk_density_kg_per_m3, p_mod, 101_325.0)
127        }
128    }
129
130    /// Validate physical bounds per C02-C06.
131    pub fn validate(&self) -> Result<(), AcousticCouplingError> {
132        if !self.density_kg_per_m3.is_finite()
133            || !self.bulk_modulus_pa.is_finite()
134            || !self.shear_modulus_pa.is_finite()
135            || !self.ambient_pressure_pa.is_finite()
136            || self.flow_velocity_m_per_s.iter().any(|v| !v.is_finite())
137        {
138            return Err(AcousticCouplingError::NonFiniteParameter);
139        }
140        if self.density_kg_per_m3 <= 0.0 {
141            return Err(AcousticCouplingError::InvalidDensity {
142                rho_kg_per_m3: self.density_kg_per_m3,
143            });
144        }
145        if self.bulk_modulus_pa <= 0.0 {
146            return Err(AcousticCouplingError::InvalidBulkModulus {
147                bulk_modulus_pa: self.bulk_modulus_pa,
148            });
149        }
150        if self.shear_modulus_pa < 0.0 {
151            return Err(AcousticCouplingError::InvalidShearModulus {
152                shear_modulus_pa: self.shear_modulus_pa,
153            });
154        }
155        match self.kind {
156            MediumKind::Fluid => {
157                if self.shear_modulus_pa != 0.0 {
158                    return Err(AcousticCouplingError::FluidRequiresZeroShearModulus {
159                        shear_modulus_pa: self.shear_modulus_pa,
160                    });
161                }
162            }
163            MediumKind::IsotropicSolid => {
164                if self.shear_modulus_pa <= 0.0 {
165                    return Err(AcousticCouplingError::SolidRequiresPositiveShearModulus);
166                }
167            }
168        }
169        Ok(())
170    }
171
172    /// First Lamé parameter $\lambda = K - \frac{2}{3}\mu$ in $\text{Pa}$.
173    #[inline]
174    pub fn lame_lambda_pa(&self) -> f64 {
175        self.bulk_modulus_pa - (2.0 / 3.0) * self.shear_modulus_pa
176    }
177
178    /// P-wave (plane-strain longitudinal) modulus $M = K + \frac{4}{3}\mu = \lambda + 2\mu$ in $\text{Pa}$.
179    #[inline]
180    pub fn p_wave_modulus_pa(&self) -> f64 {
181        self.bulk_modulus_pa + (4.0 / 3.0) * self.shear_modulus_pa
182    }
183
184    /// Longitudinal (compressional P-wave) phase speed $c_P = \sqrt{\frac{K + \frac{4}{3}\mu}{\rho}}$ in $\text{m}\cdot\text{s}^{-1}$.
185    #[inline]
186    pub fn longitudinal_speed_m_per_s(&self) -> f64 {
187        (self.p_wave_modulus_pa() / self.density_kg_per_m3).sqrt()
188    }
189
190    /// Transverse (shear S-wave) phase speed $c_S = \sqrt{\frac{\mu}{\rho}}$ in $\text{m}\cdot\text{s}^{-1}$ ($0$ for fluids).
191    #[inline]
192    pub fn shear_speed_m_per_s(&self) -> f64 {
193        (self.shear_modulus_pa / self.density_kg_per_m3).sqrt()
194    }
195
196    /// Characteristic longitudinal acoustic impedance $Z_P = \rho c_P$ in $\text{Pa}\cdot\text{s}\cdot\text{m}^{-1}$ ($\text{Rayl}$).
197    #[inline]
198    pub fn characteristic_impedance_rayl(&self) -> f64 {
199        self.density_kg_per_m3 * self.longitudinal_speed_m_per_s()
200    }
201
202    /// Characteristic shear impedance $Z_S = \rho c_S$ in $\text{Pa}\cdot\text{s}\cdot\text{m}^{-1}$.
203    #[inline]
204    pub fn shear_impedance_rayl(&self) -> f64 {
205        self.density_kg_per_m3 * self.shear_speed_m_per_s()
206    }
207}
208
209/// Six-component symmetric Cauchy stress tensor (`[xx, yy, zz, xy, yz, xz]`, tensile-positive) per C02-C04 / QAC Mode 01.
210#[derive(Clone, Copy, Debug, Default, PartialEq)]
211pub struct CauchyStress6 {
212    pub xx_yy_zz_xy_yz_xz_pa: [f64; 6],
213}
214
215/// Six-component symmetric small-strain tensor (`[xx, yy, zz, xy, yz, xz]` using tensor shear $\varepsilon_{xy}$,
216/// NOT engineering shear $\gamma_{xy} = 2\varepsilon_{xy}$) per C02-C04.
217#[derive(Clone, Copy, Debug, Default, PartialEq)]
218pub struct TensorStrain6 {
219    pub xx_yy_zz_xy_yz_xz: [f64; 6],
220}
221
222impl TensorStrain6 {
223    /// Volumetric dilatation $\operatorname{tr}(\varepsilon) = \varepsilon_{xx} + \varepsilon_{yy} + \varepsilon_{zz}$.
224    #[inline]
225    pub fn trace(&self) -> f64 {
226        self.xx_yy_zz_xy_yz_xz[0] + self.xx_yy_zz_xy_yz_xz[1] + self.xx_yy_zz_xy_yz_xz[2]
227    }
228
229    /// Convert to full $3\times 3$ symmetric matrix.
230    #[inline]
231    pub fn to_matrix(&self) -> [[f64; 3]; 3] {
232        let [xx, yy, zz, xy, yz, xz] = self.xx_yy_zz_xy_yz_xz;
233        [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]
234    }
235}
236
237impl CauchyStress6 {
238    /// Compute isotropic Cauchy stress from tensor strain:
239    /// $\sigma_{ij} = \lambda \operatorname{tr}(\varepsilon)\delta_{ij} + 2\mu \varepsilon_{ij}$.
240    pub fn from_isotropic_strain(medium: &ContinuumMedium, strain: &TensorStrain6) -> Self {
241        let lambda = medium.lame_lambda_pa();
242        let two_mu = 2.0 * medium.shear_modulus_pa;
243        let tr = strain.trace();
244        let [exx, eyy, ezz, exy, eyz, exz] = strain.xx_yy_zz_xy_yz_xz;
245        Self {
246            xx_yy_zz_xy_yz_xz_pa: [
247                lambda * tr + two_mu * exx,
248                lambda * tr + two_mu * eyy,
249                lambda * tr + two_mu * ezz,
250                two_mu * exy,
251                two_mu * eyz,
252                two_mu * exz,
253            ],
254        }
255    }
256
257    /// Trace $\operatorname{tr}(\sigma) = \sigma_{xx} + \sigma_{yy} + \sigma_{zz}$ in $\text{Pa}$.
258    #[inline]
259    pub fn trace_pa(&self) -> f64 {
260        self.xx_yy_zz_xy_yz_xz_pa[0] + self.xx_yy_zz_xy_yz_xz_pa[1] + self.xx_yy_zz_xy_yz_xz_pa[2]
261    }
262
263    /// Mechanical hydrostatic pressure $p = -\frac{1}{3}\operatorname{tr}(\sigma)$ in $\text{Pa}$ (compressive-positive).
264    #[inline]
265    pub fn mechanical_pressure_pa(&self) -> f64 {
266        -self.trace_pa() / 3.0
267    }
268
269    /// Convert to full $3\times 3$ symmetric matrix.
270    #[inline]
271    pub fn to_matrix(&self) -> [[f64; 3]; 3] {
272        let [xx, yy, zz, xy, yz, xz] = self.xx_yy_zz_xy_yz_xz_pa;
273        [[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]]
274    }
275
276    /// Construct from a $3\times 3$ symmetric matrix.
277    #[inline]
278    pub fn from_matrix(m: &[[f64; 3]; 3]) -> Self {
279        Self {
280            xx_yy_zz_xy_yz_xz_pa: [
281                m[0][0],
282                m[1][1],
283                m[2][2],
284                0.5 * (m[0][1] + m[1][0]),
285                0.5 * (m[1][2] + m[2][1]),
286                0.5 * (m[0][2] + m[2][0]),
287            ],
288        }
289    }
290
291    /// Rotate stress tensor into parent frame via $R(q)\,\sigma\,R(q)^T$ per C02-C04.
292    pub fn rotate_to_parent(&self, rot: &ActiveHamiltonRotation) -> Self {
293        let rotated = rot.rotate_tensor_real(&self.to_matrix());
294        Self::from_matrix(&rotated)
295    }
296}
297
298/// Orthotropic 9-constant elastic stiffness tensor in Voigt order `[xx, yy, zz, xy, yz, xz]`.
299#[derive(Clone, Copy, Debug, PartialEq)]
300pub struct OrthotropicElasticMedium {
301    pub density_kg_per_m3: f64,
302    pub c11: f64,
303    pub c22: f64,
304    pub c33: f64,
305    pub c12: f64,
306    pub c13: f64,
307    pub c23: f64,
308    pub c44: f64,
309    pub c55: f64,
310    pub c66: f64,
311}
312
313impl OrthotropicElasticMedium {
314    /// Validate thermodynamic stability (Sylvester's criterion on upper $3\times 3$ block and shear diagonals).
315    pub fn validate(&self) -> Result<(), AcousticCouplingError> {
316        let vals = [
317            self.density_kg_per_m3,
318            self.c11,
319            self.c22,
320            self.c33,
321            self.c12,
322            self.c13,
323            self.c23,
324            self.c44,
325            self.c55,
326            self.c66,
327        ];
328        if vals.iter().any(|v| !v.is_finite()) {
329            return Err(AcousticCouplingError::NonFiniteParameter);
330        }
331        if self.density_kg_per_m3 <= 0.0 {
332            return Err(AcousticCouplingError::InvalidDensity {
333                rho_kg_per_m3: self.density_kg_per_m3,
334            });
335        }
336        let m1 = self.c11;
337        let m2 = self.c11 * self.c22 - self.c12 * self.c12;
338        let m3 = self.c11 * (self.c22 * self.c33 - self.c23 * self.c23)
339            - self.c12 * (self.c12 * self.c33 - self.c23 * self.c13)
340            + self.c13 * (self.c12 * self.c23 - self.c22 * self.c13);
341        if m1 <= 0.0 || m2 <= 0.0 || m3 <= 0.0 || self.c44 <= 0.0 || self.c55 <= 0.0 || self.c66 <= 0.0 {
342            return Err(AcousticCouplingError::NonPositiveDefiniteOrthotropicStiffness);
343        }
344        Ok(())
345    }
346
347    /// Evaluate Cauchy stress from tensor strain (`[exx, eyy, ezz, exy, eyz, exz]`).
348    pub fn evaluate_stress(&self, strain: &TensorStrain6) -> CauchyStress6 {
349        let [exx, eyy, ezz, exy, eyz, exz] = strain.xx_yy_zz_xy_yz_xz;
350        CauchyStress6 {
351            xx_yy_zz_xy_yz_xz_pa: [
352                self.c11 * exx + self.c12 * eyy + self.c13 * ezz,
353                self.c12 * exx + self.c22 * eyy + self.c23 * ezz,
354                self.c13 * exx + self.c23 * eyy + self.c33 * ezz,
355                2.0 * self.c66 * exy,
356                2.0 * self.c44 * eyz,
357                2.0 * self.c55 * exz,
358            ],
359        }
360    }
361}
362
363/// Planar acoustic interface reflection and transmission coefficients (pressure amplitude & energy flux).
364#[derive(Clone, Copy, Debug, PartialEq)]
365pub struct InterfaceScatteringCoefficients {
366    /// Pressure reflection coefficient $r_p = p_{\text{refl}} / p_{\text{inc}}$.
367    pub pressure_reflection: f64,
368    /// Pressure transmission coefficient $t_p = p_{\text{trans}} / p_{\text{inc}}$ (can exceed $1.0$ when $Z_2 > Z_1$).
369    pub pressure_transmission: f64,
370    /// Reflected normal intensity/energy fraction $R_E \in [0, 1]$.
371    pub energy_reflection: f64,
372    /// Transmitted normal intensity/energy fraction $T_E \in [0, 1]$, satisfying $R_E + T_E = 1$.
373    pub energy_transmission: f64,
374    /// True if incidence angle exceeds critical angle $\theta_c = \arcsin(c_1 / c_2)$ (total internal reflection).
375    pub total_internal_reflection: bool,
376}
377
378/// Evaluate normal or oblique planar interface reflection and transmission between two media
379/// using longitudinal impedances $Z_1 = \rho_1 c_{P,1}$ and $Z_2 = \rho_2 c_{P,2}$.
380pub fn evaluate_planar_interface_scattering(
381    medium_1: &ContinuumMedium,
382    medium_2: &ContinuumMedium,
383    theta_incident_rad: f64,
384) -> Result<InterfaceScatteringCoefficients, AcousticCouplingError> {
385    medium_1.validate()?;
386    medium_2.validate()?;
387    if !theta_incident_rad.is_finite() || !(0.0..(0.5 * PI)).contains(&theta_incident_rad) {
388        return Err(AcousticCouplingError::InvalidIncidenceAngle {
389            theta_rad: theta_incident_rad,
390        });
391    }
392    let c1 = medium_1.longitudinal_speed_m_per_s();
393    let c2 = medium_2.longitudinal_speed_m_per_s();
394    let z1 = medium_1.characteristic_impedance_rayl();
395    let z2 = medium_2.characteristic_impedance_rayl();
396
397    let cos_theta_1 = theta_incident_rad.cos();
398    let sin_theta_1 = theta_incident_rad.sin();
399    let sin_theta_2 = (c2 / c1) * sin_theta_1;
400
401    if sin_theta_2 >= 1.0 {
402        // Total internal reflection: evanescent transmitted wave carries zero normal active power
403        return Ok(InterfaceScatteringCoefficients {
404            pressure_reflection: 1.0,
405            pressure_transmission: 0.0,
406            energy_reflection: 1.0,
407            energy_transmission: 0.0,
408            total_internal_reflection: true,
409        });
410    }
411
412    let cos_theta_2 = (1.0 - sin_theta_2 * sin_theta_2).sqrt();
413    let z1_obl = z1 / cos_theta_1;
414    let z2_obl = z2 / cos_theta_2;
415
416    let rp = (z2_obl - z1_obl) / (z2_obl + z1_obl);
417    let tp = (2.0 * z2_obl) / (z2_obl + z1_obl);
418    let re = rp * rp;
419    let te = (z1_obl / z2_obl) * tp * tp;
420
421    Ok(InterfaceScatteringCoefficients {
422        pressure_reflection: rp,
423        pressure_transmission: tp,
424        energy_reflection: re,
425        energy_transmission: te,
426        total_internal_reflection: false,
427    })
428}
429
430/// Oblique fluid-solid interface energy partitioning (incident fluid P-wave into reflected fluid P,
431/// transmitted solid P, and mode-converted solid SV shear wave).
432#[derive(Clone, Copy, Debug, PartialEq)]
433pub struct FluidSolidObliquePartition {
434    pub pressure_reflection: f64,
435    pub energy_reflection_p: f64,
436    pub energy_transmission_p: f64,
437    pub energy_transmission_sv: f64,
438}
439
440/// Evaluate oblique fluid-to-isotropic-solid wave partitioning via effective normal impedances
441/// $Z_{\text{eff}} = Z_P \cos^2(2\theta_S) + Z_S \sin^2(2\theta_S)$.
442pub fn evaluate_fluid_solid_oblique_partition(
443    fluid: &ContinuumMedium,
444    solid: &ContinuumMedium,
445    theta_incident_rad: f64,
446) -> Result<FluidSolidObliquePartition, AcousticCouplingError> {
447    fluid.validate()?;
448    solid.validate()?;
449    if fluid.kind != MediumKind::Fluid {
450        return Err(AcousticCouplingError::FluidRequiresZeroShearModulus {
451            shear_modulus_pa: fluid.shear_modulus_pa,
452        });
453    }
454    if solid.kind != MediumKind::IsotropicSolid {
455        return Err(AcousticCouplingError::SolidRequiresPositiveShearModulus);
456    }
457    if !theta_incident_rad.is_finite() || !(0.0..(0.5 * PI)).contains(&theta_incident_rad) {
458        return Err(AcousticCouplingError::InvalidIncidenceAngle {
459            theta_rad: theta_incident_rad,
460        });
461    }
462    let cf = fluid.longitudinal_speed_m_per_s();
463    let cp = solid.longitudinal_speed_m_per_s();
464    let cs = solid.shear_speed_m_per_s();
465
466    let sin_i = theta_incident_rad.sin();
467    let cos_i = theta_incident_rad.cos();
468    let zf_obl = fluid.characteristic_impedance_rayl() / cos_i;
469
470    let sin_p = (cp / cf) * sin_i;
471    let sin_s = (cs / cf) * sin_i;
472
473    if sin_p >= 1.0 && sin_s >= 1.0 {
474        return Ok(FluidSolidObliquePartition {
475            pressure_reflection: 1.0,
476            energy_reflection_p: 1.0,
477            energy_transmission_p: 0.0,
478            energy_transmission_sv: 0.0,
479        });
480    }
481
482    let cos_2s = 1.0 - 2.0 * sin_s * sin_s;
483    let sin_2s = 2.0 * sin_s * (1.0 - sin_s * sin_s).max(0.0).sqrt();
484
485    let zp_part = if sin_p < 1.0 {
486        let cos_p = (1.0 - sin_p * sin_p).sqrt();
487        (solid.characteristic_impedance_rayl() / cos_p) * cos_2s * cos_2s
488    } else {
489        0.0
490    };
491    let zs_part = if sin_s < 1.0 {
492        let cos_s = (1.0 - sin_s * sin_s).sqrt();
493        (solid.shear_impedance_rayl() / cos_s) * sin_2s * sin_2s
494    } else {
495        0.0
496    };
497
498    let z_solid_eff = zp_part + zs_part;
499    let rp = (z_solid_eff - zf_obl) / (z_solid_eff + zf_obl);
500    let re = rp * rp;
501    let trans_total = 1.0 - re;
502    let (tp_e, tsv_e) = if z_solid_eff > 0.0 {
503        (
504            trans_total * (zp_part / z_solid_eff),
505            trans_total * (zs_part / z_solid_eff),
506        )
507    } else {
508        (0.0, 0.0)
509    };
510
511    Ok(FluidSolidObliquePartition {
512        pressure_reflection: rp,
513        energy_reflection_p: re,
514        energy_transmission_p: tp_e,
515        energy_transmission_sv: tsv_e,
516    })
517}
518
519/// Power-law acoustic attenuation & Kramers-Kronig causal dispersion model (Szabo / Waters law):
520/// $\alpha(\omega) = \alpha_0 |\omega|^y$ ($\text{Np}\cdot\text{m}^{-1}$).
521#[derive(Clone, Copy, Debug, PartialEq)]
522pub struct PowerLawAcousticAttenuation {
523    /// Reference angular frequency $\omega_0 > 0$ ($\text{rad}\cdot\text{s}^{-1}$).
524    pub omega_0_rad_s: f64,
525    /// Phase speed $c(\omega_0) > 0$ at reference frequency ($\text{m}\cdot\text{s}^{-1}$).
526    pub c_0_m_per_s: f64,
527    /// Power-law prefactor $\alpha_0 \ge 0$ in $\text{Np}\cdot\text{m}^{-1}\cdot(\text{rad/s})^{-y}$.
528    pub alpha_0_np_per_m_rad_s_y: f64,
529    /// Power-law exponent $y \in (0, 2]$.
530    pub exponent_y: f64,
531}
532
533impl PowerLawAcousticAttenuation {
534    pub fn validate(&self) -> Result<(), AcousticCouplingError> {
535        if !self.omega_0_rad_s.is_finite()
536            || !self.c_0_m_per_s.is_finite()
537            || !self.alpha_0_np_per_m_rad_s_y.is_finite()
538            || !self.exponent_y.is_finite()
539        {
540            return Err(AcousticCouplingError::NonFiniteParameter);
541        }
542        if self.omega_0_rad_s <= 0.0 {
543            return Err(AcousticCouplingError::InvalidFrequency {
544                omega_rad_s: self.omega_0_rad_s,
545            });
546        }
547        if self.c_0_m_per_s <= 0.0 {
548            return Err(AcousticCouplingError::InvalidBulkModulus {
549                bulk_modulus_pa: self.c_0_m_per_s,
550            });
551        }
552        if self.alpha_0_np_per_m_rad_s_y < 0.0 || self.exponent_y <= 0.0 || self.exponent_y > 2.0 {
553            return Err(AcousticCouplingError::InvalidAttenuationExponent { y: self.exponent_y });
554        }
555        Ok(())
556    }
557
558    /// Attenuation $\alpha(\omega) = \alpha_0 \omega^y$ in $\text{Np}\cdot\text{m}^{-1}$.
559    pub fn attenuation_np_per_m(&self, omega_rad_s: f64) -> Result<f64, AcousticCouplingError> {
560        self.validate()?;
561        if !omega_rad_s.is_finite() || omega_rad_s <= 0.0 {
562            return Err(AcousticCouplingError::InvalidFrequency { omega_rad_s });
563        }
564        Ok(self.alpha_0_np_per_m_rad_s_y * omega_rad_s.powf(self.exponent_y))
565    }
566
567    /// Kramers-Kronig causal phase velocity $c(\omega)$ in $\text{m}\cdot\text{s}^{-1}$:
568    /// - For $y = 1$: $\frac{1}{c(\omega)} = \frac{1}{c(\omega_0)} - \frac{2\alpha_0}{\pi}\ln\left(\frac{\omega}{\omega_0}\right)$
569    /// - For $y \ne 1, y < 2$: $\frac{1}{c(\omega)} = \frac{1}{c(\omega_0)} + \alpha_0 \tan\left(\frac{\pi y}{2}\right)\left(\omega^{y-1} - \omega_0^{y-1}\right)$
570    /// - For $y = 2$ (thermoviscous Stokes limit): nondispersive to leading order, $c(\omega) = c(\omega_0)$.
571    pub fn phase_velocity_m_per_s(&self, omega_rad_s: f64) -> Result<f64, AcousticCouplingError> {
572        self.validate()?;
573        if !omega_rad_s.is_finite() || omega_rad_s <= 0.0 {
574            return Err(AcousticCouplingError::InvalidFrequency { omega_rad_s });
575        }
576        let inv_c0 = 1.0 / self.c_0_m_per_s;
577        let delta_slowness = if (self.exponent_y - 1.0).abs() < 1e-9 {
578            -(2.0 * self.alpha_0_np_per_m_rad_s_y / PI) * (omega_rad_s / self.omega_0_rad_s).ln()
579        } else if (self.exponent_y - 2.0).abs() < 1e-9 {
580            0.0
581        } else {
582            self.alpha_0_np_per_m_rad_s_y
583                * (0.5 * PI * self.exponent_y).tan()
584                * (omega_rad_s.powf(self.exponent_y - 1.0)
585                    - self.omega_0_rad_s.powf(self.exponent_y - 1.0))
586        };
587        let inv_c = inv_c0 + delta_slowness;
588        if inv_c <= 0.0 {
589            return Err(AcousticCouplingError::InvalidFrequency { omega_rad_s });
590        }
591        Ok(1.0 / inv_c)
592    }
593}
594
595/// C02-C06 EMF `material_entry == 0` policy: `0` is unbound unless the stream profile explicitly
596/// declares `0 = vacuum` (e.g. Mode 0x0101 `polarimetric_ray_v1`).
597#[derive(Clone, Copy, Debug, PartialEq, Eq)]
598pub enum EmfMaterialZeroPolicy {
599    UnboundRejected,
600    ExplicitVacuumAdmitted,
601}
602
603/// Resolved EMF material reference under C02-C06.
604#[derive(Clone, Copy, Debug, PartialEq, Eq)]
605pub enum ResolvedEmfMaterial {
606    ExplicitVacuum,
607    TableEntry { one_based_index: u32 },
608}
609
610/// Resolve an EMF `material_entry` (`u32`) under C02-C06 without conflating `0` with QAC's uniform medium.
611pub fn resolve_emf_material_entry(
612    material_entry: u32,
613    table_len: usize,
614    zero_policy: EmfMaterialZeroPolicy,
615) -> Result<ResolvedEmfMaterial, AcousticCouplingError> {
616    if material_entry == 0 {
617        match zero_policy {
618            EmfMaterialZeroPolicy::UnboundRejected => {
619                Err(AcousticCouplingError::EmfMaterialZeroUnbound)
620            }
621            EmfMaterialZeroPolicy::ExplicitVacuumAdmitted => Ok(ResolvedEmfMaterial::ExplicitVacuum),
622        }
623    } else if (material_entry as usize) > table_len {
624        Err(AcousticCouplingError::MaterialEntryOutOfBounds {
625            index: material_entry,
626            len: table_len,
627        })
628    } else {
629        Ok(ResolvedEmfMaterial::TableEntry {
630            one_based_index: material_entry,
631        })
632    }
633}
634
635/// Resolve a QAC `material_ref` (`u32`) under C02-C06:
636/// `material_ref == 0` resolves to the explicitly declared uniform `ContinuumMedium` (Schema 200),
637/// NEVER vacuum or $\rho = 0$.
638pub fn resolve_qac_material_ref<'a>(
639    material_ref: u32,
640    declared_uniform_medium: Option<&'a ContinuumMedium>,
641    material_table: &'a [ContinuumMedium],
642) -> Result<&'a ContinuumMedium, AcousticCouplingError> {
643    if material_ref == 0 {
644        let m = declared_uniform_medium.ok_or(AcousticCouplingError::QacUniformMediumNotDeclared)?;
645        m.validate()?;
646        Ok(m)
647    } else {
648        let idx = (material_ref as usize) - 1;
649        let m = material_table
650            .get(idx)
651            .ok_or(AcousticCouplingError::MaterialEntryOutOfBounds {
652                index: material_ref,
653                len: material_table.len(),
654            })?;
655        m.validate()?;
656        Ok(m)
657    }
658}