Skip to main content

lensbench_analysis/
polgrid.rs

1//! 偏光追跡を粗い瞳格子で行い、全光線へ補間して Jones 行列を配る。
2//!
3//! 伝搬の位相 exp(−ik·OPL) を除いた Jones 行列([`lensbench_core::system::System::trace_pol_launch`] の phase = false)は
4//! 瞳の上で滑らかなので、正規化瞳座標の [−1, 1]² の正規の格子(nx × ny 点)で偏光追跡し、その値を 2 次元の
5//! 3 次スプライン(not-a-knot の 1 次元スプラインのテンソル積)で補間する。全光線の偏光追跡より速い
6//! (偏光追跡は普通の追跡の約 10 倍かかる)。
7//!
8//! 格子点の扱い:
9//! - 追跡が止まった・けられた格子点(瞳の縁の外側など)は、格子の上で最も近い有効な点の値で埋める。
10//! - 瞳の内側(px² + py² ≤ 1)で欠けた格子点は「欠け」として返す([`PolGrid::missing`])。欠けた点から
11//!   [`BAD_MARGIN`] 点の範囲のセルにある光線は NaN にする(黙って埋めない)。
12//!
13//! 値は格子点ごとに 8 つの複素数: Jones 行列 [xx, xy, yx, yy](行 = 出射の x・y、列 = 入射の x・y)と
14//! z 成分 [z_x, z_y](列 = 入射の x・y)、物体空間の光線の向きの単位ベクトルの、物体の座標系での x・y 成分 [kx, ky]
15//! (実部だけ)。
16//! 追跡の入射は物体の座標系の x・y の単位ベクトルを光線に垂直な面へ射影したもの(規格化しない)。入射の偏光 (Jx, Jy) は
17//! OpticStudio の系の偏光と同じく、光線に垂直な面の正規直交の基底 e_x' = x の射影を規格化したもの、e_y' = k × e_x' で
18//! E = Jx·e_x' + Jy·e_y' とし、追跡の線形性で 2 つの列の重ね合わせに直す([`basis_coeffs`])。
19use lensbench_core::coating::{Coatings, C64};
20use lensbench_core::grid::Grid2;
21use lensbench_core::interp::Spline;
22use lensbench_core::pupil::{PupilGrid, Rim};
23use lensbench_core::system::{Launch, PolIn, RecSel, System};
24use lensbench_core::{invalid, Result};
25
26/// 格子点ごとの値の数(Jones 4 + z 成分 2 + 物体空間の向き 2)
27pub(crate) const NV: usize = 8;
28
29/// 大域座標の向き d(物体空間の光線)を、物体の座標系(面 1 の変換の前、入射の偏光 (Ex, Ey) を測る座標系)の単位ベクトルに
30/// したときの x・y 成分
31pub fn obj_dir(sys: &System, d: [f64; 3]) -> [f64; 2] {
32    let r = sys.frames().obj.r;
33    let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
34    [0, 1].map(|c| (r[0][c] * d[0] + r[1][c] * d[1] + r[2][c] * d[2]) / n)
35}
36
37/// 入射の偏光 j = (Jx, Jy) の場 E = Jx·e_x' + Jy·e_y'(e_x' = x の射影を規格化、e_y' = k × e_x'。OpticStudio の
38/// 系の偏光の基底、2026 R1.01 で実測)を、追跡の入射の x・y の射影 p_x = x − kx·k・p_y = y − ky·k の重ね合わせ
39/// a·p_x + b·p_y で表した (a, b)。(kx, ky) は物体の座標系の光線の単位ベクトルの x・y 成分([`obj_dir`]、kz > 0)。
40/// |E|² = |Jx|² + |Jy|² なので、透過率は出射の |a·E_x + b·E_y|² を |j|² で割る
41pub fn basis_coeffs(j: [C64; 2], kx: f64, ky: f64) -> [C64; 2] {
42    let s = (1.0 - kx * kx).sqrt();
43    let kz = (1.0 - kx * kx - ky * ky).max(0.0).sqrt();
44    // e_y' = k × x / s = (kx·ky / (s·kz))·p_x + (s / kz)·p_y(グラム行列の行列式は kz²)
45    [j[0] / s + j[1] * (kx * ky / (s * kz)), j[1] * (s / kz)]
46}
47
48/// 欠けた格子点から何点の範囲のセルの光線を補間しないか(スプラインは大域なので、埋めた値の影響は
49/// 1 点離れるごとに約 0.27 倍に減る。2 点で 4×4 の近傍の外側にもう 1 点の余裕)
50pub(crate) const BAD_MARGIN: usize = 2;
51
52/// 補間に使う 1 軸の格子の点数の下限(not-a-knot のスプラインに 4 点要る)
53pub const MIN_POINTS: usize = 4;
54
55/// 粗い瞳格子での偏光追跡の結果と、補間の係数
56#[derive(Debug, Clone)]
57pub struct PolGrid {
58    /// 格子点の値(座標は正規化瞳座標 px・py の [`axis`]、行 = py。欠けた点は最も近い有効な点の値)
59    f: Grid2<[C64; NV]>,
60    /// ∂f/∂px・∂f/∂py・∂²f/∂px∂py(スプラインの節点での微分)
61    fx: Vec<[C64; NV]>,
62    fy: Vec<[C64; NV]>,
63    fxy: Vec<[C64; NV]>,
64    /// 瞳の内側で欠けた格子点(j * nx + i)
65    missing: Vec<usize>,
66    /// 補間に使えない格子点(欠けた点。missing と同じ集合を引きやすい形で)
67    bad: Vec<bool>,
68}
69
70/// 1 軸の格子の座標([−1, 1] を n − 1 等分、[`PupilGrid::Linear`] の座標)
71pub fn axis(n: usize) -> Vec<f64> {
72    PupilGrid::Linear {
73        n,
74        rim: Rim::Padded,
75    }
76    .axis()
77    .unwrap_or_default()
78}
79
80impl PolGrid {
81    /// 光線の始め方 l([`Launch::Pupil`]。px・py は無視して格子に置き換える)の物体・ケラレ係数で、
82    /// 波長 w の偏光追跡を nx × ny の格子で行う(伝搬の位相なし)
83    pub fn trace(
84        sys: &System,
85        l: &Launch,
86        w: usize,
87        coat: &Coatings,
88        nx: usize,
89        ny: usize,
90    ) -> Result<PolGrid> {
91        if nx < MIN_POINTS || ny < MIN_POINTS {
92            invalid!("the polarization grid needs {MIN_POINTS} points or more on each axis ({nx} × {ny})");
93        }
94        let (ax, ay) = (axis(nx), axis(ny));
95        let mut gx = Vec::with_capacity(nx * ny);
96        let mut gy = Vec::with_capacity(nx * ny);
97        for &y in &ay {
98            for &x in &ax {
99                gx.push(x);
100                gy.push(y);
101            }
102        }
103        let gl = match *l {
104            Launch::Pupil {
105                spec,
106                signed,
107                vig,
108                hxy,
109                ..
110            } => Launch::Pupil {
111                spec,
112                signed,
113                px: &gx,
114                py: &gy,
115                vig,
116                hxy,
117            },
118            _ => invalid!("the polarization grid is only for rays started in pupil coordinates (normalized, signed)"),
119        };
120        let x = [C64::new(1.0, 0.0), C64::new(0.0, 0.0)];
121        let y = [C64::new(0.0, 0.0), C64::new(1.0, 0.0)];
122        let p = sys.trace_pol_launch(&gl, w, PolIn::new(&[x, y], coat).no_phase(), RecSel::Off)?;
123        let n = nx * ny;
124        let mut vals = vec![[C64::new(0.0, 0.0); NV]; n];
125        let mut good = vec![false; n];
126        for k in 0..n {
127            let e = &p.e[k];
128            let (ex, ey) = (e[0], e[1]);
129            let [kx, ky] = obj_dir(sys, p.trace.k0[k]).map(|c| C64::new(c, 0.0));
130            let v = [ex[0], ey[0], ex[1], ey[1], ex[2], ey[2], kx, ky];
131            if p.trace.ok(k) && v.iter().all(|c| c.re.is_finite() && c.im.is_finite()) {
132                vals[k] = v;
133                good[k] = true;
134            }
135        }
136        if !good.iter().any(|&g| g) {
137            invalid!("no point of the polarization grid passes");
138        }
139        let inside = |k: usize| Rim::Padded.inside(gx[k], gy[k]);
140        let missing: Vec<usize> = (0..n).filter(|&k| !good[k] && inside(k)).collect();
141        let mut bad = vec![false; n];
142        missing.iter().for_each(|&k| bad[k] = true);
143        fill_nearest(&mut vals, &good, nx, ny);
144        let (hx, hy) = (2.0 / (nx - 1) as f64, 2.0 / (ny - 1) as f64);
145        let sx = SlopeOp::new(nx, hx);
146        let sy = SlopeOp::new(ny, hy);
147        let fx = sx.along_x(&vals, nx, ny);
148        let fy = sy.along_y(&vals, nx, ny);
149        let fxy = sx.along_x(&fy, nx, ny);
150        Ok(PolGrid {
151            f: Grid2::new(ax, ay, vals),
152            fx,
153            fy,
154            fxy,
155            missing,
156            bad,
157        })
158    }
159
160    /// px の向きの格子点の数
161    pub fn nx(&self) -> usize {
162        self.f.nx()
163    }
164
165    /// py の向きの格子点の数
166    pub fn ny(&self) -> usize {
167        self.f.ny()
168    }
169
170    /// 格子点の値(Jones 行列 [xx, xy, yx, yy]、z 成分 [z_x, z_y]、物体空間の向き [kx, ky]。欠けた点は最も近い有効な点の値で埋めたもの)
171    pub fn values(&self) -> &Grid2<[C64; NV]> {
172        &self.f
173    }
174
175    /// 瞳の内側で欠けた格子点の座標 (px, py)
176    pub fn missing(&self) -> Vec<[f64; 2]> {
177        let (ax, ay, nx) = (self.f.x(), self.f.y(), self.nx());
178        self.missing
179            .iter()
180            .map(|&k| [ax[k % nx], ay[k / nx]])
181            .collect()
182    }
183
184    /// 正規化瞳座標 (px, py) での補間値。格子の外(|p| > 1)は端の多項式を延ばす。セルから
185    /// [`BAD_MARGIN`] 点の範囲に欠けた格子点があれば None
186    pub fn eval(&self, px: f64, py: f64) -> Option<[C64; NV]> {
187        if !(px.is_finite() && py.is_finite()) {
188            return None;
189        }
190        let (nx, ny) = (self.nx(), self.ny());
191        let f = self.f.data();
192        let (hx, hy) = (2.0 / (nx - 1) as f64, 2.0 / (ny - 1) as f64);
193        let cell = |p: f64, h: f64, n: usize| -> (usize, f64) {
194            let s = (p + 1.0) / h;
195            let i = (s.floor().max(0.0) as usize).min(n - 2);
196            (i, s - i as f64)
197        };
198        let (i, t) = cell(px, hx, nx);
199        let (j, u) = cell(py, hy, ny);
200        if !self.missing.is_empty() {
201            let m = BAD_MARGIN;
202            let (i0, i1) = (i.saturating_sub(m), (i + 1 + m).min(nx - 1));
203            let (j0, j1) = (j.saturating_sub(m), (j + 1 + m).min(ny - 1));
204            for jj in j0..=j1 {
205                for ii in i0..=i1 {
206                    if self.bad[jj * nx + ii] {
207                        return None;
208                    }
209                }
210            }
211        }
212        // 3 次 Hermite の基底(値と、h を掛けた微分)
213        let h = |s: f64| {
214            let (s2, s3) = (s * s, s * s * s);
215            (
216                [2.0 * s3 - 3.0 * s2 + 1.0, -2.0 * s3 + 3.0 * s2],
217                [s3 - 2.0 * s2 + s, s3 - s2],
218            )
219        };
220        let (ax, bx) = h(t);
221        let (ay, by) = h(u);
222        let mut out = [C64::new(0.0, 0.0); NV];
223        for (b, jj) in [j, j + 1].into_iter().enumerate() {
224            for (a, ii) in [i, i + 1].into_iter().enumerate() {
225                let k = jj * nx + ii;
226                let w0 = ax[a] * ay[b];
227                let w1 = bx[a] * ay[b] * hx;
228                let w2 = ax[a] * by[b] * hy;
229                let w3 = bx[a] * by[b] * hx * hy;
230                for c in 0..NV {
231                    out[c] += f[k][c] * w0
232                        + self.fx[k][c] * w1
233                        + self.fy[k][c] * w2
234                        + self.fxy[k][c] * w3;
235                }
236            }
237        }
238        Some(out)
239    }
240}
241
242/// 有効でない点を、格子の上で最も近い(添字の距離の 2 乗が最小、同じなら添字の小さい)有効な点の値で埋める
243fn fill_nearest(v: &mut [[C64; NV]], good: &[bool], nx: usize, ny: usize) {
244    let gk: Vec<usize> = (0..nx * ny).filter(|&k| good[k]).collect();
245    for k in 0..nx * ny {
246        if good[k] {
247            continue;
248        }
249        let (i, j) = ((k % nx) as i64, (k / nx) as i64);
250        let mut best = (i64::MAX, 0);
251        for &q in &gk {
252            let (a, b) = ((q % nx) as i64 - i, (q / nx) as i64 - j);
253            let d = a * a + b * b;
254            if d < best.0 {
255                best = (d, q);
256            }
257        }
258        v[k] = v[best.1];
259    }
260}
261
262/// 等間隔 n 点の値から not-a-knot の 3 次スプラインの節点の傾きを出す線形の演算子(n × n の行列)
263struct SlopeOp {
264    n: usize,
265    m: Vec<f64>,
266}
267
268impl SlopeOp {
269    fn new(n: usize, h: f64) -> SlopeOp {
270        // 傾きは値について線形なので、単位の値 e_c のスプラインの傾きが演算子の列 c(膜の表と同じスプライン)
271        let x: Vec<f64> = (0..n).map(|i| i as f64 * h).collect();
272        let mut m = vec![0.0; n * n];
273        for c in 0..n {
274            let mut e = vec![0.0; n];
275            e[c] = 1.0;
276            let d = Spline::not_a_knot_slopes(&x, &e)
277                .expect("equally spaced nodes with MIN_POINTS (4) points or more");
278            for (i, v) in d.into_iter().enumerate() {
279                m[i * n + c] = v;
280            }
281        }
282        SlopeOp { n, m }
283    }
284
285    fn apply(&self, src: &[[C64; NV]], dst: &mut [[C64; NV]], idx: impl Fn(usize) -> usize) {
286        let n = self.n;
287        for i in 0..n {
288            let mut acc = [C64::new(0.0, 0.0); NV];
289            for c in 0..n {
290                let w = self.m[i * n + c];
291                if w != 0.0 {
292                    let s = &src[idx(c)];
293                    for q in 0..NV {
294                        acc[q] += s[q] * w;
295                    }
296                }
297            }
298            dst[idx(i)] = acc;
299        }
300    }
301
302    /// 各行(py 一定)に沿った傾き
303    fn along_x(&self, v: &[[C64; NV]], nx: usize, ny: usize) -> Vec<[C64; NV]> {
304        let mut d = vec![[C64::new(0.0, 0.0); NV]; nx * ny];
305        for j in 0..ny {
306            self.apply(v, &mut d, |i| j * nx + i);
307        }
308        d
309    }
310
311    /// 各列(px 一定)に沿った傾き
312    fn along_y(&self, v: &[[C64; NV]], nx: usize, ny: usize) -> Vec<[C64; NV]> {
313        let mut d = vec![[C64::new(0.0, 0.0); NV]; nx * ny];
314        for i in 0..nx {
315            self.apply(v, &mut d, |j| j * nx + i);
316        }
317        d
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    /// 3 次の多項式は not-a-knot のスプラインで厳密に再現する
326    #[test]
327    fn slope_exact_for_cubic() {
328        let n = 7;
329        let h = 2.0 / (n - 1) as f64;
330        let op = SlopeOp::new(n, h);
331        let xs = axis(n);
332        let f = |x: f64| 0.3 - 1.2 * x + 0.7 * x * x + 2.1 * x * x * x;
333        let df = |x: f64| -1.2 + 1.4 * x + 6.3 * x * x;
334        for i in 0..n {
335            let d: f64 = (0..n).map(|c| op.m[i * n + c] * f(xs[c])).sum();
336            assert!((d - df(xs[i])).abs() < 1e-12, "{i}: {d} {}", df(xs[i]));
337        }
338    }
339
340    /// 双 3 次の多項式は補間で厳密に再現する(格子点の間・格子の外の延長でも)
341    #[test]
342    fn eval_exact_for_bicubic() {
343        let (nx, ny) = (6, 5);
344        let g = |x: f64, y: f64| {
345            C64::new(
346                1.0 + x - 0.5 * y + 0.3 * x * y * y + 0.8 * x * x * x * y,
347                0.2 * y * y * y - x * x,
348            )
349        };
350        let (ax, ay) = (axis(nx), axis(ny));
351        let mut f = Vec::new();
352        for &y in &ay {
353            for &x in &ax {
354                f.push([g(x, y); NV]);
355            }
356        }
357        let (hx, hy) = (2.0 / (nx - 1) as f64, 2.0 / (ny - 1) as f64);
358        let (sx, sy) = (SlopeOp::new(nx, hx), SlopeOp::new(ny, hy));
359        let fy = sy.along_y(&f, nx, ny);
360        let pg = PolGrid {
361            fx: sx.along_x(&f, nx, ny),
362            fxy: sx.along_x(&fy, nx, ny),
363            fy,
364            f: Grid2::new(ax, ay, f),
365            missing: vec![],
366            bad: vec![false; nx * ny],
367        };
368        for &(x, y) in &[
369            (0.13, -0.77),
370            (-0.99, 0.5),
371            (1.0, 1.0),
372            (0.0, 0.0),
373            (1.02, -1.01),
374        ] {
375            let v = pg.eval(x, y).unwrap()[3];
376            assert!((v - g(x, y)).norm() < 1e-12, "({x}, {y}): {v} {}", g(x, y));
377        }
378    }
379
380    #[test]
381    fn fill_nearest_picks_closest() {
382        let (nx, ny) = (4, 4);
383        let mut v = vec![[C64::new(0.0, 0.0); NV]; 16];
384        let mut good = vec![false; 16];
385        v[5][0] = C64::new(1.0, 0.0);
386        good[5] = true;
387        v[15][0] = C64::new(2.0, 0.0);
388        good[15] = true;
389        fill_nearest(&mut v, &good, nx, ny);
390        assert_eq!(v[0][0].re, 1.0);
391        assert_eq!(v[14][0].re, 2.0);
392        assert_eq!(v[10][0].re, 1.0); // (2, 2) は 5 にも 15 にも距離² 2 → 添字の小さい 5
393    }
394}