1use std::collections::HashMap;
31use std::path::Path;
32use std::sync::Arc;
33
34use crate::coating::{CoatModel, CoatingFile, Layer, Measured, Table, C64};
35use crate::{invalid, Result};
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum CoatPath {
41 Transmit,
43 Mirror,
45 Reflect,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq)]
51#[non_exhaustive]
52pub struct CoatInput {
53 pub wl: f64,
55 pub n1: f64,
57 pub n2: f64,
59 pub cos1: f64,
61 pub path: CoatPath,
62 pub from_substrate: bool,
65}
66
67impl CoatInput {
68 pub fn new(wl: f64, n1: f64, n2: f64, cos1: f64, path: CoatPath, from_substrate: bool) -> Self {
70 CoatInput {
71 wl,
72 n1,
73 n2,
74 cos1,
75 path,
76 from_substrate,
77 }
78 }
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Default)]
83pub struct CoatCoefs {
84 pub rs: C64,
85 pub rp: C64,
86 pub ts: C64,
87 pub tp: C64,
88}
89
90pub trait CoatingModel: Send + Sync + std::fmt::Debug {
99 fn coefs(&self, x: &CoatInput) -> Result<CoatCoefs>;
101 fn doc(&self) -> String {
103 String::new()
104 }
105 fn example_wavelengths(&self) -> Vec<f64> {
107 vec![0.4861327, 0.5875618, 0.6562725]
108 }
109}
110
111pub fn check_coating_model(m: &dyn CoatingModel) -> Result<()> {
115 const TOL: f64 = 1e-9;
116 let wls = m.example_wavelengths();
117 if wls.is_empty() || wls.iter().any(|w| !(*w > 0.0 && w.is_finite())) {
118 invalid!("example wavelengths {wls:?} are not positive numbers");
119 }
120 let cases = [
121 (1.0, 1.5, CoatPath::Transmit, false),
122 (1.5, 1.0, CoatPath::Transmit, true),
123 (1.0, 1.5, CoatPath::Reflect, false),
124 (1.5, 1.0, CoatPath::Reflect, true),
125 (1.0, f64::NAN, CoatPath::Mirror, false),
126 ];
127 for &wl in &wls {
128 for &(n1, n2, path, from_substrate) in &cases {
129 for deg in (0..90).step_by(5).chain([89]) {
130 let (s1, c1) = (deg as f64).to_radians().sin_cos();
131 if path != CoatPath::Mirror && n1 * s1 >= n2 {
132 break;
133 }
134 let x = CoatInput::new(
135 wl,
136 n1,
137 n2,
138 if deg == 0 { 1.0 } else { c1 },
139 path,
140 from_substrate,
141 );
142 let at = format!("{path:?} n1={n1} n2={n2} {deg}° {wl} µm");
143 let c = m
144 .coefs(&x)
145 .map_err(|e| crate::Error::Invalid(format!("{at}: {e}")))?;
146 let fin = |z: &C64| z.re.is_finite() && z.im.is_finite();
147 let used = match path {
148 CoatPath::Transmit => [c.ts, c.tp],
149 _ => [c.rs, c.rp],
150 };
151 let all = path == CoatPath::Mirror || [c.rs, c.rp, c.ts, c.tp].iter().all(fin);
153 if !used.iter().all(fin) || !all {
154 invalid!("{at}: the coefficients are not finite ({c:?})");
155 }
156 let e = |r: C64, t: C64| {
157 if path == CoatPath::Mirror {
158 r.norm_sqr()
159 } else {
160 r.norm_sqr() + t.norm_sqr()
161 }
162 };
163 if e(c.rs, c.ts) > 1.0 + TOL || e(c.rp, c.tp) > 1.0 + TOL {
164 invalid!("{at}: |r|² + |t|² is more than 1 ({c:?})");
165 }
166 if deg == 0 && (used[0] - used[1]).norm() > 1e-9 * (1.0 + used[0].norm()) {
167 invalid!("{at}: s and p differ at normal incidence ({c:?})");
168 }
169 }
170 }
171 }
172 Ok(())
173}
174
175#[derive(Debug, Clone, Default)]
178#[non_exhaustive]
179pub struct CoatingSet {
180 pub mate: HashMap<String, Vec<[f64; 3]>>,
182 pub coat: HashMap<String, Vec<Layer>>,
184 pub table: HashMap<String, Table>,
186 pub models: HashMap<String, CoatModel>,
188 pub measured: HashMap<String, Measured>,
190 pub user: HashMap<String, Arc<dyn CoatingModel>>,
192}
193
194impl CoatingSet {
195 pub fn new() -> Self {
196 Self::default()
197 }
198
199 pub fn parse_dat(txt: &str) -> Result<Self> {
201 Ok(Self::from_file(CoatingFile::parse(txt)?))
202 }
203
204 pub fn from_file(f: CoatingFile) -> Self {
206 CoatingSet {
207 mate: f.mate,
208 coat: f.coat,
209 table: f.table,
210 ..Self::default()
211 }
212 }
213
214 pub fn add_layers(&mut self, name: &str, layers: Vec<Layer>) -> &mut Self {
216 self.coat.insert(name.to_string(), layers);
217 self
218 }
219
220 pub fn add_material(&mut self, name: &str, rows: Vec<[f64; 3]>) -> &mut Self {
222 self.mate.insert(name.to_string(), rows);
223 self
224 }
225
226 pub fn add_user(&mut self, name: &str, model: Arc<dyn CoatingModel>) -> &mut Self {
228 self.user.insert(name.to_string(), model);
229 self
230 }
231
232 pub fn add_models_text(&mut self, txt: &str) -> Result<&mut Self> {
234 self.models.extend(crate::coating::parse_models(txt)?);
235 Ok(self)
236 }
237
238 pub fn add_measured_text(&mut self, txt: &str) -> Result<&mut Self> {
240 self.measured.extend(crate::coating::parse_measured(txt)?);
241 Ok(self)
242 }
243
244 pub fn add_file(&mut self, path: &Path) -> Result<usize> {
247 use crate::coating::{is_models_bin, parse_models, parse_models_bin, MODEL_HEADER};
248 let at = |e: crate::Error| match e {
249 crate::Error::Invalid(m) => crate::Error::Invalid(format!("{}: {m}", path.display())),
250 e => e,
251 };
252 let b = crate::vfs::read(path)
253 .map_err(|e| crate::Error::Io(format!("{}: {e}", path.display())))?;
254 if is_models_bin(&b) {
255 let v = parse_models_bin(&b).map_err(at)?;
256 let n = v.len();
257 self.models.extend(v);
258 return Ok(n);
259 }
260 let txt = String::from_utf8_lossy(&b);
261 let first = txt
262 .lines()
263 .map(str::trim)
264 .find(|l| !l.is_empty() && !l.starts_with('#'))
265 .unwrap_or("");
266 if first == MODEL_HEADER {
267 let v = parse_models(&txt).map_err(at)?;
268 let n = v.len();
269 self.models.extend(v);
270 Ok(n)
271 } else if first == crate::coating::MEASURED_HEADER {
272 let v = crate::coating::parse_measured(&txt).map_err(at)?;
273 let n = v.len();
274 self.measured.extend(v);
275 Ok(n)
276 } else {
277 let f = CoatingFile::parse(&txt).map_err(at)?;
278 let n = f.coat.len() + f.table.len();
279 self.mate.extend(f.mate);
280 self.coat.extend(f.coat);
281 self.table.extend(f.table);
282 Ok(n)
283 }
284 }
285
286 pub fn names(&self) -> Vec<String> {
288 let mut v: Vec<String> = self
289 .coat
290 .keys()
291 .chain(self.table.keys())
292 .chain(self.models.keys())
293 .chain(self.user.keys())
294 .cloned()
295 .chain(
296 self.measured
297 .keys()
298 .map(|k| k.split('|').next().unwrap_or("").to_string()),
299 )
300 .collect();
301 v.sort();
302 v.dedup();
303 v
304 }
305
306 pub fn contains(&self, name: &str) -> bool {
308 let eq = |k: &String| k.eq_ignore_ascii_case(name);
309 self.coat.keys().any(eq)
310 || self.table.keys().any(eq)
311 || self.models.keys().any(eq)
312 || self.user.keys().any(eq)
313 || self.measured.keys().any(|k| {
314 k.split('|')
315 .next()
316 .is_some_and(|c| c.eq_ignore_ascii_case(name))
317 })
318 }
319}
320
321pub trait CoatingSource: Send + Sync {
324 fn extensions(&self) -> &[&str];
326 fn load(&self, path: &Path) -> Result<CoatingSet>;
328}
329
330#[derive(Debug, Clone)]
332pub struct CoatingCatalog {
333 pub name: String,
334 set: CoatingSet,
335}
336
337impl CoatingCatalog {
338 pub fn new(name: &str, set: CoatingSet) -> Self {
339 CoatingCatalog {
340 name: name.to_string(),
341 set,
342 }
343 }
344
345 pub fn set(&self) -> &CoatingSet {
347 &self.set
348 }
349}
350
351fn check_name(name: &str) -> Result<()> {
353 if name.is_empty() || name.contains('|') || name == "-" || name.starts_with("I.") {
354 invalid!("coating name {name:?} is not allowed (empty, contains |, or is - or I.xx)");
355 }
356 Ok(())
357}
358
359pub fn check_coatings(set: &CoatingSet) -> Result<()> {
363 for n in set.names() {
364 check_name(&n)?;
365 }
366 for n in set.coat.keys().chain(set.table.keys()) {
367 let pre = format!("{}|", n.to_ascii_uppercase());
368 if set.models.keys().any(|m| m.eq_ignore_ascii_case(n))
369 || set
370 .measured
371 .keys()
372 .any(|k| k.to_ascii_uppercase().starts_with(&pre))
373 {
374 invalid!("coating {n} has layers or a table and also a model or measured table; use one of them");
375 }
376 }
377 for (m, rows) in &set.mate {
378 if rows.is_empty() {
379 invalid!("coating material {m} has no data");
380 }
381 if rows.windows(2).any(|w| !(w[0][0] < w[1][0])) || rows.iter().any(|r| !(r[0] > 0.0)) {
382 invalid!("coating material {m}: the wavelengths are not positive and ascending");
383 }
384 if rows
385 .iter()
386 .any(|r| !(r[1] > 0.0) || !(r[2] <= crate::coating::MATE_K_POS_TOL))
387 {
388 invalid!("coating material {m}: n must be positive and k ≤ 0 (absorption is k < 0)");
389 }
390 }
391 for (c, ls) in &set.coat {
392 if ls.is_empty() {
393 invalid!("coating {c} has no layers");
394 }
395 for l in ls {
396 if !(l.d.is_finite() && l.d >= 0.0) {
397 invalid!(
398 "coating {c}: the thickness {} of layer {} is not a number ≥ 0",
399 l.d,
400 l.mat
401 );
402 }
403 }
404 }
405 for (c, t) in &set.table {
406 if t.is_empty() {
407 invalid!("coating table {c} has no data");
408 }
409 if t.windows(2).any(|w| !(w[0].0 < w[1].0)) {
410 invalid!("coating table {c}: the angles are not ascending");
411 }
412 }
413 for (k, m) in &set.measured {
414 if k.split('|').count() < 3 {
415 invalid!("measured table key {k} is not coating|medium before|medium after");
416 }
417 if m.data.len() != m.wavelengths.len()
418 || m.data.iter().any(|r| r.len() != m.angles_deg.len())
419 {
420 invalid!("size of measured table {k}");
421 }
422 if m.angles_deg.windows(2).any(|w| !(w[0] < w[1])) {
423 invalid!("the angles of measured table {k} are not ascending");
424 }
425 }
426 for (c, m) in &set.models {
427 if m.wavelengths.is_empty() && m.mirror.is_none() {
428 invalid!("coating model {c} has neither transmission nor mirror data");
429 }
430 }
431 for (c, m) in &set.user {
432 let pre = format!("{}|", c.to_ascii_uppercase());
433 let eq = |k: &String| k.eq_ignore_ascii_case(c);
434 if set.coat.keys().any(eq)
435 || set.table.keys().any(eq)
436 || set.models.keys().any(eq)
437 || set
438 .measured
439 .keys()
440 .any(|k| k.to_ascii_uppercase().starts_with(&pre))
441 {
442 invalid!("coating {c} is a user coating and also has layers, a table, a model or a measured table; use one of them");
443 }
444 check_coating_model(m.as_ref()).map_err(|e| match e {
445 crate::Error::Invalid(x) => crate::Error::Invalid(format!("user coating {c}: {x}")),
446 e => e,
447 })?;
448 }
449 Ok(())
450}