Skip to main content

qualia_core_db/q42/science_validation/
stokes_mueller.rs

1//! Stokes vector and Mueller $4\times 4$ matrix polarimetric realizability verifiers (C02 Mode 1 & Mode 4).
2//!
3//! All reference calculations are evaluated from first principles in independent `f64` arithmetic:
4//! - Overflow-safe scaled 3D hypotenuse $\operatorname{hypot}_3(S_1, S_2, S_3)$.
5//! - Physical Stokes admission: $S_0 \ge 0$ and
6//!   $\operatorname{hypot}_3(S_1, S_2, S_3) \le S_0 + 64\,\varepsilon \max(S_0, \operatorname{hypot}_3(S_1, S_2, S_3))$.
7//! - Degree of Polarization $\text{DoP} = \operatorname{hypot}_3(S_1, S_2, S_3) / S_0 \in [0, 1]$,
8//!   never clamping source components to mask over-polarized states.
9//! - Cloude $4\times 4$ Hermitian coherency matrix $\mathbf{C}(\mathbf{M})$ constructed from the 16
10//!   Pauli-basis Dirac-Kronig projections in the candidate C02 $V$-sign convention, with
11//!   deterministic complex Hermitian Jacobi eigenvalue verification ($\lambda_i \ge -64\,\varepsilon \|\mathbf{M}\|_F$).
12//! - Fry-Kattawar trace/transmittance passivity conditions and Jones-to-Mueller exact equivalence.
13
14/// Machine epsilon for IEEE-754 `f64` ($2^{-52}$).
15pub const F64_EPS: f64 = f64::EPSILON;
16
17/// Standard C02 small-operation rounding allowance factor ($64 \times 2^{-52}$).
18pub const C02_ROUNDING_FACTOR: f64 = 64.0 * F64_EPS;
19
20/// Exact defined speed of light in vacuum $c_0$ ($\text{m/s}$).
21pub const VACUUM_SPEED_OF_LIGHT_M_PER_S: f64 = 299_792_458.0;
22
23/// Structured rejection reason for Stokes or Mueller physical realizability failures.
24#[derive(Debug, Clone, PartialEq)]
25pub enum PolarimetricValidationError {
26    NonFiniteStokesComponent { index: usize, value: f64 },
27    NegativeTotalIntensity { s0: f64 },
28    OverPolarizedState { s0: f64, polarized_norm: f64, allowance: f64, excess: f64 },
29    InvalidPropagationDirection { norm_sq: f64 },
30    InvalidFrequencyHz { frequency_hz: f64 },
31    InvalidBandwidthHz { bandwidth_hz: f64 },
32    InvalidGeometricPathM { path_m: f64 },
33    NonFiniteMuellerEntry { row: usize, col: usize, value: f64 },
34    NegativeMuellerM00 { m00: f64 },
35    ActiveGainViolation { max_forward_gain: f64, max_column_gain: f64, tolerance: f64 },
36    CloudeNegativeEigenvalue { min_eigenvalue: f64, eigenvalues: [f64; 4], tolerance: f64 },
37    JonesMuellerMismatch { row: usize, col: usize, actual: f64, reference: f64, abs_error: f64, budget: f64 },
38}
39
40/// Verified Stokes physical state summary (retaining original unmodified components).
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct VerifiedStokesState {
43    pub stokes: [f64; 4],
44    pub polarized_norm: f64,
45    pub raw_degree_of_polarization: f64,
46    pub degree_of_polarization: f64,
47    pub realizability_margin: f64,
48}
49
50/// Verified Mueller $4\times 4$ physical realizability report.
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct VerifiedMuellerReport {
53    pub frobenius_norm: f64,
54    pub cloude_trace: f64,
55    pub cloude_eigenvalues: [f64; 4],
56    pub max_transmittance_gain: f64,
57    pub max_polarizance_gain: f64,
58    pub depolarization_index: f64,
59}
60
61/// Complex scalar in `f64` precision for independent Jones & Cloude algebra.
62#[derive(Debug, Clone, Copy, PartialEq)]
63pub struct Complex64 {
64    pub re: f64,
65    pub im: f64,
66}
67
68impl Complex64 {
69    pub const ZERO: Self = Self { re: 0.0, im: 0.0 };
70    pub const ONE: Self = Self { re: 1.0, im: 0.0 };
71    pub const I: Self = Self { re: 0.0, im: 1.0 };
72
73    #[inline]
74    pub const fn new(re: f64, im: f64) -> Self { Self { re, im } }
75    #[inline]
76    pub const fn conj(self) -> Self { Self { re: self.re, im: -self.im } }
77    #[inline]
78    pub fn norm_sq(self) -> f64 { self.re * self.re + self.im * self.im }
79    #[inline]
80    pub fn abs(self) -> f64 { self.re.hypot(self.im) }
81    #[inline]
82    pub fn add(self, rhs: Self) -> Self { Self { re: self.re + rhs.re, im: self.im + rhs.im } }
83    #[inline]
84    pub fn sub(self, rhs: Self) -> Self { Self { re: self.re - rhs.re, im: self.im - rhs.im } }
85    #[inline]
86    pub fn mul(self, rhs: Self) -> Self {
87        Self { re: self.re * rhs.re - self.im * rhs.im, im: self.re * rhs.im + self.im * rhs.re }
88    }
89    #[inline]
90    pub fn scale(self, s: f64) -> Self { Self { re: self.re * s, im: self.im * s } }
91}
92
93/// Overflow- and underflow-safe 3D Euclidean norm $\sqrt{x^2 + y^2 + z^2}$.
94#[inline]
95pub fn scaled_hypot3(x: f64, y: f64, z: f64) -> f64 {
96    let (ax, ay, az) = (x.abs(), y.abs(), z.abs());
97    let max_c = ax.max(ay).max(az);
98    if max_c == 0.0 || !max_c.is_finite() {
99        return max_c;
100    }
101    let (sx, sy, sz) = (ax / max_c, ay / max_c, az / max_c);
102    max_c * ((sx * sx + sy * sy) + sz * sz).sqrt()
103}
104
105/// Verify physical Stokes realizability per C02 Mode 1.
106/// Never clamps or modifies input components.
107pub fn verify_stokes_realizability(
108    stokes: [f64; 4],
109) -> Result<VerifiedStokesState, PolarimetricValidationError> {
110    for (index, &value) in stokes.iter().enumerate() {
111        if !value.is_finite() {
112            return Err(PolarimetricValidationError::NonFiniteStokesComponent { index, value });
113        }
114    }
115    let s0 = stokes[0];
116    if s0 < 0.0 {
117        return Err(PolarimetricValidationError::NegativeTotalIntensity { s0 });
118    }
119    let polarized_norm = scaled_hypot3(stokes[1], stokes[2], stokes[3]);
120    if !polarized_norm.is_finite() {
121        return Err(PolarimetricValidationError::NonFiniteStokesComponent {
122            index: 1,
123            value: polarized_norm,
124        });
125    }
126    let scale = s0.max(polarized_norm);
127    let allowance = C02_ROUNDING_FACTOR * scale;
128    let margin = s0 - polarized_norm;
129    if polarized_norm > s0 + allowance {
130        return Err(PolarimetricValidationError::OverPolarizedState {
131            s0,
132            polarized_norm,
133            allowance,
134            excess: polarized_norm - s0,
135        });
136    }
137    let (raw_dop, dop) = if s0 == 0.0 {
138        (0.0, 0.0)
139    } else {
140        let raw = polarized_norm / s0;
141        (raw, raw.min(1.0))
142    };
143    Ok(VerifiedStokesState {
144        stokes,
145        polarized_norm,
146        raw_degree_of_polarization: raw_dop,
147        degree_of_polarization: dop,
148        realizability_margin: margin,
149    })
150}
151
152/// Convert a complex Jones vector $(E_x, E_y)$ to a Stokes vector $(S_0, S_1, S_2, S_3)$
153/// in the C02 Mode 1 convention where $(1, i)/\sqrt{2} \mapsto (1, 0, 0, -1)$.
154pub fn jones_vector_to_stokes(ex: Complex64, ey: Complex64) -> [f64; 4] {
155    let (ex2, ey2, cross) = (ex.norm_sq(), ey.norm_sq(), ex.mul(ey.conj()));
156    [ex2 + ey2, ex2 - ey2, 2.0 * cross.re, 2.0 * cross.im]
157}
158
159/// Passive transverse basis rotation of a Stokes vector by angle $\theta$ ($\text{rad}$).
160pub fn rotate_stokes_transverse_basis(stokes: [f64; 4], theta_rad: f64) -> [f64; 4] {
161    let (c, s) = ((2.0 * theta_rad).cos(), (2.0 * theta_rad).sin());
162    let (q, u) = (stokes[1], stokes[2]);
163    [stokes[0], q * c + u * s, -q * s + u * c, stokes[3]]
164}
165
166/// Deterministic transverse basis $(\mathbf{e}_1, \mathbf{e}_2)$ for propagation unit vector $\mathbf{k}$.
167pub fn deterministic_transverse_basis(
168    direction: [f64; 3],
169) -> Result<([f64; 3], [f64; 3]), PolarimetricValidationError> {
170    let norm = scaled_hypot3(direction[0], direction[1], direction[2]);
171    if !norm.is_finite() || (norm - 1.0).abs() > 1e-12 {
172        return Err(PolarimetricValidationError::InvalidPropagationDirection { norm_sq: norm * norm });
173    }
174    let k = [direction[0] / norm, direction[1] / norm, direction[2] / norm];
175    if (k[2] - 1.0).abs() <= 1e-12 && k[0].abs() <= 1e-12 && k[1].abs() <= 1e-12 {
176        return Ok(([1.0, 0.0, 0.0], [0.0, 1.0, 0.0]));
177    }
178    if (k[2] + 1.0).abs() <= 1e-12 && k[0].abs() <= 1e-12 && k[1].abs() <= 1e-12 {
179        return Ok(([1.0, 0.0, 0.0], [0.0, -1.0, 0.0]));
180    }
181    let seed = if k[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
182    let dot = seed[0] * k[0] + seed[1] * k[1] + seed[2] * k[2];
183    let raw_e1 = [seed[0] - dot * k[0], seed[1] - dot * k[1], seed[2] - dot * k[2]];
184    let e1_norm = scaled_hypot3(raw_e1[0], raw_e1[1], raw_e1[2]);
185    let e1 = [raw_e1[0] / e1_norm, raw_e1[1] / e1_norm, raw_e1[2] / e1_norm];
186    let e2 = [
187        k[1] * e1[2] - k[2] * e1[1],
188        k[2] * e1[0] - k[0] * e1[2],
189        k[0] * e1[1] - k[1] * e1[0],
190    ];
191    Ok((e1, e2))
192}
193
194/// Compute geometric propagation time $\Delta t = \frac{n \cdot d}{c_0}$ in a homogeneous medium.
195pub fn vacuum_or_homogeneous_propagation_delay_s(
196    geometric_path_m: f64,
197    refractive_index: f64,
198) -> Result<f64, PolarimetricValidationError> {
199    if !geometric_path_m.is_finite() || geometric_path_m < 0.0 {
200        return Err(PolarimetricValidationError::InvalidGeometricPathM { path_m: geometric_path_m });
201    }
202    if !refractive_index.is_finite() || refractive_index <= 0.0 {
203        return Err(PolarimetricValidationError::InvalidGeometricPathM { path_m: refractive_index });
204    }
205    Ok((geometric_path_m * refractive_index) / VACUUM_SPEED_OF_LIGHT_M_PER_S)
206}
207
208/// Apply a $4\times 4$ Mueller matrix to a Stokes vector: $\mathbf{S}_{\text{out}} = \mathbf{M}\mathbf{S}_{\text{in}}$.
209pub fn apply_mueller_matrix(mueller: &[[f64; 4]; 4], stokes: [f64; 4]) -> [f64; 4] {
210    let mut out = [0.0f64; 4];
211    for r in 0..4 {
212        out[r] = (mueller[r][0] * stokes[0] + mueller[r][1] * stokes[1])
213            + (mueller[r][2] * stokes[2] + mueller[r][3] * stokes[3]);
214    }
215    out
216}
217
218/// Convert a $2\times 2$ complex Jones matrix $\mathbf{J}$ to its exact $4\times 4$ Mueller matrix
219/// $\mathbf{M}(\mathbf{J}) = \mathbf{A}(\mathbf{J} \otimes \mathbf{J}^*)\mathbf{A}^{-1}$ in the C02 Mode 1/4 convention.
220pub fn jones_to_mueller_matrix(jones: &[[Complex64; 2]; 2]) -> [[f64; 4]; 4] {
221    let taus = pauli_tau_basis();
222    let j_dag = [[jones[0][0].conj(), jones[1][0].conj()], [jones[0][1].conj(), jones[1][1].conj()]];
223    let mut m = [[0.0f64; 4]; 4];
224    for mu in 0..4 {
225        for nu in 0..4 {
226            let prod = mat2_mul(&taus[mu], &mat2_mul(&mat2_mul(jones, &taus[nu]), &j_dag));
227            m[mu][nu] = 0.5 * prod[0][0].add(prod[1][1]).re;
228        }
229    }
230    m
231}
232
233/// Construct the $4\times 4$ Hermitian Cloude coherency matrix $\mathbf{C}(\mathbf{M})$ from a $4\times 4$
234/// Mueller matrix $\mathbf{M}$ using the 16 Hermitian Pauli-basis projections:
235///
236/// $$C_{\alpha\beta} = \frac{1}{8} \sum_{\mu,\nu=0}^3 M_{\mu\nu} \operatorname{tr}(\tau_\alpha \tau_\mu \tau_\beta \tau_\nu).$$
237///
238/// Normalization is chosen such that $\operatorname{tr}(\mathbf{C}(\mathbf{M})) = M_{00}$ and a pure
239/// Jones-Mueller matrix $\mathbf{M}(\mathbf{J})$ has eigenvalues $(M_{00}, 0, 0, 0)$.
240pub fn compute_cloude_coherency_matrix(mueller: &[[f64; 4]; 4]) -> [[Complex64; 4]; 4] {
241    let taus = pauli_tau_basis();
242    let mut cloude = [[Complex64::ZERO; 4]; 4];
243    for alpha in 0..4 {
244        for beta in 0..4 {
245            let mut sum = Complex64::ZERO;
246            for mu in 0..4 {
247                for nu in 0..4 {
248                    let prod = mat2_mul(&mat2_mul(&mat2_mul(&taus[alpha], &taus[mu]), &taus[beta]), &taus[nu]);
249                    let tr = prod[0][0].add(prod[1][1]);
250                    sum = sum.add(tr.scale(mueller[mu][nu]));
251                }
252            }
253            cloude[alpha][beta] = sum.scale(0.125);
254        }
255    }
256    for i in 0..4 {
257        cloude[i][i].im = 0.0;
258        for j in (i + 1)..4 {
259            let avg = cloude[i][j].add(cloude[j][i].conj()).scale(0.5);
260            cloude[i][j] = avg;
261            cloude[j][i] = avg.conj();
262        }
263    }
264    cloude
265}
266
267/// Compute all 4 real eigenvalues (sorted ascending) of a $4\times 4$ complex Hermitian matrix
268/// using deterministic two-stage complex-phase clearing + real Jacobi rotations.
269pub fn hermitian_4x4_eigenvalues(h_in: &[[Complex64; 4]; 4]) -> [f64; 4] {
270    let mut a = *h_in;
271    for _sweep in 0..64 {
272        let mut max_off = 0.0f64;
273        for p in 0..4 {
274            for q in (p + 1)..4 {
275                max_off = max_off.max(a[p][q].abs());
276            }
277        }
278        if max_off <= 1e-15 {
279            break;
280        }
281        for p in 0..4 {
282            for q in (p + 1)..4 {
283                let apq = a[p][q];
284                let mag = apq.abs();
285                if mag <= 1e-16 {
286                    continue;
287                }
288                let phase = Complex64::new(apq.re / mag, apq.im / mag);
289                let (app, aqq) = (a[p][p].re, a[q][q].re);
290                let diff = aqq - app;
291                let t = if diff.abs() <= 1e-30 {
292                    1.0
293                } else {
294                    let tau = diff / (2.0 * mag);
295                    let sign = if tau >= 0.0 { 1.0 } else { -1.0 };
296                    sign / (tau.abs() + (1.0 + tau * tau).sqrt())
297                };
298                let c = 1.0 / (1.0 + t * t).sqrt();
299                let s = t * c;
300                let (s_phase, s_phase_conj) = (phase.scale(s), phase.conj().scale(s));
301                for k in 0..4 {
302                    if k != p && k != q {
303                        let (akp, akq) = (a[k][p], a[k][q]);
304                        let new_akp = akp.scale(c).sub(akq.mul(s_phase_conj));
305                        let new_akq = akp.mul(s_phase).add(akq.scale(c));
306                        a[k][p] = new_akp;
307                        a[p][k] = new_akp.conj();
308                        a[k][q] = new_akq;
309                        a[q][k] = new_akq.conj();
310                    }
311                }
312                a[p][p] = Complex64::new(app - t * mag, 0.0);
313                a[q][q] = Complex64::new(aqq + t * mag, 0.0);
314                a[p][q] = Complex64::ZERO;
315                a[q][p] = Complex64::ZERO;
316            }
317        }
318    }
319    let mut eigs = [a[0][0].re, a[1][1].re, a[2][2].re, a[3][3].re];
320    if eigs[0] > eigs[1] { eigs.swap(0, 1); }
321    if eigs[2] > eigs[3] { eigs.swap(2, 3); }
322    if eigs[0] > eigs[2] { eigs.swap(0, 2); }
323    if eigs[1] > eigs[3] { eigs.swap(1, 3); }
324    if eigs[1] > eigs[2] { eigs.swap(1, 2); }
325    eigs
326}
327
328/// Verify physical realizability and passivity of a $4\times 4$ Mueller matrix (C02 Mode 4).
329pub fn verify_mueller_realizability(
330    mueller: &[[f64; 4]; 4],
331    require_passive: bool,
332) -> Result<VerifiedMuellerReport, PolarimetricValidationError> {
333    let mut frob_sq = 0.0f64;
334    for r in 0..4 {
335        for c in 0..4 {
336            let v = mueller[r][c];
337            if !v.is_finite() {
338                return Err(PolarimetricValidationError::NonFiniteMuellerEntry { row: r, col: c, value: v });
339            }
340            frob_sq += v * v;
341        }
342    }
343    let frobenius_norm = frob_sq.sqrt();
344    let m00 = mueller[0][0];
345    if m00 < 0.0 {
346        return Err(PolarimetricValidationError::NegativeMuellerM00 { m00 });
347    }
348    let diattenuation_norm = scaled_hypot3(mueller[0][1], mueller[0][2], mueller[0][3]);
349    let polarizance_norm = scaled_hypot3(mueller[1][0], mueller[2][0], mueller[3][0]);
350    let max_transmittance_gain = m00 + diattenuation_norm;
351    let max_polarizance_gain = m00 + polarizance_norm;
352
353    if require_passive {
354        let passive_limit = 1.0 + C02_ROUNDING_FACTOR;
355        if max_transmittance_gain > passive_limit || max_polarizance_gain > passive_limit {
356            return Err(PolarimetricValidationError::ActiveGainViolation {
357                max_forward_gain: max_transmittance_gain,
358                max_column_gain: max_polarizance_gain,
359                tolerance: passive_limit,
360            });
361        }
362    }
363
364    let cloude = compute_cloude_coherency_matrix(mueller);
365    let cloude_trace = cloude[0][0].re + cloude[1][1].re + cloude[2][2].re + cloude[3][3].re;
366    let cloude_eigenvalues = hermitian_4x4_eigenvalues(&cloude);
367    let eig_tol = C02_ROUNDING_FACTOR * frobenius_norm.max(1.0);
368    if cloude_eigenvalues[0] < -eig_tol {
369        return Err(PolarimetricValidationError::CloudeNegativeEigenvalue {
370            min_eigenvalue: cloude_eigenvalues[0],
371            eigenvalues: cloude_eigenvalues,
372            tolerance: eig_tol,
373        });
374    }
375
376    let depolarization_index = if m00 == 0.0 {
377        0.0
378    } else {
379        ((frob_sq - m00 * m00).max(0.0).sqrt()) / (3.0f64.sqrt() * m00)
380    };
381
382    Ok(VerifiedMuellerReport {
383        frobenius_norm,
384        cloude_trace,
385        cloude_eigenvalues,
386        max_transmittance_gain,
387        max_polarizance_gain,
388        depolarization_index,
389    })
390}
391
392/// Verify that a candidate $4\times 4$ Mueller matrix agrees with the exact Jones-to-Mueller
393/// transformation $\mathbf{M}(\mathbf{J}) = \mathbf{A}(\mathbf{J} \otimes \mathbf{J}^*)\mathbf{A}^{-1}$
394/// within the C02 closed-form budget $64 \cdot 2^{-52} Q$.
395pub fn verify_jones_to_mueller_equivalence(
396    candidate_mueller: &[[f64; 4]; 4],
397    jones: &[[Complex64; 2]; 2],
398    scale_q: f64,
399) -> Result<[[f64; 4]; 4], PolarimetricValidationError> {
400    let reference = jones_to_mueller_matrix(jones);
401    let budget = C02_ROUNDING_FACTOR * scale_q.abs().max(F64_EPS);
402    for r in 0..4 {
403        for c in 0..4 {
404            let (actual, expected) = (candidate_mueller[r][c], reference[r][c]);
405            let err = (actual - expected).abs();
406            if !actual.is_finite() || err > budget {
407                return Err(PolarimetricValidationError::JonesMuellerMismatch {
408                    row: r, col: c, actual, reference: expected, abs_error: err, budget,
409                });
410            }
411        }
412    }
413    Ok(reference)
414}
415
416#[inline]
417fn pauli_tau_basis() -> [[[Complex64; 2]; 2]; 4] {
418    [
419        [[Complex64::ONE, Complex64::ZERO], [Complex64::ZERO, Complex64::ONE]],
420        [[Complex64::ONE, Complex64::ZERO], [Complex64::ZERO, Complex64::new(-1.0, 0.0)]],
421        [[Complex64::ZERO, Complex64::ONE], [Complex64::ONE, Complex64::ZERO]],
422        [[Complex64::ZERO, Complex64::I], [Complex64::new(0.0, -1.0), Complex64::ZERO]],
423    ]
424}
425
426#[inline]
427fn mat2_mul(a: &[[Complex64; 2]; 2], b: &[[Complex64; 2]; 2]) -> [[Complex64; 2]; 2] {
428    [
429        [
430            a[0][0].mul(b[0][0]).add(a[0][1].mul(b[1][0])),
431            a[0][0].mul(b[0][1]).add(a[0][1].mul(b[1][1])),
432        ],
433        [
434            a[1][0].mul(b[0][0]).add(a[1][1].mul(b[1][0])),
435            a[1][0].mul(b[0][1]).add(a[1][1].mul(b[1][1])),
436        ],
437    ]
438}