Skip to main content

lensbench_core/
usercoating.rs

1//! 利用者が足す膜の口: 膜のファイル形式(拡張子ごとの読み手、[`CoatingSource`])と、名前つきの膜の一覧
2//! ([`CoatingCatalog`])を拡張の表に足す([`crate::ext::Ext::add_coating_source`]・
3//! [`crate::ext::Ext::add_coating_catalog`])。
4//!
5//! 膜の中身は今ある型([`CoatingSet`]: 層の並びとその材料・TABLE・特性行列のモデル・実測表)か、係数を計算で返す
6//! 利用者の膜([`CoatingModel`])。膜の計算は同梱の膜と同じ経路([`crate::coating::Iface`])を通る。
7//!
8//! 系の面の膜の名前は、次の順に引く(上ほど先。大文字小文字は問わない):
9//!
10//! 1. 系に書いた表(フィルタ)
11//! 2. 明示して読んだモデル・実測表([`crate::coating::Coatings::load_file`]、CLI の `--coatings`)
12//! 3. 登録した膜の一覧([`CoatingCatalog`])
13//! 4. 系の膜ファイル(.zmx の COFN、COATING.DAT の形式)の COAT・TABLE
14//! 5. 膜ファイルのフォルダの `<膜の名前>.lbcb`・`.lbcm`・`.lbct`・`.lbcs` と、登録した形式の `<膜の名前>.<拡張子>`
15//! 6. 共有の置き場([`crate::coating::set_remote_loader`])
16//!
17//! 一覧の膜と同じ名前の膜が系の表・膜ファイル・フォルダにあれば、先のものを使い注意を返す
18//! ([`crate::coating::Coatings::notes`])。拡張を入れると、同じ .zmx でも膜ファイルの膜が一覧の膜に替わる。
19//! 2 つの登録した一覧に同じ名前の膜があると、`Extensions` を入れる時の誤り(表に直接足したときは一覧の名前の順で先)。
20//!
21//! 約束:
22//! - [`CoatingSource::load`] は状態を持たず、どのスレッドから呼んでもよい。ファイルの膜の名前はファイル名
23//!   (拡張子なし)と同じにする(大文字小文字は問わない)
24//! - 膜の名前に `|` を含めず、`-` そのものと `I.` で始まる名前にしない(境界の鍵・膜なし・理想膜と区別できない)
25//! - 1 つの膜の名前は、層の並び・TABLE か、モデル・実測表か、利用者の膜([`CoatingModel`])のどれか 1 つだけに使う
26//!   (層・TABLE があるとモデル・実測表は使われない)
27//! - 層の材料は、組の [`CoatingSet::mate`] か系のガラスの表で引く。系の膜ファイルに同じ名前の違う材料があれば、
28//!   組の材料を `<材料>@<一覧の名前(ファイルなら名前)>` に名前を替えて入れる(系の膜ファイルの材料は変えない)
29
30use std::collections::HashMap;
31use std::path::Path;
32use std::sync::Arc;
33
34use crate::coating::{CoatModel, CoatingFile, Layer, Measured, Table, C64};
35use crate::{invalid, Result};
36
37/// 利用者の膜の境界の通り方
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum CoatPath {
41    /// 透過(屈折面)。[`CoatCoefs::ts`]・[`CoatCoefs::tp`] を使う
42    Transmit,
43    /// 鏡。[`CoatCoefs::rs`]・[`CoatCoefs::rp`] を使う([`CoatInput::n2`] は NaN)
44    Mirror,
45    /// 屈折面での反射(ゴーストの経路)。[`CoatCoefs::rs`]・[`CoatCoefs::rp`] を使う
46    Reflect,
47}
48
49/// 利用者の膜に渡す境界の条件
50#[derive(Debug, Clone, Copy, PartialEq)]
51#[non_exhaustive]
52pub struct CoatInput {
53    /// 波長 [µm]
54    pub wl: f64,
55    /// 入射側の媒質の屈折率
56    pub n1: f64,
57    /// 反対側の媒質の屈折率(透過では後ろ、屈折面での反射では反対側。鏡では NaN)
58    pub n2: f64,
59    /// 入射角の cos(0〜1、入射側の媒質で)
60    pub cos1: f64,
61    pub path: CoatPath,
62    /// 基板の側から入る(透過で後ろが空気、屈折面での反射で反対側が空気のとき。膜は空気の側に付いているとみなす。
63    /// 鏡では false)
64    pub from_substrate: bool,
65}
66
67impl CoatInput {
68    /// 境界の条件(試験・膜の確かめ用)
69    pub fn new(wl: f64, n1: f64, n2: f64, cos1: f64, path: CoatPath, from_substrate: bool) -> Self {
70        CoatInput {
71            wl,
72            n1,
73            n2,
74            cos1,
75            path,
76            from_substrate,
77        }
78    }
79}
80
81/// 利用者の膜の複素振幅係数(s・p の反射と透過)
82#[derive(Debug, Clone, Copy, PartialEq, Default)]
83pub struct CoatCoefs {
84    pub rs: C64,
85    pub rp: C64,
86    pub ts: C64,
87    pub tp: C64,
88}
89
90/// 利用者が係数を計算で返す膜。登録した膜の一覧([`CoatingSet::add_user`])か膜のファイル形式から、膜の名前で引く。
91///
92/// 約束(同梱の膜と同じ。膜なしのフレネルの係数はこの約束を満たす):
93/// - 係数はパワーで規格化した複素振幅(|t|² が強度透過率)。s・p の基底は各側で p = s × k
94/// - 伝搬の位相は含めない。位相の基準は面の頂点(基板の面)。鏡・屈折面での反射の p は反射の後で反転する約束
95///   (垂直入射で rs = rp)
96/// - 吸収がなければ |rs|² + |ts|² = |rp|² + |tp|² = 1、吸収があれば 1 より小さい
97/// - 状態を持たず、どのスレッドから呼んでもよい(光線ごとに呼ぶ)。求められない条件は誤りを返す
98pub trait CoatingModel: Send + Sync + std::fmt::Debug {
99    /// 係数([`CoatInput::path`] の使わない側は 0 でよい)
100    fn coefs(&self, x: &CoatInput) -> Result<CoatCoefs>;
101    /// 1 行の説明(CLI の coatings の注記)
102    fn doc(&self) -> String {
103        String::new()
104    }
105    /// [`check_coating_model`] で確かめる波長 [µm](既定は F・d・C 線)
106    fn example_wavelengths(&self) -> Vec<f64> {
107        vec![0.4861327, 0.5875618, 0.6562725]
108    }
109}
110
111/// 利用者の膜が約束を守るかを確かめる(拡張の試験から呼ぶ): [`CoatingModel::example_wavelengths`] の波長で、空気 → 硝材・
112/// 硝材 → 空気の透過と屈折面での反射、鏡について、0〜89° の入射角(透過・反射は全反射の手前まで)で、係数が有限、
113/// |r|² + |t|² ≤ 1(s・p ごと。鏡は |r|² ≤ 1)、垂直入射で s と p が同じ
114pub fn check_coating_model(m: &dyn CoatingModel) -> Result<()> {
115    const TOL: f64 = 1e-9;
116    let wls = m.example_wavelengths();
117    if wls.is_empty() || wls.iter().any(|w| !(*w > 0.0 && w.is_finite())) {
118        invalid!("example wavelengths {wls:?} are not positive numbers");
119    }
120    let cases = [
121        (1.0, 1.5, CoatPath::Transmit, false),
122        (1.5, 1.0, CoatPath::Transmit, true),
123        (1.0, 1.5, CoatPath::Reflect, false),
124        (1.5, 1.0, CoatPath::Reflect, true),
125        (1.0, f64::NAN, CoatPath::Mirror, false),
126    ];
127    for &wl in &wls {
128        for &(n1, n2, path, from_substrate) in &cases {
129            for deg in (0..90).step_by(5).chain([89]) {
130                let (s1, c1) = (deg as f64).to_radians().sin_cos();
131                if path != CoatPath::Mirror && n1 * s1 >= n2 {
132                    break;
133                }
134                let x = CoatInput::new(
135                    wl,
136                    n1,
137                    n2,
138                    if deg == 0 { 1.0 } else { c1 },
139                    path,
140                    from_substrate,
141                );
142                let at = format!("{path:?} n1={n1} n2={n2} {deg}° {wl} µm");
143                let c = m
144                    .coefs(&x)
145                    .map_err(|e| crate::Error::Invalid(format!("{at}: {e}")))?;
146                let fin = |z: &C64| z.re.is_finite() && z.im.is_finite();
147                let used = match path {
148                    CoatPath::Transmit => [c.ts, c.tp],
149                    _ => [c.rs, c.rp],
150                };
151                // 鏡は r だけ、透過・屈折面での反射は r と t の両方(エネルギーの検査に使う)
152                let all = path == CoatPath::Mirror || [c.rs, c.rp, c.ts, c.tp].iter().all(fin);
153                if !used.iter().all(fin) || !all {
154                    invalid!("{at}: the coefficients are not finite ({c:?})");
155                }
156                let e = |r: C64, t: C64| {
157                    if path == CoatPath::Mirror {
158                        r.norm_sqr()
159                    } else {
160                        r.norm_sqr() + t.norm_sqr()
161                    }
162                };
163                if e(c.rs, c.ts) > 1.0 + TOL || e(c.rp, c.tp) > 1.0 + TOL {
164                    invalid!("{at}: |r|² + |t|² is more than 1 ({c:?})");
165                }
166                if deg == 0 && (used[0] - used[1]).norm() > 1e-9 * (1.0 + used[0].norm()) {
167                    invalid!("{at}: s and p differ at normal incidence ({c:?})");
168                }
169            }
170        }
171    }
172    Ok(())
173}
174
175/// 膜の組: 名前つきの膜(層の並び・TABLE・特性行列のモデル・実測表)と、層の材料。
176/// 膜の種類は今後足すことがあるので(利用者が計算を書く膜など)、`CoatingSet::default()` から欄に足して作る
177#[derive(Debug, Clone, Default)]
178#[non_exhaustive]
179pub struct CoatingSet {
180    /// 層の材料: 波長 [µm]・n・k(COATING.DAT の MATE。k < 0 で吸収、波長の昇順)
181    pub mate: HashMap<String, Vec<[f64; 3]>>,
182    /// 膜の名前 → 層の並び(COATING.DAT の COAT。入射側から)
183    pub coat: HashMap<String, Vec<Layer>>,
184    /// 膜の名前 → 表(COATING.DAT の TABLE)
185    pub table: HashMap<String, Table>,
186    /// 膜の名前 → 特性行列のモデル(`.lbcm`・`.lbcb`)
187    pub models: HashMap<String, CoatModel>,
188    /// 境界の鍵(`膜|前の媒質|後の媒質`、鏡は後が `MIRROR`)→ 実測表(`.lbct`)
189    pub measured: HashMap<String, Measured>,
190    /// 膜の名前 → 係数を計算で返す利用者の膜
191    pub user: HashMap<String, Arc<dyn CoatingModel>>,
192}
193
194impl CoatingSet {
195    pub fn new() -> Self {
196        Self::default()
197    }
198
199    /// COATING.DAT の形式の文から(MATE・COAT・TABLE)
200    pub fn parse_dat(txt: &str) -> Result<Self> {
201        Ok(Self::from_file(CoatingFile::parse(txt)?))
202    }
203
204    /// 膜ファイルの中身から
205    pub fn from_file(f: CoatingFile) -> Self {
206        CoatingSet {
207            mate: f.mate,
208            coat: f.coat,
209            table: f.table,
210            ..Self::default()
211        }
212    }
213
214    /// 層の並びの膜を足す(同じ名前は差し替える)
215    pub fn add_layers(&mut self, name: &str, layers: Vec<Layer>) -> &mut Self {
216        self.coat.insert(name.to_string(), layers);
217        self
218    }
219
220    /// 層の材料を足す(行は 波長 [µm]・n・k、波長の昇順)
221    pub fn add_material(&mut self, name: &str, rows: Vec<[f64; 3]>) -> &mut Self {
222        self.mate.insert(name.to_string(), rows);
223        self
224    }
225
226    /// 係数を計算で返す利用者の膜を足す(同じ名前は差し替える)
227    pub fn add_user(&mut self, name: &str, model: Arc<dyn CoatingModel>) -> &mut Self {
228        self.user.insert(name.to_string(), model);
229        self
230    }
231
232    /// 特性行列のモデルの文(`.lbcm`、[`crate::coating::parse_models`] の形式)を足す
233    pub fn add_models_text(&mut self, txt: &str) -> Result<&mut Self> {
234        self.models.extend(crate::coating::parse_models(txt)?);
235        Ok(self)
236    }
237
238    /// 実測表の文(`.lbct`、[`crate::coating::parse_measured`] の形式)を足す
239    pub fn add_measured_text(&mut self, txt: &str) -> Result<&mut Self> {
240        self.measured.extend(crate::coating::parse_measured(txt)?);
241        Ok(self)
242    }
243
244    /// 膜のファイルを読んで足し、足した膜の数を返す: 特性行列のモデル(`.lbcm`・`.lbcb`)・実測表(`.lbct`)は
245    /// 1 行目で、それ以外は COATING.DAT の形式(`.dat`・`.lbcs` など。MATE・COAT・TABLE)として読む
246    pub fn add_file(&mut self, path: &Path) -> Result<usize> {
247        use crate::coating::{is_models_bin, parse_models, parse_models_bin, MODEL_HEADER};
248        let at = |e: crate::Error| match e {
249            crate::Error::Invalid(m) => crate::Error::Invalid(format!("{}: {m}", path.display())),
250            e => e,
251        };
252        let b = crate::vfs::read(path)
253            .map_err(|e| crate::Error::Io(format!("{}: {e}", path.display())))?;
254        if is_models_bin(&b) {
255            let v = parse_models_bin(&b).map_err(at)?;
256            let n = v.len();
257            self.models.extend(v);
258            return Ok(n);
259        }
260        let txt = String::from_utf8_lossy(&b);
261        let first = txt
262            .lines()
263            .map(str::trim)
264            .find(|l| !l.is_empty() && !l.starts_with('#'))
265            .unwrap_or("");
266        if first == MODEL_HEADER {
267            let v = parse_models(&txt).map_err(at)?;
268            let n = v.len();
269            self.models.extend(v);
270            Ok(n)
271        } else if first == crate::coating::MEASURED_HEADER {
272            let v = crate::coating::parse_measured(&txt).map_err(at)?;
273            let n = v.len();
274            self.measured.extend(v);
275            Ok(n)
276        } else {
277            let f = CoatingFile::parse(&txt).map_err(at)?;
278            let n = f.coat.len() + f.table.len();
279            self.mate.extend(f.mate);
280            self.coat.extend(f.coat);
281            self.table.extend(f.table);
282            Ok(n)
283        }
284    }
285
286    /// 膜の名前(足したときの綴り、名前の順、重なりなし)
287    pub fn names(&self) -> Vec<String> {
288        let mut v: Vec<String> = self
289            .coat
290            .keys()
291            .chain(self.table.keys())
292            .chain(self.models.keys())
293            .chain(self.user.keys())
294            .cloned()
295            .chain(
296                self.measured
297                    .keys()
298                    .map(|k| k.split('|').next().unwrap_or("").to_string()),
299            )
300            .collect();
301        v.sort();
302        v.dedup();
303        v
304    }
305
306    /// 名前の膜があるか(大文字小文字は問わない)
307    pub fn contains(&self, name: &str) -> bool {
308        let eq = |k: &String| k.eq_ignore_ascii_case(name);
309        self.coat.keys().any(eq)
310            || self.table.keys().any(eq)
311            || self.models.keys().any(eq)
312            || self.user.keys().any(eq)
313            || self.measured.keys().any(|k| {
314                k.split('|')
315                    .next()
316                    .is_some_and(|c| c.eq_ignore_ascii_case(name))
317            })
318    }
319}
320
321/// 膜のファイル形式(拡張子ごとの読み手)。膜ファイルのフォルダの `<膜の名前>.<拡張子>` を膜の名前で読む。
322/// 明示して読むファイル([`crate::coating::Coatings::load_file`])も拡張子でこの読み手を選ぶ
323pub trait CoatingSource: Send + Sync {
324    /// この実装が読める拡張子(小文字、ドットなし)。同梱の形式(lbcb・lbcm・lbct・lbcs)と同じなら、こちらが勝つ
325    fn extensions(&self) -> &[&str];
326    /// ファイルを読み、膜の組を返す(読めなければ `Error::Io`、中身の誤りは `Error::Invalid` など)
327    fn load(&self, path: &Path) -> Result<CoatingSet>;
328}
329
330/// 名前つきの膜の一覧(カタログの単位)
331#[derive(Debug, Clone)]
332pub struct CoatingCatalog {
333    pub name: String,
334    set: CoatingSet,
335}
336
337impl CoatingCatalog {
338    pub fn new(name: &str, set: CoatingSet) -> Self {
339        CoatingCatalog {
340            name: name.to_string(),
341            set,
342        }
343    }
344
345    /// 膜の組
346    pub fn set(&self) -> &CoatingSet {
347        &self.set
348    }
349}
350
351/// 膜の名前が約束(`|` を含まない、`-` そのものでも `I.` で始まるのでもない、空でない)を守るか
352fn check_name(name: &str) -> Result<()> {
353    if name.is_empty() || name.contains('|') || name == "-" || name.starts_with("I.") {
354        invalid!("coating name {name:?} is not allowed (empty, contains |, or is - or I.xx)");
355    }
356    Ok(())
357}
358
359/// 膜の組が約束を守るかを確かめる(拡張の試験から呼ぶ): 膜の名前、材料の行(波長が正で昇順、n が正、k ≤ 0)、
360/// 層の厚さが有限で 0 以上、TABLE の角度の昇順、実測表の大きさと角度の昇順、モデルに透過か鏡のデータがあること、
361/// 利用者の膜が約束を守ること([`check_coating_model`])
362pub fn check_coatings(set: &CoatingSet) -> Result<()> {
363    for n in set.names() {
364        check_name(&n)?;
365    }
366    for n in set.coat.keys().chain(set.table.keys()) {
367        let pre = format!("{}|", n.to_ascii_uppercase());
368        if set.models.keys().any(|m| m.eq_ignore_ascii_case(n))
369            || set
370                .measured
371                .keys()
372                .any(|k| k.to_ascii_uppercase().starts_with(&pre))
373        {
374            invalid!("coating {n} has layers or a table and also a model or measured table; use one of them");
375        }
376    }
377    for (m, rows) in &set.mate {
378        if rows.is_empty() {
379            invalid!("coating material {m} has no data");
380        }
381        if rows.windows(2).any(|w| !(w[0][0] < w[1][0])) || rows.iter().any(|r| !(r[0] > 0.0)) {
382            invalid!("coating material {m}: the wavelengths are not positive and ascending");
383        }
384        if rows
385            .iter()
386            .any(|r| !(r[1] > 0.0) || !(r[2] <= crate::coating::MATE_K_POS_TOL))
387        {
388            invalid!("coating material {m}: n must be positive and k ≤ 0 (absorption is k < 0)");
389        }
390    }
391    for (c, ls) in &set.coat {
392        if ls.is_empty() {
393            invalid!("coating {c} has no layers");
394        }
395        for l in ls {
396            if !(l.d.is_finite() && l.d >= 0.0) {
397                invalid!(
398                    "coating {c}: the thickness {} of layer {} is not a number ≥ 0",
399                    l.d,
400                    l.mat
401                );
402            }
403        }
404    }
405    for (c, t) in &set.table {
406        if t.is_empty() {
407            invalid!("coating table {c} has no data");
408        }
409        if t.windows(2).any(|w| !(w[0].0 < w[1].0)) {
410            invalid!("coating table {c}: the angles are not ascending");
411        }
412    }
413    for (k, m) in &set.measured {
414        if k.split('|').count() < 3 {
415            invalid!("measured table key {k} is not coating|medium before|medium after");
416        }
417        if m.data.len() != m.wavelengths.len()
418            || m.data.iter().any(|r| r.len() != m.angles_deg.len())
419        {
420            invalid!("size of measured table {k}");
421        }
422        if m.angles_deg.windows(2).any(|w| !(w[0] < w[1])) {
423            invalid!("the angles of measured table {k} are not ascending");
424        }
425    }
426    for (c, m) in &set.models {
427        if m.wavelengths.is_empty() && m.mirror.is_none() {
428            invalid!("coating model {c} has neither transmission nor mirror data");
429        }
430    }
431    for (c, m) in &set.user {
432        let pre = format!("{}|", c.to_ascii_uppercase());
433        let eq = |k: &String| k.eq_ignore_ascii_case(c);
434        if set.coat.keys().any(eq)
435            || set.table.keys().any(eq)
436            || set.models.keys().any(eq)
437            || set
438                .measured
439                .keys()
440                .any(|k| k.to_ascii_uppercase().starts_with(&pre))
441        {
442            invalid!("coating {c} is a user coating and also has layers, a table, a model or a measured table; use one of them");
443        }
444        check_coating_model(m.as_ref()).map_err(|e| match e {
445            crate::Error::Invalid(x) => crate::Error::Invalid(format!("user coating {c}: {x}")),
446            e => e,
447        })?;
448    }
449    Ok(())
450}