Skip to main content

lensbench_core/coating/format/
lbct.rs

1//! 実測表 LBCT(テキスト)の読み書き
2
3use super::super::*;
4
5/// 暗号化された膜の実測の係数: 波長ごと・入射角ごとの (s, p)(透過、鏡では反射)。
6/// 全反射より先の角度は NaN にしておく(補間に使わない)。
7#[derive(Debug, Clone)]
8pub struct Measured {
9    pub wavelengths: Vec<f64>,
10    /// 入射角 [deg]、昇順
11    pub angles_deg: Vec<f64>,
12    /// [波長][角度] → (s, p)
13    pub data: Vec<Vec<[C64; 2]>>,
14}
15
16/// 読込中の KEY: (キー, [(波長, [(角度, (s, p))])])
17pub(in crate::coating) type Pending = (String, Vec<(f64, Vec<(f64, [C64; 2])>)>);
18
19/// 実測表のファイル形式の 1 行目
20pub const MEASURED_HEADER: &str = "LBCT 1";
21
22/// 実測表のファイル(テキスト、UTF-8)を読む。
23///
24/// ```text
25/// LBCT 1
26/// # コメント
27/// KEY 膜|前の媒質|後の媒質(鏡は MIRROR)
28/// WAVE 波長 [µm]
29/// 入射角 [deg]  Re s  Im s  Re p  Im p      (角度の昇順。全反射より先は nan)
30/// ...
31/// WAVE ...
32/// KEY ...
33/// ```
34///
35/// 係数は OpticStudio の偏光追跡の約束(透過、鏡では反射。パワー規格化、p = s × k、伝搬の位相なし)。
36/// 1 つの KEY の中では、どの波長も同じ角度の並びにする。
37pub fn parse_measured(txt: &str) -> Result<Vec<(String, Measured)>> {
38    let mut out: Vec<(String, Measured)> = Vec::new();
39    let mut header = false;
40    // 今の KEY の (波長, [(角度, s, p)])
41    let mut cur: Option<Pending> = None;
42    fn finish(cur: Option<Pending>, out: &mut Vec<(String, Measured)>) -> Result<()> {
43        let Some((key, waves)) = cur else {
44            return Ok(());
45        };
46        if waves.is_empty() || waves.iter().any(|w| w.1.is_empty()) {
47            invalid!("measured table {key} has no data");
48        }
49        let angles: Vec<f64> = waves[0].1.iter().map(|r| r.0).collect();
50        if waves
51            .iter()
52            .any(|w| w.1.iter().map(|r| r.0).ne(angles.iter().copied()))
53        {
54            invalid!("measured table {key}: the angles differ between wavelengths");
55        }
56        if out.iter().any(|(k, _)| *k == key) {
57            invalid!("measured table {key} appears twice");
58        }
59        let m = Measured {
60            wavelengths: waves.iter().map(|w| w.0).collect(),
61            angles_deg: angles,
62            data: waves
63                .iter()
64                .map(|w| w.1.iter().map(|r| r.1).collect())
65                .collect(),
66        };
67        out.push((key, m));
68        Ok(())
69    }
70    for (ln, line) in txt.lines().enumerate() {
71        let line = line.trim();
72        if line.is_empty() || line.starts_with('#') {
73            continue;
74        }
75        if !header {
76            if line != MEASURED_HEADER {
77                invalid!("line 1 of the measured table is not {MEASURED_HEADER}");
78            }
79            header = true;
80            continue;
81        }
82        let n = |s: &str| -> Result<f64> {
83            s.parse::<f64>()
84                .map_err(|_| Error::Invalid(format!("measured table line {} number {s}", ln + 1)))
85        };
86        if let Some(k) = line.strip_prefix("KEY ") {
87            finish(cur.take(), &mut out)?;
88            cur = Some((k.trim().to_string(), Vec::new()));
89        } else if let Some(w) = line.strip_prefix("WAVE ") {
90            let Some(c) = cur.as_mut() else {
91                invalid!("measured table line {}: WAVE before KEY", ln + 1);
92            };
93            c.1.push((n(w.trim())?, Vec::new()));
94        } else {
95            let t: Vec<&str> = line.split_whitespace().collect();
96            let Some(w) = cur.as_mut().and_then(|c| c.1.last_mut()) else {
97                invalid!("measured table line {}: data before WAVE", ln + 1);
98            };
99            if t.len() != 5 {
100                let line = ln + 1;
101                invalid!(
102                    "measured table line {line}: an angle and 4 coefficients (Re s Im s Re p Im p)"
103                );
104            }
105            let a = n(t[0])?;
106            if let Some(&(b, _)) = w.1.last() {
107                if !(a > b) {
108                    let line = ln + 1;
109                    invalid!("measured table line {line}: the angles are not ascending");
110                }
111            }
112            let v = [C64::new(n(t[1])?, n(t[2])?), C64::new(n(t[3])?, n(t[4])?)];
113            w.1.push((a, v));
114        }
115    }
116    if !header {
117        invalid!("the measured table is empty");
118    }
119    finish(cur, &mut out)?;
120    Ok(out)
121}
122
123/// 実測表をファイルの形式([`parse_measured`])にする
124pub fn format_measured(entries: &[(&str, &Measured)]) -> String {
125    use std::fmt::Write;
126    let mut s = format!("{MEASURED_HEADER}\n");
127    for (k, m) in entries {
128        writeln!(s, "KEY {k}").expect("write to String");
129        for (w, row) in m.wavelengths.iter().zip(&m.data) {
130            writeln!(s, "WAVE {w:?}").expect("write to String");
131            for (a, v) in m.angles_deg.iter().zip(row) {
132                writeln!(
133                    s,
134                    "{a:?} {:?} {:?} {:?} {:?}",
135                    v[0].re, v[0].im, v[1].re, v[1].im
136                )
137                .expect("write to String");
138            }
139        }
140    }
141    s
142}