1use lensbench_core::error::Result;
40use lensbench_core::invalid;
41use lensbench_core::par;
42use lensbench_core::param::{Kind, Param};
43use lensbench_core::system::System;
44use lensbench_core::units::UnitKind;
45use lensbench_core::LockExt;
46use lensbench_optim::{DlsOpts, Problem};
47use lensbench_runs::{self as runs, Draws, Joint};
48use std::sync::Mutex;
49
50mod inverse;
51use inverse::run_inverse;
52pub use inverse::{GlassShift, Inverse, InverseTarget, InverseTol};
53
54#[derive(Debug, Clone, Copy, PartialEq, serde::Deserialize, schemars::JsonSchema)]
56#[serde(try_from = "String")]
57pub enum Dist {
58 Uniform,
59 Normal {
61 cut: f64,
62 },
63 End,
65 DiscX {
69 normal: Option<f64>,
70 },
71 DiscY {
73 normal: Option<f64>,
74 },
75}
76
77impl TryFrom<String> for Dist {
78 type Error = String;
79 fn try_from(s: String) -> std::result::Result<Dist, String> {
80 Dist::parse(&s).map_err(|e| e.to_string())
81 }
82}
83
84impl Dist {
85 pub fn parse(s: &str) -> Result<Dist> {
86 let l = s.trim().to_ascii_lowercase();
87 Ok(match l.as_str() {
88 "uniform" | "u" => Dist::Uniform,
89 "normal" | "gauss" | "n" => Dist::Normal { cut: 2.0 },
90 "end" | "ends" | "e" => Dist::End,
91 "disc_x" => Dist::DiscX { normal: None },
92 "disc_y" => Dist::DiscY { normal: None },
93 _ => {
94 for (pre, y) in [("disc_x:", false), ("disc_y:", true)] {
96 if let Some(r) = l.strip_prefix(pre) {
97 let normal = match Dist::parse(r) {
98 Ok(Dist::Normal { cut }) => Some(cut),
99 Ok(Dist::Uniform) => None,
100 _ => invalid!(
101 "distribution {s} (disc_x, disc_x:normal, disc_x:normal:<number of σ>, and the same for y)"
102 ),
103 };
104 return Ok(if y {
105 Dist::DiscY { normal }
106 } else {
107 Dist::DiscX { normal }
108 });
109 }
110 }
111 if let Some(c) = l
113 .strip_prefix("normal:")
114 .and_then(|v| v.parse::<f64>().ok())
115 {
116 if c > 0.0 {
117 return Ok(Dist::Normal { cut: c });
118 }
119 }
120 invalid!("distribution {s} (uniform, normal, normal:<number of σ>, end, or a disc_x and disc_y pair)")
121 }
122 })
123 }
124 pub fn name(&self) -> String {
125 match self {
126 Dist::Uniform => "uniform".into(),
127 Dist::Normal { cut } if *cut == 2.0 => "normal".into(),
128 Dist::Normal { cut } => format!("normal:{cut}"),
129 Dist::End => "end".into(),
130 Dist::DiscX { normal } | Dist::DiscY { normal } => {
131 let xy = if matches!(self, Dist::DiscX { .. }) {
132 "x"
133 } else {
134 "y"
135 };
136 match normal {
137 None => format!("disc_{xy}"),
138 Some(cut) => format!("disc_{xy}:{}", Dist::Normal { cut: *cut }.name()),
139 }
140 }
141 }
142 }
143}
144
145#[derive(Debug, Clone, PartialEq)]
147pub struct Tol {
148 pub label: String,
150 pub params: Vec<Param>,
152 pub lo: f64,
153 pub hi: f64,
154 pub relative: bool,
156 pub dist: Dist,
157 pub scale: Vec<f64>,
160 pub glass: Option<GlassShift>,
163}
164
165impl Tol {
166 pub fn pm(label: impl Into<String>, param: Param, pm: f64) -> Tol {
168 Tol {
169 label: label.into(),
170 params: vec![param],
171 lo: -pm,
172 hi: pm,
173 relative: false,
174 dist: Dist::Uniform,
175 scale: Vec::new(),
176 glass: None,
177 }
178 }
179
180 pub fn scale_of(&self, k: usize) -> f64 {
182 self.scale.get(k).copied().unwrap_or(1.0)
183 }
184}
185
186#[derive(Debug, Clone)]
188pub struct McSpec {
189 pub problem: Problem,
191 pub tols: Vec<Tol>,
192 pub trials: usize,
194 pub seed: u64,
195 pub comp: DlsOpts,
197 pub sensitivity: bool,
199 pub comp_mode: CompMode,
201 pub inverse: Option<Inverse>,
203}
204
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub enum CompMode {
208 #[default]
210 Optimize,
211 Paraxial,
214 None,
216}
217
218impl McSpec {
219 pub fn new(problem: Problem, tols: Vec<Tol>) -> McSpec {
220 McSpec {
221 problem,
222 tols,
223 trials: 100,
224 seed: 1,
225 comp: DlsOpts {
226 max_iter: 10,
227 ..Default::default()
228 },
229 sensitivity: true,
230 comp_mode: CompMode::Optimize,
231 inverse: None,
232 }
233 }
234
235 pub fn check(&self) -> Result<()> {
236 self.problem.check()?;
237 if let Some(inv) = &self.inverse {
238 match inv.target {
239 InverseTarget::Limit(x) if !x.is_finite() => {
240 invalid!("inverse limit {x} is not finite")
241 }
242 InverseTarget::Increment(x) if !(x.is_finite() && x > 0.0) => {
243 invalid!("inverse increment {x} must be positive")
244 }
245 _ => {}
246 }
247 if !(inv.rtol.is_finite() && inv.rtol > 0.0) {
248 invalid!("inverse rtol {} must be positive", inv.rtol);
249 }
250 if let Some(&k) = inv.skip.iter().find(|&&k| k >= self.tols.len()) {
251 invalid!("inverse skip: no tolerance {k}");
252 }
253 }
254 if self.comp_mode == CompMode::Paraxial {
255 for s in &self.problem.configs {
256 let m = s.image().checked_sub(1).filter(|&m| m >= 1);
257 if m.is_none_or(|m| s.check_param(Param::new(m, Kind::Thick)).is_err()) {
258 invalid!(
259 "paraxial focus compensation needs a thickness before the image surface"
260 );
261 }
262 }
263 }
264 for (i, t) in self.tols.iter().enumerate() {
265 if t.params.is_empty() {
266 invalid!("tolerance {i} ({}): no parameter", t.label);
267 }
268 if !t.scale.is_empty() && t.scale.len() != t.params.len() {
269 invalid!(
270 "tolerance {i} ({}): scale has {} values (the parameters are {})",
271 t.label,
272 t.scale.len(),
273 t.params.len()
274 );
275 }
276 if !(t.lo.is_finite() && t.hi.is_finite() && t.lo <= t.hi) {
277 invalid!("tolerance {i} ({}): range [{}, {}]", t.label, t.lo, t.hi);
278 }
279 let prev = i.checked_sub(1).map(|j| self.tols[j].dist);
280 let next = self.tols.get(i + 1).map(|u| u.dist);
281 let bad = match t.dist {
282 Dist::DiscX { normal } => next != Some(Dist::DiscY { normal }),
283 Dist::DiscY { normal } => prev != Some(Dist::DiscX { normal }),
284 _ => false,
285 };
286 if bad {
287 invalid!(
288 "tolerance {i} ({}): a distribution in a circle puts y (disc_y) of the same distribution right after x (disc_x)",
289 t.label
290 );
291 }
292 if let Dist::Normal { cut }
293 | Dist::DiscX { normal: Some(cut) }
294 | Dist::DiscY { normal: Some(cut) } = t.dist
295 {
296 if !(cut > 0.0) {
297 invalid!(
298 "tolerance {i} ({}): number of σ of the normal distribution {cut}",
299 t.label
300 );
301 }
302 }
303 for p in &t.params {
304 if p.kind.is_object() {
305 invalid!(
306 "tolerance {i} ({}): moving the object point is not system data",
307 t.label
308 );
309 }
310 for s in &self.problem.configs {
311 s.check_param(*p)?;
312 if s.pickup_of(*p).is_some() {
313 invalid!(
314 "tolerance {i} ({}): {} is set by a pickup (give it to the source surface)",
315 t.label,
316 s.param_name(*p)
317 );
318 }
319 }
320 }
321 }
322 Ok(())
323 }
324}
325
326#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
328pub struct Eval {
329 #[serde(deserialize_with = "nan_null::one")]
331 pub merit: f64,
332 #[serde(with = "nan_null")]
334 pub terms: Vec<f64>,
335 #[serde(with = "nan_null")]
337 pub comp: Vec<f64>,
338}
339
340mod nan_null {
342 use serde::{Deserialize, Deserializer, Serialize, Serializer};
343
344 pub(super) fn serialize<S: Serializer>(v: &[f64], s: S) -> Result<S::Ok, S::Error> {
345 v.iter()
346 .map(|x| x.is_finite().then_some(*x))
347 .collect::<Vec<_>>()
348 .serialize(s)
349 }
350
351 pub(super) fn one<'de, D: Deserializer<'de>>(d: D) -> Result<f64, D::Error> {
353 Ok(Option::<f64>::deserialize(d)?.unwrap_or(f64::NAN))
354 }
355
356 pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<f64>, D::Error> {
357 Ok(Vec::<Option<f64>>::deserialize(d)?
358 .into_iter()
359 .map(|x| x.unwrap_or(f64::NAN))
360 .collect())
361 }
362}
363
364#[derive(serde::Serialize, serde::Deserialize)]
366struct Row {
367 #[serde(with = "nan_null")]
368 deltas: Vec<f64>,
369 eval: Option<Eval>,
370 error: Option<String>,
371}
372
373#[derive(Debug, Clone, PartialEq)]
375pub struct Trial {
376 pub deltas: Vec<f64>,
378 pub eval: Option<Eval>,
380 pub error: Option<String>,
381}
382
383#[derive(Debug, Clone, PartialEq)]
385pub struct Sens {
386 pub tol: usize,
387 pub lo: Option<Eval>,
389 pub hi: Option<Eval>,
390}
391
392impl Sens {
393 pub fn worst(&self, nominal: f64) -> f64 {
395 let d = |e: &Option<Eval>| {
396 e.as_ref()
397 .map_or(f64::INFINITY, |e| (e.merit - nominal).abs())
398 };
399 d(&self.lo).max(d(&self.hi))
400 }
401}
402
403#[derive(Debug, Clone, PartialEq)]
405pub struct Stats {
406 pub n: usize,
407 pub mean: f64,
408 pub std: f64,
409 pub min: f64,
410 pub max: f64,
411 pub percentiles: Vec<(f64, f64)>,
413}
414
415pub fn stats(values: &[f64], pcts: &[f64]) -> Stats {
417 let mut v: Vec<f64> = values.iter().copied().filter(|x| x.is_finite()).collect();
418 v.sort_by(|a, b| a.total_cmp(b));
419 let n = v.len();
420 if n == 0 {
421 return Stats {
422 n,
423 mean: f64::NAN,
424 std: f64::NAN,
425 min: f64::NAN,
426 max: f64::NAN,
427 percentiles: pcts.iter().map(|&p| (p, f64::NAN)).collect(),
428 };
429 }
430 let mean = v.iter().sum::<f64>() / n as f64;
431 let var = if n > 1 {
432 v.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64
433 } else {
434 0.0
435 };
436 let pct = |p: f64| {
437 let q = (p / 100.0).clamp(0.0, 1.0) * (n - 1) as f64;
438 let i = q.floor() as usize;
439 let f = q - i as f64;
440 if i + 1 < n {
441 v[i] + f * (v[i + 1] - v[i])
442 } else {
443 v[n - 1]
444 }
445 };
446 Stats {
447 n,
448 mean,
449 std: var.sqrt(),
450 min: v[0],
451 max: v[n - 1],
452 percentiles: pcts.iter().map(|&p| (p, pct(p))).collect(),
453 }
454}
455
456#[derive(Debug, Clone, PartialEq)]
458pub struct McResult {
459 pub nominal: Eval,
461 pub trials: Vec<Trial>,
462 pub sensitivity: Vec<Sens>,
464 pub cancelled: bool,
466 pub inverse: Option<Vec<InverseTol>>,
468}
469
470impl McResult {
471 pub fn merits(&self) -> Vec<f64> {
473 self.trials
474 .iter()
475 .filter_map(|t| t.eval.as_ref().map(|e| e.merit))
476 .collect()
477 }
478
479 pub fn term(&self, k: usize) -> Vec<f64> {
481 self.trials
482 .iter()
483 .filter_map(|t| t.eval.as_ref().and_then(|e| e.terms.get(k).copied()))
484 .collect()
485 }
486
487 pub fn correlation(&self, tols: &[Tol]) -> Vec<(f64, f64)> {
491 let ok: Vec<&Trial> = self.trials.iter().filter(|t| t.eval.is_some()).collect();
492 let m: Vec<f64> = ok
493 .iter()
494 .map(|t| {
495 t.eval
496 .as_ref()
497 .expect("only trials with an evaluation")
498 .merit
499 })
500 .collect();
501 tols.iter()
502 .enumerate()
503 .map(|(i, t)| {
504 let c = 0.5 * (t.lo + t.hi);
505 let d: Vec<f64> = ok.iter().map(|x| x.deltas[i]).collect();
506 let a: Vec<f64> = d.iter().map(|x| (x - c).abs()).collect();
507 (pearson(&d, &m), pearson(&a, &m))
508 })
509 .collect()
510 }
511}
512
513fn pearson(a: &[f64], b: &[f64]) -> f64 {
514 let n = a.len();
515 if n < 3 {
516 return f64::NAN;
517 }
518 let ma = a.iter().sum::<f64>() / n as f64;
519 let mb = b.iter().sum::<f64>() / n as f64;
520 let (mut sab, mut saa, mut sbb) = (0.0, 0.0, 0.0);
521 for i in 0..n {
522 let (x, y) = (a[i] - ma, b[i] - mb);
523 sab += x * y;
524 saa += x * x;
525 sbb += y * y;
526 }
527 if saa > 0.0 && sbb > 0.0 {
528 sab / (saa * sbb).sqrt()
529 } else {
530 f64::NAN
531 }
532}
533
534impl Tol {
537 pub fn sample_dist(&self) -> runs::Dist {
539 let (c, h) = (0.5 * (self.lo + self.hi), 0.5 * (self.hi - self.lo));
540 match self.dist {
541 Dist::Uniform => runs::Dist::Uniform {
542 lo: self.lo,
543 hi: self.hi,
544 },
545 Dist::Normal { cut } => runs::Dist::TruncNormal {
546 mean: c,
547 sigma: h / cut,
548 cut,
549 },
550 Dist::End => runs::Dist::End {
551 lo: self.lo,
552 hi: self.hi,
553 },
554 Dist::DiscX { normal } | Dist::DiscY { normal } => runs::Dist::Disc {
555 center: c,
556 radius: h,
557 normal,
558 },
559 }
560 }
561}
562
563impl McSpec {
564 pub fn draws(&self) -> Result<Draws> {
566 let mut joints = Vec::new();
567 let mut k = 0;
568 while k < self.tols.len() {
569 if let (Dist::DiscX { normal }, Some(u)) = (self.tols[k].dist, self.tols.get(k + 1)) {
570 if u.dist == (Dist::DiscY { normal }) {
571 joints.push(Joint::Disc { x: k, y: k + 1 });
572 k += 2;
573 continue;
574 }
575 }
576 k += 1;
577 }
578 let dists = self.tols.iter().map(Tol::sample_dist).collect();
579 Draws::new(dists, None, joints, self.seed)
580 }
581}
582
583pub fn perturbed(spec: &McSpec, deltas: &[f64]) -> Result<Vec<System>> {
587 if deltas.len() != spec.tols.len() {
588 invalid!(
589 "{} offsets (the tolerances are {})",
590 deltas.len(),
591 spec.tols.len()
592 );
593 }
594 spec.problem
595 .configs
596 .iter()
597 .map(|s| {
598 let mut ch: Vec<(Param, f64)> = Vec::new();
600 let mut gl: Vec<(usize, f64, f64)> = Vec::new();
602 for (t, &d) in spec.tols.iter().zip(deltas) {
603 if d == 0.0 {
604 continue;
605 }
606 if let Some(g) = &t.glass {
607 let (a, b) = if g.abbe { (0.0, d) } else { (d, 0.0) };
608 match gl.iter_mut().find(|x| x.0 == g.surf) {
609 Some(x) => (x.1, x.2) = (x.1 + a, x.2 + b),
610 None => gl.push((g.surf, a, b)),
611 }
612 continue;
613 }
614 for (k, &p) in t.params.iter().enumerate() {
615 let v0 = s.get_param(p)?;
616 let dv = t.scale_of(k) * if t.relative { v0 * d } else { d };
617 match ch.iter_mut().find(|x| x.0 == p) {
618 Some(x) => x.1 += dv,
619 None => ch.push((p, v0 + dv)),
620 }
621 }
622 }
623 let mut s = s.clone();
624 if !gl.is_empty() {
625 s.edit(|rx| {
626 for &(j, a, b) in &gl {
627 let d = &mut rx.surfaces[j];
628 d.dnd += a;
629 d.dvd += b;
630 }
631 Ok(())
632 })?;
633 }
634 if ch.is_empty() {
635 Ok(s)
636 } else {
637 s.with_params_fast(&ch)
638 }
639 })
640 .collect()
641}
642
643pub fn evaluate(spec: &McSpec, deltas: &[f64]) -> Result<Eval> {
645 let mut configs = perturbed(spec, deltas)?;
646 match spec.comp_mode {
647 CompMode::Optimize => {
648 let p = spec.problem.with_configs(configs);
649 eval_problem(&p, &spec.comp, true)
650 }
651 CompMode::Paraxial => {
652 for (c, s0) in configs.iter_mut().zip(&spec.problem.configs) {
653 *c = paraxial_focus(c, s0)?;
654 }
655 eval_fixed(&spec.problem.with_configs(configs))
656 }
657 CompMode::None => eval_fixed(&spec.problem.with_configs(configs)),
658 }
659}
660
661fn eval_fixed(p: &Problem) -> Result<Eval> {
663 eval_problem(p, &DlsOpts::default(), false)
664}
665
666fn paraxial_focus_distance(s: &System) -> Result<f64> {
668 let m = s.image() - 1;
669 let (y, u) = &s.paraxial().marginal;
670 let mirrors = s.surfaces[1..=m]
671 .iter()
672 .filter(|d| !d.ignore && d.is_mirror())
673 .count();
674 let sgn = if mirrors % 2 == 1 { -1.0 } else { 1.0 };
675 let z = -y[m] / (sgn * u[m]);
676 if !z.is_finite() {
677 invalid!("paraxial focus compensation: the marginal ray is parallel to the axis after surface {m}");
678 }
679 Ok(z)
680}
681
682fn paraxial_focus(s: &System, s0: &System) -> Result<System> {
686 let m = s.image() - 1;
687 let p = Param::new(m, Kind::Thick);
688 let defocus0 = s0.get_param(p)? - paraxial_focus_distance(s0)?;
689 let t = paraxial_focus_distance(s)? + defocus0;
690 if t == s.get_param(p)? {
691 return Ok(s.clone());
692 }
693 s.with_params_fast(&[(p, t)])
694}
695
696fn eval_problem(p: &Problem, o: &DlsOpts, compensate: bool) -> Result<Eval> {
697 let x = if compensate && !p.vars.is_empty() {
698 lensbench_optim::dls_inner(p, o)?.x
699 } else {
700 p.x0()?
701 };
702 let (merit, terms) = p.merit_and_terms(&x)?;
703 let terms = terms.into_iter().map(|t| t.value()).collect();
704 Ok(Eval {
705 merit,
706 terms,
707 comp: x,
708 })
709}
710
711type Outcome = std::result::Result<Eval, String>;
713
714type Slot = Mutex<Option<(Vec<f64>, Outcome)>>;
716
717pub fn draw_trial(spec: &McSpec, i: usize) -> Result<Vec<f64>> {
719 Ok(spec.draws()?.draw(i))
720}
721
722pub fn pair_disc(tols: &mut [Tol], normal: Option<f64>) -> usize {
726 use lensbench_core::param::Kind as K;
727 use lensbench_core::units::UnitKind as U;
728 let partner = |a: K| -> Option<K> {
729 Some(match a {
730 K::Dx => K::Dy,
731 K::Tx => K::Ty,
732 K::Unit(U::Dx) => K::Unit(U::Dy),
733 K::Unit(U::Tx) => K::Unit(U::Ty),
734 _ => return None,
735 })
736 };
737 let is_pair = |a: &Tol, b: &Tol| {
738 !a.relative
739 && !b.relative
740 && a.params.len() == b.params.len()
741 && a.scale == b.scale
742 && a.params
743 .iter()
744 .zip(&b.params)
745 .all(|(p, q)| p.index() == q.index() && partner(p.kind) == Some(q.kind))
746 };
747 let mut n = 0;
748 let mut k = 0;
749 while k + 1 < tols.len() {
750 if is_pair(&tols[k], &tols[k + 1]) {
751 tols[k].dist = Dist::DiscX { normal };
752 tols[k + 1].dist = Dist::DiscY { normal };
753 n += 1;
754 k += 2;
755 } else {
756 k += 1;
757 }
758 }
759 n
760}
761
762pub fn run(spec: &McSpec) -> Result<McResult> {
767 run_to(spec, &runs::RunOpts::default())
768}
769
770pub fn run_to(spec: &McSpec, o: &runs::RunOpts) -> Result<McResult> {
775 spec.check()?;
776 if spec.inverse.is_some() {
777 return run_inverse(spec, o);
778 }
779 let draws = spec.draws()?;
780 let nominal = match spec.comp_mode {
781 CompMode::Optimize => eval_problem(&spec.problem, &spec.comp, true)?,
782 _ => eval_fixed(&spec.problem)?,
783 };
784 let nt = spec.tols.len();
785 let ns = if spec.sensitivity { 2 * nt } else { 0 };
786 let total = ns + spec.trials;
787 let deltas_of = |k: usize| -> Vec<f64> {
789 if k < ns {
790 let (i, hi) = (k / 2, k % 2 == 1);
791 let mut d = vec![0.0; nt];
792 d[i] = if hi { spec.tols[i].hi } else { spec.tols[i].lo };
793 d
794 } else {
795 draws.draw(k - ns)
796 }
797 };
798 let out: Vec<Slot> = (0..total).map(|_| Mutex::new(None)).collect();
801 let ro = runs::RunOpts {
802 threads: o.threads,
803 out: o.out,
804 header: o.header.clone(),
805 resume: o.resume,
806 stage: "",
807 keep_going: false,
808 };
809 runs::run(total, spec.seed, &ro, |k, _| {
810 let deltas = deltas_of(k);
811 let r = evaluate(spec, &deltas);
812 if par::cancelled() {
813 return Ok(String::new());
815 }
816 let r = match r {
817 Ok(e) if e.merit.is_finite() => Ok(e),
818 Ok(_) => Err("the merit function is not finite".into()),
819 Err(e) => Err(e.to_string()),
820 };
821 let line = match (o.out, &r) {
822 (None, _) => "0".to_string(),
823 (Some(_), r) => serde_json::to_string(&Row {
824 deltas: deltas.clone(),
825 eval: r.as_ref().ok().cloned(),
826 error: r.as_ref().err().cloned(),
827 })
828 .map_err(|e| lensbench_core::Error::Invalid(e.to_string()))?,
829 };
830 *out[k].lock_ok() = Some((deltas, r));
831 Ok(line)
832 })?;
833 let mut out: Vec<Option<(Vec<f64>, Outcome)>> = out
834 .into_iter()
835 .map(|m| m.into_inner().unwrap_or_else(|e| e.into_inner()))
836 .collect();
837 if let Some(path) = o.out {
838 let (_, rows) = runs::read_results(path)?;
840 for (k, _, txt) in rows {
841 if k < total && out[k].is_none() {
842 let r: Row = serde_json::from_str(&txt)
843 .map_err(|e| format!("{}: evaluation {k}: {e}", path.display()))?;
844 let res = match (r.eval, r.error) {
845 (Some(e), _) => Ok(e),
846 (None, e) => Err(e.unwrap_or_default()),
847 };
848 out[k] = Some((r.deltas, res));
849 }
850 }
851 }
852 let trials_out = out.split_off(ns);
853 let sensitivity: Vec<Sens> = (0..ns / 2)
855 .filter_map(|i| match (&out[2 * i], &out[2 * i + 1]) {
856 (Some(lo), Some(hi)) => Some(Sens {
857 tol: i,
858 lo: lo.1.as_ref().ok().cloned(),
859 hi: hi.1.as_ref().ok().cloned(),
860 }),
861 _ => None,
862 })
863 .collect();
864 let trials = trials_out
865 .into_iter()
866 .flatten()
867 .map(|(deltas, r)| {
868 let (eval, error) = match r {
869 Ok(e) => (Some(e), None),
870 Err(e) => (None, Some(e)),
871 };
872 Trial {
873 deltas,
874 eval,
875 error,
876 }
877 })
878 .collect();
879 Ok(McResult {
880 nominal,
881 trials,
882 sensitivity,
883 cancelled: par::cancelled(),
884 inverse: None,
885 })
886}
887
888#[derive(Debug, Clone, Copy, PartialEq, Default)]
890pub struct LensTol {
891 pub radius_rel: f64,
893 pub focal_rel: f64,
895 pub thickness: f64,
897 pub wedge: f64,
899 pub dn: f64,
901 pub disp: f64,
903 pub decenter: f64,
905 pub tilt: f64,
907 pub space: f64,
909 pub wedge_first: bool,
912}
913
914impl LensTol {
915 pub fn preset(name: &str) -> Result<LensTol> {
919 let am = 1.0 / 60.0; Ok(match name.trim().to_ascii_lowercase().as_str() {
921 "commercial" | "一般" => LensTol {
922 radius_rel: 0.002,
923 focal_rel: 0.0,
924 thickness: 0.15,
925 wedge: 3.0 * am,
926 dn: 0.001,
927 disp: 0.01,
928 decenter: 0.1,
929 tilt: 3.0 * am,
930 space: 0.1,
931 wedge_first: false,
932 },
933 "precision" | "精密" => LensTol {
934 radius_rel: 0.001,
935 focal_rel: 0.0,
936 thickness: 0.05,
937 wedge: 1.0 * am,
938 dn: 0.0005,
939 disp: 0.008,
940 decenter: 0.05,
941 tilt: 1.0 * am,
942 space: 0.05,
943 wedge_first: false,
944 },
945 "high" | "高精度" => LensTol {
946 radius_rel: 0.0005,
947 focal_rel: 0.0,
948 thickness: 0.025,
949 wedge: 0.5 * am,
950 dn: 0.0002,
951 disp: 0.005,
952 decenter: 0.02,
953 tilt: 0.5 * am,
954 space: 0.02,
955 wedge_first: false,
956 },
957 "none" => LensTol::default(),
958 n => invalid!("tolerance set {n} (commercial, precision, high, none)"),
959 })
960 }
961}
962
963#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Deserialize, schemars::JsonSchema)]
965#[serde(default, deny_unknown_fields)]
966pub struct GroupTol {
967 pub decenter: f64,
969 pub tilt: f64,
971 pub shift: f64,
973}
974
975pub fn simple(
983 s: &System,
984 lens: &dyn Fn(&str) -> Option<LensTol>,
985 group: &dyn Fn(&str) -> Option<GroupTol>,
986 dist: Dist,
987) -> Vec<Tol> {
988 let ok = |p: Param| s.check_param(p).is_ok() && s.pickup_of(p).is_none();
989 let mut out: Vec<Tol> = Vec::new();
990 let mut push = |label: String, params: Vec<(Param, f64)>, pm: f64, relative: bool| {
992 let params: Vec<(Param, f64)> = params.into_iter().filter(|&(p, _)| ok(p)).collect();
993 if pm > 0.0 && !params.is_empty() {
994 let scale: Vec<f64> = if params.iter().all(|x| x.1 == 1.0) {
995 Vec::new()
996 } else {
997 params.iter().map(|x| x.1).collect()
998 };
999 out.push(Tol {
1000 label,
1001 params: params.into_iter().map(|x| x.0).collect(),
1002 lo: -pm,
1003 hi: pm,
1004 relative,
1005 dist,
1006 scale,
1007 glass: None,
1008 });
1009 }
1010 };
1011 let one = |p: Param| vec![(p, 1.0)];
1012 let auto: Vec<usize> = (0..s.units.len()).filter(|&u| s.units[u].auto).collect();
1013 let starts: Vec<usize> = auto.iter().map(|&u| s.units[u].spans[0][0]).collect();
1014 let links = lens_links(s);
1015 for (k, &u) in auto.iter().enumerate() {
1016 let unit = &s.units[u];
1017 if links.iter().any(|l| l.others.iter().any(|o| o.auto == u)) {
1019 continue;
1020 }
1021 let link = links.iter().find(|l| l.first == u);
1022 let (name, mu) = match link {
1024 Some(l) => (s.units[l.unit].name.clone(), l.unit),
1025 None => s
1026 .units
1027 .iter()
1028 .position(|v| !v.auto && v.spans == unit.spans)
1029 .map_or((unit.name.clone(), u), |i| (s.units[i].name.clone(), i)),
1030 };
1031 let Some(t) = lens(&name) else { continue };
1032 let [a, b] = unit.spans[0];
1033 let others: Vec<LinkSpan> = link.map(|l| l.others.clone()).unwrap_or_default();
1034 let surf = |j: usize, kind: Kind| -> Vec<(Param, f64)> {
1036 let mut v = vec![(Param::new(j, kind), 1.0)];
1037 for o in &others {
1038 v.push((Param::new(o.surf(a, j), kind), 1.0));
1039 }
1040 v
1041 };
1042 let medium = |j: usize, kind: Kind, thick: bool| -> Vec<(Param, f64)> {
1044 let mut v = vec![(Param::new(j, kind), 1.0)];
1045 for o in &others {
1046 let f = if thick && o.reversed { -1.0 } else { 1.0 };
1047 v.push((Param::new(o.medium(a, j), kind), f));
1048 }
1049 v
1050 };
1051 let curved: Vec<usize> = (a..=b)
1052 .filter(|&j| {
1053 let d = &s.surfaces[j];
1054 d.c != 0.0 && ok(Param::new(j, Kind::Radius))
1055 })
1056 .collect();
1057 for &j in &curved {
1058 push(
1059 format!("{name} R{}", j - a + 1),
1060 surf(j, Kind::Radius),
1061 t.radius_rel,
1062 true,
1063 );
1064 }
1065 push(
1066 format!("{name} focal length"),
1067 curved.iter().flat_map(|&j| surf(j, Kind::Radius)).collect(),
1068 t.focal_rel,
1069 true,
1070 );
1071 let media: Vec<usize> = s
1072 .unit_media(u)
1073 .into_iter()
1074 .filter(|&j| (a..=b).contains(&j))
1075 .collect();
1076 for &j in &media {
1077 if j < b {
1078 push(
1079 format!("{name} thickness {}", j - a + 1),
1080 medium(j, Kind::Thick, true),
1081 t.thickness,
1082 false,
1083 );
1084 }
1085 }
1086 for &j in &media {
1087 push(
1088 format!("{name} index {}", j - a + 1),
1089 medium(j, Kind::Dn, false),
1090 t.dn,
1091 false,
1092 );
1093 push(
1094 format!("{name} dispersion {}", j - a + 1),
1095 medium(j, Kind::Disp, false),
1096 t.disp,
1097 false,
1098 );
1099 }
1100 let flipped = s.units[u].flipped || s.units[mu].flipped;
1102 let wf = if t.wedge_first != flipped { a } else { b };
1103 push(
1104 format!("{name} wedge x"),
1105 surf(wf, Kind::Tx),
1106 t.wedge,
1107 false,
1108 );
1109 push(
1110 format!("{name} wedge y"),
1111 surf(wf, Kind::Ty),
1112 t.wedge,
1113 false,
1114 );
1115 push(
1116 format!("{name} decenter x"),
1117 one(Param::unit(mu, UnitKind::Dx)),
1118 t.decenter,
1119 false,
1120 );
1121 push(
1122 format!("{name} decenter y"),
1123 one(Param::unit(mu, UnitKind::Dy)),
1124 t.decenter,
1125 false,
1126 );
1127 push(
1128 format!("{name} tilt x"),
1129 one(Param::unit(mu, UnitKind::Tx)),
1130 t.tilt,
1131 false,
1132 );
1133 push(
1134 format!("{name} tilt y"),
1135 one(Param::unit(mu, UnitKind::Ty)),
1136 t.tilt,
1137 false,
1138 );
1139 if k + 1 < starts.len() && b < starts[k + 1] {
1140 let mut v = vec![(Param::new(b, Kind::Thick), 1.0)];
1142 for o in &others {
1143 if let Some((j, f)) = o.space() {
1144 v.push((Param::new(j, Kind::Thick), f));
1145 }
1146 }
1147 push(format!("{name} space after"), v, t.space, false);
1148 }
1149 }
1150 for u in 0..s.units.len() {
1151 let unit = &s.units[u];
1152 if unit.auto {
1153 continue;
1154 }
1155 let Some(g) = group(&unit.name) else { continue };
1156 let is_lens = s.units.iter().any(|v| v.auto && v.spans == unit.spans)
1158 || links.iter().any(|l| l.unit == u);
1159 let name = &unit.name;
1160 let lab = |g: String, b: String| if is_lens { g } else { b };
1161 push(
1162 lab(
1163 format!("{name} group decenter x"),
1164 format!("{name} decenter x"),
1165 ),
1166 one(Param::unit(u, UnitKind::Dx)),
1167 g.decenter,
1168 false,
1169 );
1170 push(
1171 lab(
1172 format!("{name} group decenter y"),
1173 format!("{name} decenter y"),
1174 ),
1175 one(Param::unit(u, UnitKind::Dy)),
1176 g.decenter,
1177 false,
1178 );
1179 push(
1180 lab(format!("{name} group tilt x"), format!("{name} tilt x")),
1181 one(Param::unit(u, UnitKind::Tx)),
1182 g.tilt,
1183 false,
1184 );
1185 push(
1186 lab(format!("{name} group tilt y"), format!("{name} tilt y")),
1187 one(Param::unit(u, UnitKind::Ty)),
1188 g.tilt,
1189 false,
1190 );
1191 push(
1192 lab(format!("{name} group shift"), format!("{name} shift")),
1193 one(Param::unit(u, UnitKind::Shift)),
1194 g.shift,
1195 false,
1196 );
1197 }
1198 out
1199}
1200
1201#[derive(Debug, Clone, Copy, PartialEq)]
1203struct LinkSpan {
1204 auto: usize,
1206 span: [usize; 2],
1208 reversed: bool,
1210 before: Option<usize>,
1212}
1213
1214impl LinkSpan {
1215 fn surf(&self, a: usize, j: usize) -> usize {
1217 let k = j - a;
1218 if self.reversed {
1219 self.span[1] - k
1220 } else {
1221 self.span[0] + k
1222 }
1223 }
1224 fn medium(&self, a: usize, j: usize) -> usize {
1226 let k = j - a;
1227 if self.reversed {
1228 self.span[1] - k - 1
1229 } else {
1230 self.span[0] + k
1231 }
1232 }
1233 fn space(&self) -> Option<(usize, f64)> {
1235 if self.reversed {
1236 self.before.map(|j| (j, -1.0))
1237 } else {
1238 Some((self.span[1], 1.0))
1239 }
1240 }
1241}
1242
1243#[derive(Debug, Clone)]
1245struct LensLink {
1246 unit: usize,
1248 first: usize,
1250 others: Vec<LinkSpan>,
1251}
1252
1253fn lens_links(s: &System) -> Vec<LensLink> {
1254 let trim = |sp: &[usize; 2]| {
1256 let cb = |j: usize| s.surfaces[j].typ() == lensbench_core::surface::SurfType::CoordBrk;
1257 let [mut a, mut b] = *sp;
1258 while a < b && cb(a) {
1259 a += 1;
1260 }
1261 while b > a && cb(b) {
1262 b -= 1;
1263 }
1264 [a, b]
1265 };
1266 let auto_of = |sp: &[usize; 2]| {
1267 s.units
1268 .iter()
1269 .position(|v| v.auto && v.spans.len() == 1 && v.spans[0] == *sp)
1270 };
1271 let mut out = Vec::new();
1272 for (i, u) in s.units.iter().enumerate() {
1273 if u.auto || u.spans.len() < 2 {
1274 continue;
1275 }
1276 let spans: Vec<[usize; 2]> = u.spans.iter().map(trim).collect();
1277 let Some(autos) = spans.iter().map(auto_of).collect::<Option<Vec<usize>>>() else {
1278 continue;
1279 };
1280 let [a, b] = spans[0];
1281 let n = b - a;
1282 let dir = |sp: &[usize; 2]| s.surfaces[sp[0]].t.signum();
1283 let mut others = Vec::new();
1284 let mut fine = true;
1285 for (k, sp) in spans.iter().enumerate().skip(1) {
1286 if sp[1] - sp[0] != n {
1287 fine = false;
1288 break;
1289 }
1290 others.push(LinkSpan {
1291 auto: autos[k],
1292 span: *sp,
1293 reversed: dir(sp) != dir(&spans[0]),
1294 before: sp[0].checked_sub(1),
1295 });
1296 }
1297 if fine {
1298 out.push(LensLink {
1299 unit: i,
1300 first: autos[0],
1301 others,
1302 });
1303 }
1304 }
1305 out
1306}