Skip to main content

lensbench_analysis/
raygrid.rs

1//! 瞳の格子の光線の追跡と画素への補間(干渉の解析で共通): 1 本の経路の光線の格子([`RayGrid`])、検出面の画素への
2//! 三角形の補間([`rasterize`])、ファイバの入射偏光([`InputPol`])と偏光追跡([`trace_path`]・[`trace_jones`])。
3//!
4//! 単色の干渉縞(lensbench-analysis の interference)と、拡張のプラグイン(干渉の計算など)が使う。
5//!
6//! - 強度は幾何光学: 瞳の格子のセル 1 つを三角形 2 つに分け、三角形ごとに
7//!   ファイバのモードの重み(ファイバ端の方向余弦のガウス)× 方向余弦の面積 / 検出面の面積。
8//!   画素は、その中心を含む最初の三角形の値を取る(ねじれた三角形 = 折り返しは除く)。
9//! - 場は中心波長の偏光追跡の Jones ベクトル(検出面の局所 x・y、約束は exp(−i k L)、[`lensbench_core::phase`])、
10//!   光路長は追跡した波長ごと。画素の値は三角形の重心座標で補間する。
11
12use lensbench_core::coating::{Coatings, C64};
13use lensbench_core::math::V3;
14use lensbench_core::par::scoped;
15use lensbench_core::system::{FieldSel, Launch, PolIn, RecSel, System};
16use lensbench_core::{invalid, Result};
17use rayon::prelude::*;
18
19fn czero() -> C64 {
20    C64::new(0.0, 0.0)
21}
22
23// ---------------------------------------------------------------------------------------------------------------
24// 光線の格子と画素への補間
25
26/// 瞳の G × G の格子(正規化瞳座標 −1〜1 を等間隔、行優先で q = iy·G + ix)。座標と単位円の中の判定の 1 か所
27/// ([`trace_jones`] と、それと同じ光線を追い直す側・微分の計算が同じ点を指すように)
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct PupilGrid {
30    g: usize,
31}
32
33impl PupilGrid {
34    /// 一辺 g 点の格子(g ≥ 2 が前提。端の点が瞳の縁 ±1 に来る。入口の trace_jones などが g < 2 を誤りにしている)
35    pub fn new(g: usize) -> Self {
36        debug_assert!(
37            g >= 2,
38            "the pupil grid needs at least 2 points per side (got {g})"
39        );
40        Self { g }
41    }
42
43    /// 一辺の点の数
44    #[inline]
45    pub fn g(&self) -> usize {
46        self.g
47    }
48
49    /// 格子点 q の正規化瞳座標 [px, py]
50    #[inline]
51    pub fn coords(&self, q: usize) -> [f64; 2] {
52        let g = self.g;
53        [
54            -1.0 + 2.0 * (q % g) as f64 / (g - 1) as f64,
55            -1.0 + 2.0 * (q / g) as f64 / (g - 1) as f64,
56        ]
57    }
58
59    /// 格子点 q が単位円の中(縁を含む)か
60    #[inline]
61    pub fn inside(&self, q: usize) -> bool {
62        let [x, y] = self.coords(q);
63        x * x + y * y <= 1.0
64    }
65
66    /// 単位円の中の格子点(行優先)の (番号, px, py)。[`trace_jones`] が追う光線の並び
67    pub fn rays(&self) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
68        self.rays_where(|q| self.inside(q))
69    }
70
71    /// 格子点 q が単位円のすぐ外で、単位円にかかる区間の双三次の支え(4 × 4 の節)になり得るか(半径 1 + 3 h まで、
72    /// h は格子の間隔)
73    #[inline]
74    pub fn rim(&self, q: usize) -> bool {
75        let [x, y] = self.coords(q);
76        let h = 2.0 / (self.g - 1) as f64;
77        // 中か([`PupilGrid::inside`]、2 乗の和で決める)の否定にする(hypot と 2 乗の和で r = 1 の点が抜けない)
78        !self.inside(q) && x.hypot(y) <= 1.0 + 3.0 * h
79    }
80
81    /// 単位円の中と、そのすぐ外([`PupilGrid::rim`])の格子点の (番号, px, py)。[`trace_jones_edge`] が追う光線の並び
82    pub fn rays_rim(&self) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
83        self.rays_where(|q| self.inside(q) || self.rim(q))
84    }
85
86    fn rays_where(&self, f: impl Fn(usize) -> bool) -> (Vec<usize>, Vec<f64>, Vec<f64>) {
87        let idx: Vec<usize> = (0..self.g * self.g).filter(|&q| f(q)).collect();
88        let px = idx.iter().map(|&q| self.coords(q)[0]).collect();
89        let py = idx.iter().map(|&q| self.coords(q)[1]).collect();
90        (idx, px, py)
91    }
92}
93
94/// 1 本の経路の光線の格子(瞳の G × G、番号 = iy·G + ix、瞳座標 −1 + 2·i/(G−1))
95#[derive(Debug, Clone, PartialEq)]
96pub struct RayGrid {
97    pub g: usize,
98    /// 検出面に届いた光線(瞳の円の外・ケラレ・開口の外は false)
99    pub ok: Vec<bool>,
100    /// 検出面の局所座標の位置 [mm]
101    pub xs: Vec<f64>,
102    pub ys: Vec<f64>,
103    /// ファイバ端での方向余弦(モードの重みに使う)
104    pub sx: Vec<f64>,
105    pub sy: Vec<f64>,
106    /// [波長][光線] の光路長 [mm](波長 0 = 中心)。どの波長も中心波長の検出面の着地点 (xs, ys) での値([`trace_jones`] が
107    /// 波長ごとの着地点のずれを 1 次で直す)
108    pub l: Vec<Vec<f64>>,
109    /// 検出面の局所 x・y の場(中心波長、約束は exp(−i k L))
110    pub ex: Vec<C64>,
111    pub ey: Vec<C64>,
112    /// 無限遠物体で光線が 1 点に集まる面が見つからず、`sx`・`sy` に瞳の座標の 1e-4 倍を入れた(モードの重みが
113    /// ほぼ一様になる。[`trace_jones`])
114    pub mode_fallback: bool,
115}
116
117impl RayGrid {
118    pub fn new(g: usize, nw: usize) -> RayGrid {
119        let n = g * g;
120        RayGrid {
121            g,
122            ok: vec![false; n],
123            xs: vec![0.0; n],
124            ys: vec![0.0; n],
125            sx: vec![0.0; n],
126            sy: vec![0.0; n],
127            l: vec![vec![0.0; n]; nw],
128            ex: vec![czero(); n],
129            ey: vec![czero(); n],
130            mode_fallback: false,
131        }
132    }
133
134    /// 配列の大きさが G² か確かめる
135    pub fn check(&self) -> Result<()> {
136        let n = self.g * self.g;
137        if self.g < 2
138            || self.ok.len() != n
139            || [&self.xs, &self.ys, &self.sx, &self.sy]
140                .iter()
141                .any(|v| v.len() != n)
142            || self.l.is_empty()
143            || self.l.iter().any(|v| v.len() != n)
144            || self.ex.len() != n
145            || self.ey.len() != n
146        {
147            invalid!("the ray grid size doesn't match (G = {})", self.g);
148        }
149        Ok(())
150    }
151}
152
153/// 画素の格子(N × N、画素 (i, j) の中心は (x0 + i·dx, y0 + j·dx)、番号 j·N + i)に補間した 1 本の経路
154#[derive(Debug, Clone)]
155pub struct PixelData {
156    pub n: usize,
157    pub x0: f64,
158    pub y0: f64,
159    pub dx: f64,
160    pub ok: Vec<bool>,
161    /// 強度(モードの重み × 方向余弦の面積 / 検出面の面積)
162    pub i: Vec<f64>,
163    pub l: Vec<Vec<f64>>,
164    pub ex: Vec<C64>,
165    pub ey: Vec<C64>,
166    /// 折り返した(向きが逆の)三角形の割合
167    pub fold_fraction: f64,
168}
169
170/// ファイバのモードの重み(方向余弦のガウス、NA で 1/e²)。NA が無限大なら一様(重み 1、単色の干渉縞が使う)
171pub fn mode_weight(sx: f64, sy: f64, na: f64) -> f64 {
172    if na == f64::INFINITY {
173        return 1.0;
174    }
175    (-2.0 * (sx * sx + sy * sy) / (na * na)).exp() / (std::f64::consts::PI * na * na / 2.0)
176}
177
178fn tri_area(x: &[f64], y: &[f64], t: [usize; 3]) -> f64 {
179    0.5 * ((x[t[1]] - x[t[0]]) * (y[t[2]] - y[t[0]]) - (x[t[2]] - x[t[0]]) * (y[t[1]] - y[t[0]]))
180}
181
182/// 光線の格子を画素の格子へ(瞳のセルごとに三角形 2 つ)。画素はその中心を含む最初の三角形の値を取る
183pub fn rasterize(r: &RayGrid, npx: usize, x0: f64, y0: f64, dx: f64, na: f64) -> PixelData {
184    rasterize_with(r, None, npx, x0, y0, dx, na).0
185}
186
187/// [`rasterize`] に、光線ごとの複素の値をもう 1 つ(`extra`、場の z 成分など)同じ三角形・同じ重みで補間して添える
188/// (1 回の走査で。`extra` が無ければ空の列)
189pub fn rasterize_with(
190    r: &RayGrid,
191    extra: Option<&[C64]>,
192    npx: usize,
193    x0: f64,
194    y0: f64,
195    dx: f64,
196    na: f64,
197) -> (PixelData, Vec<C64>) {
198    let nw = r.l.len();
199    let g = r.g;
200    let mut tris = Vec::new();
201    for iy in 0..g - 1 {
202        for ix in 0..g - 1 {
203            let a = iy * g + ix;
204            let (b, c) = (a + 1, a + g);
205            let d = c + 1;
206            if r.ok[a] && r.ok[b] && r.ok[d] {
207                tris.push([a, b, d]);
208            }
209            if r.ok[a] && r.ok[d] && r.ok[c] {
210                tris.push([a, d, c]);
211            }
212        }
213    }
214    // 多い方の向き。裏返った三角形(折り返し・焦線)は除く
215    let pos = tris
216        .iter()
217        .filter(|t| tri_area(&r.xs, &r.ys, **t) > 0.0)
218        .count();
219    let sgn = if pos * 2 >= tris.len() { 1.0 } else { -1.0 };
220    let mut fold = 0usize;
221    // 使う三角形: 頂点、強度、行の範囲
222    let mut good: Vec<([usize; 3], f64, usize, usize)> = Vec::with_capacity(tris.len());
223    let last = npx as i64 - 1;
224    for t in &tris {
225        let a_s = tri_area(&r.xs, &r.ys, *t);
226        if a_s * sgn <= 0.0 {
227            fold += 1;
228            continue;
229        }
230        let a_d = tri_area(&r.sx, &r.sy, *t).abs();
231        let w = (mode_weight(r.sx[t[0]], r.sy[t[0]], na)
232            + mode_weight(r.sx[t[1]], r.sy[t[1]], na)
233            + mode_weight(r.sx[t[2]], r.sy[t[2]], na))
234            / 3.0;
235        let (ya, yb, yc) = (r.ys[t[0]], r.ys[t[1]], r.ys[t[2]]);
236        let j0 = (((ya.min(yb.min(yc)) - y0) / dx).floor() as i64).max(0);
237        let j1 = (((ya.max(yb.max(yc)) - y0) / dx).ceil() as i64).min(last);
238        if j0 > j1 {
239            good.push((*t, w * a_d / a_s.abs(), 1, 0));
240            continue;
241        }
242        good.push((*t, w * a_d / a_s.abs(), j0 as usize, j1 as usize));
243    }
244    // 行ごとに、その行に掛かる三角形の番号(good の順のまま)。行 × 三角形の総当たりを避ける
245    let mut start = vec![0usize; npx + 1];
246    for &(_, _, j0, j1) in &good {
247        for j in j0..=j1 {
248            start[j + 1] += 1;
249        }
250    }
251    for j in 0..npx {
252        start[j + 1] += start[j];
253    }
254    let mut fill = start.clone();
255    let mut by_row = vec![0usize; start[npx]];
256    for (k, &(_, _, j0, j1)) in good.iter().enumerate() {
257        for j in j0..=j1 {
258            by_row[fill[j]] = k;
259            fill[j] += 1;
260        }
261    }
262    let n2 = npx * npx;
263    let mut ok = vec![false; n2];
264    let mut ii = vec![0.0; n2];
265    let mut ll = vec![0.0; n2 * nw];
266    let mut ex = vec![czero(); n2];
267    let mut ey = vec![czero(); n2];
268    // 無いときも行ごとに分ける都合で同じ大きさを作り、返すときに捨てる
269    let mut ez = vec![czero(); n2];
270    // 行ごとに並列。行の中では三角形を同じ順に見るので、最初に覆った三角形が勝つ(逐次と同じ結果)
271    type Cols<'a> = ((&'a mut [bool], &'a mut [f64]), &'a mut [f64]);
272    type Row<'a> = (
273        usize,
274        ((Cols<'a>, (&'a mut [C64], &'a mut [C64])), &'a mut [C64]),
275    );
276    let row = |(j, ((((okr, ir), lr), (exr, eyr)), ezr)): Row| {
277        let y = y0 + j as f64 * dx;
278        for &k in &by_row[start[j]..start[j + 1]] {
279            let (t, irr, _, _) = good[k];
280            let (xa, ya, xb, yb, xc, yc) = (
281                r.xs[t[0]], r.ys[t[0]], r.xs[t[1]], r.ys[t[1]], r.xs[t[2]], r.ys[t[2]],
282            );
283            let i0 = (((xa.min(xb.min(xc)) - x0) / dx).floor() as i64).max(0);
284            let i1 = (((xa.max(xb.max(xc)) - x0) / dx).ceil() as i64).min(last);
285            if i0 > i1 {
286                continue;
287            }
288            let den = (yb - yc) * (xa - xc) + (xc - xb) * (ya - yc);
289            for i in i0 as usize..=i1 as usize {
290                if okr[i] {
291                    continue;
292                }
293                let x = x0 + i as f64 * dx;
294                let l1 = ((yb - yc) * (x - xc) + (xc - xb) * (y - yc)) / den;
295                let l2 = ((yc - ya) * (x - xc) + (xa - xc) * (y - yc)) / den;
296                let l3 = 1.0 - l1 - l2;
297                if l1 < -1e-12 || l2 < -1e-12 || l3 < -1e-12 {
298                    continue;
299                }
300                okr[i] = true;
301                ir[i] = irr;
302                for w in 0..nw {
303                    lr[w * npx + i] = l1 * r.l[w][t[0]] + l2 * r.l[w][t[1]] + l3 * r.l[w][t[2]];
304                }
305                exr[i] = r.ex[t[0]] * l1 + r.ex[t[1]] * l2 + r.ex[t[2]] * l3;
306                eyr[i] = r.ey[t[0]] * l1 + r.ey[t[1]] * l2 + r.ey[t[2]] * l3;
307                if let Some(z) = extra {
308                    ezr[i] = z[t[0]] * l1 + z[t[1]] * l2 + z[t[2]] * l3;
309                }
310            }
311        }
312    };
313    // 逐次の指定では rayon を使わない(fork した子プロセスでも動く)
314    if lensbench_core::par::sequential() {
315        ok.chunks_mut(npx)
316            .zip(ii.chunks_mut(npx))
317            .zip(ll.chunks_mut(npx * nw))
318            .zip(ex.chunks_mut(npx).zip(ey.chunks_mut(npx)))
319            .zip(ez.chunks_mut(npx))
320            .enumerate()
321            .for_each(row);
322    } else {
323        ok.par_chunks_mut(npx)
324            .zip(ii.par_chunks_mut(npx))
325            .zip(ll.par_chunks_mut(npx * nw))
326            .zip(ex.par_chunks_mut(npx).zip(ey.par_chunks_mut(npx)))
327            .zip(ez.par_chunks_mut(npx))
328            .enumerate()
329            .for_each(scoped(row));
330    }
331    // 行ごとの [波長][画素] を [波長][全画素] に並べ直す
332    let mut l = vec![vec![0.0; n2]; nw];
333    for j in 0..npx {
334        for w in 0..nw {
335            l[w][j * npx..(j + 1) * npx]
336                .copy_from_slice(&ll[j * npx * nw + w * npx..j * npx * nw + (w + 1) * npx]);
337        }
338    }
339    let p = PixelData {
340        n: npx,
341        x0,
342        y0,
343        dx,
344        ok,
345        i: ii,
346        l,
347        ex,
348        ey,
349        fold_fraction: if tris.is_empty() {
350            0.0
351        } else {
352            fold as f64 / tris.len() as f64
353        },
354    };
355    (p, if extra.is_some() { ez } else { Vec::new() })
356}
357
358// ---------------------------------------------------------------------------------------------------------------
359// 追跡
360
361/// ファイバの入射偏光(物体の座標系の Jones ベクトル、約束は exp(−i k L))
362#[derive(Debug, Clone, Copy, PartialEq)]
363pub enum InputPol {
364    X,
365    Y,
366    /// 直線(x から測った角度 [deg])
367    Angle(f64),
368    /// 円 +(x → y の向きに回る、S3 > 0)
369    CircularPlus,
370    CircularMinus,
371}
372
373impl InputPol {
374    pub fn jones(self) -> [C64; 2] {
375        let r = 0.5f64.sqrt();
376        match self {
377            InputPol::X => [C64::new(1.0, 0.0), czero()],
378            InputPol::Y => [czero(), C64::new(1.0, 0.0)],
379            InputPol::Angle(d) => [
380                C64::new(d.to_radians().cos(), 0.0),
381                C64::new(d.to_radians().sin(), 0.0),
382            ],
383            InputPol::CircularPlus => [C64::new(r, 0.0), C64::new(0.0, -r)],
384            InputPol::CircularMinus => [C64::new(r, 0.0), C64::new(0.0, r)],
385        }
386    }
387
388    pub fn parse(s: &str) -> Result<InputPol> {
389        let t = s.trim().to_ascii_lowercase();
390        Ok(match t.as_str() {
391            "x" | "s" => InputPol::X,
392            "y" | "p" => InputPol::Y,
393            "+" | "circ+" | "circular+" | "rcp" => InputPol::CircularPlus,
394            "-" | "circ-" | "circular-" | "lcp" => InputPol::CircularMinus,
395            _ => match t.parse::<f64>() {
396                Ok(d) => InputPol::Angle(d),
397                Err(_) => invalid!("input polarization {s} (x, y, angle [deg], circ+, circ-)"),
398            },
399        })
400    }
401}
402
403/// 位相の項(理想レンズ)がある系か
404fn has_phase_terms(sys: &System) -> bool {
405    sys.surfaces
406        .iter()
407        .any(|s| !s.ignore && s.action().is_ideal())
408}
409
410/// 1 本の経路(系 `sys` = その構成、波長は追跡する波長 [`traced_wavelengths`] に置き換え、主波長 0)の光線の格子を
411/// 瞳 G × G で追う。視野 `field`、入射偏光 `input`、膜 `coat`。
412///
413/// - 光路長: 生の光路長(物体から最後の面まで)。理想レンズがあれば、瞳の中は位相を含めた光路(主光線の生の
414///   光路長 + (光線 − 主光線) の位相込みの光路)
415/// - ファイバ端の方向余弦: 有限物体は物体点からの方向。無限遠物体は視野の光線が 1 点に集まる最初の面での方向
416///   (その面がなければ一様な瞳)
417/// - 場: 中心波長の偏光追跡を検出面の局所 x・y で(exp(−i k L) の約束)
418pub fn trace_path(
419    sys: &System,
420    field: FieldSel,
421    g: usize,
422    input: InputPol,
423    coat: &Coatings,
424) -> Result<RayGrid> {
425    let t = trace_jones(sys, field, g, coat, None)?;
426    let jin = input.jones();
427    let mut r = t.rays;
428    for q in 0..g * g {
429        if r.ok[q] {
430            let j = t.jones[q];
431            r.ex[q] = j[0][0] * jin[0] + j[0][1] * jin[1];
432            r.ey[q] = j[1][0] * jin[0] + j[1][1] * jin[1];
433        }
434    }
435    Ok(r)
436}
437
438/// [`trace_jones`] の結果: 光線の格子(場 `ex`・`ey` は 0 のまま)、光線ごとの Jones 行列(行 = 検出面の局所 x・y、
439/// 列 = ファイバ端の入射 x・y、中心波長、exp(−i k L) の約束)と、面 `surf` を指定したときのその面の局所座標の交点
440#[derive(Debug, Clone)]
441#[non_exhaustive]
442pub struct JonesGrid {
443    pub rays: RayGrid,
444    pub jones: Vec<[[C64; 2]; 2]>,
445    /// 指定面の交点 [mm](面を指定しないときは空。有効でない光線は NaN)
446    pub xf: Vec<f64>,
447    pub yf: Vec<f64>,
448    /// [波長][光線] の、光路長を中心波長の着地点へ移した量 [mm](`rays.l` に足してある。波長 0 は 0)。
449    /// 引けば各波長の光線の着地点での値になる(追跡の照合用)
450    pub landing: Vec<Vec<f64>>,
451    /// 光線ごとの、光が通る範囲の縁までの符号付きの距離 [正規化瞳の半径の単位](中が正。[`trace_jones_edge`] だけ、
452    /// ほかは空)。縁は瞳の単位円と、光線をける開口。値(位置・光路長・方向・Jones)のある光線(けられた光線と単位円の
453    /// すぐ外の光線を含む)は有限、ほかは NaN。`rays.ok` は値があって距離が 0 以上の光線
454    pub edge: Vec<f64>,
455    /// [`JonesGrid::edge`] を決めた開口の面(0 は単位円)と、距離のその面の交点 (x, y) についての勾配(瞳の単位 / mm、
456    /// 縁までの距離のパラメータ微分 = 勾配 · 交点の動き)。[`trace_jones_edge`] だけ、ほかは空
457    pub edge_surf: Vec<usize>,
458    pub edge_dm: Vec<[f64; 2]>,
459}
460
461/// [`trace_path`] と同じ追跡で、入射の x・y の 2 つを追って Jones 行列にする。`surf` を指定すると、その面の
462/// 局所座標の交点も記録する(全視野干渉の解析格子を指定面の座標で作るため)。
463pub fn trace_jones(
464    sys: &System,
465    field: FieldSel,
466    g: usize,
467    coat: &Coatings,
468    surf: Option<usize>,
469) -> Result<JonesGrid> {
470    trace_jones_in(sys, field, g, coat, surf, false)
471}
472
473/// [`trace_jones`] に、光が通る範囲の縁までの距離([`JonesGrid::edge`])を足したもの。単位円のすぐ外の光線
474/// ([`PupilGrid::rim`])も追い、けられた光線もそのまま追った値を残す(補間の支え)。縁までの距離は、光線をける開口
475/// ごとの縁までの距離 [mm](けられた面の交点)を、瞳の格子の差分で求めた勾配で瞳の単位に直したものと、単位円までの
476/// 距離 1 − r の最小。値のある範囲を瞳の格子の区間でなく、この距離の補間で点ごとに決めるため。開口は中心波長で
477/// 光線をけた面だけを見る。浮動開口(自動の半径)ではけない(半径は光束から決めたもので、ほかの波長の縁の光線を
478/// わずかにけるのは半径の決め方による)
479pub fn trace_jones_edge(
480    sys: &System,
481    field: FieldSel,
482    g: usize,
483    coat: &Coatings,
484    surf: Option<usize>,
485) -> Result<JonesGrid> {
486    if !sys.floating_clip {
487        return trace_jones_in(sys, field, g, coat, surf, true);
488    }
489    let mut s = sys.clone();
490    s.edit(|p| {
491        p.floating_clip = false;
492        Ok(())
493    })?;
494    trace_jones_in(&s, field, g, coat, surf, true)
495}
496
497/// 瞳の格子 g × g の値 `m`(値のない点は NaN)を、差分の勾配の大きさで割った値(縁までの距離の 1 次の近似、
498/// [瞳の半径の単位])と、その勾配の大きさ。勾配を求められない点(隣に値がない)は、符号だけを残して半間隔
499/// (勾配は NaN)
500fn distance_by_gradient(g: usize, m: &[f64]) -> Vec<(f64, f64)> {
501    let h = 2.0 / (g - 1) as f64;
502    let at = |i: i64, j: i64| -> Option<f64> {
503        if i < 0 || j < 0 || i >= g as i64 || j >= g as i64 {
504            return None;
505        }
506        let v = m[j as usize * g + i as usize];
507        v.is_finite().then_some(v)
508    };
509    let diff = |c: f64, lo: Option<f64>, hi: Option<f64>| match (lo, hi) {
510        (Some(a), Some(b)) => Some((b - a) / (2.0 * h)),
511        (None, Some(b)) => Some((b - c) / h),
512        (Some(a), None) => Some((c - a) / h),
513        (None, None) => None,
514    };
515    (0..g * g)
516        .map(|q| {
517            let c = m[q];
518            if !c.is_finite() {
519                return (c, f64::NAN);
520            }
521            let (i, j) = ((q % g) as i64, (q / g) as i64);
522            let gx = diff(c, at(i - 1, j), at(i + 1, j));
523            let gy = diff(c, at(i, j - 1), at(i, j + 1));
524            let n = gx.unwrap_or(0.0).hypot(gy.unwrap_or(0.0));
525            if (gx.is_none() && gy.is_none()) || !(n > 0.0) {
526                (0.5 * h * c.signum(), f64::NAN)
527            } else {
528                (c / n, n)
529            }
530        })
531        .collect()
532}
533
534fn trace_jones_in(
535    sys: &System,
536    field: FieldSel,
537    g: usize,
538    coat: &Coatings,
539    surf: Option<usize>,
540    with_edge: bool,
541) -> Result<JonesGrid> {
542    if let Some(s) = surf {
543        if s == 0 || s > sys.image() {
544            invalid!("surface {s} is out of range (1 to {})", sys.image());
545        }
546    }
547    if g < 2 {
548        invalid!("the pupil grid must be 2 or more");
549    }
550    if sys.primary != 0 {
551        invalid!("the primary wavelength must be the center wavelength (wavelength 1)");
552    }
553    let nw = sys.wavelengths.len();
554    let mut r = RayGrid::new(g, nw);
555    let pg = PupilGrid::new(g);
556    let (idx, pxs, pys) = if with_edge { pg.rays_rim() } else { pg.rays() };
557    // 縁を求めるときは、けられた光線も値を残す(追跡はけられても続く)
558    let pass = |t: &lensbench_core::system::Trace, m: usize| {
559        if with_edge {
560            t.rays[m].status.is_ok()
561        } else {
562            t.ok(m)
563        }
564    };
565    let mut good = vec![false; g * g];
566    for &q in &idx {
567        good[q] = true;
568    }
569    let phase = has_phase_terms(sys);
570    // 中心波長の検出面の着地点の z(曲がった検出面でも 3 次元で直すため)
571    let mut zs0 = vec![0.0; g * g];
572    let mut landing = vec![vec![0.0; g * g]; nw];
573    let mut t0 = None;
574    // 中心波長は偏光追跡 1 回で光線と場を得る(同じ光線を通常の追跡でもう一度追わない)。指定面の交点も一緒に
575    // 記録する。物体・ケラレ係数は try_trace と同じ
576    let (hx, hy) = sys.field_sel_norm(field, 0)?;
577    let launch = Launch::Pupil {
578        spec: sys.object_spec(hx, hy)?,
579        signed: false,
580        px: &pxs,
581        py: &pys,
582        vig: Some(sys.vig_factors(hx, hy)?),
583        hxy: Some((hx, hy)),
584    };
585    let surfs = surf.map(|s| [s]);
586    let rec = surfs.as_ref().map_or(RecSel::Off, |s| RecSel::Surfs(s));
587    let pols = [[C64::new(1.0, 0.0), czero()], [czero(), C64::new(1.0, 0.0)]];
588    let pt = sys.trace_pol_launch(&launch, 0, PolIn::new(&pols, coat).no_phase(), rec)?;
589    let (mut center, pol_e) = (Some(pt.trace), pt.e);
590    for w in 0..nw {
591        let t = match center.take() {
592            Some(mut t) => {
593                t.hx_hy = (hx, hy);
594                t
595            }
596            None => sys.try_trace(field, &pxs, &pys, Some(w), None, false)?,
597        };
598        let chief = if phase {
599            let c = sys.try_trace(field, &[0.0], &[0.0], Some(w), None, false)?;
600            if !c.traced(0) {
601                invalid!("the chief ray doesn't reach the sensor");
602            }
603            Some((c.opl_os[0], c.opl_os[0] + c.rays[0].lens_opd))
604        } else {
605            None
606        };
607        // 像空間の屈折率(向きの符号は使わない)
608        let nimg = sys.image_index(w).abs();
609        for (m, &q) in idx.iter().enumerate() {
610            if !pass(&t, m) {
611                good[q] = false;
612                continue;
613            }
614            let lraw = t.opl_os[m];
615            let mut l = match chief {
616                Some((craw, cpath)) => craw + (lraw + t.rays[m].lens_opd - cpath),
617                None => lraw,
618            };
619            if w == 0 {
620                r.xs[q] = t.rays[m].xyz[0];
621                r.ys[q] = t.rays[m].xyz[1];
622                zs0[q] = t.rays[m].xyz[2];
623            } else if good[q] {
624                // 波長 w の光線は中心波長の着地点 x0 とは別の点 x_w に着く(倍率の色収差)。格子の値は中心波長の
625                // 着地点の値なので、波面を 1 次で x0 へ移す: L_w(x0) = L_w(x_w) + n s_w·(x0 − x_w)(アイコナール)
626                let (p, d) = (t.rays[m].xyz, t.rays[m].lmn);
627                let dl = nimg
628                    * (d[0] * (r.xs[q] - p[0]) + d[1] * (r.ys[q] - p[1]) + d[2] * (zs0[q] - p[2]));
629                landing[w][q] = dl;
630                l += dl;
631            }
632            r.l[w][q] = l;
633        }
634        if w == 0 {
635            t0 = Some(t);
636        }
637    }
638    let t0 = t0.expect("first sample set above");
639    // ファイバ端の方向余弦
640    if !sys.infinite() {
641        let of = sys.object_frame();
642        for (m, &q) in idx.iter().enumerate() {
643            // 物体の座標系へ(回転の列が軸)
644            let d = lensbench_core::math::mtv(&of.r, t0.k0[m]);
645            r.sx[q] = d[0];
646            r.sy[q] = d[1];
647        }
648    } else {
649        let probe = [(0.0, 0.0), (0.7, 0.0), (-0.7, 0.0), (0.0, 0.7), (0.0, -0.7)];
650        let ppx: Vec<f64> = probe.iter().map(|p| p.0).collect();
651        let ppy: Vec<f64> = probe.iter().map(|p| p.1).collect();
652        let ima = sys.image();
653        let tp = sys.try_trace(field, &ppx, &ppy, Some(0), None, RecSel::All)?;
654        let mut fs = None;
655        for k in 1..ima {
656            let Some(rec) = tp.rec_at(k) else { continue };
657            let pts: Vec<V3> = rec.xyz.clone();
658            if pts.iter().any(|p| !p[0].is_finite()) {
659                continue;
660            }
661            if pts
662                .iter()
663                .all(|p| (p[0] - pts[0][0]).abs() < 1e-6 && (p[1] - pts[0][1]).abs() < 1e-6)
664            {
665                fs = Some(k);
666                break;
667            }
668        }
669        match fs {
670            None => {
671                r.mode_fallback = true;
672                for (m, &q) in idx.iter().enumerate() {
673                    r.sx[q] = 1e-4 * pxs[m];
674                    r.sy[q] = 1e-4 * pys[m];
675                }
676            }
677            Some(fsurf) => {
678                let ta =
679                    sys.try_trace(field, &pxs, &pys, Some(0), None, RecSel::Surfs(&[fsurf]))?;
680                let rec = ta.rec_at(fsurf).expect("record");
681                for (m, &q) in idx.iter().enumerate() {
682                    let d = rec.lmn[m];
683                    if !d[0].is_finite() {
684                        good[q] = false;
685                        continue;
686                    }
687                    r.sx[q] = d[0];
688                    r.sy[q] = d[1];
689                }
690            }
691        }
692    }
693    // 偏光: 検出面の局所 x・y の場。伝搬の位相を除いた振幅(OpticStudio の E = J exp(−i k L_raw)、約束は
694    // [`lensbench_core::phase`] の exp(−i k L))
695    let mut jones = vec![[[czero(); 2]; 2]; g * g];
696    for (m, &q) in idx.iter().enumerate() {
697        if !pass(&t0, m) || !good[q] {
698            good[q] = false;
699            continue;
700        }
701        for (b, pol) in pol_e[m].iter().enumerate().take(2) {
702            jones[q][0][b] = pol[0];
703            jones[q][1][b] = pol[1];
704        }
705    }
706    let (mut xf, mut yf) = (Vec::new(), Vec::new());
707    if let Some(s) = surf {
708        xf = vec![f64::NAN; g * g];
709        yf = vec![f64::NAN; g * g];
710        let tr = &t0;
711        if let Some(rec) = tr.rec_at(s) {
712            for (m, &q) in idx.iter().enumerate() {
713                if good[q] && pass(tr, m) && rec.xyz[m][0].is_finite() {
714                    xf[q] = rec.xyz[m][0];
715                    yf[q] = rec.xyz[m][1];
716                }
717            }
718        }
719    }
720    let (mut edge_surf, mut edge_dm) = (Vec::new(), Vec::new());
721    let edge = if with_edge {
722        // 中心波長で光線をけた面(けられた最初の面)の開口ごとの縁までの距離
723        let mut vs: Vec<usize> = t0.rays.iter().map(|r| r.vig).filter(|&v| v > 0).collect();
724        vs.sort_unstable();
725        vs.dedup();
726        edge_surf = vec![0usize; g * g];
727        edge_dm = vec![[0.0; 2]; g * g];
728        let mut edge: Vec<f64> = (0..g * g)
729            .map(|q| {
730                if good[q] {
731                    let [x, y] = pg.coords(q);
732                    // 2 乗の和の平方根(中か [`PupilGrid::inside`] と同じ境: 中の光線は 0 以上)
733                    1.0 - (x * x + y * y).sqrt()
734                } else {
735                    f64::NAN
736                }
737            })
738            .collect();
739        if !vs.is_empty() {
740            let ta = sys.try_trace(field, &pxs, &pys, Some(0), None, RecSel::Surfs(&vs))?;
741            for &k in &vs {
742                let ap = sys.surfaces[k].ap;
743                let rec = ta.rec_at(k).expect("record");
744                let mut m = vec![f64::NAN; g * g];
745                let mut at = vec![[f64::NAN; 2]; g * g];
746                for (i, &q) in idx.iter().enumerate() {
747                    let p = rec.xyz[i];
748                    if good[q] && p[0].is_finite() {
749                        m[q] = lensbench_core::trace::aperture_margin(ap, p[0], p[1]);
750                        at[q] = [p[0], p[1]];
751                    }
752                }
753                for (q, (d, n)) in distance_by_gradient(g, &m).into_iter().enumerate() {
754                    if !edge[q].is_finite() {
755                        continue;
756                    }
757                    let d = if d.is_nan() { f64::NEG_INFINITY } else { d };
758                    if d < edge[q] {
759                        edge[q] = d;
760                        edge_surf[q] = k;
761                        // 距離の、開口の面の交点での勾配(中心差分)/ 瞳での勾配の大きさ
762                        let [x, y] = at[q];
763                        let dl = 1e-6 * x.abs().max(y.abs()).max(1.0);
764                        let mg = |a: f64, b: f64| lensbench_core::trace::aperture_margin(ap, a, b);
765                        edge_dm[q] = if n.is_finite() {
766                            [
767                                (mg(x + dl, y) - mg(x - dl, y)) / (2.0 * dl * n),
768                                (mg(x, y + dl) - mg(x, y - dl)) / (2.0 * dl * n),
769                            ]
770                        } else {
771                            [0.0; 2]
772                        };
773                    }
774                }
775            }
776        }
777        // 単位円の外の光線は距離が 0 に丸まっても(r = 1 の格子点)使う光線にしない
778        for (q, (o, e)) in good.iter_mut().zip(&edge).enumerate() {
779            *o = *o && *e >= 0.0 && pg.inside(q);
780        }
781        edge
782    } else {
783        Vec::new()
784    };
785    r.ok = good;
786    Ok(JonesGrid {
787        rays: r,
788        jones,
789        xf,
790        yf,
791        landing,
792        edge,
793        edge_surf,
794        edge_dm,
795    })
796}