Skip to main content

lensbench_core/coating/
interpolate.rs

1//! 補間の道具: 波長の区間、有理補間、鏡の分岐点、線形補間
2
3use super::*;
4
5/// wl をはさむ折れ目の間の点の範囲 [s, e)(範囲外や点が足りなければ None)
6pub(in crate::coating) fn wave_segment(
7    wls: &[f64],
8    wl: f64,
9    kinks: &[f64],
10) -> Option<(usize, usize)> {
11    const EPS: f64 = 1e-9;
12    let n = wls.len();
13    if n == 0 || !(wls[0] - EPS <= wl && wl <= wls[n - 1] + EPS) {
14        return None;
15    }
16    // wl をはさむ折れ目の間 [lo, hi] の点だけを使う(折れ目の上の点は両側で使う)
17    let lo = kinks
18        .iter()
19        .copied()
20        .filter(|&k| k <= wl + EPS)
21        .fold(f64::NEG_INFINITY, f64::max);
22    let hi = kinks
23        .iter()
24        .copied()
25        .filter(|&k| k > wl + EPS)
26        .fold(f64::INFINITY, f64::min);
27    let s = wls.partition_point(|&w| w < lo - EPS);
28    let e = wls.partition_point(|&w| w <= hi + EPS);
29    let n = e - s;
30    // 折れ目の間に点が 1 つ以下だと補間できない(呼ぶ側が範囲の外と区別して知らせる)
31    if n == 0 || (n < 2 && n < wls.len()) {
32        return None;
33    }
34    Some((s, e))
35}
36
37/// 波長 wl での値: 近い p 点(少なければ全点)を 1/λ の多項式で補間する(範囲外は None)。
38/// 重みは点 i から p 点(区間の端では内側へ寄せる)
39pub(in crate::coating) fn wave_weights(
40    wls: &[f64],
41    wl: f64,
42    kinks: &[f64],
43    p: usize,
44) -> Option<(usize, Vec<f64>)> {
45    let (s, e) = wave_segment(wls, wl, kinks)?;
46    let seg = &wls[s..e];
47    let n = seg.len();
48    let m = n.min(p);
49    let i = seg
50        .partition_point(|&w| w < wl)
51        .saturating_sub(m / 2)
52        .min(n - m);
53    let x: Vec<f64> = seg[i..i + m].iter().map(|w| 1.0 / w).collect();
54    Some((s + i, lagrange_weights(&x, 1.0 / wl)))
55}
56
57/// 点 x を通る多項式の q での値を、点の値の重み付きの和にする重み(ラグランジュ)
58pub(in crate::coating) fn lagrange_weights(x: &[f64], q: f64) -> Vec<f64> {
59    let m = x.len();
60    (0..m)
61        .map(|a| {
62            (0..m)
63                .filter(|&b| b != a)
64                .map(|b| (q - x[b]) / (x[a] - x[b]))
65                .product()
66        })
67        .collect()
68}
69
70/// 昇順の点 xs[..n] のうち q に近い p 点の始まり(端では内側へ寄せる)と、その多項式の重み
71pub(in crate::coating) fn local_weights(
72    xs: &[f64],
73    n: usize,
74    p: usize,
75    q: f64,
76) -> (usize, Vec<f64>) {
77    let m = n.min(p);
78    let i = xs[..n]
79        .partition_point(|&x| x < q)
80        .saturating_sub(m / 2)
81        .min(n - m);
82    (i, lagrange_weights(&xs[i..i + m], q))
83}
84
85/// 鏡の 1 つの波長の分岐点([`mirror_branch`])
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub(crate) struct MirrorBranch {
88    /// 分岐点の β²
89    pub(in crate::coating) xb: f64,
90    /// 全反射が最後まで続く最初の点。分岐点は点 k − 1 と k の間にある
91    pub(in crate::coating) k: usize,
92    /// 分岐点が測った点の上にある([`MIRROR_BRANCH_SNAP`] で寄せた)
93    pub(in crate::coating) on_grid: bool,
94}
95
96/// 鏡の分岐点として扱う、全反射の手前の 2 点での |r| の 1 からのずれの下限。これより小さい sqrt の項は、
97/// 分岐点をまたいで補間しても誤差がその数分の 1 に収まる(|r| が 1 の 2e-6 手前で全反射に移る膜では、
98/// 分岐点として扱うと推定の位置が 1e-4 ずれて係数が 1.2e-3 ずれ、またいで補間すると 3e-7)
99pub(in crate::coating) const MIRROR_BRANCH_MIN_DEV: f64 = 1e-5;
100
101/// 鏡の分岐点を探すとき、|r| = 1 からのずれがこれ未満の点を全反射とみる。値の 1e-9 ほどの違い(丸め・測定の桁)で
102/// 全反射の判定が外れないよう、それより十分大きくする(1e-10 だと r を 1e-9 に丸めただけで分岐点が消え、
103/// 分岐点をまたいで補間して係数が 2e-2 変わった)
104pub const MIRROR_TIR_TOL: f64 = 1e-8;
105
106/// 鏡の分岐点の推定が、隣り合う β² の点の間隔のこの割合より格子の点に近ければ、その点に寄せる。
107/// 分岐点が測った点の上にある(層の屈折率がちょうど格子の β)とき、推定は値の 1e-9 の違いで 4e-10 ほど揺れ、
108/// 分岐点のそばでは r が sqrt(|β² − xb|) で変わるので、揺れが係数で 5e-5 に広がる。格子の点に寄せれば推定は揺れない
109pub(in crate::coating) const MIRROR_BRANCH_SNAP: f64 = 1e-6;
110
111/// 鏡の補間に使う有理関数の点の数
112pub(in crate::coating) const RATIONAL_N: usize = 8;
113
114/// 昇順の点 xs[s..e] のうち q に近い m 点([`RATIONAL_N`] から始めて、解けなければ 2 点ずつ減らす)を通る
115/// 有理関数(分子 m/2 − 1 次・分母 m/2 次)の q での値。4 点でも解けなければ近い 4 点の多項式にする。
116/// 連立方程式が退化する(データがもっと低い次数の有理関数で表せる)ときは、ピボットが相対的に小さくなるので次の m にする
117pub(in crate::coating) fn rational_at(
118    xs: &[f64],
119    s: usize,
120    e: usize,
121    q: f64,
122    f: &dyn Fn(usize) -> C64,
123) -> C64 {
124    let n = e - s;
125    let start = |m: usize| {
126        s + xs[s..e]
127            .partition_point(|&x| x < q)
128            .saturating_sub(m / 2)
129            .min(n - m)
130    };
131    let mut m = RATIONAL_N.min(n - n % 2);
132    while m >= 4 {
133        if let Some(v) = rational_solve(xs, start(m), m, q, f) {
134            return v;
135        }
136        m -= 2;
137    }
138    let m = n.min(4);
139    let i = start(m);
140    (i..i + m)
141        .map(|a| {
142            let w: f64 = (i..i + m)
143                .filter(|&b| b != a)
144                .map(|b| (q - xs[b]) / (xs[a] - xs[b]))
145                .product();
146            f(a) * w
147        })
148        .sum::<C64>()
149}
150
151/// xs[i..i+m] を通る有理関数 P/Q(Q(q) = 1)の q での値。退化していれば None
152pub(in crate::coating) fn rational_solve(
153    xs: &[f64],
154    i: usize,
155    m: usize,
156    q: f64,
157    f: &dyn Fn(usize) -> C64,
158) -> Option<C64> {
159    let t: Vec<f64> = (i..i + m).map(|j| xs[j] - q).collect();
160    let h = t.iter().fold(0.0f64, |a, b| a.max(b.abs())).max(1e-300);
161    // P(t) − f Q(t) = 0、Q(0) = 1(t は h で割って条件をよくする)
162    let (np, nq) = (m / 2, m - m / 2);
163    let mut a = vec![vec![C64::new(0.0, 0.0); m + 1]; m];
164    for (r, row) in a.iter_mut().enumerate() {
165        let u = t[r] / h;
166        let fv = f(i + r);
167        for (k, v) in row.iter_mut().enumerate().take(np) {
168            *v = C64::new(u.powi(k as i32), 0.0);
169        }
170        for k in 1..=nq {
171            row[np + k - 1] = -fv * u.powi(k as i32);
172        }
173        row[m] = fv;
174    }
175    let scale = a
176        .iter()
177        .flat_map(|r| r[..m].iter().map(|v| v.norm()))
178        .fold(0.0, f64::max);
179    for c in 0..m {
180        let p = (c..m).max_by(|&x, &y| a[x][c].norm().total_cmp(&a[y][c].norm()))?;
181        if a[p][c].norm() <= 1e-11 * scale {
182            return None;
183        }
184        a.swap(c, p);
185        for r in 0..m {
186            if r != c {
187                let g = a[r][c] / a[c][c];
188                for k in c..=m {
189                    let v = a[c][k];
190                    a[r][k] -= g * v;
191                }
192            }
193        }
194    }
195    let v = a[0][m] / a[0][0];
196    (v.re.is_finite() && v.im.is_finite()).then_some(v)
197}
198
199/// 鏡の 1 つの波長の表(β² の昇順 b2、点ごとに偏光 s・p の r)から、β² 方向の分岐点を探す。
200/// 膜の外の媒質(屈折率 n)へ光が抜ける鏡では、β > n で全反射になって |r| = 1 に張り付き、
201/// β = n で r が sqrt(n² − β²) の形で変わる。有理関数でも多項式でも表せないので、補間の点がまたがないようにし、
202/// 両側それぞれ t = sqrt(|β² − xb|) で補間する(r は t の滑らかな関数)。
203/// |r| = 1([`MIRROR_TIR_TOL`] 以内)が最後まで続く最初の点を k として、位置 xb は k とその手前の点の間で、両側から t = 0 へ外挿した r が一致する点。
204/// 推定が k か k − 1 の点にごく近ければ([`MIRROR_BRANCH_SNAP`])、その点にする。
205/// 層が吸収して |r| < 1 のままなら None(分岐点は扱わない)
206pub(in crate::coating) fn mirror_branch(b2: &[f64], r: &[[C64; 2]]) -> Option<MirrorBranch> {
207    let dev = |j: usize| {
208        r[j].iter()
209            .map(|v| (v.norm() - 1.0).abs())
210            .fold(0.0, f64::max)
211    };
212    let n = b2.len();
213    let k = (0..n).rev().find(|&j| !(dev(j) < MIRROR_TIR_TOL))? + 1;
214    // 両側に 4 点以上。sqrt の形なら手前で |r| は 1 からはっきり離れている(全反射しにくい高反射膜で
215    // |r| が β とともに少しずつ 1 に近づくだけのときは分岐点ではない)
216    if k < 4 || n - k < 4 || dev(k - 1).max(dev(k - 2)) < MIRROR_BRANCH_MIN_DEV {
217        return None;
218    }
219    let m = RATIONAL_N.min(k).min(n - k);
220    // 両側から t = 0 へ外挿した r の食い違い
221    let gap = |xb: f64| -> f64 {
222        let tl: Vec<f64> = (0..m)
223            .map(|i| (xb - b2[k - 1 - i]).max(0.0).sqrt())
224            .collect();
225        let th: Vec<f64> = (0..m).map(|i| (b2[k + i] - xb).max(0.0).sqrt()).collect();
226        (0..2)
227            .map(|pol| {
228                let lo = rational_at(&tl, 0, m, 0.0, &|i| r[k - 1 - i][pol]);
229                let hi = rational_at(&th, 0, m, 0.0, &|i| r[k + i][pol]);
230                (lo - hi).norm()
231            })
232            .sum::<f64>()
233    };
234    let (a0, c0) = (b2[k - 1], b2[k]);
235    const N: usize = 200;
236    let grid = |i: usize| a0 + (c0 - a0) * i as f64 / N as f64;
237    let j = (0..=N)
238        .min_by(|&p, &q| gap(grid(p)).total_cmp(&gap(grid(q))))
239        .unwrap_or(0);
240    let (mut a, mut c) = (grid(j.saturating_sub(1)), grid((j + 1).min(N)));
241    // 黄金分割で詰める
242    for _ in 0..60 {
243        let (p, q) = (a + (c - a) * 0.381_966, a + (c - a) * 0.618_034);
244        if gap(p) < gap(q) {
245            c = q;
246        } else {
247            a = p;
248        }
249    }
250    let xb = 0.5 * (a + c);
251    // 格子の点より悪ければ格子の点
252    let xb = if gap(xb) <= gap(grid(j)) { xb } else { grid(j) };
253    // 測った点のすぐそばなら、その点に寄せる
254    let tol = MIRROR_BRANCH_SNAP * (c0 - a0);
255    let (xb, on_grid) = if xb - a0 <= tol {
256        (a0, true)
257    } else if c0 - xb <= tol {
258        (c0, true)
259    } else {
260        (xb, false)
261    };
262    Some(MirrorBranch { xb, k, on_grid })
263}
264
265/// [`wave_weights`] が補間できない理由
266pub(in crate::coating) fn out_of_waves(wls: &[f64], wl: f64) -> String {
267    match (wls.first(), wls.last()) {
268        (Some(&a), Some(&b)) if a - 1e-9 <= wl && wl <= b + 1e-9 => {
269            "has fewer than 2 measured wavelengths between the kinks (KINKS) around it".to_string()
270        }
271        (Some(&a), Some(&b)) => format!("is outside the range ({a} to {b} µm)"),
272        _ => "has no wavelength data".to_string(),
273    }
274}
275
276/// 実数の値の列を β² の not-a-knot スプラインにする
277pub(in crate::coating) fn beta_spline(name: &str, b2: &[f64], ys: &[f64]) -> Result<Spline> {
278    match Spline::not_a_knot(b2, ys) {
279        Some(s) => Ok(s),
280        None => invalid!("coating model {name}: β can't be interpolated"),
281    }
282}
283
284/// 線形補間(xs は昇順。範囲外は端の値、numpy の interp と同じ)
285/// 度の位相の列の ±180° の飛びをほどく(隣との差が 180° を超えれば 360° ずらす)
286pub(in crate::coating) fn unwrap_deg(v: &mut [f64]) {
287    for i in 1..v.len() {
288        let d = v[i] - v[i - 1];
289        v[i] -= 360.0 * (d / 360.0).round();
290    }
291}
292
293pub fn interp(x: f64, xs: &[f64], ys: &[f64]) -> f64 {
294    let n = xs.len();
295    if x.is_nan() {
296        return f64::NAN;
297    }
298    if n == 1 || x <= xs[0] {
299        return ys[0];
300    }
301    if x >= xs[n - 1] {
302        return ys[n - 1];
303    }
304    let i = xs.partition_point(|&v| v <= x) - 1;
305    let t = (x - xs[i]) / (xs[i + 1] - xs[i]);
306    ys[i] + t * (ys[i + 1] - ys[i])
307}
308
309/// 鏡の β² 方向の分岐点 xb と、その両側の点の座標 t = sqrt(|β² − xb|)(どちらも t の昇順)。
310/// r は分岐点の両側それぞれで t の滑らかな関数なので、t で補間する
311#[derive(Debug, Clone)]
312pub(in crate::coating) struct Branch {
313    pub(in crate::coating) xb: f64,
314    /// 下側: 点 lo_end − 1 − i の t
315    pub(in crate::coating) lo_end: usize,
316    pub(in crate::coating) t_lo: Vec<f64>,
317    /// 上側: 点 hi_start + i の t
318    pub(in crate::coating) hi_start: usize,
319    pub(in crate::coating) t_hi: Vec<f64>,
320}
321
322impl Branch {
323    pub(in crate::coating) fn new(b2: &[f64], xb: f64) -> Branch {
324        // 分岐点ちょうどの点は両側で使う
325        let lo_end = b2.partition_point(|&v| v <= xb + 1e-12);
326        let hi_start = b2.partition_point(|&v| v < xb - 1e-12);
327        Branch {
328            xb,
329            lo_end,
330            t_lo: (0..lo_end)
331                .rev()
332                .map(|j| (xb - b2[j]).max(0.0).sqrt())
333                .collect(),
334            hi_start,
335            t_hi: (hi_start..b2.len())
336                .map(|j| (b2[j] - xb).max(0.0).sqrt())
337                .collect(),
338        }
339    }
340
341    /// β² = x での値(f(j) は点 j の値)
342    pub(in crate::coating) fn eval(&self, x: f64, f: &dyn Fn(usize) -> C64) -> C64 {
343        if x <= self.xb {
344            let q = (self.xb - x).sqrt();
345            rational_at(&self.t_lo, 0, self.t_lo.len(), q, &|i| {
346                f(self.lo_end - 1 - i)
347            })
348        } else {
349            let q = (x - self.xb).sqrt();
350            rational_at(&self.t_hi, 0, self.t_hi.len(), q, &|i| f(self.hi_start + i))
351        }
352    }
353}