Skip to main content

lensbench_core/
thermal.rs

1//! 熱の構成を作る(OpticStudio の Make Thermal に当たる)。
2//!
3//! 温度の一覧から、多重構成の表に温度・気圧の行と、各温度での曲率・厚さ・非球面の係数・半直径・機械半径・
4//! チップゾーンの行を作る。構成 1 は元の系(今の温度・気圧)で、構成 2 以降が与えた温度。屈折率は構成の温度・気圧から
5//! 材料の式で決まる(屈折率を環境に合わせる設定 [`System::adjust_index`] が切れていれば入れる。OpticStudio と同じ)。
6//!
7//! 規則(OpticStudio 2026 R1.01 の Make Thermal の熱のピックアップの値で確かめた):
8//! - 線膨張係数 α: ガラスの面はカタログの TCE(面の後ろがガラスならそのガラス、空気なら前のガラス)、鏡と前後とも空気の
9//!   面はレンズデータの TCE の列。温度差 ΔT は元の系の温度から
10//! - 曲率 c / (1 + α ΔT)、非球面(偶数次)の r^(2n) の係数 × (1 + α ΔT)^(1 − 2n)、円錐係数はそのまま。半直径・機械半径・
11//!   チップゾーンは × (1 + α ΔT)。ガラスの厚さは × (1 + α ΔT)(そのガラスの α)
12//! - 面タイプのパラメータ(2026 R1.01 で 10 種を確かめた)は [`asph_exponent`]。表に置けないもの(トロイダル面・Binary 2・
13//!   Fresnel の曲率と係数、Zernike の項など)は変えずに注意を出す
14//! - 空気の間隔は、間隔の前後の面の半直径の縁を結ぶ薄い円筒のスペーサー(α は間隔の面のレンズデータの TCE)とみる。
15//!   スペーサーの長さ(縁から縁)が × (1 + α_m ΔT)。縁の高さは、半直径の小さい方の面(像面までは前の面)はスペーサーの α_m で、大きい方は
16//!   その面のガラスの α で変わる。中心の厚さは縁の長さと、その高さでの温度の後の矢高から決める
17//!
18//! 熱のピックアップ(元の系を変えると追いかける)は作らず、作った時の値を表に書く。
19
20use crate::error::Result;
21use crate::invalid;
22use crate::material::Material;
23use crate::param::{Kind, Param};
24use crate::surface::{SurfType, Surface};
25use crate::system::System;
26
27/// 熱の構成の設定
28#[derive(Debug, Clone, Default)]
29pub struct ThermalSpec {
30    /// 足す構成の温度 [°C]
31    pub temps: Vec<f64>,
32    /// 足す構成の気圧 [atm](空なら元の系の気圧、それ以外は temps と同じ数)
33    pub pressures: Vec<f64>,
34}
35
36/// 熱の構成を作った結果
37#[derive(Debug, Clone)]
38pub struct Thermal {
39    /// 構成 1 が元の系、構成 2 以降が与えた温度の系(今の構成は 1)
40    pub system: System,
41    pub warnings: Vec<String>,
42}
43
44/// 面 j の線膨張係数 [1/°C](モジュールの説明の規則)
45fn alpha(s: &System, j: usize, warn: &mut Vec<String>) -> f64 {
46    let glass_tce = |m: &Material, warn: &mut Vec<String>| -> Option<f64> {
47        match m {
48            Material::Glass(name) => Some(match s.glasses.get(name).and_then(|g| g.props) {
49                Some(p) => p.tce * 1e-6,
50                None => {
51                    warn.push(format!("surface {j}: no TCE for {name} (taken as 0)"));
52                    0.0
53                }
54            }),
55            Material::Model { .. } | Material::Index(_) => {
56                warn.push(format!(
57                    "surface {j}: a model glass has no TCE (taken as 0)"
58                ));
59                Some(0.0)
60            }
61            _ => None,
62        }
63    };
64    let d = &s.surfaces[j];
65    if let Some(a) = glass_tce(&d.mat, warn) {
66        return a;
67    }
68    if !d.is_mirror() && j > 0 {
69        if let Some(a) = glass_tce(&s.surfaces[j - 1].mat, warn) {
70            return a;
71        }
72    }
73    d.tce * 1e-6
74}
75
76/// 面 j がレンズの面(前か後ろがガラス、または鏡)か
77fn lens_surface(s: &System, j: usize) -> bool {
78    let glass = |m: &Material| m.is_medium() && !m.is_air();
79    let d = &s.surfaces[j];
80    d.is_mirror() || glass(&d.mat) || (j > 0 && glass(&s.surfaces[j - 1].mat))
81}
82
83/// 面 j の y = h の矢高(形の外は NaN)
84fn sag(s: &System, j: usize, h: f64) -> f64 {
85    s.surfaces[j].shape().sag(0.0, h).0
86}
87
88/// 熱の構成を作る(元の系が多重構成なら、構成 base の系を元にし、表はその系の値で作り直す)
89pub fn make_thermal(s: &System, base: usize, spec: &ThermalSpec) -> Result<Thermal> {
90    if spec.temps.is_empty() {
91        invalid!("give one or more temperatures");
92    }
93    if !spec.pressures.is_empty() && spec.pressures.len() != spec.temps.len() {
94        invalid!(
95            "{} pressures for {} temperatures",
96            spec.pressures.len(),
97            spec.temps.len()
98        );
99    }
100    if let Some(t) = spec
101        .temps
102        .iter()
103        .find(|t| !(t.is_finite() && **t >= -273.15))
104    {
105        invalid!("temperature {t} °C");
106    }
107    if let Some(p) = spec
108        .pressures
109        .iter()
110        .find(|p| !(p.is_finite() && **p >= 0.0))
111    {
112        invalid!("pressure {p} atm");
113    }
114    let mut warnings = Vec::new();
115    let mut s0 = s.config(base)?;
116    if s0.configs.is_some() {
117        s0.set_config_count(1)?;
118    }
119    if !s0.adjust_index {
120        // 屈折率を構成の温度・気圧に合わせる(OpticStudio の Make Thermal も入れる)
121        s0.edit(|p| {
122            p.adjust_index = true;
123            Ok(())
124        })?;
125        warnings.push(
126            "turned on adjust index to the environment (the glass indices follow the temperature and pressure)"
127                .into(),
128        );
129    }
130    let img = s0.image();
131    let t_nom = s0.temperature;
132    let al: Vec<f64> = (0..=img).map(|j| alpha(&s0, j, &mut warnings)).collect();
133    let lens: Vec<bool> = (0..=img).map(|j| lens_surface(&s0, j)).collect();
134    if s0.surfaces.iter().any(|d| d.is_coord_break() && !d.ignore) {
135        warnings
136            .push("coordinate breaks are left as they are (their thickness doesn't expand)".into());
137    }
138    let n = spec.temps.len() + 1;
139    // 構成 k(0 始まり、0 が元の系)の温度差
140    let dts: Vec<f64> = std::iter::once(0.0)
141        .chain(spec.temps.iter().map(|t| t - t_nom))
142        .collect();
143    let mut rows: Vec<(Param, Vec<f64>)> = Vec::new();
144    let temps: Vec<f64> = std::iter::once(t_nom)
145        .chain(spec.temps.iter().copied())
146        .collect();
147    let pres: Vec<f64> = std::iter::once(s0.pressure)
148        .chain((0..spec.temps.len()).map(|i| spec.pressures.get(i).copied().unwrap_or(s0.pressure)))
149        .collect();
150    rows.push((Param::system(Kind::Temp), temps));
151    rows.push((Param::system(Kind::Pres), pres));
152    let scaled = |v: f64, a: f64| -> Vec<f64> { dts.iter().map(|dt| v * (1.0 + a * dt)).collect() };
153    // 曲率
154    for j in 1..img {
155        let d = &s0.surfaces[j];
156        if d.ignore || d.is_coord_break() || !lens[j] {
157            continue;
158        }
159        // 曲率を表に置けない面(Tilted は形に効かない。トロイダル面・Binary 2 は lensbench の表に置けない)
160        if s0.check_param(Param::new(j, Kind::Curv)).is_err() {
161            if d.c != 0.0 {
162                warnings.push(format!("surface {j}: the curvature is not scaled (it can't be a configuration row of this surface type)"));
163            }
164            continue;
165        }
166        rows.push((
167            Param::new(j, Kind::Curv),
168            dts.iter().map(|dt| d.c / (1.0 + al[j] * dt)).collect(),
169        ));
170    }
171    // 厚さ
172    for j in 1..img {
173        let d = &s0.surfaces[j];
174        if d.ignore || d.is_coord_break() || !d.t.is_finite() {
175            continue;
176        }
177        let glass = d.mat.is_medium() && !d.mat.is_air();
178        let v = if glass {
179            scaled(d.t, al[j])
180        } else {
181            // 次の有効な面(無視した面は飛ばす)
182            let Some(b) = (j + 1..=img).find(|&i| !s0.surfaces[i].ignore) else {
183                continue;
184            };
185            let am = d.tce * 1e-6;
186            let (hf, hb) = (d.semi.abs(), s0.surfaces[b].semi.abs());
187            let sf = |h: f64| if lens[j] { sag(&s0, j, h) } else { 0.0 };
188            let sb = |h: f64| if lens[b] { sag(&s0, b, h) } else { 0.0 };
189            let e0 = d.t - sf(hf) + sb(hb);
190            // 縁の高さの α: 半直径の小さい方はスペーサーの α
191            // (像面までの間隔は、像面の半直径によらず面の縁がスペーサーに載る。OpticStudio 2026 R1.01 で確かめた)
192            let (xf, xb) = if b == img || hf <= hb {
193                (am, al[b])
194            } else {
195                (al[j], am)
196            };
197            dts.iter()
198                .map(|dt| {
199                    let (gf, gb) = (1.0 + al[j] * dt, 1.0 + al[b] * dt);
200                    // 温度の後の形は長さが全部 (1 + α ΔT) 倍: z_T(h) = g z(h / g)
201                    let zf = gf * sf(hf * (1.0 + xf * dt) / gf);
202                    let zb = gb * sb(hb * (1.0 + xb * dt) / gb);
203                    e0 * (1.0 + am * dt) + zf - zb
204                })
205                .collect()
206        };
207        if v.iter().any(|x| !x.is_finite()) {
208            invalid!("surface {j}: the thickness can't be expanded (the sag at the semi-diameter is undefined)");
209        }
210        rows.push((Param::new(j, Kind::Thick), v));
211    }
212    // 非球面の係数・半直径・機械半径・チップゾーン
213    for j in 1..img {
214        let d = &s0.surfaces[j];
215        if d.ignore || d.is_coord_break() || !lens[j] {
216            continue;
217        }
218        // 面タイプのパラメータ(asph の i 番目): 形の長さが全部 (1 + α ΔT) 倍になる z_T(h) = g z(h / g) の倍率
219        let n_asph = d.asph().len().min(8);
220        let mut lost = false;
221        for i in 0..n_asph as u8 {
222            let Some(e) = asph_exponent(d.typ(), i as usize) else {
223                continue;
224            };
225            let par = Param::new(j, Kind::Asph(i));
226            let Ok(v) = s0.get_param(par) else {
227                if d.asph()[i as usize] != 0.0 {
228                    lost = true;
229                }
230                continue;
231            };
232            rows.push((
233                par,
234                dts.iter()
235                    .map(|dt| v * (1.0 + al[j] * dt).powf(e))
236                    .collect(),
237            ));
238        }
239        if lost {
240            warnings.push(format!(
241                "surface {j}: the surface type parameters are not scaled (they can't be configuration rows of this surface type)"
242            ));
243        }
244        if let Some(w) = unscaled(d, j) {
245            warnings.push(w);
246        }
247        rows.push((Param::new(j, Kind::Semi), scaled(d.semi.abs(), al[j])));
248        rows.push((
249            Param::new(j, Kind::MechSemi),
250            scaled(s0.lens_radius(j), al[j]),
251        ));
252        rows.push((Param::new(j, Kind::ChipZone), scaled(d.chip_zone, al[j])));
253    }
254    let mut out = s0.clone();
255    // 表の値を書く曲率・厚さのソルブは外す(値は元の系のまま。OpticStudio も熱の解析の前に外すよう求める)
256    for (p, _) in &rows {
257        let k = match p.kind {
258            Kind::Curv | Kind::Thick => p.kind,
259            _ => continue,
260        };
261        let j = p.index();
262        if out
263            .solves
264            .iter()
265            .any(|q| q.surf == j && q.kind.param_kind() == k)
266        {
267            out.remove_solve(j, k)?;
268            warnings.push(if k == Kind::Curv {
269                format!("removed the curvature solve of surface {j} (the value of the original system is kept)")
270            } else {
271                format!("removed the thickness solve of surface {j} (the value of the original system is kept)")
272            });
273        }
274    }
275    out.set_config_count(n)?;
276    for (p, v) in rows {
277        out.set_config_row(p, v)?;
278    }
279    let system = out.config(1)?;
280    Ok(Thermal { system, warnings })
281}
282
283/// 面タイプ t のパラメータ asph[i](.zmx の PARM i + 1。トロイダル面は表に置けないので使わない)の、(1 + α ΔT) の何乗を掛けるか。
284/// 変えないものは None(OpticStudio 2026 R1.01 の Make Thermal と同じ)
285fn asph_exponent(t: SurfType, i: usize) -> Option<f64> {
286    let n = i as f64 + 1.0;
287    match t {
288        // r^(2n) の係数
289        SurfType::EvenAsph
290        | SurfType::Binary2
291        | SurfType::Fresnel
292        | SurfType::CylFresnel
293        | SurfType::ZernikeStd
294        | SurfType::ZernikeFringe
295        | SurfType::GridSag => Some(1.0 - 2.0 * n),
296        // r^n の係数
297        SurfType::OddAsph => Some(1.0 - n),
298        // 偏心 x・y と Zs・Za・Zc(半直径で正規化した ρ の項の大きさ)は長さ、傾き・角度は変えない
299        SurfType::Irregular => matches!(i, 0 | 1 | 4 | 5 | 6).then_some(1.0),
300        // Tilted の tan は変えない
301        _ => None,
302    }
303}
304
305/// 熱の構成で伸び縮みさせられない面 j のパラメータの注意(OpticStudio は伸び縮みさせるが、lensbench の多重構成の表に置けないもの)
306fn unscaled(d: &Surface, j: usize) -> Option<String> {
307    Some(match d.typ() {
308        SurfType::Toroidal => format!(
309            "surface {j}: the radius of rotation and the aspheric terms of the toroidal surface are not scaled"
310        ),
311        SurfType::ZernikeStd | SurfType::ZernikeFringe => format!(
312            "surface {j}: the Zernike terms and their normalization radius and decenter are not scaled"
313        ),
314        SurfType::GridSag => {
315            format!("surface {j}: the Zernike terms and the grid of the grid sag surface are not scaled")
316        }
317        SurfType::Binary2 => {
318            format!("surface {j}: the normalization radius of the binary 2 phase is not scaled")
319        }
320        SurfType::User | SurfType::UserShape => {
321            format!("surface {j}: the parameters of the user-defined surface are not scaled")
322        }
323        _ => return None,
324    })
325}