Skip to main content

lensbench_core/coating/
iface.rs

1//! 境界の係数の用意([`Coatings::prepare`])と評価([`Iface`])
2
3use super::*;
4
5impl Coatings {
6    /// 境界 key の波長 wl [µm] での係数を用意する(n1・n2 は前後の屈折率、鏡では n2 は使わない)
7    ///
8    /// 屈折面での反射(鍵 `膜|入射側|反対側|R`、ゴーストの経路)は鏡と同じ約束(p = s × k を反射の後で反転)の r を返す。
9    /// n2 は反対側の媒質の屈折率。膜の向き(基板の側)は透過と同じく、反対側が空気でなければ反対側が基板、空気なら
10    /// 入射側が基板。位相は基板の面を面の頂点に置いた値(膜の側から入るときは鏡と同じく exp(2 i k n1 cosθ1 Σ d_j)
11    /// を掛け、基板の側から入るときは掛けない)。暗号化された膜は特性行列モデルの M から r を求める(透過の実測表
12    /// だけでは求められない)
13    pub fn prepare(&self, sys: &System, key: &str, wl: f64, n1: f64, n2: f64) -> Result<Iface> {
14        let k = IfaceKey::parse(key);
15        let coat = k.coat;
16        let reflect = k.is_reflect();
17        let to_mirror = k.after == After::Mirror;
18        let mirror = to_mirror || reflect;
19        let kind = match self.resolve(&k, key) {
20            CoatKind::Table => {
21                let tab = &self.file.table[coat];
22                let angs: Vec<f64> = tab.iter().map(|a| a.0).collect();
23                let mut vals: [Vec<f64>; 8] = Default::default();
24                for (a, rows) in tab {
25                    if rows.is_empty() {
26                        invalid!("coating table {coat} has no row for angle {a}");
27                    }
28                    let xs: Vec<f64> = rows.iter().map(|r| r[0]).collect();
29                    for c in 0..8 {
30                        let mut ys: Vec<f64> = rows.iter().map(|r| r[c + 1]).collect();
31                        if c >= 4 {
32                            unwrap_deg(&mut ys);
33                        }
34                        vals[c].push(interp(wl, &xs, &ys));
35                    }
36                }
37                let step = self.table_normal == TableNormal::OpticStudio;
38                if !step && angs[0] == 0.0 {
39                    // 段差なし: 0° の行の s を p で置き換えて補間する
40                    for c in [0, 2, 4, 6] {
41                        vals[c][0] = vals[c + 1][0];
42                    }
43                }
44                // 位相(度)は ±180° の折り返しをほどいてから補間する(+179° と −179° の間を 0° にしない)
45                for v in &mut vals[4..] {
46                    unwrap_deg(v);
47                }
48                Kind::Table {
49                    name: coat.to_string(),
50                    step,
51                    xc: angs.iter().map(|a| -a.to_radians().cos()).collect(),
52                    angs,
53                    vals: Box::new(vals),
54                    out: (!mirror && n1 > n2 && n2 > 0.0).then_some(n1 / n2),
55                }
56            }
57            CoatKind::Bare => Kind::Fresnel {
58                ns: if to_mirror {
59                    MIRROR_N
60                } else {
61                    C64::new(n2, 0.0)
62                },
63            },
64            CoatKind::Ideal => {
65                // I.xx: 透過率 .xx。I.s=Ts,p=Tp: s・p で別の透過率(理想の偏光ビームスプリッター)。
66                // 反射(鏡・屈折面での反射)は −√(1 − T)
67                let [ts, tp] = ideal_t(coat)?;
68                let v = |t: f64| C64::new(if mirror { -(1.0 - t).sqrt() } else { t.sqrt() }, 0.0);
69                Kind::Ideal([v(ts), v(tp)])
70            }
71            CoatKind::Stack => {
72                let ls = &self.file.coat[coat];
73                let wl_ref = sys.wavelengths[sys.primary];
74                let mut layers = Vec::with_capacity(ls.len());
75                for l in ls {
76                    let n = self.mat_n(sys, &l.mat, wl)?;
77                    let d = if l.absolute {
78                        l.d
79                    } else {
80                        l.d * wl_ref / self.mat_n(sys, &l.mat, wl_ref)?.re
81                    };
82                    layers.push((n, d));
83                }
84                // OpticStudio の約束(COATING.DAT の膜で、空気・硝材どうし・両向き・鏡を偏光追跡と照合):
85                // - 層は膜の外側(基板と反対側)から順。透過で後ろの媒質が空気なら、基板は前の媒質(層を逆に通る)
86                // - 鏡の基板は最後の層の材料(半無限)。最後の層より上だけが薄膜
87                // - 係数に位相 exp(i k Σ d_j (n_o / cos_o − β² / q_j)) が掛かる(n_o・cos_o は膜の外側の媒質、
88                //   β = n1 sinθ1、q_j = sqrt(Re(n_j)² − β²))。鏡では exp(2 i k n1 cosθ1 Σ d_j)
89                if to_mirror {
90                    let ns = match layers.pop() {
91                        Some((n, _)) => n,
92                        None => MIRROR_N,
93                    };
94                    Kind::Stack {
95                        layers,
96                        ns,
97                        n_out: n1,
98                        layer_phase: true,
99                        front: true,
100                    }
101                } else if reflect {
102                    // 反対側が空気なら基板は入射側(層を逆に、基板の側から入る)
103                    let front = !k.after_is_air();
104                    if !front {
105                        layers.reverse();
106                    }
107                    Kind::Stack {
108                        layers,
109                        ns: C64::new(n2, 0.0),
110                        n_out: n1,
111                        layer_phase: false,
112                        front,
113                    }
114                } else {
115                    if k.after_is_air() {
116                        layers.reverse();
117                    }
118                    Kind::Stack {
119                        layers,
120                        ns: C64::new(n2, 0.0),
121                        n_out: if k.after_is_air() { n2 } else { n1 },
122                        layer_phase: self.phase == PhaseConvention::OpticStudio,
123                        front: false,
124                    }
125                }
126            }
127            // モデル(なければ理由を返す): 暗号化された膜
128            CoatKind::Model | CoatKind::Missing => {
129                if reflect && !self.models.contains_key(coat) {
130                    notimpl!("coating {coat} (interface {key}): reflection coefficients need a characteristic matrix model (a measured table is transmission only)");
131                }
132                return match self.models.get(coat) {
133                    Some(md) => Ok(Iface {
134                        kind: prepare_model(
135                            coat,
136                            md,
137                            to_mirror,
138                            reflect,
139                            k.after_is_air(),
140                            wl,
141                            n2,
142                            self.phase,
143                        )?,
144                        mirror,
145                        n1,
146                        wl,
147                    }),
148                    None => notimpl!(
149                        "coating {coat} (interface {key}): not in the coating file, and no measured table or model (an encrypted coating?)"
150                    ),
151                };
152            }
153            CoatKind::User => {
154                let path = if to_mirror {
155                    crate::usercoating::CoatPath::Mirror
156                } else if reflect {
157                    crate::usercoating::CoatPath::Reflect
158                } else {
159                    crate::usercoating::CoatPath::Transmit
160                };
161                Kind::User {
162                    name: coat.to_string(),
163                    model: self.user[coat].clone(),
164                    path,
165                    n2: if to_mirror { f64::NAN } else { n2 },
166                    // 膜は空気の側に付いているとみなす(層の並びの膜と同じ)
167                    from_substrate: !to_mirror && k.after_is_air(),
168                }
169            }
170            CoatKind::Measured => {
171                let m = &self.measured[key];
172                let Some(w) = m.wavelengths.iter().position(|&v| (v - wl).abs() <= 1e-9) else {
173                    let have = &m.wavelengths;
174                    notimpl!("measured coating table {key} has no wavelength {wl} µm (the table has {have:?})");
175                };
176                // 屈折角の余弦のスプライン(0 付近で角度に偶、全反射の平方根の振舞いもこれに線形)。鏡では入射角の余弦
177                let r = if mirror { 1.0 } else { n1 / n2 };
178                let mut xs = Vec::new();
179                let mut ys: [Vec<f64>; 4] = Default::default();
180                for (a, v) in m.angles_deg.iter().zip(&m.data[w]) {
181                    if !(v[0].re.is_finite() && v[0].im.is_finite()) {
182                        continue;
183                    }
184                    xs.push(xcos(r, a.to_radians()));
185                    ys[0].push(v[0].re);
186                    ys[1].push(v[0].im);
187                    ys[2].push(v[1].re);
188                    ys[3].push(v[1].im);
189                }
190                let sp = [0, 1, 2, 3].map(|c| Spline::not_a_knot(&xs, &ys[c]));
191                let sp = match sp {
192                    [Some(a), Some(b), Some(c), Some(d)] => [a, b, c, d],
193                    _ => invalid!("measured coating table {key}: too few points to interpolate"),
194                };
195                Kind::Measured {
196                    key: key.to_string(),
197                    r,
198                    max_deg: *m.angles_deg.last().expect("angles checked when reading"),
199                    cmax: m
200                        .angles_deg
201                        .last()
202                        .expect("angles checked when reading")
203                        .to_radians()
204                        .cos(),
205                    sp: Box::new(sp),
206                }
207            }
208        };
209        Ok(Iface {
210            kind,
211            mirror,
212            n1,
213            wl,
214        })
215    }
216}
217
218/// 実測表の横軸: −cos(屈折角)(増加)
219pub(in crate::coating) fn xcos(r: f64, th: f64) -> f64 {
220    xcos_s(r, th.sin())
221}
222
223/// [`xcos`] を入射角の sin で
224pub(in crate::coating) fn xcos_s(r: f64, s0: f64) -> f64 {
225    let s = r * s0;
226    -(1.0 - s * s).max(0.0).sqrt()
227}
228
229/// 理想膜の名前から (s, p) の強度透過率: `I.xx`(s・p 共通、`I.98` は 0.98)、`I.s=Ts,p=Tp`(s・p で別)
230pub(crate) fn ideal_t(coat: &str) -> Result<[f64; 2]> {
231    let bad = || Error::Invalid(format!("ideal coating {coat} (I.xx or I.s=Ts,p=Tp)"));
232    let rest = coat.strip_prefix("I.").ok_or_else(bad)?;
233    let v = if rest.contains('=') {
234        let (mut ts, mut tp) = (None, None);
235        for part in rest.split(',') {
236            let (k, x) = part.split_once('=').ok_or_else(bad)?;
237            let x: f64 = x.trim().parse().map_err(|_| bad())?;
238            match k.trim() {
239                "s" => ts = Some(x),
240                "p" => tp = Some(x),
241                _ => return Err(bad()),
242            }
243        }
244        [ts.ok_or_else(bad)?, tp.ok_or_else(bad)?]
245    } else {
246        let t: f64 = coat[1..].parse().map_err(|_| bad())?;
247        [t, t]
248    };
249    if v.iter().any(|t| !(0.0..=1.0).contains(t)) {
250        return Err(bad());
251    }
252    Ok(v)
253}
254
255#[derive(Debug, Clone)]
256pub(in crate::coating) enum Kind {
257    Fresnel {
258        ns: C64,
259    },
260    /// 理想膜の (s, p) の係数
261    Ideal([C64; 2]),
262    Stack {
263        layers: Vec<(C64, f64)>,
264        ns: C64,
265        /// 膜の外側(基板と反対側)の媒質の屈折率(位相の約束に使う)
266        n_out: f64,
267        /// 透過で層ごとの位相を含める([`PhaseConvention::OpticStudio`])
268        layer_phase: bool,
269        /// 反射で、膜の側から入る(位相 exp(2 i k n1 cosθ1 Σ d_j) を掛ける。基板が頂点にある)
270        front: bool,
271    },
272    Table {
273        name: String,
274        /// 垂直入射(1 − cosθ < TABLE_NORMAL)だけ s に p を使う([`TableNormal::OpticStudio`])
275        step: bool,
276        angs: Vec<f64>,
277        /// −cos(角度)(補間の横軸、増加)
278        xc: Vec<f64>,
279        /// 量ごと(Rs Rp Ts Tp と位相)の角度に対する値
280        vals: Box<[Vec<f64>; 8]>,
281        /// 透過で屈折率の高い側から入るとき n1 / n2(表の角度は屈折率の低い側の角度で引く。OpticStudio と同じ)
282        out: Option<f64>,
283    },
284    Measured {
285        key: String,
286        r: f64,
287        max_deg: f64,
288        /// cos(max_deg)
289        cmax: f64,
290        sp: Box<[Spline; 4]>,
291    },
292    /// モデルの透過: β² の補間(偏光ごとに M̃ の実部・虚部 8 本と ψ)
293    Model {
294        name: String,
295        /// 層ごとの位相(ψ)を含める([`PhaseConvention::OpticStudio`])
296        layer_phase: bool,
297        /// 屈折面での反射 r を返す(M から。ψ は打ち消し合うので使わない)
298        reflect: bool,
299        reverse: bool,
300        n2: f64,
301        d: f64,
302        bmax: f64,
303        b2: (f64, f64),
304        sp: Box<BetaInterp>,
305    },
306    /// 係数を計算で返す利用者の膜
307    User {
308        name: String,
309        model: std::sync::Arc<dyn crate::usercoating::CoatingModel>,
310        path: crate::usercoating::CoatPath,
311        /// 反対側の媒質の屈折率(鏡は NaN)
312        n2: f64,
313        from_substrate: bool,
314    },
315    /// モデルの鏡: 基準の媒質での r(この波長、β² の点ごと、偏光ごと)。β² の有理関数で補間する
316    /// (高い β では導波の共鳴で、β 方向にも鋭く変わる)
317    ModelMirror {
318        name: String,
319        n_ref: f64,
320        d: f64,
321        b2: Vec<f64>,
322        r: Box<[Vec<C64>; 2]>,
323        /// β² 方向の分岐点(膜の外の媒質で全反射が始まる β²)。補間の点はこれをまたがない
324        branch: Option<Box<Branch>>,
325        /// 値が決まらない β² の区間(両端を含む)。ここでは notimpl
326        band: Option<(f64, f64)>,
327    },
328}
329
330/// モデルの透過の β² 方向の補間(ある波長で、偏光ごとに M̃ の実部・虚部 8 本と ψ)
331#[derive(Debug, Clone)]
332pub(in crate::coating) enum BetaInterp {
333    /// 従来([`CoatModel::order`] が 0): not-a-knot スプライン。ψ は BMAX までの節
334    Spline(Box<[[Spline; 9]; 2]>),
335    /// 近い p 点の β² の多項式。ψ は BMAX までの npsi 点だけで
336    Local {
337        b2: Vec<f64>,
338        v: [Vec<[f64; 9]>; 2],
339        npsi: usize,
340        p: usize,
341    },
342}
343
344impl BetaInterp {
345    /// β² = x での偏光ごとの M̃(M00 M10 M01 M11)。psi なら ψ も(BMAX の内側だけで呼ぶ)
346    pub(in crate::coating) fn eval(&self, x: f64, psi: bool) -> [([C64; 4], f64); 2] {
347        match self {
348            BetaInterp::Spline(sp) => {
349                // 18 本のスプラインは同じ β² の節(ψ はその前の部分)なので、区間は 1 回だけ探す
350                let i = sp[0][0].locate(x);
351                std::array::from_fn(|pol| {
352                    let s = &sp[pol];
353                    let m = std::array::from_fn(|c| {
354                        C64::new(s[2 * c].eval_at(i, x), s[2 * c + 1].eval_at(i, x))
355                    });
356                    (m, if psi { s[8].eval_at(i, x) } else { 0.0 })
357                })
358            }
359            BetaInterp::Local { b2, v, npsi, p } => {
360                let (i, w) = local_weights(b2, b2.len(), *p, x);
361                let pw = psi.then(|| local_weights(b2, *npsi, *p, x));
362                std::array::from_fn(|pol| {
363                    let vv = &v[pol];
364                    let sum = |c: usize| -> f64 {
365                        w.iter().enumerate().map(|(a, wa)| wa * vv[i + a][c]).sum()
366                    };
367                    let m = std::array::from_fn(|c| C64::new(sum(2 * c), sum(2 * c + 1)));
368                    let ps = pw.as_ref().map_or(0.0, |(i, w)| {
369                        w.iter().enumerate().map(|(a, wa)| wa * vv[i + a][8]).sum()
370                    });
371                    (m, ps)
372                })
373            }
374        }
375    }
376}
377
378impl CoatModel {
379    /// このモデルだけで境界 key(`膜|前|後`、鏡は後が `MIRROR`)の波長 wl [µm] の係数を用意する。
380    /// 系も膜ファイルも使わない(モデルと OpticStudio の実測表を比べる道具用)。n1・n2 は前後の屈折率
381    pub fn iface(
382        &self,
383        key: &str,
384        wl: f64,
385        n1: f64,
386        n2: f64,
387        phase: PhaseConvention,
388    ) -> Result<Iface> {
389        let k = IfaceKey::parse(key);
390        let to_mirror = k.after == After::Mirror;
391        let reflect = k.is_reflect();
392        Ok(Iface {
393            kind: prepare_model(
394                k.coat,
395                self,
396                to_mirror,
397                reflect,
398                k.after_is_air(),
399                wl,
400                n2,
401                phase,
402            )?,
403            mirror: to_mirror || reflect,
404            n1,
405            wl,
406        })
407    }
408}
409
410/// 膜のモデルを波長 wl で用意する
411#[allow(clippy::too_many_arguments)]
412pub(in crate::coating) fn prepare_model(
413    name: &str,
414    md: &CoatModel,
415    mirror: bool,
416    reflect: bool,
417    reverse: bool,
418    wl: f64,
419    n2: f64,
420    phase: PhaseConvention,
421) -> Result<Kind> {
422    let range = |b: &[f64]| (b[0] * b[0], b[b.len() - 1] * b[b.len() - 1]);
423    if mirror {
424        let Some(m) = &md.mirror else {
425            notimpl!("coating model {name} has no mirror data");
426        };
427        let Some((s0, e0)) = wave_segment(&m.wavelengths, wl, &md.kinks) else {
428            let why = out_of_waves(&m.wavelengths, wl);
429            notimpl!("coating model {name} (mirror): wavelength {wl} µm {why}");
430        };
431        // 波数の昇順に並べた点で補間する(波長は昇順なので逆順)
432        let xs: Vec<f64> = (s0..e0).rev().map(|i| 1.0 / m.wavelengths[i]).collect();
433        let b2: Vec<f64> = m.betas.iter().map(|b| b * b).collect();
434        let brb = m.branches(&b2);
435        let brs: Vec<Option<f64>> = brb.iter().map(|v| v.map(|v| v.xb)).collect();
436        // 分岐点の位置は波長の滑らかな関数(基板の屈折率の 2 乗)なので、近い 4 点の 1/λ の 3 次式で補間する
437        // (区間のどの波長にもあるときだけ使う)
438        let branch = if brs[s0..e0].iter().all(Option::is_some) {
439            let bx: Vec<f64> = (s0..e0).rev().map(|i| brs[i].unwrap_or(0.0)).collect();
440            // どの波長でも同じ(分散のない媒質。格子の点に寄せたときなど)なら、補間の丸めで動かさない
441            if bx.iter().all(|&v| v == bx[0]) {
442                Some(bx[0])
443            } else {
444                let n = xs.len().min(4);
445                let i = xs
446                    .partition_point(|&x| x < 1.0 / wl)
447                    .saturating_sub(n / 2)
448                    .min(xs.len() - n);
449                let q = 1.0 / wl;
450                Some(
451                    (i..i + n)
452                        .map(|a| {
453                            let w: f64 = (i..i + n)
454                                .filter(|&c| c != a)
455                                .map(|c| (q - xs[c]) / (xs[a] - xs[c]))
456                                .product();
457                            w * bx[a]
458                        })
459                        .sum::<f64>(),
460                )
461            }
462        } else {
463            None
464        };
465        let branch = branch.map(|xb| Box::new(Branch::new(&b2, xb)));
466        // 補間に使いそうな波長(近い RATIONAL_N 点と、その両側に 2 点ずつ)で分岐点が点 j の β² の両側にあるなら、
467        // β² を固定すると波長の補間が分岐点をまたぐ。その点は、各波長の表を分岐点からの β² の差 u = β² − xb で
468        // 揃えてから波長で補間する。ほかの点は β² を固定して補間する(測った点で値が厳密に合う)
469        // rational_at が選ぶ波長の点(端では内側へ寄せる)と、その両側 2 点
470        let (w0, w1) = {
471            let n = xs.len();
472            let m = RATIONAL_N.min(n - n % 2).max(n.min(4));
473            let st = xs
474                .partition_point(|&x| x < 1.0 / wl)
475                .saturating_sub(m / 2)
476                .min(n - m);
477            // xs の k 番目は波長の e0 − 1 − k 番目
478            (
479                (e0 - (st + m)).saturating_sub(2).max(s0),
480                (e0 - st + 2).min(e0),
481            )
482        };
483        // 分岐点が測った点の間にある波長では、そのそば(全反射の手前の最後の点 k − 1 から、全反射の 2 点目 k + 1 まで)は
484        // r が急に変わるのに測った点が足りず、値が r のわずかな違いで大きく変わり、OpticStudio とも合わない
485        // (細かく測った OpticStudio の値と 2.6e-2 違った。この範囲を外すと 8e-6 以下)。
486        // 補間に使う波長のその範囲を合わせた区間では notimpl にする(測った点の上にある分岐点は除く)
487        let band = if let Some(bb) = &branch {
488            // この波長の分岐点(補間した位置)のまわりも。測った点の上に分岐点のある波長だけで補間すると、
489            // 間の波長の分岐点は測った点の間にあり、そのそばで同じように値が決まらない(2.05 側の鏡で 7e-3)
490            let kq = b2.partition_point(|&x| x < bb.xb).clamp(1, b2.len() - 1);
491            let own = (b2[kq] - bb.xb > MIRROR_BRANCH_SNAP * (b2[kq] - b2[kq - 1]))
492                .then(|| (b2[kq - 1], b2[(kq + 1).min(b2.len() - 1)]));
493            (w0..w1)
494                .filter_map(|w| brb[w].filter(|v| !v.on_grid))
495                .map(|v| (b2[v.k - 1], b2[(v.k + 1).min(b2.len() - 1)]))
496                .chain(own)
497                .reduce(|a, c| (a.0.min(c.0), a.1.max(c.1)))
498        } else {
499            partial_branch_band(&b2, &m.r[w0..w1], &brb[w0..w1])
500        };
501        let near = |j: usize| {
502            branch.is_some() && {
503                let above = |w: usize| brs[w].is_some_and(|xb| xb > b2[j]);
504                let a = above(w0);
505                (w0..w1).any(|w| above(w) != a)
506            }
507        };
508        let side: Vec<Option<Branch>> = (s0..e0)
509            .map(|i| {
510                brs[i]
511                    .filter(|_| branch.is_some())
512                    .map(|xb| Branch::new(&b2, xb))
513            })
514            .collect();
515        let mut r: [Vec<C64>; 2] = [Vec::new(), Vec::new()];
516        for (pol, rp) in r.iter_mut().enumerate() {
517            *rp = (0..m.betas.len())
518                .map(|j| {
519                    if near(j) {
520                        let u = b2[j] - branch.as_ref().map_or(0.0, |bb| bb.xb);
521                        rational_at(&xs, 0, xs.len(), 1.0 / wl, &|k| {
522                            let w = e0 - 1 - k;
523                            let bk = side[w - s0].as_ref().expect("分岐点");
524                            bk.eval(bk.xb + u, &|jj| m.r[w][jj][pol])
525                        })
526                    } else {
527                        rational_at(&xs, 0, xs.len(), 1.0 / wl, &|k| m.r[e0 - 1 - k][j][pol])
528                    }
529                })
530                .collect();
531        }
532        return Ok(Kind::ModelMirror {
533            name: name.to_string(),
534            n_ref: m.n_ref,
535            d: m.d,
536            b2,
537            r: Box::new(r),
538            branch,
539            band,
540        });
541    }
542    if !md.has_transmit() {
543        notimpl!("coating model {name} has no transmission data");
544    }
545    let p = if md.order == 0 { 4 } else { md.order };
546    let Some((i, w)) = wave_weights(&md.wavelengths, wl, &md.kinks, p) else {
547        let why = out_of_waves(&md.wavelengths, wl);
548        notimpl!("coating model {name}: wavelength {wl} µm {why}");
549    };
550    let b2: Vec<f64> = md.betas.iter().map(|b| b * b).collect();
551    // ψ は BMAX までの点だけで(その先は層の屈折率で発散する)
552    let npsi = md.betas.partition_point(|&b| b <= md.bmax + 1e-12);
553    if npsi < 4 {
554        invalid!("coating model {name}: too few β points up to BMAX (4 or more)");
555    }
556    // 波長で補間した、β の点ごと・偏光ごとの 9 つの値(M̃ の実部・虚部と ψ)
557    let vals: [Vec<[f64; 9]>; 2] = std::array::from_fn(|pol| {
558        (0..md.betas.len())
559            .map(|j| {
560                std::array::from_fn(|c| {
561                    w.iter()
562                        .enumerate()
563                        .map(|(a, wa)| {
564                            let k = i + a;
565                            wa * if c == 8 {
566                                md.psi[k][j][pol]
567                            } else {
568                                let z = md.m[k][j][pol][c / 2];
569                                if c % 2 == 0 {
570                                    z.re
571                                } else {
572                                    z.im
573                                }
574                            }
575                        })
576                        .sum()
577                })
578            })
579            .collect()
580    });
581    let sp = if md.order == 0 {
582        let mut sp: Vec<[Spline; 9]> = Vec::new();
583        for v in &vals {
584            let mut s: Vec<Spline> = Vec::new();
585            for c in 0..9 {
586                let m = if c == 8 { npsi } else { b2.len() };
587                let ys: Vec<f64> = v[..m].iter().map(|x| x[c]).collect();
588                s.push(beta_spline(name, &b2[..m], &ys)?);
589            }
590            sp.push(s.try_into().expect("9 splines"));
591        }
592        BetaInterp::Spline(Box::new(sp.try_into().expect("2 sides")))
593    } else {
594        BetaInterp::Local {
595            b2,
596            v: vals,
597            npsi,
598            p: md.order,
599        }
600    };
601    Ok(Kind::Model {
602        name: name.to_string(),
603        layer_phase: phase == PhaseConvention::OpticStudio,
604        reflect,
605        reverse,
606        n2,
607        d: md.d,
608        bmax: md.bmax,
609        b2: range(&md.betas),
610        sp: Box::new(sp),
611    })
612}
613
614/// ある波長で用意した境界の係数
615#[derive(Debug, Clone)]
616pub struct Iface {
617    pub(in crate::coating) kind: Kind,
618    pub(in crate::coating) mirror: bool,
619    pub(in crate::coating) n1: f64,
620    pub(in crate::coating) wl: f64,
621}
622
623impl Iface {
624    /// 入射角の cos(0〜1)での (s, p)。屈折率が実数の境界(膜なし)は角度を経由せず実数で計算する
625    /// (偏光追跡の面ごとの処理で、acos・複素数の計算を省く)。ほかは [`Self::eval`] と同じ
626    pub fn eval_cos(&self, c0: f64) -> Result<[C64; 2]> {
627        if let Kind::Fresnel { ns } = &self.kind {
628            if ns.im == 0.0 && self.n1 > 0.0 {
629                let (n0, ns) = (self.n1, ns.re);
630                let s0 = ((1.0 - c0) * (1.0 + c0)).max(0.0).sqrt();
631                let q = n0 * s0 / ns;
632                let cc = 1.0 - q * q;
633                if cc >= 0.0 && c0 > 0.0 {
634                    let cs = cc.sqrt();
635                    // s: η = n cosθ、p: η = n / cosθ(stack と同じ約束、パワー規格化)
636                    let rt = |e0: f64, es: f64| {
637                        let r = (e0 - es) / (e0 + es);
638                        let t = 2.0 * e0 / (e0 + es) * (es / e0).sqrt();
639                        (r, t)
640                    };
641                    let (rs, ts) = rt(n0 * c0, ns * cs);
642                    let (rp, tp) = rt(n0 / c0, ns / cs);
643                    return Ok(if self.mirror {
644                        [C64::new(rs, 0.0), C64::new(rp, 0.0)]
645                    } else {
646                        [C64::new(ts, 0.0), C64::new(tp, 0.0)]
647                    });
648                }
649            }
650        }
651        let c0 = c0.clamp(0.0, 1.0);
652        self.eval_sc(((1.0 - c0) * (1.0 + c0)).sqrt(), c0)
653    }
654
655    /// 複屈折材の板の境界で、板の側の屈折率を `n` に置き換えた [`Self::eval_cos`](異常光の成分の係数)。
656    /// `entering` = true は板へ入る面(後ろの媒質が板)、false は板から出る面(前の媒質が板)。
657    /// 屈折率で決まる係数(膜なし・膜ファイルの層)だけ置き換え、理想膜・実測表・表・モデル・鏡は [`Self::eval_cos`] と同じ
658    pub fn eval_cos_crystal(&self, c0: f64, entering: bool, n: f64) -> Result<[C64; 2]> {
659        if entering {
660            self.eval_cos_media(c0, None, Some(n))
661        } else {
662            self.eval_cos_media(c0, Some(n), None)
663        }
664    }
665
666    /// 前の媒質の屈折率を `n1`、後ろの媒質の屈折率を `n2` に置き換えた [`Self::eval_cos`](None は置き換えない)。
667    /// 複屈折材の板の境界と、板どうしの貼り合わせの境界(前の板の o・e → 次の板の o・e)に使う。
668    /// 置き換えるのは [`Self::eval_cos_crystal`] と同じく屈折率で決まる係数だけ
669    pub fn eval_cos_media(&self, c0: f64, n1: Option<f64>, n2: Option<f64>) -> Result<[C64; 2]> {
670        if self.mirror {
671            return self.eval_cos(c0);
672        }
673        match &self.kind {
674            Kind::Fresnel { ns } => {
675                // 膜なしの境界はヒープを持たないので、置き換えた境界を作って同じ計算に通す
676                let f = Iface {
677                    kind: Kind::Fresnel {
678                        ns: n2.map_or(*ns, |n| C64::new(n, 0.0)),
679                    },
680                    mirror: false,
681                    n1: n1.unwrap_or(self.n1),
682                    wl: self.wl,
683                };
684                f.eval_cos(c0)
685            }
686            Kind::Stack {
687                layers,
688                ns,
689                n_out,
690                layer_phase,
691                front,
692            } => {
693                // n_out(位相の約束の外側の媒質)が板なら、それも置き換える(判定は置き換える前の値で)
694                let (out_is_2, out_is_1) = (ns.im == 0.0 && *n_out == ns.re, *n_out == self.n1);
695                let mut m = StackMedia {
696                    n1: self.n1,
697                    ns: *ns,
698                    n_out: *n_out,
699                };
700                if let Some(n) = n2 {
701                    if out_is_2 {
702                        m.n_out = n;
703                    }
704                    m.ns = C64::new(n, 0.0);
705                }
706                if let Some(n) = n1 {
707                    if out_is_1 {
708                        m.n_out = n;
709                    }
710                    m.n1 = n;
711                }
712                // eval_cos と同じ cos の丸め
713                let c0 = c0.clamp(0.0, 1.0);
714                let s0 = ((1.0 - c0) * (1.0 + c0)).sqrt();
715                stack_coef(m, layers, *layer_phase, *front, false, self.wl, s0, c0)
716            }
717            _ => self.eval_cos(c0),
718        }
719    }
720
721    /// 入射角 theta [rad] での (s, p): 透過、鏡では反射
722    pub fn eval(&self, theta: f64) -> Result<[C64; 2]> {
723        let (s0, c0) = theta.sin_cos();
724        self.eval_sc(s0, c0)
725    }
726
727    /// 入射角の sin・cos での (s, p)(角度を経由しない)
728    fn eval_sc(&self, s0: f64, c0: f64) -> Result<[C64; 2]> {
729        let mirror = self.mirror;
730        Ok(match &self.kind {
731            Kind::Ideal(v) => *v,
732            Kind::Fresnel { ns } => {
733                let (rs, rp, ts, tp) = stack_sc(self.n1, &[], *ns, self.wl, s0, c0);
734                if mirror {
735                    [rs, rp]
736                } else {
737                    [ts, tp]
738                }
739            }
740            Kind::Stack {
741                layers,
742                ns,
743                n_out,
744                layer_phase,
745                front,
746            } => {
747                let m = StackMedia {
748                    n1: self.n1,
749                    ns: *ns,
750                    n_out: *n_out,
751                };
752                stack_coef(m, layers, *layer_phase, *front, mirror, self.wl, s0, c0)?
753            }
754            Kind::Table {
755                name,
756                step,
757                angs,
758                xc,
759                vals,
760                out,
761            } => {
762                // 屈折率の高い側から入る透過(硝材 → 空気など)は、出る側(低い側)の屈折角で表を引く
763                // (OpticStudio と同じ。tests/filter_os の裏面の膜で照合)
764                let c0 = match out {
765                    Some(r) => {
766                        let so = r * s0;
767                        ((1.0 - so) * (1.0 + so)).max(0.0).sqrt()
768                    }
769                    None => c0,
770                };
771                // 角度ではなく cosθ について線形(OpticStudio と同じ。偏光追跡で照合)
772                let x = -c0;
773                // 範囲の検査: 横軸 −cosθ が表の範囲の中なら角度も中(外れそうなときだけ角度にして調べる)
774                if !(x >= xc[0] && x <= xc[xc.len() - 1]) {
775                    let deg = c0.clamp(-1.0, 1.0).acos().to_degrees();
776                    let (lo, hi) = (angs[0], *angs.last().expect("angles checked when reading"));
777                    if deg.is_finite() && (deg > hi + 1e-9 || deg < lo - 1e-9) {
778                        let what = if out.is_some() {
779                            "exit refraction angle"
780                        } else {
781                            "incidence angle"
782                        };
783                        notimpl!("coating table {name}: {what} {deg:.4} deg is outside the table range {lo} to {hi}");
784                    }
785                }
786                let v = |k: usize| interp(x, xc, &vals[k]);
787                let (a, b) = if mirror { (0, 4) } else { (2, 6) };
788                let p = C64::from_polar(v(a + 1).sqrt(), v(b + 1).to_radians());
789                // 垂直入射では s・p の区別がないので p の値を使う。OpticStudio と同じく、ごく小さい角度
790                // (1 − cosθ < TABLE_NORMAL)だけを垂直入射とみなす(その外は表の s に段差で戻る)
791                if *step && 1.0 - c0 < TABLE_NORMAL {
792                    return Ok([p, p]);
793                }
794                [C64::from_polar(v(a).sqrt(), v(b).to_radians()), p]
795            }
796            Kind::User {
797                name,
798                model,
799                path,
800                n2,
801                from_substrate,
802            } => {
803                use crate::usercoating::{CoatInput, CoatPath};
804                let x = CoatInput::new(self.wl, self.n1, *n2, c0, *path, *from_substrate);
805                let c = model.coefs(&x).map_err(|e| match e {
806                    Error::Invalid(m) => Error::Invalid(format!("coating {name}: {m}")),
807                    Error::NotImplemented(m) => {
808                        Error::NotImplemented(format!("coating {name}: {m}"))
809                    }
810                    e => e,
811                })?;
812                match path {
813                    CoatPath::Transmit => [c.ts, c.tp],
814                    _ => [c.rs, c.rp],
815                }
816            }
817            Kind::Measured {
818                key,
819                r,
820                max_deg,
821                cmax,
822                sp,
823            } => {
824                // 範囲の検査: cosθ が表の最大角の cos より十分大きければ範囲内(境目の近くだけ角度にして調べる)
825                if !(c0 > cmax + 1e-12) {
826                    let deg = c0.clamp(-1.0, 1.0).acos().to_degrees();
827                    if deg.is_finite() && deg > max_deg + 1e-12_f64.to_degrees() {
828                        notimpl!(
829                            "coating {key}: incidence angle {deg:.4} deg is outside the measured table range (0 to {max_deg} deg)"
830                        );
831                    }
832                }
833                let x = xcos_s(*r, s0);
834                // 4 本のスプラインは同じ節なので、区間は 1 回だけ探す
835                let i = sp[0].locate(x);
836                [
837                    C64::new(sp[0].eval_at(i, x), sp[1].eval_at(i, x)),
838                    C64::new(sp[2].eval_at(i, x), sp[3].eval_at(i, x)),
839                ]
840            }
841            Kind::Model {
842                name,
843                layer_phase,
844                reflect,
845                reverse,
846                n2,
847                d,
848                bmax,
849                b2,
850                sp,
851            } => {
852                let b = self.n1 * s0;
853                let x = b * b;
854                if *reflect {
855                    if x < b2.0 - 1e-12 || x > b2.1 + 1e-12 {
856                        let top = b2.1.sqrt();
857                        notimpl!("coating model {name} (reflection): β = {b:.4} is outside the model range (β ≤ {top:.4})");
858                    }
859                    let k = 2.0 * PI / self.wl;
860                    let ph = if *reverse {
861                        C64::new(1.0, 0.0)
862                    } else {
863                        C64::new(0.0, 2.0 * k * self.n1 * c0 * d).exp()
864                    };
865                    let mut out = [C64::new(0.0, 0.0); 2];
866                    let mv = sp.eval(x, false);
867                    for (pol, o) in out.iter_mut().enumerate() {
868                        let m = mv[pol].0;
869                        let (m00, m10, m01, m11) = if *reverse {
870                            (m[3], m[1], m[2], m[0])
871                        } else {
872                            (m[0], m[1], m[2], m[3])
873                        };
874                        let e1 = admittance(self.n1, b, pol);
875                        let e2 = admittance_ev(*n2, b, pol);
876                        let (bb, cc) = (m00 + m01 * e2, m10 + m11 * e2);
877                        *o = (e1 * bb - cc) / (e1 * bb + cc) * ph;
878                    }
879                    return Ok(out);
880                }
881                if (*layer_phase && b > bmax + 1e-12) || x < b2.0 - 1e-12 || x > b2.1 + 1e-12 {
882                    let top = b2.1.sqrt();
883                    notimpl!("coating model {name}: β = {b:.4} is outside the model range (β ≤ {top:.4}, BMAX {bmax})");
884                }
885                if n2 * n2 <= x {
886                    // 後ろの媒質で全反射(光線の追跡ではその前に止まる)
887                    return Ok([C64::new(0.0, 0.0); 2]);
888                }
889                let n_out = if *reverse { *n2 } else { self.n1 };
890                let co = (1.0 - x / (n_out * n_out)).max(0.0).sqrt();
891                if co == 0.0 {
892                    notimpl!("coating transmission: total reflection in the outer medium n = {n_out} (β = {b})");
893                }
894                let k = 2.0 * PI / self.wl;
895                let ph = C64::new(0.0, k * d * n_out / co).exp();
896                let mut out = [C64::new(0.0, 0.0); 2];
897                let mv = sp.eval(x, *layer_phase);
898                for (pol, o) in out.iter_mut().enumerate() {
899                    let g = if *layer_phase {
900                        C64::new(0.0, k * mv[pol].1).exp()
901                    } else {
902                        C64::new(1.0, 0.0)
903                    };
904                    let m: [C64; 4] = std::array::from_fn(|c| g * mv[pol].0[c]);
905                    let (m00, m10, m01, m11) = if *reverse {
906                        (m[3], m[1], m[2], m[0])
907                    } else {
908                        (m[0], m[1], m[2], m[3])
909                    };
910                    let e1 = admittance(self.n1, b, pol);
911                    let e2 = admittance(*n2, b, pol);
912                    let tp = e1 * 2.0 / (e1 * m00 + m10 + e1 * e2 * m01 + e2 * m11);
913                    *o = tp * (e2 / e1).sqrt() * ph;
914                }
915                out
916            }
917            Kind::ModelMirror {
918                name,
919                n_ref,
920                d,
921                b2,
922                r: rr,
923                branch,
924                band,
925            } => {
926                let b = self.n1 * s0;
927                let x = b * b;
928                let (lo, hi) = (b2[0], b2[b2.len() - 1]);
929                if x < lo - 1e-12 || x > hi + 1e-12 {
930                    let top = hi.sqrt();
931                    notimpl!("coating model {name} (mirror): β = {b:.4} is outside the model range (β ≤ {top:.4})");
932                }
933                if let Some((a, c)) = band {
934                    if *a <= x && x <= *c {
935                        let (lo, hi) = (a.sqrt(), c.sqrt());
936                        notimpl!("coating model {name} (mirror): β = {b:.5} is near where the outer medium turns to total reflection (β {lo:.5} to {hi:.5}); too few measured points to set the value");
937                    }
938                }
939                let k = 2.0 * PI / self.wl;
940                let ph = C64::new(0.0, 2.0 * k * self.n1 * c0 * d).exp();
941                let mut out = [C64::new(0.0, 0.0); 2];
942                for (pol, o) in out.iter_mut().enumerate() {
943                    let r = match branch.as_deref() {
944                        Some(bb) => bb.eval(x, &|j| rr[pol][j]),
945                        None => rational_at(b2, 0, b2.len(), x, &|j| rr[pol][j]),
946                    };
947                    let one = C64::new(1.0, 0.0);
948                    let y = admittance(*n_ref, b, pol) * (one - r) / (one + r);
949                    let e0 = admittance(self.n1, b, pol);
950                    *o = (e0 - y) / (e0 + y) * ph;
951                }
952                out
953            }
954        })
955    }
956}
957
958/// 補間に使う波長の一部にだけ鏡の分岐点([`mirror_branch`])があり、ほかの波長では一番大きい β まで全反射にならない
959/// (分岐点が測った β の範囲より上にある。層の屈折率が波長で変わり、範囲の上端を横切る)とき、notimpl にする β² の範囲。
960/// 分岐点のある波長の、全反射の手前の最後の点から上端まで。そこでは波長の補間が分岐点をまたぎ、両側を揃える
961/// 分岐点の位置もそろわないので値が決まらない(OpticStudio とガラス側の鏡で 3e-2 違った)
962fn partial_branch_band(
963    b2: &[f64],
964    r: &[Vec<[C64; 2]>],
965    brb: &[Option<MirrorBranch>],
966) -> Option<(f64, f64)> {
967    let n = b2.len();
968    let dev = |rw: &Vec<[C64; 2]>, j: usize| {
969        rw[j]
970            .iter()
971            .map(|v| (v.norm() - 1.0).abs())
972            .fold(0.0, f64::max)
973    };
974    // 波長ごとの分岐点の手前の点。見つかった分岐点か、上端に近すぎて mirror_branch が見ない分岐点(上端の点まで
975    // |r| = 1 が続き、その手前で |r| が 1 からはっきり離れている)か、上端のすぐ上の分岐点。上端でも |r| が 1 から離れている
976    // (分岐点が範囲のずっと上)は None、
977    // 全部 |r| = 1 に近い(分岐点の無い鏡)はこの帯を作らない
978    let mut lo: Option<f64> = None;
979    for (rw, b) in r.iter().zip(brb) {
980        let edge = match b {
981            Some(v) => Some(v.k - 1),
982            None => {
983                let kt = (0..n)
984                    .rev()
985                    .find(|&j| !(dev(rw, j) < MIRROR_TIR_TOL))
986                    .map_or(0, |j| j + 1);
987                if kt == n {
988                    let lossy = rw[n.saturating_sub(6)..]
989                        .iter()
990                        .flatten()
991                        .any(|v| (v.norm() - 1.0).abs() >= MIRROR_BRANCH_MIN_DEV);
992                    if !lossy {
993                        return None;
994                    }
995                    // 分岐点が上端のすぐ上(2 刻み以内)にあるか。分岐点の手前では 1 − |r| が sqrt(xb − β²) で 0 に向かうので、
996                    // 上端の 2 点の (1 − |r|)² を β² で直線に外挿して 0 になる所を分岐点とみる。上端の点のすぐ外の sqrt の曲がりで、
997                    // 最後の刻みの補間が 2e-3 ずれた
998                    let (h, d1, d2) = (b2[n - 1] - b2[n - 2], dev(rw, n - 1), dev(rw, n - 2));
999                    let slope = (d1 * d1 - d2 * d2) / h;
1000                    (d1 < d2 && slope < 0.0 && -d1 * d1 / slope < 2.0 * h).then_some(n - 1)
1001                    // 8 は分岐点として扱うのに要る両側 4 点に余裕を見たもの。それより長い全反射の続きは分岐点として見つかる
1002                } else if kt >= 1 && n - kt < 8 && dev(rw, kt - 1) >= MIRROR_BRANCH_MIN_DEV {
1003                    Some(kt - 1)
1004                } else {
1005                    return None;
1006                }
1007            }
1008        };
1009        if let Some(e) = edge {
1010            // その 2 点下から。分岐点に揃えずに補間するので、すぐ下でも分岐点の sqrt の曲がりで 1e-4 ほどずれる
1011            let e = e.saturating_sub(2);
1012            lo = Some(lo.map_or(b2[e], |l: f64| l.min(b2[e])));
1013        }
1014    }
1015    lo.map(|l| (l, b2[n - 1]))
1016}