lensbench_core/coating/format/
lbcm.rs1use super::super::*;
4
5pub const MODEL_HEADER: &str = "LBCM 2";
7
8pub const MODEL_BIN_HEADER: &[u8] = b"LBCM 3\n";
10pub const MODEL_BIN_HEADER4: &[u8] = b"LBCM 4\n";
12
13pub fn is_models_bin(b: &[u8]) -> bool {
15 b.starts_with(MODEL_BIN_HEADER) || b.starts_with(MODEL_BIN_HEADER4)
16}
17
18pub const MODEL_ORDER_RANGE: std::ops::RangeInclusive<usize> = 4..=12;
20pub const MODEL_BIN_NOTES: &[u8] = b"NOTES\n";
22
23#[derive(Debug, Clone, Default)]
37pub struct CoatModel {
38 pub d: f64,
40 pub bmax: f64,
42 pub wavelengths: Vec<f64>,
43 pub betas: Vec<f64>,
45 pub m: Vec<Vec<[[C64; 4]; 2]>>,
47 pub psi: Vec<Vec<[f64; 2]>>,
49 pub mirror: Option<MirrorModel>,
50 pub kinks: Vec<f64>,
53 pub note: String,
55 pub order: usize,
58}
59
60#[derive(Debug, Clone, Default)]
62pub struct MirrorModel {
63 pub n_ref: f64,
65 pub d: f64,
67 pub wavelengths: Vec<f64>,
68 pub betas: Vec<f64>,
69 pub r: Vec<Vec<[C64; 2]>>,
71 pub(crate) branches: std::sync::OnceLock<Vec<Option<MirrorBranch>>>,
73}
74
75impl MirrorModel {
76 pub(in crate::coating) fn branches(&self, b2: &[f64]) -> &[Option<MirrorBranch>] {
77 self.branches
78 .get_or_init(|| self.r.iter().map(|rw| mirror_branch(b2, rw)).collect())
79 }
80}
81
82impl CoatModel {
83 pub(in crate::coating) fn has_transmit(&self) -> bool {
84 !self.wavelengths.is_empty()
85 }
86}
87
88pub fn parse_models(txt: &str) -> Result<Vec<(String, CoatModel)>> {
110 type Waves<T> = (f64, Vec<(f64, T)>);
112 type TRow = ([[C64; 4]; 2], [f64; 2]);
114 #[derive(Default)]
115 struct Cur {
116 name: String,
117 model: CoatModel,
118 d: Option<f64>,
119 bmax: Option<f64>,
120 t: Vec<Waves<TRow>>,
122 r: Vec<Waves<[C64; 2]>>,
123 in_mirror: bool,
124 }
125 fn same_betas<T>(name: &str, w: &[(f64, Vec<(f64, T)>)]) -> Result<Vec<f64>>
126 where
127 T: Clone,
128 {
129 let b: Vec<f64> = w[0].1.iter().map(|r| r.0).collect();
130 if w.iter()
131 .any(|x| x.1.iter().map(|r| r.0).ne(b.iter().copied()))
132 {
133 invalid!("coating model {name}: the β values differ between wavelengths");
134 }
135 if b.len() < 4 || w.iter().any(|x| x.1.is_empty()) {
136 invalid!("coating model {name}: too few β points (4 or more)");
137 }
138 if w.windows(2).any(|x| !(x[0].0 < x[1].0)) {
139 invalid!("coating model {name}: the wavelengths are not ascending");
140 }
141 Ok(b)
142 }
143 fn finish(cur: Option<Cur>, out: &mut Vec<(String, CoatModel)>) -> Result<()> {
144 let Some(mut c) = cur else { return Ok(()) };
145 let name = c.name.clone();
146 if c.t.is_empty() && c.r.is_empty() {
147 invalid!("coating model {name} has no data");
148 }
149 if !c.t.is_empty() {
150 let (Some(d), Some(bmax)) = (c.d, c.bmax) else {
151 invalid!("coating model {name}: transmission needs D and BMAX");
152 };
153 c.model.d = d;
154 c.model.bmax = bmax;
155 c.model.betas = same_betas(&name, &c.t)?;
156 c.model.wavelengths = c.t.iter().map(|w| w.0).collect();
157 c.model.m =
158 c.t.iter()
159 .map(|w| w.1.iter().map(|r| r.1 .0).collect())
160 .collect();
161 c.model.psi =
162 c.t.iter()
163 .map(|w| w.1.iter().map(|r| r.1 .1).collect())
164 .collect();
165 }
166 if let Some(m) = c.model.mirror.as_mut() {
167 if c.r.is_empty() {
168 invalid!("coating model {name}: MIRROR has no data");
169 }
170 m.betas = same_betas(&name, &c.r)?;
171 m.wavelengths = c.r.iter().map(|w| w.0).collect();
172 m.r =
173 c.r.iter()
174 .map(|w| w.1.iter().map(|r| r.1).collect())
175 .collect();
176 }
177 if out.iter().any(|(k, _)| *k == name) {
178 invalid!("coating model {name} appears twice");
179 }
180 out.push((name, c.model));
181 Ok(())
182 }
183 let mut out = Vec::new();
184 let mut header = false;
185 let mut cur: Option<Cur> = None;
186 for (ln, line) in txt.lines().enumerate() {
187 let line = line.trim();
188 if line.is_empty() || line.starts_with('#') {
189 continue;
190 }
191 if !header {
192 if line != MODEL_HEADER {
193 invalid!("line 1 of the coating model is not {MODEL_HEADER}");
194 }
195 header = true;
196 continue;
197 }
198 let n = |s: &str| -> Result<f64> {
199 s.parse::<f64>()
200 .map_err(|_| Error::Invalid(format!("coating model line {} number {s}", ln + 1)))
201 };
202 let t: Vec<&str> = line.split_whitespace().collect();
203 if t[0] == "COAT" {
204 finish(cur.take(), &mut out)?;
205 if t.len() != 2 {
206 invalid!("coating model line {}: COAT name", ln + 1);
207 }
208 cur = Some(Cur {
209 name: t[1].to_string(),
210 ..Default::default()
211 });
212 continue;
213 }
214 let Some(c) = cur.as_mut() else {
215 invalid!("coating model line {}: before COAT", ln + 1);
216 };
217 match t[0] {
218 "D" | "BMAX" if t.len() == 2 && !c.in_mirror => {
219 let v = Some(n(t[1])?);
220 if t[0] == "D" {
221 c.d = v
222 } else {
223 c.bmax = v
224 }
225 }
226 "NOTE" => {
227 c.model.note = line[4..].trim().to_string();
228 }
229 "ORDER" if t.len() == 2 && !c.in_mirror => {
230 let p: usize = t[1].parse().map_err(|_| {
231 Error::Invalid(format!("coating model line {}: ORDER {}", ln + 1, t[1]))
232 })?;
233 if !MODEL_ORDER_RANGE.contains(&p) {
234 invalid!("coating model line {}: ORDER {p} is not 4 to 12", ln + 1);
235 }
236 c.model.order = p;
237 }
238 "KINKS" => {
239 let mut k = t[1..].iter().map(|x| n(x)).collect::<Result<Vec<f64>>>()?;
240 k.sort_by(f64::total_cmp);
241 c.model.kinks = k;
242 }
243 "MIRROR" if t.len() == 3 && !c.in_mirror => {
244 c.in_mirror = true;
245 c.model.mirror = Some(MirrorModel {
246 n_ref: n(t[1])?,
247 d: n(t[2])?,
248 ..Default::default()
249 });
250 }
251 "WAVE" if t.len() == 2 => {
252 let w = n(t[1])?;
253 if c.in_mirror {
254 c.r.push((w, Vec::new()))
255 } else {
256 c.t.push((w, Vec::new()))
257 }
258 }
259 _ => {
260 let v = t.iter().map(|x| n(x)).collect::<Result<Vec<f64>>>()?;
261 let b = v[0];
262 let prev = if c.in_mirror {
263 c.r.last().map(|w| w.1.last().map(|r| r.0))
264 } else {
265 c.t.last().map(|w| w.1.last().map(|r| r.0))
266 };
267 let Some(prev) = prev else {
268 invalid!("coating model line {}: data before WAVE", ln + 1);
269 };
270 if prev.is_some_and(|p| !(b > p)) {
271 invalid!("coating model line {}: β is not ascending", ln + 1);
272 }
273 let z = |i: usize| C64::new(v[i], v[i + 1]);
274 if c.in_mirror {
275 if v.len() != 5 {
276 let line = ln + 1;
277 invalid!("coating model line {line}: a mirror has β and 4 coefficients");
278 }
279 c.r.last_mut()
280 .expect("block started above")
281 .1
282 .push((b, [z(1), z(3)]));
283 } else {
284 if v.len() != 19 {
285 let line = ln + 1;
286 invalid!("coating model line {line}: transmission has β and 18 columns");
287 }
288 let m = [[z(1), z(3), z(5), z(7)], [z(10), z(12), z(14), z(16)]];
289 c.t.last_mut()
290 .expect("block started above")
291 .1
292 .push((b, (m, [v[9], v[18]])));
293 }
294 }
295 }
296 }
297 if !header {
298 invalid!("the coating model is empty");
299 }
300 finish(cur, &mut out)?;
301 Ok(out)
302}
303
304pub fn format_models(entries: &[(&str, &CoatModel)]) -> String {
306 use std::fmt::Write;
307 let mut s = format!("{}\n", MODEL_HEADER);
308 for (name, m) in entries {
309 writeln!(s, "COAT {name}").expect("write to String");
310 if !m.note.is_empty() {
311 writeln!(s, "NOTE {}", m.note.replace(['\n', '\r'], " ")).expect("write to String");
312 }
313 if !m.kinks.is_empty() {
314 let k: Vec<String> = m.kinks.iter().map(|k| format!("{k:?}")).collect();
315 writeln!(s, "KINKS {}", k.join(" ")).expect("write to String");
316 }
317 if !m.wavelengths.is_empty() {
318 writeln!(s, "D {:?}\nBMAX {:?}", m.d, m.bmax).expect("write to String");
319 if m.order != 0 {
320 writeln!(s, "ORDER {}", m.order).expect("write to String");
321 }
322 for (iw, w) in m.wavelengths.iter().enumerate() {
323 writeln!(s, "WAVE {w:?}").expect("write to String");
324 for (j, b) in m.betas.iter().enumerate() {
325 write!(s, "{b:?}").expect("write to String");
326 for pol in 0..2 {
327 for z in m.m[iw][j][pol] {
328 write!(s, " {:?} {:?}", z.re, z.im).expect("write to String");
329 }
330 write!(s, " {:?}", m.psi[iw][j][pol]).expect("write to String");
331 }
332 s.push('\n');
333 }
334 }
335 }
336 if let Some(r) = &m.mirror {
337 writeln!(s, "MIRROR {:?} {:?}", r.n_ref, r.d).expect("write to String");
338 for (iw, w) in r.wavelengths.iter().enumerate() {
339 writeln!(s, "WAVE {w:?}").expect("write to String");
340 for (j, b) in r.betas.iter().enumerate() {
341 let v = r.r[iw][j];
342 writeln!(
343 s,
344 "{b:?} {:?} {:?} {:?} {:?}",
345 v[0].re, v[0].im, v[1].re, v[1].im
346 )
347 .expect("write to String");
348 }
349 }
350 }
351 }
352 s
353}