Skip to main content

lensbench_core/
quantity.rs

1//! 取り違えやすい 2 つの量の型: 波長 [`Wavelength`](系は µm で持ち、光路長・位相は mm で計算する)と
2//! 角度 [`Angle`](入出力は deg、三角関数は rad)。
3//!
4//! 長さはどこでも mm なので素の f64 のまま。波長と角度だけは同じ f64 に 2 つの単位が混ざり、`* 1e-3` や
5//! `to_radians()` を書き忘れても型では止まらないので、変換をこの型の名前のある関数に集める。
6
7use std::f64::consts::PI;
8
9/// 波長(中身は µm)
10#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
11pub struct Wavelength(f64);
12
13impl Wavelength {
14    /// µm で与える(系の波長・.zmx・CLI の単位)
15    pub const fn from_um(um: f64) -> Self {
16        Self(um)
17    }
18
19    /// mm で与える
20    pub fn from_mm(mm: f64) -> Self {
21        Self(mm * 1e3)
22    }
23
24    /// µm
25    pub const fn um(self) -> f64 {
26        self.0
27    }
28
29    /// mm(光路長と同じ単位。光路長 / これ = 波の数)
30    pub fn mm(self) -> f64 {
31        self.0 * 1e-3
32    }
33
34    /// 真空の波数 2π/λ [rad/mm]
35    pub fn k_mm(self) -> f64 {
36        2.0 * PI / self.mm()
37    }
38}
39
40/// 角度(中身は rad)
41#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
42pub struct Angle(f64);
43
44impl Angle {
45    /// deg で与える(系の視野・傾き・入出力の単位)
46    pub fn from_deg(deg: f64) -> Self {
47        Self(deg.to_radians())
48    }
49
50    /// rad で与える
51    pub const fn from_rad(rad: f64) -> Self {
52        Self(rad)
53    }
54
55    pub fn deg(self) -> f64 {
56        self.0.to_degrees()
57    }
58
59    pub const fn rad(self) -> f64 {
60        self.0
61    }
62
63    pub fn sin_cos(self) -> (f64, f64) {
64        self.0.sin_cos()
65    }
66
67    pub fn cos(self) -> f64 {
68        self.0.cos()
69    }
70
71    pub fn tan(self) -> f64 {
72        self.0.tan()
73    }
74}
75
76impl crate::system::System {
77    /// 波長 w(0 から)。範囲の外なら panic(`wavelengths[w]` と同じ)
78    pub fn wave(&self, w: usize) -> Wavelength {
79        Wavelength::from_um(self.wavelengths[w])
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    #[test]
88    fn wavelength_units() {
89        let w = Wavelength::from_um(0.5875618);
90        assert_eq!(w.um(), 0.5875618);
91        assert!((w.mm() - 0.5875618e-3).abs() < 1e-18);
92        assert!((Wavelength::from_mm(w.mm()).um() - w.um()).abs() < 1e-15);
93        assert!((w.k_mm() * w.mm() - 2.0 * PI).abs() < 1e-12);
94    }
95
96    #[test]
97    fn angle_units() {
98        let a = Angle::from_deg(30.0);
99        assert!((a.rad() - PI / 6.0).abs() < 1e-15);
100        assert!((a.deg() - 30.0).abs() < 1e-12);
101        assert!((a.sin_cos().0 - 0.5).abs() < 1e-15);
102        assert!((Angle::from_deg(45.0).tan() - 1.0).abs() < 1e-15);
103    }
104}