Skip to main content

qualia_core_db/q42/material_coupling/
constitutive.rs

1//! Constitutive electromagnetic models, multi-pole dispersion (Debye + Lorentz + Drude/Ohmic),
2//! and C02-C04 active Hamilton quaternion frame & $3\times 3$ tensor transformations.
3//!
4//! Governs Schema 133 (`ConstitutiveModel`) and couples `.m64` (`Q42ConstituentLutEntry` /
5//! `M64StrataColumnRecord`), EMF v4 (`Q42EMF64`), and QAC v1 (`qac\0\0\0\0\0`).
6
7use crate::q42::m64_matter::{M64StrataColumnRecord, Q42ConstituentLutEntry};
8
9/// Vacuum electric permittivity $\varepsilon_0$ in $\text{F}\cdot\text{m}^{-1}$ (SI 2019 value).
10pub const EPSILON_0_F_PER_M: f64 = 8.854_187_812_8e-12;
11
12/// Vacuum magnetic permeability $\mu_0$ in $\text{H}\cdot\text{m}^{-1}$ (SI 2019 value).
13pub const MU_0_H_PER_M: f64 = 1.256_637_062_12e-6;
14
15/// Speed of light in vacuum $c_0$ in $\text{m}\cdot\text{s}^{-1}$ (exact SI definition).
16pub const C_0_M_PER_S: f64 = 299_792_458.0;
17
18/// Free-space wave impedance $Z_0 = \sqrt{\mu_0 / \varepsilon_0}$ in $\Omega$.
19pub const Z_0_OHMS: f64 = 376.730_313_668;
20
21/// Maximum admitted deviation of raw quaternion squared norm from $1.0$ per C02-C04.
22pub const QUATERNION_NORM_SQ_TOLERANCE: f64 = 1e-12;
23
24/// Maximum orthogonality residual for derived $3\times 3$ rotation matrices ($64 \times 2^{-52}$).
25pub const ROTATION_ORTHOGONALITY_BUDGET: f64 = 64.0 * f64::EPSILON;
26
27/// Errors arising during constitutive model admission, evaluation, or frame rotation.
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub enum ConstitutiveError {
30    NonFiniteParameter,
31    InvalidHighFrequencyLimit { value: f64 },
32    InvalidConductivity { sigma_s_per_m: f64 },
33    InvalidDebyePole { index: usize, delta: f64, tau_s: f64 },
34    InvalidLorentzPole {
35        index: usize,
36        delta: f64,
37        omega_0_rad_s: f64,
38        gamma_rad_s: f64,
39    },
40    InvalidFrequency { omega_rad_s: f64 },
41    QuaternionNormOutOfBounds { norm_sq: f64, deviation: f64 },
42    NonSymmetricTensor { max_asymmetry: f64 },
43    NonPositiveDefiniteTensor { min_diagonal_or_minor: f64 },
44}
45
46/// Complex scalar $z = \text{re} + i\,\text{im}$ in `f64` precision under the $\exp(-i\omega t)$ harmonic convention.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct Complex64 {
49    pub re: f64,
50    pub im: f64,
51}
52
53impl Complex64 {
54    #[inline]
55    pub const fn new(re: f64, im: f64) -> Self {
56        Self { re, im }
57    }
58
59    #[inline]
60    pub fn is_finite(self) -> bool {
61        self.re.is_finite() && self.im.is_finite()
62    }
63
64    #[inline]
65    pub const fn conj(self) -> Self {
66        Self {
67            re: self.re,
68            im: -self.im,
69        }
70    }
71
72    #[inline]
73    pub fn norm_sq(self) -> f64 {
74        self.re * self.re + self.im * self.im
75    }
76
77    #[inline]
78    pub fn abs(self) -> f64 {
79        self.re.hypot(self.im)
80    }
81
82    #[inline]
83    pub fn add(self, rhs: Self) -> Self {
84        Self {
85            re: self.re + rhs.re,
86            im: self.im + rhs.im,
87        }
88    }
89
90    #[inline]
91    pub fn sub(self, rhs: Self) -> Self {
92        Self {
93            re: self.re - rhs.re,
94            im: self.im - rhs.im,
95        }
96    }
97
98    #[inline]
99    pub fn mul(self, rhs: Self) -> Self {
100        Self {
101            re: self.re * rhs.re - self.im * rhs.im,
102            im: self.re * rhs.im + self.im * rhs.re,
103        }
104    }
105
106    #[inline]
107    pub fn scale(self, s: f64) -> Self {
108        Self {
109            re: self.re * s,
110            im: self.im * s,
111        }
112    }
113
114    #[inline]
115    pub fn div(self, rhs: Self) -> Option<Self> {
116        let d = rhs.norm_sq();
117        if !d.is_finite() || d <= 0.0 {
118            return None;
119        }
120        Some(Self {
121            re: (self.re * rhs.re + self.im * rhs.im) / d,
122            im: (self.im * rhs.re - self.re * rhs.im) / d,
123        })
124    }
125
126    /// Principal square root with $\operatorname{Re}(\sqrt{z}) \ge 0$.
127    #[inline]
128    pub fn sqrt(self) -> Self {
129        let r = self.abs();
130        if r == 0.0 {
131            return Self::new(0.0, 0.0);
132        }
133        let re = (0.5 * (r + self.re).max(0.0)).sqrt();
134        let im_mag = (0.5 * (r - self.re).max(0.0)).sqrt();
135        let im = if self.im < 0.0 { -im_mag } else { im_mag };
136        Self::new(re, im)
137    }
138}
139
140/// Single Debye dipolar relaxation pole:
141/// $\chi_{\text{Debye},p}(\omega) = \frac{\Delta\chi_p}{1 - i\omega\tau_p}$.
142#[derive(Clone, Copy, Debug, PartialEq)]
143pub struct DebyePole {
144    /// Dimensionless static susceptibility increment $\Delta\chi_p \ge 0$.
145    pub delta_chi: f64,
146    /// Relaxation time constant $\tau_p > 0$ in seconds.
147    pub tau_s: f64,
148}
149
150impl DebyePole {
151    pub fn validate(&self, index: usize) -> Result<(), ConstitutiveError> {
152        if !self.delta_chi.is_finite() || !self.tau_s.is_finite() {
153            return Err(ConstitutiveError::NonFiniteParameter);
154        }
155        if self.delta_chi < 0.0 || self.tau_s <= 0.0 {
156            return Err(ConstitutiveError::InvalidDebyePole {
157                index,
158                delta: self.delta_chi,
159                tau_s: self.tau_s,
160            });
161        }
162        Ok(())
163    }
164
165    /// Evaluates $\frac{\Delta\chi_p}{1 - i\omega\tau_p} = \Delta\chi_p \frac{1 + i\omega\tau_p}{1 + (\omega\tau_p)^2}$.
166    #[inline]
167    pub fn evaluate(&self, omega_rad_s: f64) -> Complex64 {
168        let wt = omega_rad_s * self.tau_s;
169        let denom = 1.0 + wt * wt;
170        Complex64 {
171            re: self.delta_chi / denom,
172            im: (self.delta_chi * wt) / denom,
173        }
174    }
175
176    /// Analytical derivative $\frac{\partial \operatorname{Re}\chi_p(\omega)}{\partial \omega}$.
177    #[inline]
178    pub fn d_re_d_omega(&self, omega_rad_s: f64) -> f64 {
179        let wt = omega_rad_s * self.tau_s;
180        let denom = 1.0 + wt * wt;
181        (-2.0 * self.delta_chi * self.tau_s * wt) / (denom * denom)
182    }
183}
184
185/// Single Lorentz bound-oscillator resonance pole:
186/// $\chi_{\text{Lorentz},k}(\omega) = \frac{\Delta\chi_k \omega_{0,k}^2}{\omega_{0,k}^2 - \omega^2 - i\gamma_k\omega}$.
187#[derive(Clone, Copy, Debug, PartialEq)]
188pub struct LorentzPole {
189    /// Dimensionless oscillator strength $\Delta\chi_k \ge 0$.
190    pub delta_chi: f64,
191    /// Undamped resonance angular frequency $\omega_{0,k} > 0$ in $\text{rad}\cdot\text{s}^{-1}$.
192    pub omega_0_rad_s: f64,
193    /// Viscous damping rate $\gamma_k > 0$ in $\text{rad}\cdot\text{s}^{-1}$.
194    pub gamma_rad_s: f64,
195}
196
197impl LorentzPole {
198    pub fn validate(&self, index: usize) -> Result<(), ConstitutiveError> {
199        if !self.delta_chi.is_finite()
200            || !self.omega_0_rad_s.is_finite()
201            || !self.gamma_rad_s.is_finite()
202        {
203            return Err(ConstitutiveError::NonFiniteParameter);
204        }
205        if self.delta_chi < 0.0 || self.omega_0_rad_s <= 0.0 || self.gamma_rad_s <= 0.0 {
206            return Err(ConstitutiveError::InvalidLorentzPole {
207                index,
208                delta: self.delta_chi,
209                omega_0_rad_s: self.omega_0_rad_s,
210                gamma_rad_s: self.gamma_rad_s,
211            });
212        }
213        Ok(())
214    }
215
216    /// Evaluates $\frac{\Delta\chi_k \omega_{0,k}^2}{\omega_{0,k}^2 - \omega^2 - i\gamma_k\omega}$.
217    #[inline]
218    pub fn evaluate(&self, omega_rad_s: f64) -> Complex64 {
219        let w0_sq = self.omega_0_rad_s * self.omega_0_rad_s;
220        let w_sq = omega_rad_s * omega_rad_s;
221        let diff = w0_sq - w_sq;
222        let damp = self.gamma_rad_s * omega_rad_s;
223        let denom = diff * diff + damp * damp;
224        let num = self.delta_chi * w0_sq;
225        Complex64 {
226            re: (num * diff) / denom,
227            im: (num * damp) / denom,
228        }
229    }
230
231    /// Analytical derivative $\frac{\partial \operatorname{Re}\chi_k(\omega)}{\partial \omega}$.
232    #[inline]
233    pub fn d_re_d_omega(&self, omega_rad_s: f64) -> f64 {
234        let w0_sq = self.omega_0_rad_s * self.omega_0_rad_s;
235        let w_sq = omega_rad_s * omega_rad_s;
236        let diff = w0_sq - w_sq;
237        let g = self.gamma_rad_s;
238        let damp = g * omega_rad_s;
239        let denom = diff * diff + damp * damp;
240        let num = self.delta_chi * w0_sq;
241        // d/dw [ diff / (diff^2 + g^2 w^2) ]
242        let d_num = -2.0 * omega_rad_s * denom - diff * (-4.0 * omega_rad_s * diff + 2.0 * g * g * omega_rad_s);
243        num * d_num / (denom * denom)
244    }
245}
246
247/// Schema 133 (`ConstitutiveModel`) multi-pole isotropic electromagnetic constitutive model.
248///
249/// Under the $\exp(-i\omega t)$ harmonic convention:
250/// $$\varepsilon(\omega) = \varepsilon_0 \left(\varepsilon_\infty + \sum_p \frac{\Delta\varepsilon_p}{1 - i\omega\tau_p} + \sum_k \frac{\Delta\varepsilon_k \omega_{0,k}^2}{\omega_{0,k}^2 - \omega^2 - i\gamma_k\omega} + i\frac{\sigma}{\omega\varepsilon_0}\right)$$
251/// $$\mu(\omega) = \mu_0 \left(\mu_\infty + \sum_p \frac{\Delta\mu_p}{1 - i\omega\tau_{m,p}} + \sum_k \frac{\Delta\mu_k \omega_{m,0,k}^2}{\omega_{m,0,k}^2 - \omega^2 - i\gamma_{m,k}\omega}\right)$$
252#[derive(Clone, Debug, PartialEq)]
253pub struct ConstitutiveModel {
254    /// Optical / high-frequency relative permittivity $\varepsilon_\infty \ge 1.0$.
255    pub epsilon_infinity_relative: f64,
256    /// High-frequency relative magnetic permeability $\mu_\infty \ge 1.0$.
257    pub mu_infinity_relative: f64,
258    /// Static ohmic electrical conductivity $\sigma \ge 0$ in $\text{S}\cdot\text{m}^{-1}$.
259    pub conductivity_s_per_m: f64,
260    /// Dielectric Debye relaxation poles.
261    pub electric_debye_poles: Vec<DebyePole>,
262    /// Dielectric Lorentz resonance poles.
263    pub electric_lorentz_poles: Vec<LorentzPole>,
264    /// Magnetic Debye relaxation poles.
265    pub magnetic_debye_poles: Vec<DebyePole>,
266    /// Magnetic Lorentz resonance poles.
267    pub magnetic_lorentz_poles: Vec<LorentzPole>,
268}
269
270impl ConstitutiveModel {
271    /// Construct a vacuum constitutive model ($\varepsilon_r = 1, \mu_r = 1, \sigma = 0$).
272    pub fn vacuum() -> Self {
273        Self {
274            epsilon_infinity_relative: 1.0,
275            mu_infinity_relative: 1.0,
276            conductivity_s_per_m: 0.0,
277            electric_debye_poles: Vec::new(),
278            electric_lorentz_poles: Vec::new(),
279            magnetic_debye_poles: Vec::new(),
280            magnetic_lorentz_poles: Vec::new(),
281        }
282    }
283
284    /// Construct a constitutive model from a validated `.m64` `Q42ConstituentLutEntry`.
285    pub fn from_m64_lut_entry(entry: &Q42ConstituentLutEntry) -> Result<Self, ConstitutiveError> {
286        let eps_r = (entry.dielectric_permittivity_x100 as f64) * 0.01;
287        let sigma = (entry.electrical_conductivity_ms_m as f64) * 1e-3;
288        let model = Self {
289            epsilon_infinity_relative: eps_r,
290            mu_infinity_relative: 1.0,
291            conductivity_s_per_m: sigma,
292            electric_debye_poles: Vec::new(),
293            electric_lorentz_poles: Vec::new(),
294            magnetic_debye_poles: Vec::new(),
295            magnetic_lorentz_poles: Vec::new(),
296        };
297        model.validate()?;
298        Ok(model)
299    }
300
301    /// Construct a homogenized subsurface dielectric model from an `.m64` `M64StrataColumnRecord`.
302    pub fn from_m64_strata_summary(
303        strata: &M64StrataColumnRecord,
304        conductivity_s_per_m: f64,
305    ) -> Result<Self, ConstitutiveError> {
306        let eps_r = (strata.gpr_dielectric_perm_x100 as f64) * 0.01;
307        let model = Self {
308            epsilon_infinity_relative: eps_r,
309            mu_infinity_relative: 1.0,
310            conductivity_s_per_m,
311            electric_debye_poles: Vec::new(),
312            electric_lorentz_poles: Vec::new(),
313            magnetic_debye_poles: Vec::new(),
314            magnetic_lorentz_poles: Vec::new(),
315        };
316        model.validate()?;
317        Ok(model)
318    }
319
320    /// Validate all physical bounds and finiteness invariants.
321    pub fn validate(&self) -> Result<(), ConstitutiveError> {
322        if !self.epsilon_infinity_relative.is_finite()
323            || !self.mu_infinity_relative.is_finite()
324            || !self.conductivity_s_per_m.is_finite()
325        {
326            return Err(ConstitutiveError::NonFiniteParameter);
327        }
328        if self.epsilon_infinity_relative < 1.0 {
329            return Err(ConstitutiveError::InvalidHighFrequencyLimit {
330                value: self.epsilon_infinity_relative,
331            });
332        }
333        if self.mu_infinity_relative <= 0.0 {
334            return Err(ConstitutiveError::InvalidHighFrequencyLimit {
335                value: self.mu_infinity_relative,
336            });
337        }
338        if self.conductivity_s_per_m < 0.0 {
339            return Err(ConstitutiveError::InvalidConductivity {
340                sigma_s_per_m: self.conductivity_s_per_m,
341            });
342        }
343        for (i, p) in self.electric_debye_poles.iter().enumerate() {
344            p.validate(i)?;
345        }
346        for (i, p) in self.electric_lorentz_poles.iter().enumerate() {
347            p.validate(i)?;
348        }
349        for (i, p) in self.magnetic_debye_poles.iter().enumerate() {
350            p.validate(i)?;
351        }
352        for (i, p) in self.magnetic_lorentz_poles.iter().enumerate() {
353            p.validate(i)?;
354        }
355        Ok(())
356    }
357
358    /// Evaluate the bound electric susceptibility $\chi_e(\omega) = \varepsilon_r^{\text{bound}}(\omega) - \varepsilon_\infty$
359    /// (excluding the $i\sigma / (\omega\varepsilon_0)$ conduction pole at $\omega = 0$).
360    pub fn bound_electric_susceptibility(&self, omega_rad_s: f64) -> Result<Complex64, ConstitutiveError> {
361        if !omega_rad_s.is_finite() {
362            return Err(ConstitutiveError::InvalidFrequency { omega_rad_s });
363        }
364        let mut chi = Complex64::new(0.0, 0.0);
365        for p in &self.electric_debye_poles {
366            chi = chi.add(p.evaluate(omega_rad_s));
367        }
368        for p in &self.electric_lorentz_poles {
369            chi = chi.add(p.evaluate(omega_rad_s));
370        }
371        Ok(chi)
372    }
373
374    /// Evaluate relative complex permittivity $\varepsilon_r(\omega)$ at angular frequency $\omega > 0$.
375    pub fn relative_permittivity(&self, omega_rad_s: f64) -> Result<Complex64, ConstitutiveError> {
376        if !omega_rad_s.is_finite() || omega_rad_s <= 0.0 {
377            return Err(ConstitutiveError::InvalidFrequency { omega_rad_s });
378        }
379        let chi = self.bound_electric_susceptibility(omega_rad_s)?;
380        let cond_im = self.conductivity_s_per_m / (omega_rad_s * EPSILON_0_F_PER_M);
381        Ok(Complex64 {
382            re: self.epsilon_infinity_relative + chi.re,
383            im: chi.im + cond_im,
384        })
385    }
386
387    /// Evaluate absolute SI complex permittivity $\varepsilon(\omega) = \varepsilon_0 \varepsilon_r(\omega)$ in $\text{F}\cdot\text{m}^{-1}$.
388    pub fn permittivity_f_per_m(&self, omega_rad_s: f64) -> Result<Complex64, ConstitutiveError> {
389        Ok(self.relative_permittivity(omega_rad_s)?.scale(EPSILON_0_F_PER_M))
390    }
391
392    /// Evaluate bound magnetic susceptibility $\chi_m(\omega) = \mu_r(\omega) - \mu_\infty$.
393    pub fn bound_magnetic_susceptibility(&self, omega_rad_s: f64) -> Result<Complex64, ConstitutiveError> {
394        if !omega_rad_s.is_finite() {
395            return Err(ConstitutiveError::InvalidFrequency { omega_rad_s });
396        }
397        let mut chi = Complex64::new(0.0, 0.0);
398        for p in &self.magnetic_debye_poles {
399            chi = chi.add(p.evaluate(omega_rad_s));
400        }
401        for p in &self.magnetic_lorentz_poles {
402            chi = chi.add(p.evaluate(omega_rad_s));
403        }
404        Ok(chi)
405    }
406
407    /// Evaluate relative complex permeability $\mu_r(\omega)$ at angular frequency $\omega > 0$.
408    pub fn relative_permeability(&self, omega_rad_s: f64) -> Result<Complex64, ConstitutiveError> {
409        if !omega_rad_s.is_finite() || omega_rad_s <= 0.0 {
410            return Err(ConstitutiveError::InvalidFrequency { omega_rad_s });
411        }
412        let chi = self.bound_magnetic_susceptibility(omega_rad_s)?;
413        Ok(Complex64 {
414            re: self.mu_infinity_relative + chi.re,
415            im: chi.im,
416        })
417    }
418
419    /// Evaluate absolute SI complex permeability $\mu(\omega) = \mu_0 \mu_r(\omega)$ in $\text{H}\cdot\text{m}^{-1}$.
420    pub fn permeability_h_per_m(&self, omega_rad_s: f64) -> Result<Complex64, ConstitutiveError> {
421        Ok(self.relative_permeability(omega_rad_s)?.scale(MU_0_H_PER_M))
422    }
423
424    /// Analytical derivative $\frac{\partial (\omega \operatorname{Re}\varepsilon(\omega))}{\partial \omega}$ in $\text{F}\cdot\text{m}^{-1}$
425    /// required for Brillouin dispersive electromagnetic energy density.
426    pub fn d_omega_re_epsilon_d_omega(&self, omega_rad_s: f64) -> Result<f64, ConstitutiveError> {
427        if !omega_rad_s.is_finite() || omega_rad_s <= 0.0 {
428            return Err(ConstitutiveError::InvalidFrequency { omega_rad_s });
429        }
430        let eps_r = self.relative_permittivity(omega_rad_s)?.re;
431        let mut d_re_eps_r = 0.0;
432        for p in &self.electric_debye_poles {
433            d_re_eps_r += p.d_re_d_omega(omega_rad_s);
434        }
435        for p in &self.electric_lorentz_poles {
436            d_re_eps_r += p.d_re_d_omega(omega_rad_s);
437        }
438        Ok(EPSILON_0_F_PER_M * (eps_r + omega_rad_s * d_re_eps_r))
439    }
440
441    /// Analytical derivative $\frac{\partial (\omega \operatorname{Re}\mu(\omega))}{\partial \omega}$ in $\text{H}\cdot\text{m}^{-1}$.
442    pub fn d_omega_re_mu_d_omega(&self, omega_rad_s: f64) -> Result<f64, ConstitutiveError> {
443        if !omega_rad_s.is_finite() || omega_rad_s <= 0.0 {
444            return Err(ConstitutiveError::InvalidFrequency { omega_rad_s });
445        }
446        let mu_r = self.relative_permeability(omega_rad_s)?.re;
447        let mut d_re_mu_r = 0.0;
448        for p in &self.magnetic_debye_poles {
449            d_re_mu_r += p.d_re_d_omega(omega_rad_s);
450        }
451        for p in &self.magnetic_lorentz_poles {
452            d_re_mu_r += p.d_re_d_omega(omega_rad_s);
453        }
454        Ok(MU_0_H_PER_M * (mu_r + omega_rad_s * d_re_mu_r))
455    }
456}
457
458/// Active local-to-parent Hamilton quaternion rotation (`[x, y, z, w]`) per C02-C04.
459///
460/// Retains the exact authored `raw_xyzw` bytes for provenance while computing
461/// the derived normalized quaternion `derived_xyzw` and orthogonal rotation matrix $R(q)$
462/// using the exact non-fused ordered sum `(((x*x + y*y) + z*z) + w*w)`.
463#[derive(Clone, Copy, Debug, PartialEq)]
464pub struct ActiveHamiltonRotation {
465    pub raw_xyzw: [f64; 4],
466    pub raw_norm_sq: f64,
467    pub derived_xyzw: [f64; 4],
468    pub matrix: [[f64; 3]; 3],
469}
470
471impl ActiveHamiltonRotation {
472    /// Admit an authored `[x, y, z, w]` quaternion under C02-C04 (`|norm_sq - 1| <= 1e-12`).
473    /// Never mutates `raw_xyzw`; computes derived `q_i / sqrt(n2)` without fused multiply-add.
474    pub fn admit(raw_xyzw: [f64; 4]) -> Result<Self, ConstitutiveError> {
475        let [x, y, z, w] = raw_xyzw;
476        if !x.is_finite() || !y.is_finite() || !z.is_finite() || !w.is_finite() {
477            return Err(ConstitutiveError::NonFiniteParameter);
478        }
479        // C02-C04 ordered sum: (((x*x + y*y) + z*z) + w*w)
480        let xx = x * x;
481        let yy = y * y;
482        let zz = z * z;
483        let ww = w * w;
484        let raw_norm_sq = ((xx + yy) + zz) + ww;
485        let deviation = (raw_norm_sq - 1.0).abs();
486        if deviation > QUATERNION_NORM_SQ_TOLERANCE {
487            return Err(ConstitutiveError::QuaternionNormOutOfBounds {
488                norm_sq: raw_norm_sq,
489                deviation,
490            });
491        }
492        let n = raw_norm_sq.sqrt();
493        let dx = x / n;
494        let dy = y / n;
495        let dz = z / n;
496        let dw = w / n;
497        let derived_xyzw = [dx, dy, dz, dw];
498
499        let tx = 2.0 * dx;
500        let ty = 2.0 * dy;
501        let tz = 2.0 * dz;
502        let twx = tx * dw;
503        let twy = ty * dw;
504        let twz = tz * dw;
505        let txx = tx * dx;
506        let txy = ty * dx;
507        let txz = tz * dx;
508        let tyy = ty * dy;
509        let tyz = tz * dy;
510        let tzz = tz * dz;
511
512        let matrix = [
513            [1.0 - (tyy + tzz), txy - twz, txz + twy],
514            [txy + twz, 1.0 - (txx + tzz), tyz - twx],
515            [txz - twy, tyz + twx, 1.0 - (txx + tyy)],
516        ];
517
518        Ok(Self {
519            raw_xyzw,
520            raw_norm_sq,
521            derived_xyzw,
522            matrix,
523        })
524    }
525
526    /// Compose `self` (parent) with `local` (`q_parent * q_local` = apply `local` then `parent`).
527    pub fn compose(&self, local: &Self) -> Result<Self, ConstitutiveError> {
528        let [x1, y1, z1, w1] = self.derived_xyzw;
529        let [x2, y2, z2, w2] = local.derived_xyzw;
530        let prod = [
531            w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
532            w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
533            w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
534            w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
535        ];
536        Self::admit(prod)
537    }
538
539    /// Active vector transformation $v_{\text{parent}} = R(q)\,v_{\text{local}}$.
540    #[inline]
541    pub fn rotate_vector(&self, v_local: [f64; 3]) -> [f64; 3] {
542        let r = &self.matrix;
543        [
544            r[0][0] * v_local[0] + r[0][1] * v_local[1] + r[0][2] * v_local[2],
545            r[1][0] * v_local[0] + r[1][1] * v_local[1] + r[1][2] * v_local[2],
546            r[2][0] * v_local[0] + r[2][1] * v_local[1] + r[2][2] * v_local[2],
547        ]
548    }
549
550    /// Active rank-2 real tensor transformation $T_{\text{parent}} = R(q)\,T_{\text{local}}\,R(q)^T$.
551    pub fn rotate_tensor_real(&self, t_local: &[[f64; 3]; 3]) -> [[f64; 3]; 3] {
552        let r = &self.matrix;
553        let mut rt = [[0.0; 3]; 3];
554        for i in 0..3 {
555            for j in 0..3 {
556                rt[i][j] = r[i][0] * t_local[0][j] + r[i][1] * t_local[1][j] + r[i][2] * t_local[2][j];
557            }
558        }
559        let mut out = [[0.0; 3]; 3];
560        for i in 0..3 {
561            for j in 0..3 {
562                out[i][j] = rt[i][0] * r[j][0] + rt[i][1] * r[j][1] + rt[i][2] * r[j][2];
563            }
564        }
565        out
566    }
567
568    /// Active rank-2 complex tensor transformation $T_{\text{parent}} = R(q)\,T_{\text{local}}\,R(q)^T$.
569    pub fn rotate_tensor_complex(&self, t_local: &[[Complex64; 3]; 3]) -> [[Complex64; 3]; 3] {
570        let r = &self.matrix;
571        let mut rt = [[Complex64::default(); 3]; 3];
572        for i in 0..3 {
573            for j in 0..3 {
574                rt[i][j] = t_local[0][j]
575                    .scale(r[i][0])
576                    .add(t_local[1][j].scale(r[i][1]))
577                    .add(t_local[2][j].scale(r[i][2]));
578            }
579        }
580        let mut out = [[Complex64::default(); 3]; 3];
581        for i in 0..3 {
582            for j in 0..3 {
583                out[i][j] = rt[i][0]
584                    .scale(r[j][0])
585                    .add(rt[i][1].scale(r[j][1]))
586                    .add(rt[i][2].scale(r[j][2]));
587            }
588        }
589        out
590    }
591
592    /// Maximum absolute residual $\|R R^T - I\|_{\max}$.
593    pub fn orthogonality_residual(&self) -> f64 {
594        let r = &self.matrix;
595        let mut max_err = 0.0f64;
596        for i in 0..3 {
597            for j in 0..3 {
598                let dot = r[i][0] * r[j][0] + r[i][1] * r[j][1] + r[i][2] * r[j][2];
599                let target = if i == j { 1.0 } else { 0.0 };
600                max_err = max_err.max((dot - target).abs());
601            }
602        }
603        max_err
604    }
605
606    /// Determinant $\det(R)$ (proper rotation has $+1.0$).
607    pub fn determinant(&self) -> f64 {
608        let r = &self.matrix;
609        r[0][0] * (r[1][1] * r[2][2] - r[1][2] * r[2][1])
610            - r[0][1] * (r[1][0] * r[2][2] - r[1][2] * r[2][0])
611            + r[0][2] * (r[1][0] * r[2][1] - r[1][1] * r[2][0])
612    }
613}
614
615/// Full $3\times 3$ complex anisotropic constitutive tensor (reciprocal symmetric $T_{ij} = T_{ji}$).
616#[derive(Clone, Copy, Debug, PartialEq)]
617pub struct AnisotropicConstitutiveTensor3x3 {
618    pub components: [[Complex64; 3]; 3],
619}
620
621impl AnisotropicConstitutiveTensor3x3 {
622    /// Construct a diagonal uniaxial/biaxial constitutive tensor in its principal frame.
623    pub fn from_principal_axes(principal: [Complex64; 3]) -> Result<Self, ConstitutiveError> {
624        let z = Complex64::new(0.0, 0.0);
625        let t = Self {
626            components: [
627                [principal[0], z, z],
628                [z, principal[1], z],
629                [z, z, principal[2]],
630            ],
631        };
632        t.validate_passivity_and_symmetry(1e-12)?;
633        Ok(t)
634    }
635
636    /// Verify symmetric reciprocity ($T_{ij} = T_{ji}$), positive-definite real part,
637    /// and positive-semidefinite imaginary part (passivity under $\exp(-i\omega t)$).
638    pub fn validate_passivity_and_symmetry(&self, sym_tol: f64) -> Result<(), ConstitutiveError> {
639        for i in 0..3 {
640            for j in 0..3 {
641                if !self.components[i][j].is_finite() {
642                    return Err(ConstitutiveError::NonFiniteParameter);
643                }
644            }
645        }
646        let mut max_asym = 0.0f64;
647        for i in 0..3 {
648            for j in (i + 1)..3 {
649                let d_re = (self.components[i][j].re - self.components[j][i].re).abs();
650                let d_im = (self.components[i][j].im - self.components[j][i].im).abs();
651                max_asym = max_asym.max(d_re).max(d_im);
652            }
653        }
654        if max_asym > sym_tol {
655            return Err(ConstitutiveError::NonSymmetricTensor {
656                max_asymmetry: max_asym,
657            });
658        }
659        // Sylvester's criterion on Re(T) > 0 and Im(T) >= 0
660        let re = self.real_part();
661        let m1 = re[0][0];
662        let m2 = re[0][0] * re[1][1] - re[0][1] * re[1][0];
663        let m3 = re[0][0] * (re[1][1] * re[2][2] - re[1][2] * re[2][1])
664            - re[0][1] * (re[1][0] * re[2][2] - re[1][2] * re[2][0])
665            + re[0][2] * (re[1][0] * re[2][1] - re[1][1] * re[2][0]);
666        let min_minor = m1.min(m2).min(m3);
667        if min_minor <= 0.0 {
668            return Err(ConstitutiveError::NonPositiveDefiniteTensor {
669                min_diagonal_or_minor: min_minor,
670            });
671        }
672        let im = self.imag_part();
673        for i in 0..3 {
674            if im[i][i] < -sym_tol {
675                return Err(ConstitutiveError::NonPositiveDefiniteTensor {
676                    min_diagonal_or_minor: im[i][i],
677                });
678            }
679        }
680        Ok(())
681    }
682
683    #[inline]
684    pub fn real_part(&self) -> [[f64; 3]; 3] {
685        let mut out = [[0.0; 3]; 3];
686        for i in 0..3 {
687            for j in 0..3 {
688                out[i][j] = self.components[i][j].re;
689            }
690        }
691        out
692    }
693
694    #[inline]
695    pub fn imag_part(&self) -> [[f64; 3]; 3] {
696        let mut out = [[0.0; 3]; 3];
697        for i in 0..3 {
698            for j in 0..3 {
699                out[i][j] = self.components[i][j].im;
700            }
701        }
702        out
703    }
704
705    /// Transform tensor from local material crystal axes to parent frame via $R(q)\,T\,R(q)^T$.
706    pub fn transform_to_parent(&self, rot: &ActiveHamiltonRotation) -> Self {
707        Self {
708            components: rot.rotate_tensor_complex(&self.components),
709        }
710    }
711
712    /// Trace $\operatorname{tr}(T) = T_{00} + T_{11} + T_{22}$ (rotational invariant).
713    pub fn trace(&self) -> Complex64 {
714        self.components[0][0]
715            .add(self.components[1][1])
716            .add(self.components[2][2])
717    }
718}