1use super::*;
3use crate::pupil::quad_len;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub enum MtfDir {
8 Tan,
9 Sag,
10 Both,
12 Avg,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum MtfKind {
19 #[default]
21 Diffraction,
22 SquareWave,
25 Geometric { diff_limit: bool },
28 Huygens,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
35pub enum Quad {
36 #[default]
38 Lensbench,
39 OpticStudio,
42 Arms(usize),
45 Grid(usize),
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53pub struct Each {
54 pub medium: Medium,
55 pub upper: bool,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
60pub enum Medium {
61 #[default]
63 All,
64 Air,
66 Glass,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub enum EdgeAxis {
73 #[default]
75 PosY,
76 PosX,
78 NegY,
80 NegX,
82}
83
84impl EdgeAxis {
85 pub fn unit(self) -> (f64, f64) {
87 match self {
88 Self::PosY => (0.0, 1.0),
89 Self::PosX => (1.0, 0.0),
90 Self::NegY => (0.0, -1.0),
91 Self::NegX => (-1.0, 0.0),
92 }
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum CalcOp {
99 Sum,
101 Diff,
103 Prod,
105 Div,
107 Abs,
109 Sqrt,
111 Reci,
113 Max,
115 Min,
116 Qsum,
118 Sin,
120 Cos,
121 Tan,
122 Asin,
123 Acos,
124 Atan,
125}
126
127impl CalcOp {
128 pub fn name(self) -> &'static str {
130 match self {
131 CalcOp::Sum => "sum",
132 CalcOp::Diff => "diff",
133 CalcOp::Prod => "prod",
134 CalcOp::Div => "div",
135 CalcOp::Abs => "abs",
136 CalcOp::Sqrt => "sqrt",
137 CalcOp::Reci => "reci",
138 CalcOp::Max => "max",
139 CalcOp::Min => "min",
140 CalcOp::Qsum => "qsum",
141 CalcOp::Sin => "sin",
142 CalcOp::Cos => "cos",
143 CalcOp::Tan => "tan",
144 CalcOp::Asin => "asin",
145 CalcOp::Acos => "acos",
146 CalcOp::Atan => "atan",
147 }
148 }
149
150 pub fn apply(self, v: &[f64]) -> Result<f64> {
152 Ok(match self {
153 CalcOp::Sum => v.iter().sum(),
154 CalcOp::Diff => v[0] - v[1],
155 CalcOp::Prod => v.iter().product(),
156 CalcOp::Div | CalcOp::Reci => {
157 let (a, b) = if self == CalcOp::Div {
158 (v[0], v[1])
159 } else {
160 (1.0, v[0])
161 };
162 if b == 0.0 {
163 invalid!("division by zero in a calc term");
164 }
165 a / b
166 }
167 CalcOp::Abs => v[0].abs(),
168 CalcOp::Sqrt => v[0].abs().sqrt(),
169 CalcOp::Max => v.iter().copied().fold(f64::NEG_INFINITY, f64::max),
170 CalcOp::Min => v.iter().copied().fold(f64::INFINITY, f64::min),
171 CalcOp::Qsum => v.iter().map(|a| a * a).sum::<f64>().sqrt(),
172 CalcOp::Sin => v[0].sin(),
173 CalcOp::Cos => v[0].cos(),
174 CalcOp::Tan => v[0].tan(),
175 CalcOp::Asin | CalcOp::Acos if !(-1.0..=1.0).contains(&v[0]) => {
176 invalid!(
177 "{} of {} (outside -1 to 1) in a calc term",
178 self.name(),
179 v[0]
180 );
181 }
182 CalcOp::Asin => v[0].asin(),
183 CalcOp::Acos => v[0].acos(),
184 CalcOp::Atan => v[0].atan(),
185 })
186 }
187
188 pub fn arity(self) -> (usize, usize) {
190 match self {
191 CalcOp::Sum | CalcOp::Prod | CalcOp::Max | CalcOp::Min | CalcOp::Qsum => {
192 (1, usize::MAX)
193 }
194 CalcOp::Diff | CalcOp::Div => (2, 2),
195 _ => (1, 1),
196 }
197 }
198}
199
200#[derive(Debug, Clone, PartialEq)]
202pub enum CalcArg {
203 Term(Box<TermKind>),
205 Const(f64),
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
210pub enum SpotAxis {
211 #[default]
213 Both,
214 X,
216 Y,
218}
219
220#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum EnergyMethod {
223 Geometric { airy: bool },
226 Fft,
228 Huygens,
230}
231
232#[derive(Debug, Clone, Copy, PartialEq)]
234pub enum EnergyQ {
235 Size(f64),
237 Fraction(f64),
239}
240
241#[derive(Debug, Clone, PartialEq)]
243pub enum TermKind {
244 Spot {
246 field: FieldSel,
247 wave: Option<usize>,
248 rings: usize,
249 reference: RmsRef,
250 quad: Quad,
251 axis: SpotAxis,
252 },
253 Wavefront {
255 field: FieldSel,
256 wave: Option<usize>,
257 rings: usize,
258 reference: RmsRef,
259 quad: Quad,
260 },
261 Mtf {
263 field: FieldSel,
264 wave: Option<usize>,
265 n: Option<usize>,
266 freq: f64,
267 dir: MtfDir,
268 kind: MtfKind,
269 target: f64,
270 },
271 Paraxial {
274 q: ParaxQ,
275 wave: Option<usize>,
276 target: f64,
277 },
278 Centroid {
281 field: FieldSel,
282 wave: Option<usize>,
283 rings: usize,
284 y: bool,
285 target: f64,
286 },
287 Ray {
290 field: FieldSel,
291 wave: Option<usize>,
292 px: f64,
293 py: f64,
294 surf: Option<usize>,
295 q: RayQ,
296 target: f64,
297 },
298 ParaxRay {
301 field: FieldSel,
302 wave: Option<usize>,
303 px: f64,
304 py: f64,
305 surf: usize,
306 q: RayQ,
307 target: f64,
308 },
309 RayPath {
313 field: FieldSel,
314 wave: Option<usize>,
315 px: f64,
316 py: f64,
317 surf: usize,
318 to: usize,
319 q: RayQ,
320 upper: Option<bool>,
321 target: f64,
322 },
323 Opd {
325 field: FieldSel,
326 wave: Option<usize>,
327 px: f64,
328 py: f64,
329 target: f64,
330 },
331 Zernike {
334 field: FieldSel,
335 wave: Option<usize>,
336 kind: ZernKind,
337 term: usize,
338 fit: Option<usize>,
339 n: usize,
340 target: f64,
341 },
342 Energy {
345 field: FieldSel,
346 wave: Option<usize>,
347 n: Option<usize>,
348 method: EnergyMethod,
349 shape: lensbench_analysis::energy::EnergyShape,
350 center: lensbench_analysis::energy::EnergyCenter,
351 q: EnergyQ,
352 target: f64,
353 },
354 Spread { term: Box<TermKind>, target: f64 },
357 Diff {
360 a: usize,
361 b: usize,
362 term: Box<TermKind>,
363 target: f64,
364 },
365 Param {
368 param: lensbench_core::param::Param,
369 target: f64,
370 },
371 Strehl {
374 field: FieldSel,
375 wave: Option<usize>,
376 n: Option<usize>,
377 target: f64,
378 },
379 Illum {
382 field: FieldSel,
383 wave: Option<usize>,
384 n: Option<usize>,
385 relative: bool,
386 target: f64,
387 },
388 Coupling {
390 wave: Option<usize>,
391 opts: FiberOpts,
392 target: f64,
393 },
394 Thickness {
399 surf: usize,
400 to: usize,
401 target: f64,
402 edge: Option<f64>,
403 clear: bool,
404 axis: EdgeAxis,
405 each: Option<Each>,
406 },
407 Surface {
409 surf: usize,
410 q: SurfQ,
411 x: f64,
412 y: f64,
413 wave: Option<usize>,
415 target: f64,
416 },
417 Cardinal {
420 from: usize,
421 to: usize,
422 q: CardQ,
423 wave: Option<usize>,
424 target: f64,
425 },
426 FNum {
429 field: FieldSel,
430 wave: Option<usize>,
431 sag: bool,
432 target: f64,
433 },
434 Seidel {
437 surf: usize,
438 q: SeidelQ,
439 wave: Option<usize>,
440 target: f64,
441 },
442 Distortion {
449 wave: Option<usize>,
450 absolute: bool,
451 field: Option<FieldSel>,
452 reference: Option<FieldSel>,
453 mode: DistMode,
454 abcd: Option<[f64; 4]>,
455 component: lensbench_core::seidel::DistComp,
456 target: f64,
457 },
458 Longitudinal {
462 wave: Option<usize>,
463 wave2: Option<usize>,
464 zone: f64,
465 target: f64,
466 },
467 LateralColor {
470 wave: Option<usize>,
471 wave2: usize,
472 target: f64,
473 },
474 SurfEach {
478 q: SurfQ,
479 surf: usize,
480 to: usize,
481 upper: bool,
482 target: f64,
483 },
484 Shape { surf: usize, q: ShapeQ, target: f64 },
486 Volume {
491 surf: usize,
492 to: usize,
493 mass: bool,
494 clear: bool,
495 cylinder: bool,
497 target: f64,
498 },
499 Calc {
502 op: CalcOp,
503 args: Vec<CalcArg>,
504 target: f64,
505 },
506 User(UserTermRef),
508}
509
510#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
512pub enum DistMode {
513 #[default]
515 At,
516 Max,
518 FTheta,
520 Coef(usize),
522}
523
524#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526pub enum RayQ {
527 X,
528 Y,
529 Z,
530 L,
532 M,
533 N,
534 TraX,
536 TraY,
537 TraR,
538 AnaX,
540 AnaY,
541 AnaR,
542 DxDx,
544 DxDy,
545 DyDx,
546 DyDy,
547 FcgT,
550 FcgS,
551 Opth,
554 Gx,
556 Gy,
557 Gz,
558 Gl,
559 Gm,
560 Gn,
561 R,
563 Ang,
565 TanX,
567 TanY,
568 Nl,
570 Nm,
571 Nn,
572 Aoi,
574 Aoe,
575 CosI,
576 CosE,
577}
578
579impl RayQ {
580 pub fn recorded(&self) -> bool {
582 !matches!(
583 self,
584 RayQ::X
585 | RayQ::Y
586 | RayQ::Z
587 | RayQ::L
588 | RayQ::M
589 | RayQ::N
590 | RayQ::TraX
591 | RayQ::TraY
592 | RayQ::TraR
593 | RayQ::AnaX
594 | RayQ::AnaY
595 | RayQ::AnaR
596 | RayQ::DxDx
597 | RayQ::DxDy
598 | RayQ::DyDx
599 | RayQ::DyDy
600 | RayQ::FcgT
601 | RayQ::FcgS
602 | RayQ::Opth
603 )
604 }
605 pub fn by_diff(&self) -> bool {
607 matches!(
608 self,
609 RayQ::Z
610 | RayQ::Opth
611 | RayQ::AnaX
612 | RayQ::AnaY
613 | RayQ::AnaR
614 | RayQ::DxDx
615 | RayQ::DxDy
616 | RayQ::DyDx
617 | RayQ::DyDy
618 | RayQ::FcgT
619 | RayQ::FcgS
620 ) || self.recorded()
621 }
622 pub fn parse(s: &str) -> Result<RayQ> {
623 Ok(match s.trim().to_ascii_lowercase().as_str() {
624 "x" | "reax" => RayQ::X,
625 "y" | "reay" => RayQ::Y,
626 "z" | "reaz" => RayQ::Z,
627 "l" | "reaa" => RayQ::L,
628 "m" | "reab" => RayQ::M,
629 "n" | "reac" => RayQ::N,
630 "trax" => RayQ::TraX,
631 "tray" => RayQ::TraY,
632 "trar" => RayQ::TraR,
633 "anax" => RayQ::AnaX,
634 "anay" => RayQ::AnaY,
635 "anar" => RayQ::AnaR,
636 "dxdx" => RayQ::DxDx,
637 "dxdy" => RayQ::DxDy,
638 "dydx" => RayQ::DyDx,
639 "dydy" => RayQ::DyDy,
640 "fcgt" => RayQ::FcgT,
641 "fcgs" => RayQ::FcgS,
642 "opth" => RayQ::Opth,
643 "gx" => RayQ::Gx,
644 "gy" => RayQ::Gy,
645 "gz" => RayQ::Gz,
646 "gl" => RayQ::Gl,
647 "gm" => RayQ::Gm,
648 "gn" => RayQ::Gn,
649 "r" => RayQ::R,
650 "ang" => RayQ::Ang,
651 "tanx" => RayQ::TanX,
652 "tany" => RayQ::TanY,
653 "nl" => RayQ::Nl,
654 "nm" => RayQ::Nm,
655 "nn" => RayQ::Nn,
656 "aoi" => RayQ::Aoi,
657 "aoe" => RayQ::Aoe,
658 "cosi" => RayQ::CosI,
659 "cose" => RayQ::CosE,
660 _ => invalid!(
661 "ray quantity {s} (x, y, z, l, m, n, trax, tray, trar, anax, anay, anar, dxdx, dxdy, dydx, dydy, fcgt, fcgs, opth, gx, gy, gz, gl, gm, gn, r, ang, tanx, tany, nl, nm, nn, aoi, aoe, cosi, cose)"
662 ),
663 })
664 }
665 pub fn name(&self) -> &'static str {
666 match self {
667 RayQ::X => "x",
668 RayQ::Y => "y",
669 RayQ::Z => "z",
670 RayQ::L => "l",
671 RayQ::M => "m",
672 RayQ::N => "n",
673 RayQ::TraX => "trax",
674 RayQ::TraY => "tray",
675 RayQ::TraR => "trar",
676 RayQ::AnaX => "anax",
677 RayQ::AnaY => "anay",
678 RayQ::AnaR => "anar",
679 RayQ::DxDx => "dxdx",
680 RayQ::DxDy => "dxdy",
681 RayQ::DyDx => "dydx",
682 RayQ::DyDy => "dydy",
683 RayQ::FcgT => "fcgt",
684 RayQ::FcgS => "fcgs",
685 RayQ::Opth => "opth",
686 RayQ::Gx => "gx",
687 RayQ::Gy => "gy",
688 RayQ::Gz => "gz",
689 RayQ::Gl => "gl",
690 RayQ::Gm => "gm",
691 RayQ::Gn => "gn",
692 RayQ::R => "r",
693 RayQ::Ang => "ang",
694 RayQ::TanX => "tanx",
695 RayQ::TanY => "tany",
696 RayQ::Nl => "nl",
697 RayQ::Nm => "nm",
698 RayQ::Nn => "nn",
699 RayQ::Aoi => "aoi",
700 RayQ::Aoe => "aoe",
701 RayQ::CosI => "cosi",
702 RayQ::CosE => "cose",
703 }
704 }
705}
706
707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
710pub enum ParaxQ {
711 Efl,
713 Pmag,
715 Enpp,
717 Epd,
719 Expp,
721 Expd,
723 Wfno,
725 Pwfn,
727 Isfn,
729 Pimh,
731 Totr,
733 Obsn,
735 Isna,
737 Amag,
739 Linv,
741 Petc,
743 Petz,
744 Wlen,
746}
747
748impl ParaxQ {
749 pub const ALL: [ParaxQ; 18] = [
750 ParaxQ::Efl,
751 ParaxQ::Pmag,
752 ParaxQ::Enpp,
753 ParaxQ::Epd,
754 ParaxQ::Expp,
755 ParaxQ::Expd,
756 ParaxQ::Wfno,
757 ParaxQ::Pwfn,
758 ParaxQ::Isfn,
759 ParaxQ::Pimh,
760 ParaxQ::Totr,
761 ParaxQ::Obsn,
762 ParaxQ::Isna,
763 ParaxQ::Amag,
764 ParaxQ::Linv,
765 ParaxQ::Petc,
766 ParaxQ::Petz,
767 ParaxQ::Wlen,
768 ];
769 pub fn parse(s: &str) -> Result<ParaxQ> {
770 let t = s.trim().to_ascii_lowercase();
771 Ok(match t.as_str() {
772 "effl" => ParaxQ::Efl,
773 "mag" => ParaxQ::Pmag,
774 "epdi" => ParaxQ::Epd,
775 _ => match ParaxQ::ALL.iter().find(|q| q.name() == t) {
776 Some(q) => *q,
777 None => invalid!("paraxial {s} ({})", ParaxQ::ALL.map(|q| q.name()).join(",")),
778 },
779 })
780 }
781 pub fn name(&self) -> &'static str {
782 match self {
783 ParaxQ::Efl => "efl",
784 ParaxQ::Pmag => "pmag",
785 ParaxQ::Enpp => "enpp",
786 ParaxQ::Epd => "epd",
787 ParaxQ::Expp => "expp",
788 ParaxQ::Expd => "expd",
789 ParaxQ::Wfno => "wfno",
790 ParaxQ::Pwfn => "pwfn",
791 ParaxQ::Isfn => "isfn",
792 ParaxQ::Pimh => "pimh",
793 ParaxQ::Totr => "totr",
794 ParaxQ::Obsn => "obsn",
795 ParaxQ::Isna => "isna",
796 ParaxQ::Amag => "amag",
797 ParaxQ::Linv => "linv",
798 ParaxQ::Petc => "petc",
799 ParaxQ::Petz => "petz",
800 ParaxQ::Wlen => "wlen",
801 }
802 }
803 pub fn value_at(&self, s: &System, wave: Option<usize>) -> f64 {
805 if let Some(v) = self.at_wave(s, wave.unwrap_or(s.primary)) {
806 return v;
807 }
808 match wave {
809 Some(w) if w != s.primary => {
810 let mut d = s.clone();
811 match d.edit_raw(|rx| {
812 rx.primary = w;
813 Ok(())
814 }) {
815 Ok(()) => self.value(&d),
816 Err(_) => f64::NAN,
817 }
818 }
819 _ => self.value(s),
820 }
821 }
822 pub fn has_wave(&self) -> bool {
824 matches!(
825 self,
826 ParaxQ::Efl
827 | ParaxQ::Pimh
828 | ParaxQ::Amag
829 | ParaxQ::Linv
830 | ParaxQ::Petc
831 | ParaxQ::Petz
832 | ParaxQ::Wlen
833 )
834 }
835 fn at_wave(&self, s: &System, w: usize) -> Option<f64> {
837 let p = s.paraxial();
838 let img = s.image();
839 let chief = || {
841 let (y0, u0) = (p.chief.0[1], p.chief.1[0]);
842 s.ptrace(y0, u0, w, None)
843 };
844 Some(match self {
845 ParaxQ::Wlen => s.wavelengths[w],
846 ParaxQ::Amag => {
847 let (_, uc) = chief();
848 uc[img - 1] / p.chief.1[0]
849 }
850 ParaxQ::Linv if mirror_in(s, 1, s.stop()) => f64::NAN,
852 ParaxQ::Petc | ParaxQ::Petz if mirror_in(s, 1, img - 1) => f64::NAN,
853 ParaxQ::Linv => {
854 let (y0, u0) = (p.marginal.0[1], p.marginal.1[0]);
856 let (ym, _) = s.ptrace(y0, u0, w, None);
857 let (_, uc) = chief();
858 let st = s.stop();
859 s.n(st)[w] * uc[st] * ym[st] * chief_scale(s)
860 }
861 ParaxQ::Petc | ParaxQ::Petz => {
862 let mut sum = 0.0;
863 for j in 1..img {
864 let f = &s.surfaces[j];
865 if f.ignore || f.is_coord_break() {
866 continue;
867 }
868 let (n1, n2) = (s.index_before(j, w), s.n(j)[w]);
869 sum += (n2 - n1) * f.shape().paraxial_curv() / (n1 * n2);
870 }
871 let c = -s.image_index(w) * sum;
872 if *self == ParaxQ::Petc {
873 c
874 } else {
875 1.0 / c
876 }
877 }
878 _ => return None,
879 })
880 }
881 pub fn value(&self, s: &System) -> f64 {
883 let p = s.paraxial();
884 match self {
885 ParaxQ::Efl => return p.efl,
886 ParaxQ::Pmag => return p.pmag,
887 ParaxQ::Enpp => return p.enpp,
888 ParaxQ::Epd => return p.epd,
889 ParaxQ::Expp => return p.expp,
890 ParaxQ::Pwfn => return p.wfno,
891 ParaxQ::Isfn => return p.isfn,
892 _ => {}
893 }
894 let d = lensbench_core::report::system_data(s);
895 match self {
896 ParaxQ::Expd => d.expd,
897 ParaxQ::Wfno => d.wfno,
898 ParaxQ::Pimh => d.pimh,
899 ParaxQ::Totr => d.totr,
900 ParaxQ::Obsn => d.obsn,
901 ParaxQ::Isna => d.isna,
902 _ => unreachable!(),
903 }
904 }
905}
906
907pub trait UserTerm: Send + Sync {
909 fn name(&self) -> &str;
911 fn rows(&self) -> usize;
913 fn eval(&self, systems: &[&System]) -> Result<Vec<Vec<f64>>>;
915 fn grad(&self, _s: &System, _params: &[Param]) -> Result<Option<Vec<f64>>> {
917 Ok(None)
918 }
919}
920
921#[derive(Clone)]
923pub struct UserTermRef(pub Arc<dyn UserTerm>);
924
925impl std::fmt::Debug for UserTermRef {
926 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
927 write!(f, "UserTerm({}, {} 行)", self.0.name(), self.0.rows())
928 }
929}
930
931impl PartialEq for UserTermRef {
932 fn eq(&self, o: &Self) -> bool {
933 Arc::ptr_eq(&self.0, &o.0)
934 }
935}
936
937impl UserTermRef {
938 pub(crate) fn eval_checked(&self, systems: &[&System]) -> Result<Vec<Vec<f64>>> {
940 let v = self.0.eval(systems)?;
941 if v.len() != systems.len() {
942 invalid!(
943 "user term {}: {} results for {} systems",
944 self.0.name(),
945 systems.len(),
946 v.len()
947 );
948 }
949 for r in &v {
950 if r.len() != self.0.rows() {
951 invalid!(
952 "user term {}: {} residuals (expected {})",
953 self.0.name(),
954 r.len(),
955 self.0.rows()
956 );
957 }
958 if r.iter().any(|x| !x.is_finite()) {
959 invalid!("user term {}: non-finite residual", self.0.name());
960 }
961 }
962 Ok(v)
963 }
964}
965
966#[derive(Debug, Clone, Copy, PartialEq)]
968pub enum ShapeQ {
969 Tsag {
973 p: [f64; 3],
974 tilt: [f64; 3],
975 flat: bool,
976 },
977 Bfs { data: BfsData, rmin: f64, rmax: f64 },
979}
980
981#[derive(Debug, Clone, Copy, PartialEq, Eq)]
983pub enum BfsData {
984 Curv,
986 Radius,
988 Vertex,
990 Depth,
992 Volume,
994 Slope,
996 DepthRms,
998 SlopeRms,
1000}
1001
1002impl BfsData {
1003 pub const ALL: [BfsData; 8] = [
1004 BfsData::Curv,
1005 BfsData::Radius,
1006 BfsData::Vertex,
1007 BfsData::Depth,
1008 BfsData::Volume,
1009 BfsData::Slope,
1010 BfsData::DepthRms,
1011 BfsData::SlopeRms,
1012 ];
1013 pub fn name(self) -> &'static str {
1014 match self {
1015 BfsData::Curv => "curv",
1016 BfsData::Radius => "radius",
1017 BfsData::Vertex => "vertex",
1018 BfsData::Depth => "depth",
1019 BfsData::Volume => "volume",
1020 BfsData::Slope => "slope",
1021 BfsData::DepthRms => "depth_rms",
1022 BfsData::SlopeRms => "slope_rms",
1023 }
1024 }
1025 pub fn parse(s: &str) -> Option<BfsData> {
1026 BfsData::ALL.into_iter().find(|d| d.name() == s)
1027 }
1028}
1029
1030impl TermKind {
1031 pub fn target(&self) -> Option<f64> {
1033 match self {
1034 TermKind::Mtf { dir, target, .. } if *dir != MtfDir::Both => Some(*target),
1035 TermKind::Paraxial { target, .. }
1036 | TermKind::Ray { target, .. }
1037 | TermKind::RayPath { target, .. }
1038 | TermKind::ParaxRay { target, .. }
1039 | TermKind::Centroid { target, .. }
1040 | TermKind::Opd { target, .. }
1041 | TermKind::Zernike { target, .. }
1042 | TermKind::Coupling { target, .. }
1043 | TermKind::Thickness { target, .. }
1044 | TermKind::Surface { target, .. }
1045 | TermKind::Cardinal { target, .. }
1046 | TermKind::FNum { target, .. }
1047 | TermKind::Seidel { target, .. }
1048 | TermKind::Distortion { target, .. }
1049 | TermKind::Longitudinal { target, .. }
1050 | TermKind::LateralColor { target, .. }
1051 | TermKind::SurfEach { target, .. }
1052 | TermKind::Volume { target, .. }
1053 | TermKind::Shape { target, .. }
1054 | TermKind::Energy { target, .. }
1055 | TermKind::Strehl { target, .. }
1056 | TermKind::Param { target, .. }
1057 | TermKind::Spread { target, .. }
1058 | TermKind::Diff { target, .. }
1059 | TermKind::Illum { target, .. }
1060 | TermKind::Calc { target, .. } => Some(*target),
1061 _ => None,
1062 }
1063 }
1064}
1065
1066#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1068pub enum Side {
1069 #[default]
1071 Eq,
1072 Min,
1074 Max,
1076}
1077
1078impl Side {
1079 pub(crate) fn active(self, r: f64) -> bool {
1081 match self {
1082 Side::Eq => true,
1083 Side::Min => r < 0.0,
1084 Side::Max => r > 0.0,
1085 }
1086 }
1087}
1088
1089#[derive(Debug, Clone, PartialEq)]
1091pub struct Term {
1092 pub config: usize,
1094 pub weight: f64,
1095 pub kind: TermKind,
1096 pub side: Side,
1098}
1099
1100impl Term {
1101 pub(crate) fn clamp(&self, r: &mut [f64], j: Option<&mut Vec<f64>>) {
1103 if self.side == Side::Eq || r.len() != 1 || self.side.active(r[0]) {
1104 return;
1105 }
1106 r[0] = 0.0;
1107 if let Some(j) = j {
1108 j.iter_mut().for_each(|v| *v = 0.0);
1109 }
1110 }
1111}
1112
1113#[derive(Debug, Clone, Copy, PartialEq)]
1115pub enum TermValue {
1116 Quantity(f64),
1118 Rms(f64),
1120}
1121
1122impl TermValue {
1123 pub fn value(self) -> f64 {
1125 match self {
1126 TermValue::Quantity(v) | TermValue::Rms(v) => v,
1127 }
1128 }
1129 pub fn kind_name(self) -> &'static str {
1131 match self {
1132 TermValue::Quantity(_) => "quantity",
1133 TermValue::Rms(_) => "rms",
1134 }
1135 }
1136}
1137
1138#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1140pub struct RayCounts {
1141 pub total: usize,
1143 pub vignetted: usize,
1145 pub stopped: usize,
1147}
1148
1149impl Problem {
1150 pub fn ray_counts(&self, x: &[f64]) -> Result<Vec<Option<RayCounts>>> {
1153 let sys = self.systems(x)?;
1154 map_maybe_par(&self.terms, |t| {
1155 let (field, wave, rings, quad) = match &t.kind {
1156 TermKind::Spot {
1157 field,
1158 wave,
1159 rings,
1160 quad,
1161 ..
1162 }
1163 | TermKind::Wavefront {
1164 field,
1165 wave,
1166 rings,
1167 quad,
1168 ..
1169 } => (*field, *wave, *rings, *quad),
1170 TermKind::Centroid {
1171 field, wave, rings, ..
1172 } => (*field, *wave, *rings, Quad::Lensbench),
1173 _ => return Ok(None),
1174 };
1175 let s = &sys[t.config];
1176 let pg = crate::pupil::apodized_gauss(s, field, rings, quad, false)?.0;
1177 let mut c = RayCounts::default();
1178 for w in waves(s, wave) {
1179 let tr = s.try_trace(field, &pg.0, &pg.1, Some(w), None, false)?;
1180 c.total += tr.rays.len();
1181 c.stopped += tr.rays.iter().filter(|r| r.status.surf().is_some()).count();
1182 c.vignetted += tr
1183 .rays
1184 .iter()
1185 .filter(|r| r.status.is_ok() && r.vig != 0)
1186 .count();
1187 }
1188 Ok(Some(c))
1189 })
1190 }
1191}
1192
1193pub(super) fn term_value(k: &TermKind, r: &[f64]) -> TermValue {
1195 match k.target() {
1196 Some(target) => TermValue::Quantity(r[0] + target),
1197 None => TermValue::Rms(r.iter().map(|v| v * v).sum::<f64>().sqrt()),
1198 }
1199}
1200
1201pub(super) fn term_rows(s: &System, k: &TermKind) -> usize {
1203 match k {
1204 TermKind::Spot {
1205 wave, rings, quad, ..
1206 } => 2 * waves(s, *wave).len() * quad_len(*rings, *quad),
1207 TermKind::Wavefront {
1208 wave, rings, quad, ..
1209 } => waves(s, *wave).len() * quad_len(*rings, *quad),
1210 TermKind::Mtf { dir, .. } => {
1211 if *dir == MtfDir::Both {
1212 2
1213 } else {
1214 1
1215 }
1216 }
1217 TermKind::Paraxial { .. }
1218 | TermKind::Ray { .. }
1219 | TermKind::RayPath { .. }
1220 | TermKind::ParaxRay { .. }
1221 | TermKind::Centroid { .. }
1222 | TermKind::Opd { .. }
1223 | TermKind::Zernike { .. }
1224 | TermKind::Coupling { .. }
1225 | TermKind::Thickness { .. }
1226 | TermKind::Surface { .. }
1227 | TermKind::Cardinal { .. }
1228 | TermKind::FNum { .. }
1229 | TermKind::Seidel { .. }
1230 | TermKind::Distortion { .. }
1231 | TermKind::Longitudinal { .. }
1232 | TermKind::LateralColor { .. }
1233 | TermKind::SurfEach { .. }
1234 | TermKind::Volume { .. }
1235 | TermKind::Shape { .. }
1236 | TermKind::Energy { .. }
1237 | TermKind::Strehl { .. }
1238 | TermKind::Param { .. }
1239 | TermKind::Spread { .. }
1240 | TermKind::Diff { .. }
1241 | TermKind::Illum { .. }
1242 | TermKind::Calc { .. } => 1,
1243 TermKind::User(u) => u.0.rows(),
1244 }
1245}
1246
1247pub(super) fn mirror_in(s: &System, a: usize, b: usize) -> bool {
1249 s.surfaces
1250 .get(a..=b)
1251 .unwrap_or(&[])
1252 .iter()
1253 .any(|f| !f.ignore && f.is_mirror())
1254}
1255
1256fn chief_scale(s: &System) -> f64 {
1258 use lensbench_core::system::FieldType;
1259 let hmax = s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max);
1260 match s.field_type {
1261 FieldType::Angle => hmax.to_radians().tan(),
1262 _ => hmax,
1263 }
1264}