1use lensbench_core::error::{Error, Result};
26use lensbench_core::glass::Glass;
27use lensbench_core::material::Material;
28use lensbench_core::param::{Kind, Param};
29use lensbench_core::{invalid, par, System};
30use lensbench_optim::{dls_inner, DlsOpts, DlsResult, Problem};
31use std::collections::HashMap;
32use std::sync::Arc;
33
34const LD: f64 = 0.587_561_8;
36const LF: f64 = 0.486_132_7;
37const LC: f64 = 0.656_272_5;
38
39#[derive(Debug, Clone)]
41pub struct GlassSubOpts {
42 pub surfaces: Vec<usize>,
44 pub glasses: Arc<HashMap<String, Glass>>,
46 pub candidates: usize,
48 pub passes: usize,
50 pub local: DlsOpts,
52 pub filter: GlassFilter,
54 pub closeness: Closeness,
56}
57
58#[derive(Debug, Clone, Default, PartialEq)]
61pub struct GlassFilter {
62 pub max_cost: Option<f64>,
64 pub max_resist: [Option<f64>; 5],
66 pub status: Option<Vec<u8>>,
68 pub exclude: Vec<String>,
70 pub exclude_incomplete: bool,
73}
74
75pub const STATUS_NAMES: [&str; 5] = ["standard", "preferred", "obsolete", "special", "melt"];
77
78pub const RESIST_NAMES: [&str; 5] = ["cr", "fr", "sr", "ar", "pr"];
80
81impl GlassFilter {
82 pub fn status_of(name: &str) -> Result<u8> {
84 let n = name.trim().to_ascii_lowercase();
85 match STATUS_NAMES.iter().position(|x| *x == n) {
86 Some(i) => Ok(i as u8),
87 None => invalid!("glass status {name} (one of {})", STATUS_NAMES.join(", ")),
88 }
89 }
90
91 pub fn allows(&self, key: &str, g: &Glass) -> bool {
93 !g.no_substitute && self.passes(key, g)
94 }
95
96 pub fn passes(&self, key: &str, g: &Glass) -> bool {
98 let base = lensbench_core::glass::base_name(key);
99 let excluded = self.exclude.iter().any(|e| {
100 let e = e.trim();
101 match e.split_once('@') {
102 Some((n, c)) => n.eq_ignore_ascii_case(base) && c.eq_ignore_ascii_case(&g.catalog),
103 None => e.eq_ignore_ascii_case(base) || e.eq_ignore_ascii_case(key),
104 }
105 });
106 if excluded {
107 return false;
108 }
109 if let (Some(ok), Some(st)) = (&self.status, g.status) {
110 if !ok.contains(&st) {
111 return false;
112 }
113 }
114 if self.exclude_incomplete && self.incomplete(g) {
115 return false;
116 }
117 if let (Some(m), Some(c)) = (self.max_cost, g.props.and_then(|p| p.cost())) {
118 if c > m {
119 return false;
120 }
121 }
122 if let Some(r) = g.props.and_then(|p| p.resist) {
123 for (lim, v) in self.max_resist.iter().zip(r) {
124 if let (Some(lim), Some(v)) = (lim, v) {
125 if v > *lim {
126 return false;
127 }
128 }
129 }
130 }
131 true
132 }
133
134 pub fn from_template(t: &lensbench_core::system::GlassTemplate) -> Option<GlassFilter> {
137 if !t.enabled {
138 return None;
139 }
140 let lim = |k: usize| (t.check[k] && t.max[k] > 0.0).then_some(t.max[k]);
141 Some(GlassFilter {
142 max_cost: lim(0),
143 max_resist: [lim(1), lim(2), lim(3), lim(4), lim(5)],
144 status: Some((0..4u8).filter(|&k| t.status[k as usize]).collect()),
145 exclude: Vec::new(),
146 exclude_incomplete: t.exclude_incomplete,
147 })
148 }
149
150 fn incomplete(&self, g: &Glass) -> bool {
152 let on = |l: Option<f64>| l.is_some_and(|x| x != 0.0);
153 if on(self.max_cost) && g.props.and_then(|p| p.cost()).is_none() {
154 return true;
155 }
156 let r = g.props.and_then(|p| p.resist).unwrap_or([None; 5]);
157 self.max_resist
158 .iter()
159 .zip(r)
160 .enumerate()
161 .any(|(k, (&lim, v))| {
162 on(lim) && v.is_none_or(|x| x == 0.0 && k != 1)
164 })
165 }
166
167 pub fn is_empty(&self) -> bool {
169 *self == GlassFilter::default()
170 }
171}
172
173#[derive(Debug, Clone, Copy, PartialEq)]
175pub struct Closeness {
176 pub nd_step: f64,
177 pub vd_step: f64,
178 pub dpgf_step: Option<f64>,
180}
181
182impl Default for Closeness {
183 fn default() -> Self {
184 Closeness {
185 nd_step: 0.01,
186 vd_step: 1.0,
187 dpgf_step: None,
188 }
189 }
190}
191
192impl Closeness {
193 fn check(&self) -> Result<()> {
194 let ok = |x: f64| x.is_finite() && x > 0.0;
195 if !ok(self.nd_step) || !ok(self.vd_step) || self.dpgf_step.is_some_and(|x| !ok(x)) {
196 invalid!("the closeness steps (nd_step, vd_step, dpgf_step) must be positive");
197 }
198 Ok(())
199 }
200
201 fn distance2(&self, a: Nv, b: Nv) -> f64 {
202 let mut d = ((a.0 - b.0) / self.nd_step).powi(2) + ((a.1 - b.1) / self.vd_step).powi(2);
203 if let Some(s) = self.dpgf_step {
204 d += ((a.2 - b.2) / s).powi(2);
205 }
206 d
207 }
208}
209
210type Nv = (f64, f64, f64);
212
213#[derive(Debug, Clone, PartialEq)]
215pub struct GlassChange {
216 pub surface: usize,
217 pub from: String,
219 pub to: String,
220 pub target_nd: f64,
222 pub target_vd: f64,
223 pub nd: f64,
225 pub vd: f64,
226 pub merit: f64,
228 pub configs: Option<Vec<usize>>,
230}
231
232#[derive(Debug, Clone)]
234pub struct GlassSubResult {
235 pub problem: Problem,
237 pub result: DlsResult,
239 pub changes: Vec<GlassChange>,
241 pub tried: usize,
243 pub passes: usize,
245}
246
247fn nd_vd(n: impl Fn(f64) -> f64) -> (f64, f64) {
249 let (d, f, c) = (n(LD), n(LF), n(LC));
250 (d, (d - 1.0) / (f - c))
251}
252
253pub fn effective_nd_vd(s: &System, j: usize) -> Result<(f64, f64)> {
255 let d = &s.surfaces[j];
256 if d.is_mirror() || d.is_coord_break() || d.grin().is_some() {
257 invalid!("surface {j}: no glass to substitute (mirror, coordinate break or GRIN)");
258 }
259 if matches!(d.mat, Material::Air) {
260 invalid!("surface {j}: the medium is air");
261 }
262 let lp = s.wavelengths[s.primary];
263 let b = s
265 .surface_medium_index_at(j, &[LD, LF, LC, lp])?
266 .ok_or_else(|| format!("surface {j}: no medium"))?;
267 let eff = |x: f64| x + d.dn + d.disp * (x - b[3]);
268 let (nd, nf, nc) = (eff(b[0]), eff(b[1]), eff(b[2]));
269 Ok((nd, (nd - 1.0) / (nf - nc)))
270}
271
272fn effective_dpgf(s: &System, j: usize) -> f64 {
274 match &s.surfaces[j].mat {
275 Material::Model { dpgf, .. } => *dpgf,
276 Material::Glass(m) => s
277 .glasses
278 .get(m)
279 .and_then(|g| g.props)
280 .map_or(0.0, |p| p.dpgf),
281 _ => 0.0,
282 }
283}
284
285fn glass_nd_vd(s: &System, g: &Glass) -> Option<(f64, f64)> {
287 if lensbench_core::usermaterial::missing(g).is_some() {
288 return None;
289 }
290 if let Some([lo, hi]) = g.ld {
291 if s.wavelengths.iter().any(|&w| w < lo || w > hi) {
292 return None;
293 }
294 }
295 let (t, p, a) = (s.temperature, s.pressure, s.adjust_index);
296 let (nd, vd) = nd_vd(|l| g.index(l, t, p, a));
297 (nd.is_finite() && vd.is_finite() && nd > 1.0 && vd > 0.0).then_some((nd, vd))
298}
299
300fn nearest(
302 s: &System,
303 o: &GlassSubOpts,
304 target: Nv,
305 n: usize,
306 exclude: Option<&str>,
307) -> Vec<(String, (f64, f64))> {
308 let mut v: Vec<(f64, String, (f64, f64))> = o
309 .glasses
310 .iter()
311 .filter(|(k, g)| Some(k.as_str()) != exclude && o.filter.allows(k, g))
312 .filter_map(|(k, g)| {
313 let (nd, vd) = glass_nd_vd(s, g)?;
314 let dp = g.props.map_or(0.0, |p| p.dpgf);
315 Some((
316 o.closeness.distance2((nd, vd, dp), target),
317 k.clone(),
318 (nd, vd),
319 ))
320 })
321 .collect();
322 v.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
323 v.into_iter().take(n).map(|(_, k, nv)| (k, nv)).collect()
324}
325
326fn with_glass(s: &System, j: usize, name: &str, g: &Glass) -> Result<(System, String)> {
329 let mut t = s.clone();
330 let used = match t.glasses.get(name) {
331 Some(h) if h == g => name.to_string(),
332 None => {
333 t.add_glasses(HashMap::from([(name.to_string(), g.clone())]));
334 name.to_string()
335 }
336 Some(_) => {
337 let q = lensbench_core::glass::qualified(
338 lensbench_core::glass::base_name(name),
339 &g.catalog,
340 );
341 if t.glasses.get(&q) != Some(g) {
342 t.add_glasses(HashMap::from([(q.clone(), g.clone())]));
343 }
344 q
345 }
346 };
347 t.set_material(j, &used)?;
348 let d = &t.surfaces[j];
349 let mut ch = Vec::new();
350 if d.dn != 0.0 {
351 ch.push((Param::new(j, Kind::Dn), 0.0));
352 }
353 if d.disp != 0.0 {
354 ch.push((Param::new(j, Kind::Disp), 0.0));
355 }
356 if !ch.is_empty() {
357 t = t.with_params(&ch)?;
358 }
359 if t.surfaces[j].dnd != 0.0 || t.surfaces[j].dvd != 0.0 {
360 t.edit(|rx| {
361 rx.surfaces[j].dnd = 0.0;
362 rx.surfaces[j].dvd = 0.0;
363 Ok(())
364 })?;
365 }
366 Ok((t, used))
367}
368
369fn must_replace(s: &System, j: usize, o: &GlassSubOpts) -> bool {
371 let d = &s.surfaces[j];
372 let filtered = match &d.mat {
373 Material::Glass(m) => {
374 !o.filter.is_empty() && s.glasses.get(m).is_some_and(|g| !o.filter.passes(m, g))
375 }
376 _ => false,
377 };
378 matches!(d.mat, Material::Model { .. } | Material::Index(_))
379 || d.dn != 0.0
380 || d.disp != 0.0
381 || d.dnd != 0.0
382 || d.dvd != 0.0
383 || filtered
384}
385
386fn config_groups(p: &Problem, j: usize) -> Vec<Vec<usize>> {
388 let key = |s: &System| {
389 let d = &s.surfaces[j];
390 (
391 d.mat.name(),
392 d.dn.to_bits(),
393 d.disp.to_bits(),
394 d.dnd.to_bits(),
395 d.dvd.to_bits(),
396 )
397 };
398 let mut out: Vec<(_, Vec<usize>)> = Vec::new();
399 for (k, s) in p.configs.iter().enumerate() {
400 let x = key(s);
401 match out.iter_mut().find(|(y, _)| *y == x) {
402 Some((_, v)) => v.push(k),
403 None => out.push((x, vec![k])),
404 }
405 }
406 out.into_iter().map(|(_, v)| v).collect()
407}
408
409fn drop_index_vars(p: &mut Problem, j: usize) {
411 p.vars.retain(|v| {
412 !(matches!(v.param.kind, Kind::Dn | Kind::Disp)
413 && !v.param.kind.is_unit()
414 && v.param.index() == j)
415 });
416}
417
418pub fn candidate_pool(
421 s: &System,
422 catalogs: &[String],
423 dirs: &[std::path::PathBuf],
424) -> Result<Arc<HashMap<String, Glass>>> {
425 if catalogs.is_empty() {
426 if s.glasses.is_empty() {
427 invalid!("no candidate glasses: name the glass catalogs to choose from");
428 }
429 return Ok(s.glasses.clone());
430 }
431 let dirs = lensbench_core::glass::catalog_dirs(dirs);
432 let (g, missing) = lensbench_core::glass::load_catalogs_shared(catalogs, &dirs);
433 if !missing.is_empty() {
434 invalid!("glass catalogs not found: {}", missing.join(", "));
435 }
436 if g.is_empty() {
437 invalid!("no candidate glasses in {}", catalogs.join(", "));
438 }
439 Ok(g)
440}
441
442pub fn substitute(p: &Problem, x: &[f64], o: &GlassSubOpts) -> Result<GlassSubResult> {
444 p.check()?;
445 if o.surfaces.is_empty() {
446 invalid!("no surfaces to substitute glass on");
447 }
448 if o.candidates == 0 {
449 invalid!("candidates must be 1 or more");
450 }
451 if o.passes == 0 {
452 invalid!("passes must be 1 or more");
453 }
454 o.closeness.check()?;
455 if !o.glasses.iter().any(|(k, g)| o.filter.allows(k, g)) {
456 invalid!("no candidate glass passes the filter");
457 }
458 let s0 = &p.configs[0];
459 for (i, &j) in o.surfaces.iter().enumerate() {
460 if j == 0 || j >= s0.image() {
461 invalid!(
462 "surface {j} to substitute glass on (1 to {})",
463 s0.image() - 1
464 );
465 }
466 if o.surfaces[..i].contains(&j) {
467 invalid!("surface {j} given twice");
468 }
469 for s in &p.configs {
470 effective_nd_vd(s, j)?;
471 }
472 }
473 let mut cur = p.with_configs(p.systems(x)?);
475 let x0 = x.to_vec();
476 let merit0 = p.merit(x)?;
477 let mut best: Option<DlsResult> = None;
478 let mut cur_merit = merit0;
479 let mut changes = Vec::new();
480 let mut tried = 0;
481 let mut passes = 0;
482 for _ in 0..o.passes {
483 passes += 1;
484 let mut changed = false;
485 for &j in &o.surfaces {
486 for group in config_groups(&cur, j) {
487 par::check_cancel()?;
488 let s = &cur.configs[group[0]];
489 let forced = must_replace(s, j, o);
490 let (tnd, tvd) = effective_nd_vd(s, j)?;
491 let target = (tnd, tvd, effective_dpgf(s, j));
492 let from = s.surfaces[j].mat.name();
493 let keep = match &s.surfaces[j].mat {
494 Material::Glass(m) if !forced => Some(m.clone()),
495 _ => None,
496 };
497 let cands = nearest(s, o, target, o.candidates, keep.as_deref());
498 if cands.is_empty() {
499 return Err(Error::Invalid(format!(
500 "surface {j}: no candidate glass passes the filter and covers the system wavelengths"
501 )));
502 }
503 let mut q = cur.clone();
504 drop_index_vars(&mut q, j);
506 let evals: Vec<Option<(DlsResult, Problem, String)>> =
507 par::map(&cands, |(name, _)| {
508 let g = &o.glasses[name];
509 let mut used = String::new();
510 let mut cs = Vec::with_capacity(q.configs.len());
511 for (k, c) in q.configs.iter().enumerate() {
512 if group.contains(&k) {
513 let (t, u) = with_glass(c, j, name, g).ok()?;
514 used = u;
515 cs.push(t);
516 } else {
517 cs.push(c.clone());
518 }
519 }
520 let qq = q.with_configs(cs);
521 let r = dls_inner(&qq, &o.local).ok()?;
522 r.merit.is_finite().then_some((r, qq, used))
523 });
524 tried += cands.len();
525 let pick = evals
526 .into_iter()
527 .zip(&cands)
528 .filter_map(|(e, c)| e.map(|e| (e, c)))
529 .min_by(|a, b| a.0 .0.merit.total_cmp(&b.0 .0.merit));
530 let Some(((r, qq, used), (_, nv))) = pick else {
531 if forced {
532 return Err(Error::Invalid(format!(
533 "surface {j}: no candidate glass could be traced and optimized"
534 )));
535 }
536 continue;
537 };
538 if !forced && !(r.merit < cur_merit * (1.0 - 1e-9)) {
540 continue;
541 }
542 changes.push(GlassChange {
543 surface: j,
544 from,
545 to: used,
546 target_nd: target.0,
547 target_vd: target.1,
548 nd: nv.0,
549 vd: nv.1,
550 merit: r.merit,
551 configs: (group.len() < cur.configs.len()).then(|| group.clone()),
552 });
553 cur_merit = r.merit;
554 cur = qq.with_configs(r.systems.clone());
555 best = Some(r);
556 changed = true;
557 }
558 }
559 if !changed {
560 break;
561 }
562 }
563 let mut result = match best {
564 Some(r) => r,
565 None => {
567 let systems = p.systems(x)?;
568 DlsResult {
569 x0: x0.clone(),
570 x: x0.clone(),
571 merit0,
572 merit: merit0,
573 history: vec![merit0],
574 iterations: 0,
575 evals: 1,
576 stop: lensbench_optim::Stop::NoProgress,
577 note: None,
578 inactive: Vec::new(),
579 systems,
580 }
581 }
582 };
583 result.merit0 = merit0;
584 Ok(GlassSubResult {
585 problem: cur,
586 result,
587 changes,
588 tried,
589 passes,
590 })
591}