lensbench_core/
thermal.rs1use 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#[derive(Debug, Clone, Default)]
29pub struct ThermalSpec {
30 pub temps: Vec<f64>,
32 pub pressures: Vec<f64>,
34}
35
36#[derive(Debug, Clone)]
38pub struct Thermal {
39 pub system: System,
41 pub warnings: Vec<String>,
42}
43
44fn 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
76fn 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
83fn sag(s: &System, j: usize, h: f64) -> f64 {
85 s.surfaces[j].shape().sag(0.0, h).0
86}
87
88pub 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 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 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 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 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 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 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 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 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 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 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 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
283fn asph_exponent(t: SurfType, i: usize) -> Option<f64> {
286 let n = i as f64 + 1.0;
287 match t {
288 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 SurfType::OddAsph => Some(1.0 - n),
298 SurfType::Irregular => matches!(i, 0 | 1 | 4 | 5 | 6).then_some(1.0),
300 _ => None,
302 }
303}
304
305fn 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}