Skip to main content

refloxide_tmm/kernel/
rmatrix.rs

1//! Reflection-matrix 4x4 recursion with cancellation-free interface matrices.
2//!
3//! The transfer-matrix product of [`super::solve_point`] recovers `r` as a
4//! ratio of `O(1)` matrix entries, so absolute rounding near machine epsilon
5//! becomes a large relative error once `|r|` is small, and growing
6//! propagators overflow the dynamic range of thick absorbing films. This
7//! module keeps the full 4x4 mode description but instead carries the 2x2
8//! reflection matrix `G` (up-going amplitudes `= G` times down-going
9//! amplitudes) from the backing to the fronting:
10//!
11//! `G_above = (K_-+ + K_-- G)(K_++ + K_+- G)^-1`, with `K = (D_a^-1 D_b) o W`,
12//!
13//! and forms `K = I + D_a^-1 (D_b - D_a)` from analytic eigenvector
14//! differences so the small off-diagonal blocks that determine `r` are never
15//! obtained by subtracting `O(1)` numbers. Propagation of `G` across a slab
16//! only multiplies by decaying exponentials.
17//!
18//! The recursion is generic over an [`Eigenmodes`] provider: the
19//! closed-form uniaxial-z provider here supplies analytic, cancellation-free
20//! differences, and [`super::general`] supplies numerically solved modes of
21//! an arbitrary dielectric tensor.
22
23use num_complex::Complex;
24
25use super::{mode_kz, LayerCoeffs, Real};
26use refloxide_core::c4x4::{zero, Mat4};
27use refloxide_core::error::{RefloxideError, Result};
28use refloxide_core::math::exact_inv_4x4_generic;
29
30type C<T> = Complex<T>;
31type Mat2<T> = [[C<T>; 2]; 2];
32
33/// Down-going mode columns `[e+, o+]` and up-going columns `[e-, o-]`.
34const DOWN: [usize; 2] = [0, 2];
35const UP: [usize; 2] = [1, 3];
36
37/// Mode data of one layer at fixed `(q, k0)`, unnormalized.
38///
39/// Columns follow the kernel ordering `[e+, e-, o+, o-]` and rows
40/// `[Ex, Hy, Ey, Hx]`: `e+- = [+-z/k0, 1, 0, 0]` with `z = kz_e / eps_o`,
41/// `o+- = [0, 0, 1, -+k_o/k0]`.
42struct Medium<T: Real> {
43    chi_o: C<T>,
44    chi_e: C<T>,
45    k0: T,
46    kx: T,
47    k_o: C<T>,
48    k_e: C<T>,
49    z: C<T>,
50    x_e: C<T>,
51    pi: C<T>,
52}
53
54/// Mode data consumed by the reflection-matrix recursion.
55///
56/// Columns of [`Eigenmodes::dynamic`] follow `[p+, p-, s+, s-]` (the
57/// kernel's `[e+, e-, o+, o-]`), rows `[Ex, Hy, Ey, Hx]` with `H` in units of
58/// `k0`; `+` modes carry energy toward the backing. Column normalization is
59/// arbitrary except in the fronting, where [`Eigenmodes::e_norms`] rescales
60/// to unit `|E|` so reflection amplitudes refer to unit-field modes.
61pub(crate) trait Eigenmodes<T: Real> {
62    /// Mode `kz` in `1/Angstrom`, ordered like the dynamic-matrix columns.
63    fn kz(&self) -> [C<T>; 4];
64    /// Dynamic matrix of field components per mode.
65    fn dynamic(&self) -> Mat4<T>;
66    /// Electric-field magnitude of each dynamic-matrix column.
67    fn e_norms(&self) -> [T; 4];
68    /// `(D_below - D_self, kz_below - kz_self)`, as accurately as the
69    /// provider can form them.
70    fn diff(&self, below: &Self) -> (Mat4<T>, [C<T>; 4]);
71}
72
73/// Cancellation-free differences `b - a` of the mode quantities.
74struct Delta<T: Real> {
75    k_o: C<T>,
76    k_e: C<T>,
77    z: C<T>,
78}
79
80impl<T: Real> Medium<T> {
81    fn new(l: &LayerCoeffs<T>, k0: T, kx: T, neg_kzv2: C<T>) -> Self {
82        let one = C::new(T::one(), T::zero());
83        let (k_o, k_e, x_e) = mode_kz(l.chi_o, l.chi_e, k0 * k0, neg_kzv2);
84        Self {
85            chi_o: l.chi_o,
86            chi_e: l.chi_e,
87            k0,
88            kx,
89            k_o,
90            k_e,
91            z: k_e / (one + l.chi_o),
92            x_e,
93            pi: l.chi_o + l.chi_e + l.chi_o * l.chi_e,
94        }
95    }
96
97    /// `below - self` for `k_o`, `k_e`, and `z`, written in terms of
98    /// susceptibility differences.
99    fn delta(&self, below: &Self) -> Delta<T> {
100        let one = C::new(T::one(), T::zero());
101        let k0sq = self.k0 * self.k0;
102        let k_o = (below.chi_o - self.chi_o) * k0sq / (self.k_o + below.k_o);
103        let dz2 = ((below.chi_e - self.chi_e) * k0sq + below.x_e * self.pi - self.x_e * below.pi)
104            / ((one + self.pi) * (one + below.pi));
105        let z = dz2 / (self.z + below.z);
106        let cross_b = (below.chi_o + self.chi_e + below.chi_o * self.chi_e) * below.x_e;
107        let cross_a = (self.chi_o + below.chi_e + self.chi_o * below.chi_e) * self.x_e;
108        let dk_e2 = ((below.chi_e - self.chi_e) * k0sq + cross_b - cross_a)
109            / ((one + self.chi_e) * (one + below.chi_e));
110        let k_e = dk_e2 / (self.k_e + below.k_e);
111        Delta { k_o, k_e, z }
112    }
113}
114
115impl<T: Real> Eigenmodes<T> for Medium<T> {
116    fn kz(&self) -> [C<T>; 4] {
117        [self.k_e, -self.k_e, self.k_o, -self.k_o]
118    }
119
120    fn dynamic(&self) -> Mat4<T> {
121        let z0 = zero();
122        let one = C::new(T::one(), T::zero());
123        let a = self.z / self.k0;
124        let b = self.k_o / self.k0;
125        [
126            [a, -a, z0, z0],
127            [one, one, z0, z0],
128            [z0, z0, one, one],
129            [z0, z0, -b, b],
130        ]
131    }
132
133    fn e_norms(&self) -> [T; 4] {
134        let e_e = C::new(T::one(), T::zero()) + self.chi_e;
135        let ez = C::new(self.kx, T::zero()) / (e_e * self.k0);
136        let ex = self.z / self.k0;
137        let p = (ex.norm_sqr() + ez.norm_sqr()).sqrt() + T::epsilon();
138        [p, p, T::one(), T::one()]
139    }
140
141    fn diff(&self, below: &Self) -> (Mat4<T>, [C<T>; 4]) {
142        let z0 = zero();
143        let d = self.delta(below);
144        let dz = d.z / self.k0;
145        let dk = d.k_o / self.k0;
146        let dd = [
147            [dz, -dz, z0, z0],
148            [z0, z0, z0, z0],
149            [z0, z0, z0, z0],
150            [z0, z0, -dk, dk],
151        ];
152        (dd, [d.k_e, -d.k_e, d.k_o, -d.k_o])
153    }
154}
155
156/// Interface matrix `K = (I + D_a^-1 dD) o W` between `a` (above) and `b` (below).
157fn interface<T: Real>(
158    di_a: &Mat4<T>,
159    kz_a: &[C<T>; 4],
160    kz_b: &[C<T>; 4],
161    dd: &Mat4<T>,
162    dkz: &[C<T>; 4],
163    sigma: T,
164) -> Mat4<T> {
165    let z0 = zero();
166    let mut k = [[z0; 4]; 4];
167    for (i, row) in k.iter_mut().enumerate() {
168        for (j, v) in row.iter_mut().enumerate() {
169            let mut s = z0;
170            for m in 0..4 {
171                s += di_a[i][m] * dd[m][j];
172            }
173            if i == j {
174                s += C::new(T::one(), T::zero());
175            }
176            *v = s;
177        }
178    }
179    if sigma != T::zero() {
180        let r2_half = C::new(sigma * sigma * T::lit(0.5), T::zero());
181        for s in 0..4 {
182            let plus = kz_b[s] + kz_a[s];
183            let eplus = (-plus * plus * r2_half).exp();
184            let eminus = (-dkz[s] * dkz[s] * r2_half).exp();
185            for (row, k_row) in k.iter_mut().enumerate() {
186                k_row[s] *= if (row + s) % 2 == 0 { eminus } else { eplus };
187            }
188        }
189    }
190    k
191}
192
193fn block<T: Real>(k: &Mat4<T>, rows: [usize; 2], cols: [usize; 2]) -> Mat2<T> {
194    [
195        [k[rows[0]][cols[0]], k[rows[0]][cols[1]]],
196        [k[rows[1]][cols[0]], k[rows[1]][cols[1]]],
197    ]
198}
199
200fn mul2<T: Real>(a: &Mat2<T>, b: &Mat2<T>) -> Mat2<T> {
201    [
202        [
203            a[0][0] * b[0][0] + a[0][1] * b[1][0],
204            a[0][0] * b[0][1] + a[0][1] * b[1][1],
205        ],
206        [
207            a[1][0] * b[0][0] + a[1][1] * b[1][0],
208            a[1][0] * b[0][1] + a[1][1] * b[1][1],
209        ],
210    ]
211}
212
213fn add2<T: Real>(a: &Mat2<T>, b: &Mat2<T>) -> Mat2<T> {
214    [
215        [a[0][0] + b[0][0], a[0][1] + b[0][1]],
216        [a[1][0] + b[1][0], a[1][1] + b[1][1]],
217    ]
218}
219
220/// `num * den^-1` for 2x2 matrices; `None` when `den` is singular.
221fn right_divide<T: Real>(num: &Mat2<T>, den: &Mat2<T>) -> Option<Mat2<T>> {
222    let det = den[0][0] * den[1][1] - den[0][1] * den[1][0];
223    let det_norm = det.norm();
224    if det_norm.is_nan() || det_norm == T::zero() {
225        return None;
226    }
227    let inv = [
228        [den[1][1] / det, -den[0][1] / det],
229        [-den[1][0] / det, den[0][0] / det],
230    ];
231    Some(mul2(num, &inv))
232}
233
234/// Polarized reflectance at one q-point from the 4x4 reflection-matrix recursion.
235///
236/// Agrees with [`super::solve_point`] in exact arithmetic (including
237/// cross-polarized terms and the fronting unit-`|E|` mode normalization) and
238/// is accurate to near working precision in `f32` and `f64`; see the module
239/// documentation for the formulation. Transmission is not computed.
240///
241/// # Parameters
242/// Same as [`super::solve_point`].
243///
244/// # Returns
245/// Reflectance in the [`super::PointResult`] packing: `(0, 0) = R_pp`,
246/// `(1, 1) = R_ss`, off-diagonals cross-polarized.
247///
248/// # Errors
249/// [`RefloxideError::SingularDynamicMatrix`] with the failing layer index
250/// and `q_index = usize::MAX` when a dynamic matrix or the 2x2 recursion
251/// denominator is singular.
252pub fn solve_point_rmatrix<T: Real>(q: T, k0: T, layers: &[LayerCoeffs<T>]) -> Result<[[T; 2]; 2]> {
253    let kz_vac = (q * T::lit(0.5)).max(-k0).min(k0);
254    let neg_kzv2 = C::new(-(kz_vac * kz_vac), T::zero());
255    let kx = (k0 * k0 - kz_vac * kz_vac).sqrt();
256    reflect_chain(
257        layers.len(),
258        |j| Medium::new(&layers[j], k0, kx, neg_kzv2),
259        |j| (layers[j].thickness, layers[j].sigma),
260    )
261}
262
263/// Reflection-matrix recursion over `n` layers built by `medium(j)`.
264///
265/// `slab(j)` returns `(thickness, sigma)` of layer `j`, with `sigma` the
266/// roughness of the interface above it. Returns reflectance in the
267/// [`super::PointResult`] packing, normalized to unit-`|E|` fronting modes.
268pub(crate) fn reflect_chain<T: Real, M: Eigenmodes<T>>(
269    n: usize,
270    medium: impl Fn(usize) -> M,
271    slab: impl Fn(usize) -> (T, T),
272) -> Result<[[T; 2]; 2]> {
273    let singular = |layer| RefloxideError::SingularDynamicMatrix {
274        layer,
275        q_index: usize::MAX,
276        energy_index: None,
277    };
278    let mut below = medium(n - 1);
279    let mut g: Mat2<T> = [[zero(); 2]; 2];
280    let mut front = None;
281    for j in (1..n).rev() {
282        let above = medium(j - 1);
283        let (thickness, sigma) = slab(j);
284        if j < n - 1 {
285            let kz = below.kz();
286            let i_d = C::new(T::zero(), thickness);
287            for (a, &u) in UP.iter().enumerate() {
288                for (b, &dn) in DOWN.iter().enumerate() {
289                    g[a][b] *= (-(kz[u] - kz[dn]) * i_d).exp();
290                }
291            }
292        }
293        let di_a = exact_inv_4x4_generic(&above.dynamic()).ok_or_else(|| singular(j - 1))?;
294        let (dd, dkz) = above.diff(&below);
295        let k = interface(&di_a, &above.kz(), &below.kz(), &dd, &dkz, sigma);
296        let num = add2(&block(&k, UP, DOWN), &mul2(&block(&k, UP, UP), &g));
297        let den = add2(&block(&k, DOWN, DOWN), &mul2(&block(&k, DOWN, UP), &g));
298        g = right_divide(&num, &den).ok_or_else(|| singular(j - 1))?;
299        if j == 1 {
300            front = Some(above);
301            break;
302        }
303        below = above;
304    }
305    let norms = front.ok_or_else(|| singular(0))?.e_norms();
306    // refl(a, b): UP[a] amplitude from DOWN[b] incident.
307    // DOWN = [p+, s+], UP = [p-, s-] => [[R_pp, R_sp], [R_ps, R_ss]]
308    // with R_sp = s reflected from p and R_ps = p reflected from s.
309    let refl = |a: usize, b: usize| {
310        (g[a][b] * (norms[UP[a]] / norms[DOWN[b]]))
311            .norm_sqr()
312            .min(T::one())
313    };
314    Ok([[refl(0, 0), refl(1, 0)], [refl(0, 1), refl(1, 1)]])
315}