Skip to main content

lensbench_core/
seidel.rs

1//! ザイデル収差係数(3 次の収差、面ごと)と、実光線の歪曲・縦収差
2
3use crate::error::Result;
4use crate::invalid;
5use crate::shape::{Base, Shape};
6use crate::system::{FieldSel, FieldType, System};
7
8/// 面ごとのザイデル和 S_I〜S_V [レンズ単位](Welford の定義。近軸周辺光線と、最大の視野へ合わせた近軸主光線から)。
9/// `surf[j]` は面 j の寄与(物体面・像面・無視する面・座標ブレークは 0)
10#[derive(Debug, Clone, PartialEq)]
11pub struct Seidel {
12    pub surf: Vec<[f64; 5]>,
13    /// 波長 [レンズ単位](波の数に直すのに使う)
14    pub wavelength: f64,
15}
16
17impl Seidel {
18    /// 面 j の寄与(0 なら全部の面の和)
19    pub fn at(&self, j: usize) -> [f64; 5] {
20        if j == 0 {
21            self.surf.iter().fold([0.0; 5], |mut a, v| {
22                for i in 0..5 {
23                    a[i] += v[i];
24                }
25                a
26            })
27        } else {
28            self.surf.get(j).copied().unwrap_or([0.0; 5])
29        }
30    }
31
32    /// 面 j の寄与を波面収差の係数 [波] で: W040 = S_I/8、W131 = S_II/2、W222 = S_III/2、W220 = S_IV/4、W311 = S_V/2
33    /// (OpticStudio の SPHA・COMA・ASTI・FCUR・DIST と同じ。26.1 で実測)
34    pub fn waves(&self, j: usize) -> [f64; 5] {
35        let s = self.at(j);
36        let l = self.wavelength;
37        [
38            s[0] / (8.0 * l),
39            s[1] / (2.0 * l),
40            s[2] / (2.0 * l),
41            s[3] / (4.0 * l),
42            s[4] / (2.0 * l),
43        ]
44    }
45}
46
47/// 近軸主光線(物体空間の傾き 1 か物体の高さ 1)を最大の視野に合わせる倍率
48pub fn chief_scale(s: &System) -> f64 {
49    let hmax = s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max);
50    match s.field_type {
51        FieldType::Angle => hmax.to_radians().tan(),
52        FieldType::ObjH => hmax,
53        // 像高の視野は近軸像高から
54        _ => {
55            let p = s.paraxial();
56            let pimh = crate::report::system_data(s).pimh;
57            (pimh / p.chief_parimage_per_unit).abs()
58        }
59    }
60}
61
62/// 面の形の r⁴ の係数のうち、近軸の曲率の球からずれる分(二次曲面・偶数次非球面だけ)
63fn quartic_excess(sh: Shape, c0: f64) -> Option<f64> {
64    let (c, k, a4) = match sh {
65        Shape::Plane => return Some(0.0),
66        Shape::Conic { c, k } => (c, k, 0.0),
67        Shape::EvenAsphere(Base { c, k, a }) => (c, k, a.get(1).copied().unwrap_or(0.0)),
68        _ => return None,
69    };
70    Some((1.0 + k) * c.powi(3) / 8.0 + a4 - c0.powi(3) / 8.0)
71}
72
73/// 波長 w のザイデル和。ミラー・二次曲面と偶数次非球面でない面のある系は誤り
74pub fn seidel(s: &System, w: usize) -> Result<Seidel> {
75    if !s.symmetric() {
76        invalid!("Seidel coefficients need a rotationally symmetric system");
77    }
78    let sf = &s.surfaces;
79    let img = s.image();
80    let p = s.paraxial();
81    let k = chief_scale(s);
82    let (ym, um) = s.ptrace(p.marginal.0[1], p.marginal.1[0], w, None);
83    let (yc, uc) = s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None);
84    // ラグランジュ不変量(物体空間の n (ū y − u ȳ))。OpticStudio 26.1 は絞りの n ū y(LINV)を使い、主光線を主波長の
85    // 入射瞳の中心に通すので、主波長でない波長では絞りの中心を外れて不変量と少し違う(FCUR で 0.12%、DIST で最大 0.9%)
86    let h = s.n(0)[w] * (uc[0] * ym[1] - um[0] * yc[1]);
87    let mut out = vec![[0.0; 5]; sf.len()];
88    for j in 1..img {
89        let f = &sf[j];
90        if f.ignore || f.is_coord_break() {
91            continue;
92        }
93        if !matches!(
94            f.action(),
95            crate::action::Action::Refract | crate::action::Action::Reflect { .. }
96        ) {
97            invalid!("Seidel coefficients need refracting or reflecting surfaces (surface {j})");
98        }
99        if f.is_mirror() {
100            invalid!(
101                "Seidel coefficients of systems with mirrors are not supported yet (surface {j})"
102            );
103        }
104        let sh = f.shape();
105        let c = sh.paraxial_curv();
106        let Some(d4) = quartic_excess(sh, c) else {
107            invalid!("Seidel coefficients need standard or even asphere surfaces (surface {j})");
108        };
109        let (n1, n2) = (s.index_before(j, w), s.n(j)[w]);
110        let a = n1 * (um[j - 1] + ym[j] * c);
111        let ab = n1 * (uc[j - 1] + yc[j] * c);
112        let y = ym[j];
113        let du = um[j] / n2 - um[j - 1] / n1;
114        let mut v = [
115            -a * a * y * du,
116            -a * ab * y * du,
117            -ab * ab * y * du,
118            -h * h * c * (1.0 / n2 - 1.0 / n1),
119            0.0,
120        ];
121        // S_V = Ā (−² y Δ(1/n²) + ȳ c Δ(1/n) (Ā y + H))。Ā/A · (S_III + S_IV) を割り算なしに書いた形で、
122        // 周辺光線が面に垂直に入る(A = 0、同心の面)ときも平面でも有限
123        v[4] = ab
124            * (-ab * ab * y * (1.0 / (n2 * n2) - 1.0 / (n1 * n1))
125                + yc[j] * c * (1.0 / n2 - 1.0 / n1) * (ab * y + h));
126        // 非球面の分: ΔS_I = 8 Δ₄ (n′ − n) y⁴、ΔS_II〜ΔS_V は ȳ/y の 1〜3 乗を掛ける
127        if d4 != 0.0 {
128            let ds = 8.0 * d4 * (n2 - n1) * y.powi(4);
129            let r = if y != 0.0 { yc[j] / y } else { 0.0 };
130            v[0] += ds;
131            v[1] += ds * r;
132            v[2] += ds * r * r;
133            v[4] += ds * r * r * r;
134        }
135        if v.iter().any(|x| !x.is_finite()) {
136            invalid!("Seidel coefficients of surface {j} are not finite");
137        }
138        out[j] = v;
139    }
140    Ok(Seidel {
141        surf: out,
142        wavelength: s.wave(w).mm(),
143    })
144}
145
146/// 面ごとの 1 次の色収差の和 C_L(軸上色)・C_T(倍率色)[レンズ単位](Welford の C_I = A y Δ(δn/n)、C_II = Ā y Δ(δn/n)。
147/// A・Ā・y は波長 w の近軸周辺光線と最大の視野へ合わせた近軸主光線([`seidel`] と同じ)、δn は波長 long の屈折率 − short の屈折率。
148/// 符号は OpticStudio の Seidel Coefficients の CLA・CTR に合わせた(26.1 で実測、Welford の δn = n_F − n_C と逆)。
149/// `[j]` は面 j の寄与(物体面・像面・無視する面・座標ブレークは 0)
150pub fn chromatic(s: &System, w: usize, short: usize, long: usize) -> Result<Vec<[f64; 2]>> {
151    if !s.symmetric() {
152        invalid!("Seidel coefficients need a rotationally symmetric system");
153    }
154    let sf = &s.surfaces;
155    let img = s.image();
156    let p = s.paraxial();
157    let k = chief_scale(s);
158    let (ym, um) = s.ptrace(p.marginal.0[1], p.marginal.1[0], w, None);
159    let (yc, uc) = s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None);
160    let mut out = vec![[0.0; 2]; sf.len()];
161    for j in 1..img {
162        let f = &sf[j];
163        if f.ignore || f.is_coord_break() {
164            continue;
165        }
166        if f.is_mirror() {
167            invalid!(
168                "Seidel coefficients of systems with mirrors are not supported yet (surface {j})"
169            );
170        }
171        let c = f.shape().paraxial_curv();
172        let (n1, n2) = (s.index_before(j, w), s.n(j)[w]);
173        let dn1 = s.index_before(j, long) - s.index_before(j, short);
174        let dn2 = s.n(j)[long] - s.n(j)[short];
175        let a = n1 * (um[j - 1] + ym[j] * c);
176        let ab = n1 * (uc[j - 1] + yc[j] * c);
177        let d = dn2 / n2 - dn1 / n1;
178        let v = [a * ym[j] * d, ab * ym[j] * d];
179        if v.iter().any(|x| !x.is_finite()) {
180            invalid!("Seidel coefficients of surface {j} are not finite");
181        }
182        out[j] = v;
183    }
184    Ok(out)
185}
186
187/// 軸上の光線が光軸を横切る点の、像面の頂点からの距離 [レンズ単位](波長 w)。zone 0 は近軸周辺光線(主波長の入射瞳の縁を
188/// 通す)、zone > 0 は正規化瞳座標 (0, zone) の実光線。OpticStudio の LONA(26.1 で実測)
189pub fn longitudinal(s: &System, w: usize, zone: f64) -> Result<f64> {
190    let img = s.image();
191    let v = if zone == 0.0 {
192        let p = s.paraxial();
193        let (ym, um) = s.ptrace(p.marginal.0[1], p.marginal.1[0], w, None);
194        -ym[img] / um[img - 1]
195    } else {
196        let t = s.try_trace(
197            FieldSel::Norm(0.0, 0.0),
198            &[0.0],
199            &[zone],
200            Some(w),
201            None,
202            false,
203        )?;
204        let r = &t.rays[0];
205        if let Some(j) = r.status.surf() {
206            invalid!("the ray of zone {zone} stopped (surface {j})");
207        }
208        // 像面の局所座標で、交点から軸と交わる点まで(曲面の像面では交点の z = 矢高を足し、頂点から測る)
209        r.xyz[2] - r.xyz[1] * r.lmn[2] / r.lmn[1]
210    };
211    if !v.is_finite() {
212        invalid!("the longitudinal aberration of zone {zone} is not finite");
213    }
214    Ok(v)
215}
216
217/// 最大の視野へ合わせた近軸主光線の像面での高さ [レンズ単位](波長 w。主光線は主波長の入射瞳の中心を通す)。
218/// 2 つの波長の差が OpticStudio の LACL(26.1 で実測)
219pub fn chief_height(s: &System, w: usize) -> f64 {
220    let p = s.paraxial();
221    let k = chief_scale(s);
222    s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None).0[s.image()]
223}
224
225/// 視野 (hx, hy) の、歪曲の線形の予測に使う座標 t(角度の視野は各向きの角の tan、ほかは正規化視野 × 正規化の値)
226fn field_t(s: &System, hx: f64, hy: f64) -> Result<[f64; 2]> {
227    let (nx, ny) = s.field_norm_values();
228    if s.field_type == FieldType::Angle {
229        let (ax, ay) = ((hx * nx).to_radians(), (hy * ny).to_radians());
230        if ax.abs() >= std::f64::consts::FRAC_PI_2 || ay.abs() >= std::f64::consts::FRAC_PI_2 {
231            invalid!("the distortion of field ({hx}, {hy}) needs field angles below 90 degrees");
232        }
233        return Ok([ax.tan(), ay.tan()]);
234    }
235    Ok([hx * nx, hy * ny])
236}
237
238/// [`field_t`] の逆
239fn field_of_t(s: &System, t: [f64; 2]) -> (f64, f64) {
240    let (nx, ny) = s.field_norm_values();
241    if s.field_type == FieldType::Angle {
242        return (t[0].atan().to_degrees() / nx, t[1].atan().to_degrees() / ny);
243    }
244    (t[0] / nx, t[1] / ny)
245}
246
247/// 視野 (hx, hy) の主光線の像面での (x, y)(波長 w)。アフォーカル像空間の系では向きの tan (l/n, m/n)(OpticStudio の
248/// アフォーカルの歪曲・グリッド歪曲の Real の値。2026 R1.01 で実測)
249fn chief_xy(s: &System, h: (f64, f64), w: usize) -> Result<[f64; 2]> {
250    let t = s.try_trace(
251        FieldSel::Norm(h.0, h.1),
252        &[0.0],
253        &[0.0],
254        Some(w),
255        None,
256        false,
257    )?;
258    let r = &t.rays[0];
259    if let Some(j) = r.status.surf() {
260        invalid!(
261            "the chief ray of field ({}, {}) stopped (surface {j})",
262            h.0,
263            h.1
264        );
265    }
266    if s.afocal {
267        return Ok([r.lmn[0] / r.lmn[2], r.lmn[1] / r.lmn[2]]);
268    }
269    Ok([r.xyz[0], r.xyz[1]])
270}
271
272/// 歪曲の線形の予測の基準: 基準の視野の主光線の像面の点 p、その視野の t([`field_t`])、そこでの ∂(x, y)/∂t の J
273/// (グリッド歪曲の A・B・C・D = J[0][0]・J[0][1]・J[1][0]・J[1][1])
274#[derive(Debug, Clone, Copy, PartialEq)]
275pub struct DistRef {
276    pub p: [f64; 2],
277    pub t: [f64; 2],
278    pub j: [[f64; 2]; 2],
279}
280
281/// 歪曲の向き(OpticStudio の DISA の Data 0・1・2)
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
283pub enum DistComp {
284    /// 動径(ずれの長さ、符号は予測の変位との内積の符号)
285    #[default]
286    Radial,
287    X,
288    Y,
289}
290
291/// 基準の視野(None は軸上)の主光線の点と t(J は単位行列)
292pub fn distortion_point(s: &System, w: usize, reference: Option<(f64, f64)>) -> Result<DistRef> {
293    let (p, t) = match reference {
294        None => ([0.0, 0.0], [0.0, 0.0]),
295        Some(r) => (chief_xy(s, r, w)?, field_t(s, r.0, r.1)?),
296    };
297    Ok(DistRef {
298        p,
299        t,
300        j: [[1.0, 0.0], [0.0, 1.0]],
301    })
302}
303
304/// 基準の視野(None は軸上)での [`DistRef`]。軸上の J は近軸主光線の倍率(回転対称な系だけ。アフォーカル像空間では
305/// 像空間の傾きの倍率)、ほかは主光線の点を t で中心差分した値
306pub fn distortion_ref(s: &System, w: usize, reference: Option<(f64, f64)>) -> Result<DistRef> {
307    let mut r = distortion_point(s, w, reference)?;
308    r.j = match reference {
309        None => {
310            if !s.symmetric() {
311                invalid!("the distortion against the axis needs a rotationally symmetric system");
312            }
313            // 近軸主光線の像面の高さは t に比例する(最大の半径の視野の t で割る)
314            let img = s.image();
315            let p = s.paraxial();
316            let k = chief_scale(s);
317            let (yc, uc) = s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None);
318            // t の大きさで最大の半径の視野(角度の視野は k が tan、ほかは視野の座標の最大の半径)
319            let tm = if s.field_type == FieldType::Angle {
320                k
321            } else {
322                s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max)
323            };
324            // アフォーカル像空間では像空間の近軸主光線の傾き(向きの tan の倍率)
325            let m = if s.afocal { uc[img - 1] } else { yc[img] } / tm;
326            [[m, 0.0], [0.0, m]]
327        }
328        Some(_) => {
329            let tm = field_t(s, 1.0, 0.0)?[0]
330                .abs()
331                .max(field_t(s, 0.0, 1.0)?[1].abs());
332            if tm == 0.0 {
333                invalid!("the distortion needs a field other than the axis");
334            }
335            let d = 1e-5 * tm;
336            let mut j = [[0.0; 2]; 2];
337            for k in 0..2 {
338                let (mut a, mut b) = (r.t, r.t);
339                a[k] -= d;
340                b[k] += d;
341                let (pa, pb) = (
342                    chief_xy(s, field_of_t(s, a), w)?,
343                    chief_xy(s, field_of_t(s, b), w)?,
344                );
345                for i in 0..2 {
346                    j[i][k] = (pb[i] - pa[i]) / (2.0 * d);
347                }
348            }
349            j
350        }
351    };
352    if r.j.iter().flatten().any(|v| !v.is_finite()) {
353        invalid!("the distortion is not finite");
354    }
355    Ok(r)
356}
357
358/// グリッド歪曲の格子の点 (u, v)(-1〜1)の正規化視野。格子は最大の視野(各視野の (x, y) の長さの最大)の円に内接する正方形で、
359/// 角度の視野は tan θ の、高さの視野は高さの等間隔(OpticStudio の Grid Distortion。26.1 で実測)
360pub fn grid_field(s: &System, u: f64, v: f64) -> Result<(f64, f64)> {
361    let r = s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max);
362    if r == 0.0 {
363        invalid!("the grid distortion needs a field off the axis");
364    }
365    let a = if s.field_type == FieldType::Angle {
366        if r >= 90.0 {
367            invalid!("the grid distortion needs field angles below 90 degrees");
368        }
369        r.to_radians().tan()
370    } else {
371        r
372    } / std::f64::consts::SQRT_2;
373    Ok(field_of_t(s, [a * u, a * v]))
374}
375
376/// 視野 h の主光線の像面の点 p と、基準 r からの線形の予測 p_r + J (t − t_r) の差 d を、長さと予測の変位
377/// Δ = J (t − t_r) に対する % で返す。動径は |d| と |d| / |Δ|、x・y はその成分 |d_x| と |d_x| / |Δ_x|(Δ の成分が 0 なら
378/// % は 0)。符号は実際の変位 e = p − p_r が Δ より長い(成分は絶対値が大きい)とき正。OpticStudio の DISG・DISA
379/// (26.1 で実測、e が Δ と逆の向きのとき・アフォーカル像空間の倒立の系は 2026 R1.01 で実測)
380pub fn distortion_against(
381    s: &System,
382    w: usize,
383    h: (f64, f64),
384    r: &DistRef,
385    comp: DistComp,
386) -> Result<(f64, f64)> {
387    let t = field_t(s, h.0, h.1)?;
388    let p = chief_xy(s, h, w)?;
389    let (j, dt) = (r.j, [t[0] - r.t[0], t[1] - r.t[1]]);
390    let del = [
391        j[0][0] * dt[0] + j[0][1] * dt[1],
392        j[1][0] * dt[0] + j[1][1] * dt[1],
393    ];
394    let e = [p[0] - r.p[0], p[1] - r.p[1]];
395    let d = [e[0] - del[0], e[1] - del[1]];
396    // 符号は実際の変位 e が予測の変位 Δ より長いとき正(糸巻き)
397    let (v, n) = match comp {
398        DistComp::Radial => (
399            d[0].hypot(d[1])
400                .copysign(e[0].hypot(e[1]) - del[0].hypot(del[1])),
401            del[0].hypot(del[1]),
402        ),
403        DistComp::X => (d[0].abs().copysign(e[0].abs() - del[0].abs()), del[0].abs()),
404        DistComp::Y => (d[1].abs().copysign(e[1].abs() - del[1].abs()), del[1].abs()),
405    };
406    let pct = if n != 0.0 { 100.0 * v / n } else { 0.0 };
407    if !v.is_finite() || !pct.is_finite() {
408        invalid!("the distortion is not finite");
409    }
410    Ok((v, pct))
411}
412
413/// 視野 h の主光線の像面の点 p と、基準 r からの線形の予測 p_r + J (t − t_r)(グリッド歪曲の実際の点と理想の点)
414pub fn distortion_points(
415    s: &System,
416    w: usize,
417    h: (f64, f64),
418    r: &DistRef,
419) -> Result<([f64; 2], [f64; 2])> {
420    let t = field_t(s, h.0, h.1)?;
421    let p = chief_xy(s, h, w)?;
422    let (j, dt) = (r.j, [t[0] - r.t[0], t[1] - r.t[1]]);
423    let q = [
424        r.p[0] + j[0][0] * dt[0] + j[0][1] * dt[1],
425        r.p[1] + j[1][0] * dt[0] + j[1][1] * dt[1],
426    ];
427    Ok((p, q))
428}
429
430/// 一般の歪曲(OpticStudio の DISG): 基準の視野 reference(None は軸上)からの [`distortion_against`] の動径。
431/// OpticStudio 26.1 で実測(Double Gauss 28 の軸上・視野 2 の基準、斜めの視野で 1e-10)
432pub fn distortion_at(
433    s: &System,
434    w: usize,
435    h: (f64, f64),
436    reference: Option<(f64, f64)>,
437) -> Result<(f64, f64)> {
438    let r = distortion_ref(s, w, reference)?;
439    distortion_against(s, w, h, &r, DistComp::Radial)
440}
441
442/// 軸上から視野 h までの線の上(100 等分の点)の、軸上を基準にした [`distortion_at`] の絶対値の最大(absolute なら長さ、
443/// でなければ %)。OpticStudio の DIMX
444pub fn distortion_max(s: &System, w: usize, h: (f64, f64), absolute: bool) -> Result<f64> {
445    let r = distortion_ref(s, w, None)?;
446    let mut m: f64 = 0.0;
447    for k in 1..=100 {
448        let f = k as f64 / 100.0;
449        let (v, pct) = distortion_against(s, w, (h.0 * f, h.1 * f), &r, DistComp::Radial)?;
450        m = m.max(if absolute { v.abs() } else { pct.abs() });
451    }
452    Ok(m)
453}
454
455/// 校正した f-θ 歪曲(OpticStudio の DISC): y の向きの視野を 100 等分した角 θ の主光線の高さ y に、原点を通る直線 y = cθ を
456/// 最小二乗で当て、ずれ |y − cθ| の最大と、|y − cθ| / |cθ| の最大 [%] を返す(角度の視野だけ。OpticStudio 26.1 で実測、
457/// Double Gauss 28 で 1e-13)
458pub fn ftheta_distortion(s: &System, w: usize) -> Result<(f64, f64)> {
459    if s.field_type != FieldType::Angle {
460        invalid!("the f-theta distortion needs angle fields");
461    }
462    let (_, ny) = s.field_norm_values();
463    let mut pts = Vec::with_capacity(101);
464    for k in 0..=100 {
465        let h = k as f64 / 100.0;
466        pts.push(((h * ny).to_radians(), chief_xy(s, (0.0, h), w)?[1]));
467    }
468    let c =
469        pts.iter().map(|(a, y)| a * y).sum::<f64>() / pts.iter().map(|(a, _)| a * a).sum::<f64>();
470    let (mut da, mut dp): (f64, f64) = (0.0, 0.0);
471    for &(a, y) in &pts {
472        let d = (y - c * a).abs();
473        da = da.max(d);
474        if a != 0.0 {
475            dp = dp.max(100.0 * d / (c * a).abs());
476        }
477    }
478    if !da.is_finite() || !dp.is_finite() {
479        invalid!("the f-theta distortion is not finite");
480    }
481    Ok((da, dp))
482}