Skip to main content

lensbench_project/
filter.rs

1//! フィルタ・ダイクロイックの透過特性: プロジェクト・ユーザーカタログの `coatings`(名前 → 膜の書き方)を
2//! TABLE 膜(角度・波長ごとの Rs Rp Ts Tp、[`lensbench_core::coating`])にする。面の `coat` に名前を書いて使う。
3//!
4//! - `table`: 測った・メーカーの表をそのまま(行 [入射角 deg, 波長 µm, Rs, Rp, Ts, Tp])
5//! - `curve`: 波長ごとの透過(と反射)。角度・偏光によらない(色ガラス・吸収型 ND を 1 面で表すときなど)
6//! - `longpass`・`shortpass`・`bandpass`・`notch`・`nd`: 仕様からの理想の形。帯域内の透過 `t`、帯域外は
7//!   OD(T = 10^−od)、エッジは 10〜90 % の幅 `width_nm` のロジスティック。斜め入射ではエッジが
8//!   λ(θ) = λ0·√(1 − (sinθ / neff)²) へ短波長側にずれる(s・p は同じ)。反射は 1 − T(`absorptive` なら 0)
9//!
10//! 位相は 0(TABLE 膜の位相を書かない)。
11
12use lensbench_core::coating::Table;
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16fn d_t() -> f64 {
17    0.95
18}
19fn d_od() -> f64 {
20    4.0
21}
22fn d_neff() -> f64 {
23    2.0
24}
25
26/// 理想フィルタの共通の項目
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
28pub struct Ideal {
29    /// 帯域内の透過率(0〜1)
30    #[serde(default = "d_t")]
31    pub t: f64,
32    /// 帯域外(阻止域)の光学濃度(T = 10^−od)
33    #[serde(default = "d_od")]
34    pub od: f64,
35    /// エッジの幅 [nm](透過が 10 % から 90 % まで。省略は 1 % のエッジ波長、帯域フィルタは FWHM の 10 %)
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub width_nm: Option<f64>,
38    /// 斜め入射でのエッジのずれの実効屈折率
39    #[serde(default = "d_neff")]
40    pub neff: f64,
41    /// 反射を 0 にする(吸収型)。省略は反射 = 1 − 透過(干渉型・ダイクロイック)
42    #[serde(default)]
43    pub absorptive: bool,
44}
45
46/// プロジェクト・カタログの `coatings` の 1 つ
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
48#[serde(tag = "type", rename_all = "snake_case")]
49pub enum CoatSpec {
50    /// 表: 行 [入射角 deg, 波長 µm, Rs, Rp, Ts, Tp]
51    Table { rows: Vec<[f64; 6]> },
52    /// 波長 [nm] ごとの透過 `t`(と反射 `r`、省略は 0)。角度・偏光によらない
53    Curve {
54        wavelengths_nm: Vec<f64>,
55        t: Vec<f64>,
56        #[serde(default, skip_serializing_if = "Vec::is_empty")]
57        r: Vec<f64>,
58    },
59    /// エッジ `edge_nm`(透過 50 %)より長い波長を通す
60    Longpass {
61        edge_nm: f64,
62        #[serde(flatten)]
63        ideal: Ideal,
64    },
65    /// エッジより短い波長を通す
66    Shortpass {
67        edge_nm: f64,
68        #[serde(flatten)]
69        ideal: Ideal,
70    },
71    /// 中心 `center_nm`・半値全幅 `fwhm_nm` を通す
72    Bandpass {
73        center_nm: f64,
74        fwhm_nm: f64,
75        #[serde(flatten)]
76        ideal: Ideal,
77    },
78    /// 中心・幅の帯域を od で止める(帯域外は t)
79    Notch {
80        center_nm: f64,
81        fwhm_nm: f64,
82        #[serde(flatten)]
83        ideal: Ideal,
84    },
85    /// 波長によらない ND(T = 10^−od)
86    Nd {
87        od: f64,
88        #[serde(default)]
89        absorptive: bool,
90    },
91}
92
93/// 表の入射角 [deg]
94const ANGLES: [f64; 13] = [
95    0.0, 5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0, 50.0, 60.0, 75.0,
96];
97/// 表の波長の範囲 [µm] と粗い刻み
98const WL: (f64, f64, f64) = (0.2, 2.5, 0.005);
99
100fn logistic(x: f64) -> f64 {
101    1.0 / (1.0 + (-x).exp())
102}
103
104/// 10〜90 % の幅 w のロジスティックの尺度(σ(x/s) が 0.1→0.9 になる x の幅が w)
105fn scale(w: f64) -> f64 {
106    w / (2.0 * 9f64.ln())
107}
108
109fn check01(v: f64, what: &str) -> lensbench_core::Result<()> {
110    if (0.0..=1.0).contains(&v) {
111        Ok(())
112    } else {
113        Err(format!("{what} {v} must be 0 to 1").into())
114    }
115}
116
117impl Ideal {
118    fn check(&self) -> lensbench_core::Result<()> {
119        check01(self.t, "filter transmittance")?;
120        if !(self.od >= 0.0 && self.od.is_finite()) {
121            return Err(format!("filter OD {}", self.od).into());
122        }
123        if !(self.neff >= 1.0 && self.neff.is_finite()) {
124            return Err(format!("filter neff {} (1 or more)", self.neff).into());
125        }
126        if let Some(w) = self.width_nm {
127            if !(w > 0.0 && w.is_finite()) {
128                return Err(format!("filter edge width {w} nm").into());
129            }
130        }
131        Ok(())
132    }
133    fn tmin(&self) -> f64 {
134        10f64.powf(-self.od).min(self.t)
135    }
136}
137
138fn pos(v: f64, what: &str) -> lensbench_core::Result<()> {
139    if v > 0.0 && v.is_finite() {
140        Ok(())
141    } else {
142        Err(format!("filter {what} {v}").into())
143    }
144}
145
146impl CoatSpec {
147    /// TABLE 膜の表(角度ごとの [波長, Rs, Rp, Ts, Tp, 位相 4 つ] の並び)
148    pub fn table(&self) -> lensbench_core::Result<Table> {
149        match self {
150            CoatSpec::Table { rows } => table_rows(rows),
151            CoatSpec::Curve {
152                wavelengths_nm,
153                t,
154                r,
155            } => {
156                if wavelengths_nm.len() < 2 || t.len() != wavelengths_nm.len() {
157                    return Err(
158                        "curve needs 2 or more points, and wavelengths_nm and t of the same count"
159                            .into(),
160                    );
161                }
162                if !r.is_empty() && r.len() != t.len() {
163                    return Err("curve r must have the same count as t".into());
164                }
165                if wavelengths_nm
166                    .windows(2)
167                    .any(|w| w[0].partial_cmp(&w[1]) != Some(std::cmp::Ordering::Less))
168                {
169                    return Err("the curve wavelengths are not ascending".into());
170                }
171                for (i, &x) in t.iter().enumerate() {
172                    check01(x, "curve t")?;
173                    let rr = r.get(i).copied().unwrap_or(0.0);
174                    check01(rr, "curve r")?;
175                    if x + rr > 1.0 + 1e-9 {
176                        return Err(
177                            format!("curve t + r is over 1 ({} nm)", wavelengths_nm[i]).into()
178                        );
179                    }
180                }
181                let rows: Vec<[f64; 9]> = wavelengths_nm
182                    .iter()
183                    .enumerate()
184                    .map(|(i, &l)| {
185                        let (tt, rr) = (t[i], r.get(i).copied().unwrap_or(0.0));
186                        [l * 1e-3, rr, rr, tt, tt, 0.0, 0.0, 0.0, 0.0]
187                    })
188                    .collect();
189                Ok(vec![(0.0, rows.clone()), (89.0, rows)])
190            }
191            CoatSpec::Nd { od, absorptive } => {
192                if !(*od >= 0.0 && od.is_finite()) {
193                    return Err(format!("ND OD {od}").into());
194                }
195                let t = 10f64.powf(-od);
196                let r = if *absorptive { 0.0 } else { 1.0 - t };
197                let rows = vec![
198                    [WL.0, r, r, t, t, 0.0, 0.0, 0.0, 0.0],
199                    [WL.1, r, r, t, t, 0.0, 0.0, 0.0, 0.0],
200                ];
201                Ok(vec![(0.0, rows.clone()), (89.0, rows)])
202            }
203            CoatSpec::Longpass { edge_nm, ideal } | CoatSpec::Shortpass { edge_nm, ideal } => {
204                ideal.check()?;
205                pos(*edge_nm, "edge wavelength")?;
206                let e = edge_nm * 1e-3;
207                let w = ideal.width_nm.map_or(0.01 * e, |w| w * 1e-3);
208                let long = matches!(self, CoatSpec::Longpass { .. });
209                Ok(sample(ideal, &[e], w, |l, sh| {
210                    let x = (l - e * sh) / scale(w);
211                    if long {
212                        logistic(x)
213                    } else {
214                        logistic(-x)
215                    }
216                }))
217            }
218            CoatSpec::Bandpass {
219                center_nm,
220                fwhm_nm,
221                ideal,
222            }
223            | CoatSpec::Notch {
224                center_nm,
225                fwhm_nm,
226                ideal,
227            } => {
228                ideal.check()?;
229                pos(*center_nm, "center wavelength")?;
230                pos(*fwhm_nm, "FWHM")?;
231                if fwhm_nm >= center_nm {
232                    return Err("the filter FWHM is not less than the center wavelength".into());
233                }
234                let (c, f) = (center_nm * 1e-3, fwhm_nm * 1e-3);
235                let w = ideal.width_nm.map_or(0.1 * f, |w| w * 1e-3);
236                let (lo, hi) = (c - f / 2.0, c + f / 2.0);
237                let band = matches!(self, CoatSpec::Bandpass { .. });
238                Ok(sample(ideal, &[lo, hi, c], w, |l, sh| {
239                    let s = scale(w);
240                    // 帯域の中(両側のエッジのロジスティックの積、帯域が狭くても中心で 1 になるよう正規化)
241                    let inside = |l: f64| logistic((l - lo * sh) / s) * logistic((hi * sh - l) / s);
242                    let v = inside(l) / inside(c * sh);
243                    if band {
244                        v
245                    } else {
246                        1.0 - v
247                    }
248                }))
249            }
250        }
251    }
252}
253
254/// 理想フィルタの表: 角度ごとに、粗い刻みとエッジの近く(ずれた位置の ±4 幅を幅の 1/10 で)の波長で
255/// 形 f(λ, ずれの比) ∈ [0, 1] を透過 tmin〜t に写す
256fn sample(ideal: &Ideal, edges: &[f64], w: f64, f: impl Fn(f64, f64) -> f64) -> Table {
257    let (t0, t1) = (ideal.tmin(), ideal.t);
258    ANGLES
259        .iter()
260        .map(|&a| {
261            let s = a.to_radians().sin() / ideal.neff;
262            let sh = (1.0 - s * s).sqrt();
263            let mut wl: Vec<f64> = Vec::new();
264            let n = ((WL.1 - WL.0) / WL.2).round() as usize;
265            wl.extend((0..=n).map(|i| WL.0 + i as f64 * WL.2));
266            let step = w / 10.0;
267            for &e in edges {
268                let e = e * sh;
269                wl.extend((-40..=40).map(|i| e + i as f64 * step));
270            }
271            wl.retain(|&l| l > 0.0);
272            wl.sort_by(f64::total_cmp);
273            wl.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
274            let rows = wl
275                .into_iter()
276                .map(|l| {
277                    let t = t0 + (t1 - t0) * f(l, sh).clamp(0.0, 1.0);
278                    let r = if ideal.absorptive { 0.0 } else { 1.0 - t };
279                    [l, r, r, t, t, 0.0, 0.0, 0.0, 0.0]
280                })
281                .collect();
282            (a, rows)
283        })
284        .collect()
285}
286
287fn table_rows(rows: &[[f64; 6]]) -> lensbench_core::Result<Table> {
288    let mut out: Table = Vec::new();
289    for r in rows {
290        if !r.iter().all(|v| v.is_finite()) {
291            return Err("a table value is not a number".into());
292        }
293        if !(0.0..90.0).contains(&r[0]) || r[1] <= 0.0 {
294            return Err(format!("table row angle {}, wavelength {}", r[0], r[1]).into());
295        }
296        for &v in &r[2..] {
297            check01(v, "table R or T")?;
298        }
299        let row = [r[1], r[2], r[3], r[4], r[5], 0.0, 0.0, 0.0, 0.0];
300        match out.iter_mut().find(|(a, _)| *a == r[0]) {
301            Some((_, v)) => v.push(row),
302            None => out.push((r[0], vec![row])),
303        }
304    }
305    if out.is_empty() {
306        return Err("no table rows".into());
307    }
308    out.sort_by(|a, b| a.0.total_cmp(&b.0));
309    for (a, v) in &mut out {
310        v.sort_by(|x, y| x[0].total_cmp(&y[0]));
311        if v.windows(2).any(|w| w[0][0] == w[1][0]) {
312            return Err(format!("two rows with the same wavelength at table angle {a}").into());
313        }
314    }
315    Ok(out)
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    /// 表の (角度, 波長) の透過(角度は表にある値、波長は線形補間)
323    fn t_at(t: &Table, a: f64, l: f64) -> f64 {
324        let rows = &t.iter().find(|x| x.0 == a).unwrap().1;
325        let xs: Vec<f64> = rows.iter().map(|r| r[0]).collect();
326        let ys: Vec<f64> = rows.iter().map(|r| r[3]).collect();
327        lensbench_core::coating::interp(l, &xs, &ys)
328    }
329
330    fn ideal() -> Ideal {
331        serde_json::from_str("{}").unwrap()
332    }
333
334    #[test]
335    fn longpass_edge_od_and_shift() {
336        let c = CoatSpec::Longpass {
337            edge_nm: 600.0,
338            ideal: Ideal {
339                width_nm: Some(10.0),
340                ..ideal()
341            },
342        };
343        let t = c.table().unwrap();
344        assert!((t_at(&t, 0.0, 0.6) - (1e-4 + (0.95 - 1e-4) * 0.5)).abs() < 1e-9);
345        assert!((t_at(&t, 0.0, 0.8) - 0.95).abs() < 1e-9);
346        assert!((t_at(&t, 0.0, 0.4) - 1e-4).abs() < 1e-9);
347        // 10〜90 % の幅
348        let f = |l: f64| (t_at(&t, 0.0, l) - 1e-4) / (0.95 - 1e-4);
349        assert!((f(0.605) - 0.9).abs() < 1e-3 && (f(0.595) - 0.1).abs() < 1e-3);
350        // 45° ではエッジが 600·√(1 − (sin45°/2)²) nm へ
351        let e45 = 0.6 * (1.0 - (45f64.to_radians().sin() / 2.0).powi(2)).sqrt();
352        assert!((f_at(&t, 45.0, e45) - 0.5).abs() < 1e-6, "{e45}");
353        // 反射は 1 − T
354        let r = &t[0].1[0];
355        assert!((r[1] + r[3] - 1.0).abs() < 1e-12);
356    }
357
358    fn f_at(t: &Table, a: f64, l: f64) -> f64 {
359        (t_at(t, a, l) - 1e-4) / (0.95 - 1e-4)
360    }
361
362    #[test]
363    fn bandpass_notch_nd_curve() {
364        let b = CoatSpec::Bandpass {
365            center_nm: 532.0,
366            fwhm_nm: 10.0,
367            ideal: ideal(),
368        };
369        let t = b.table().unwrap();
370        assert!((t_at(&t, 0.0, 0.532) - 0.95).abs() < 1e-6);
371        assert!((f_at(&t, 0.0, 0.527) - 0.5).abs() < 0.02);
372        assert!((t_at(&t, 0.0, 0.6) - 1e-4).abs() < 1e-9);
373        let n = CoatSpec::Notch {
374            center_nm: 532.0,
375            fwhm_nm: 10.0,
376            ideal: Ideal { od: 6.0, ..ideal() },
377        };
378        let t = n.table().unwrap();
379        assert!((t_at(&t, 0.0, 0.532) - 1e-6).abs() < 1e-8);
380        assert!((t_at(&t, 0.0, 0.7) - 0.95).abs() < 1e-9);
381        let nd = CoatSpec::Nd {
382            od: 1.0,
383            absorptive: true,
384        };
385        let t = nd.table().unwrap();
386        assert!((t_at(&t, 0.0, 1.0) - 0.1).abs() < 1e-12);
387        assert_eq!(t[0].1[0][1], 0.0);
388        let c: CoatSpec = serde_json::from_value(serde_json::json!({
389            "type": "curve", "wavelengths_nm": [400, 500, 600], "t": [0.1, 0.5, 0.9]
390        }))
391        .unwrap();
392        let t = c.table().unwrap();
393        assert!((t_at(&t, 0.0, 0.45) - 0.3).abs() < 1e-12);
394        assert!((t_at(&t, 89.0, 0.55) - 0.7).abs() < 1e-12);
395    }
396
397    #[test]
398    fn table_rows_and_errors() {
399        let c: CoatSpec = serde_json::from_value(serde_json::json!({
400            "type": "table", "rows": [[0, 0.5, 0.1, 0.1, 0.9, 0.9], [0, 0.6, 0.2, 0.2, 0.8, 0.8], [45, 0.5, 0.3, 0.2, 0.7, 0.8]]
401        }))
402        .unwrap();
403        let t = c.table().unwrap();
404        assert_eq!(t.len(), 2);
405        assert_eq!(t[0].1.len(), 2);
406        assert_eq!(t[1].1[0][2], 0.2);
407        for bad in [
408            serde_json::json!({"type": "table", "rows": []}),
409            serde_json::json!({"type": "table", "rows": [[0, 0.5, 0.1, 0.1, 1.5, 0.9]]}),
410            serde_json::json!({"type": "table", "rows": [[0, 0.5, 0, 0, 1, 1], [0, 0.5, 0, 0, 1, 1]]}),
411            serde_json::json!({"type": "curve", "wavelengths_nm": [500], "t": [0.5]}),
412            serde_json::json!({"type": "curve", "wavelengths_nm": [500, 400], "t": [0.5, 0.5]}),
413            serde_json::json!({"type": "curve", "wavelengths_nm": [400, 500], "t": [0.5, 0.6], "r": [0.6, 0]}),
414            serde_json::json!({"type": "longpass", "edge_nm": -1}),
415            serde_json::json!({"type": "longpass", "edge_nm": 500, "t": 2}),
416            serde_json::json!({"type": "bandpass", "center_nm": 500, "fwhm_nm": 600}),
417            serde_json::json!({"type": "nd", "od": -1}),
418        ] {
419            let c: CoatSpec = serde_json::from_value(bad.clone()).unwrap();
420            assert!(c.table().is_err(), "{bad}");
421        }
422    }
423}