1use crate::action::Action;
13use crate::error::Result;
14use crate::invalid;
15use crate::surface::{Aperture, Surface};
16use crate::system::System;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Kind {
20 Lens,
21 Mirror,
22 CoordBreak,
23 Surface,
25 Air,
27}
28
29#[derive(Debug, Clone)]
30pub struct Element {
31 pub kind: Kind,
32 pub from: usize,
34 pub surfaces: Vec<Surface>,
36 pub n: Vec<Vec<f64>>,
39 pub t: f64,
41 pub reversed: bool,
43}
44
45impl Element {
46 pub fn air(t: f64) -> Element {
47 Element {
48 kind: Kind::Air,
49 from: 0,
50 surfaces: Vec::new(),
51 n: Vec::new(),
52 t,
53 reversed: false,
54 }
55 }
56
57 pub fn materials(&self) -> Vec<String> {
59 let n = self.surfaces.len();
60 self.surfaces[..n.saturating_sub(1)]
61 .iter()
62 .map(|s| s.mat.name())
63 .collect()
64 }
65
66 pub fn length(&self) -> f64 {
68 self.surfaces.iter().map(|s| s.t).sum()
69 }
70
71 pub fn efl(&self, w: usize) -> f64 {
73 if self.surfaces.iter().any(|s| s.is_mirror()) {
74 return f64::NAN;
75 }
76 let mut m = [[1.0, 0.0], [0.0, 1.0]];
78 let mut n0 = 1.0;
79 let last = self.surfaces.len() - 1;
80 for (i, s) in self.surfaces.iter().enumerate() {
81 let n1 = if i == last {
82 1.0
83 } else {
84 self.n.get(i).and_then(|v| v.get(w)).copied().unwrap_or(1.0)
85 };
86 let p = match s.action() {
87 _ if s.is_coord_break() => 0.0,
88 Action::Paraxial { f, .. } => 1.0 / f,
89 Action::User(u) => u.map_or(0.0, |u| u.instance().paraxial_power()),
90 _ => (n1 - n0) * s.c,
91 };
92 m = mul(&[[1.0, 0.0], [-p, 1.0]], &m);
93 if i < last {
94 m = mul(&[[1.0, s.t / n1], [0.0, 1.0]], &m);
95 }
96 n0 = n1;
97 }
98 if m[1][0] == 0.0 {
99 f64::INFINITY
100 } else {
101 -1.0 / m[1][0]
102 }
103 }
104}
105
106fn mul(a: &[[f64; 2]; 2], b: &[[f64; 2]; 2]) -> [[f64; 2]; 2] {
107 [
108 [
109 a[0][0] * b[0][0] + a[0][1] * b[1][0],
110 a[0][0] * b[0][1] + a[0][1] * b[1][1],
111 ],
112 [
113 a[1][0] * b[0][0] + a[1][1] * b[1][0],
114 a[1][0] * b[0][1] + a[1][1] * b[1][1],
115 ],
116 ]
117}
118
119fn is_air_mat(m: &crate::surface::Material) -> bool {
120 m.is_air()
121}
122
123pub fn air_after(s: &System) -> Vec<bool> {
125 let mut out = Vec::with_capacity(s.surfaces.len());
126 let mut prev = true;
127 for (j, d) in s.surfaces.iter().enumerate() {
128 let a = if j == 0 {
129 is_air_mat(&d.mat)
130 } else if d.is_mirror() || d.is_coord_break() || d.ignore {
131 prev
132 } else {
133 is_air_mat(&d.mat)
134 };
135 out.push(a);
136 prev = a;
137 }
138 out
139}
140
141pub fn split(s: &System) -> Result<Vec<Element>> {
143 let air = air_after(s);
144 if !air[0] {
145 invalid!("a system whose object space is not air is not split into lenses");
146 }
147 if !air[s.image() - 1] {
148 invalid!("a system whose image space is not air is not split into lenses");
149 }
150 Ok(split_any(s))
151}
152
153pub fn split_any(s: &System) -> Vec<Element> {
157 let air = air_after(s);
158 let ima = s.image();
159 let sf = &s.surfaces;
160 let mut out = Vec::new();
161 let mut j = 1;
162 while j < ima {
163 let d = &sf[j];
164 let (kind, k) = if !air[j] {
165 let mut k = j;
167 while !air[k] && k + 1 < ima {
168 k += 1;
169 }
170 (Kind::Lens, k)
171 } else if d.is_coord_break() {
172 (Kind::CoordBreak, j)
173 } else if d.is_mirror() {
174 (Kind::Mirror, j)
175 } else {
176 (Kind::Surface, j)
177 };
178 let mut v: Vec<Surface> = sf[j..=k].to_vec();
179 let gap = v.last().expect("non-empty element").t;
180 v.last_mut().expect("non-empty element").t = 0.0;
181 out.push(Element {
182 kind,
183 from: j,
184 surfaces: v,
185 n: (j..=k).map(|i| s.n(i).to_vec()).collect(),
186 t: 0.0,
187 reversed: false,
188 });
189 if gap != 0.0 {
190 out.push(Element::air(gap));
191 }
192 j = k + 1;
193 }
194 out
195}
196
197pub fn reversible(s: &Surface) -> bool {
202 use crate::surface::SurfType as T;
203 matches!(
204 s.typ(),
205 T::Standard
206 | T::EvenAsph
207 | T::OddAsph
208 | T::Toroidal
209 | T::Fresnel
210 | T::Binary2
211 | T::ZernikeStd
212 | T::ZernikeFringe
213 | T::GridSag
214 | T::CylFresnel
215 | T::TiltSurf
216 | T::Irregular
217 | T::Gradium
218 | T::Gradient9
219 | T::UserShape
220 )
221}
222
223pub fn reverse(e: &Element) -> Result<Element> {
226 reverse_with(e, true)
227}
228
229pub fn reverse_folded(e: &Element) -> Result<Element> {
234 reverse_with(e, false)
235}
236
237fn reverse_with(e: &Element, mirror: bool) -> Result<Element> {
238 if e.kind != Kind::Lens {
239 invalid!("only a lens can be reversed");
240 }
241 let z_rotation = |s: &Surface| s.is_coord_break() && s.cb()[..4].iter().all(|&x| x == 0.0);
243 if e.surfaces
244 .iter()
245 .any(|s| s.is_mirror() || (s.is_coord_break() && (mirror || !z_rotation(s))))
246 {
247 notimpl_rev()?;
248 }
249 let wrapped =
251 |s: &Surface| s.before.is_some() && matches!(s.after, crate::surface::After::Reverse);
252 if e.surfaces.iter().any(|s| {
253 (s.before.is_some() || !matches!(s.after, crate::surface::After::None))
254 && (mirror || !wrapped(s))
255 }) {
256 invalid!("a lens with surface tilts or decenters is not reversed");
257 }
258 let n = e.surfaces.len();
259 let mut v = Vec::with_capacity(n);
260 let mut nv = Vec::with_capacity(n);
261 for i in 0..n {
262 let mut s = e.surfaces[n - 1 - i].clone();
263 if matches!(s.action(), Action::Jones(_)) && mirror {
264 invalid!("a lens with a Jones surface is not reversed");
265 }
266 if let Some((cb, _)) = s.cb_mut() {
267 cb[4] = -cb[4];
268 }
269 if let Some(j) = s.jones_mut() {
270 j.swap(2, 4);
271 j.swap(3, 5);
272 }
273 let passes = matches!(
275 s.typ(),
276 crate::surface::SurfType::CoordBrk | crate::surface::SurfType::Jones
277 ) && !mirror;
278 if !reversible(&s) && s.typ() != crate::surface::SurfType::User && !passes {
279 invalid!("a lens with a paraxial surface is not reversed");
280 }
281 if s.bire.is_some() {
282 invalid!("a lens with a birefringent plate is not reversed");
283 }
284 s.flip_z()?;
285 if mirror {
286 s.mirror_x()?;
287 if let Some(f) = s.grid_file_mut() {
289 f.clear();
290 }
291 }
292 if mirror {
293 s.ap = match s.ap {
294 Aperture::Circular { min, max, dx, dy } => Aperture::Circular {
295 min,
296 max,
297 dx: -dx,
298 dy,
299 },
300 Aperture::Rect { hx, hy, dx, dy } => Aperture::Rect {
301 hx,
302 hy,
303 dx: -dx,
304 dy,
305 },
306 Aperture::Ellipse { hx, hy, dx, dy } => Aperture::Ellipse {
307 hx,
308 hy,
309 dx: -dx,
310 dy,
311 },
312 Aperture::Obsc { min, max, dx, dy } => Aperture::Obsc {
313 min,
314 max,
315 dx: -dx,
316 dy,
317 },
318 Aperture::Spider {
320 width,
321 arms,
322 dx,
323 dy,
324 } => {
325 if arms % 2 == 1 {
326 invalid!(
327 "a lens with a spider aperture of an odd number of arms is not reversed"
328 );
329 }
330 Aperture::Spider {
331 width,
332 arms,
333 dx: -dx,
334 dy,
335 }
336 }
337 a => a,
338 };
339 }
340 move_grin(&mut s, e, n, i, mirror)?;
342 let inherit = s.mat == crate::material::Material::Inherit;
344 let medium = (0..n - 1 - i)
345 .rev()
346 .find(|&k| e.surfaces[k].mat != crate::material::Material::Inherit)
347 .unwrap_or(n - 1);
348 s.t = if i + 1 < n {
349 e.surfaces[n - 2 - i].t
350 } else {
351 0.0
352 };
353 if !inherit {
354 s.mat = e.surfaces[medium].mat.clone();
355 }
356 nv.extend(e.n.get(medium).cloned());
357 v.push(s);
358 }
359 Ok(Element {
360 surfaces: v,
361 n: nv,
362 reversed: !e.reversed,
363 ..e.clone()
364 })
365}
366
367fn move_grin(s: &mut Surface, e: &Element, n: usize, i: usize, mirror: bool) -> Result<()> {
371 use crate::grin::GrinKind;
372 use crate::surface::SurfType as T;
373 let unresolved =
374 |q: &Surface| matches!(q.typ(), T::Gradium | T::Gradient9) && q.grin().is_none();
375 let medium = if i + 1 < n {
376 let q = &e.surfaces[n - 2 - i];
377 if unresolved(q) {
378 invalid!("a lens with a GRIN surface without a profile is not reversed");
379 }
380 q.grin().map(|g| {
381 let mut g = g.clone();
382 g.flip_z();
383 if mirror {
384 g.mirror_x();
385 }
386 if let GrinKind::Gradium { dz, .. } = &mut g.kind {
387 *dz -= q.t;
389 }
390 g
391 })
392 } else {
393 let last = &e.surfaces[n - 1];
394 if last.grin().is_some() || unresolved(last) {
395 invalid!("a lens with a GRIN medium after its last surface is not reversed");
396 }
397 None
398 };
399 if unresolved(s) {
400 invalid!("a lens with a GRIN surface without a profile is not reversed");
401 }
402 let (tan, plane) = match (s.typ(), s.grin().map(|g| &g.kind)) {
404 (T::TiltSurf, _) => ([s.asph()[0], s.asph()[1]], true),
405 (_, Some(GrinKind::Grad9 { tan, .. })) => (*tan, false),
406 _ => ([0.0; 2], false),
407 };
408 let tilted = tan != [0.0; 2];
409 match medium {
410 Some(mut g) => {
411 if !matches!(
412 s.typ(),
413 T::Standard | T::Gradium | T::Gradient9 | T::TiltSurf
414 ) {
415 invalid!(
416 "a lens whose GRIN medium ends at a surface other than a standard or tilted one is not reversed"
417 );
418 }
419 match &mut g.kind {
420 GrinKind::Grad9 { tan: t, .. } => *t = tan,
421 GrinKind::Gradium { .. } if tilted => {
422 invalid!("a lens whose Gradium medium ends at a tilted surface is not reversed")
423 }
424 GrinKind::Gradium { .. } => {}
425 }
426 if plane {
427 s.c = 0.0;
428 s.k = 0.0;
429 }
430 s.set_type(g.surf_type());
431 *s.grin_mut().expect("GRIN surface") = Some(std::sync::Arc::new(g));
432 }
433 None if s.grin().is_some() => {
434 if let Some(g) = s.grin_mut() {
435 *g = None;
436 }
437 if !tilted {
438 s.set_type(T::Standard);
439 } else if s.c == 0.0 {
440 s.set_type(T::TiltSurf);
442 s.set_asph(tan.to_vec());
443 } else {
444 invalid!(
445 "a lens with a tilted curved Gradient 9 surface after a homogeneous medium is not reversed"
446 );
447 }
448 }
449 None => {}
450 }
451 Ok(())
452}
453
454fn notimpl_rev() -> Result<()> {
455 crate::notimpl!("reversing a lens with a mirror or coordinate break")
456}
457
458pub fn assemble(base: &System, els: &[Element]) -> Result<System> {
460 let mut sf: Vec<Surface> = vec![base.surfaces[0].clone()];
461 for e in els {
462 match e.kind {
463 Kind::Air => {
464 let last = sf.last_mut().expect("non-empty element");
465 last.t += e.t;
466 }
467 _ => sf.extend(e.surfaces.iter().cloned()),
468 }
469 }
470 sf.push(base.surfaces[base.image()].clone());
471 let mut s = base.clone();
472 s.rx_mut().surfaces = sf;
473 s.rx_mut().pickups.clear();
475 s.rx_mut().solves.clear();
476 s.rx_mut().units.clear();
477 if !s.surfaces.iter().any(|d| d.stop) {
478 invalid!("the rebuilt system has no stop");
479 }
480 s.changed()?;
481 s.rx_mut().units = s.lens_units();
482 Ok(s)
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488 use std::sync::Arc;
489
490 fn sys(txt: &str) -> System {
491 let raw = crate::test_zmx::parse_text(txt).unwrap();
492 crate::test_zmx::build(&raw, &Default::default(), &[], None).unwrap()
493 }
494
495 const HEAD: &str =
496 "VERS 260327 42\nMODE SEQ\nUNIT MM X W X CM MR CPMM\nENPD 10\nFTYP 0 0 1 1 0 0 0\n\
497 XFLN 0\nYFLN 0\nFWGN 1\nWAVM 1 0.5876 1\nPWAV 1\n\
498 SURF 0\n TYPE STANDARD\n CURV 0.0\n DISZ INFINITY\n";
499
500 fn two_lenses() -> System {
502 let t = format!(
503 "{HEAD}SURF 1\n STOP\n TYPE STANDARD\n CURV 0.02\n DISZ 4\n GLAS ___BLANK 1 0 1.5168 0 0 0 0 0 0\n\
504 SURF 2\n TYPE STANDARD\n CURV -0.005\n DISZ 5\n\
505 SURF 3\n TYPE STANDARD\n CURV 0.015\n DISZ 3\n GLAS ___BLANK 1 0 1.5168 0 0 0 0 0 0\n\
506 SURF 4\n TYPE STANDARD\n CURV -0.03\n DISZ 2\n GLAS ___BLANK 1 0 1.7 0 0 0 0 0 0\n\
507 SURF 5\n TYPE STANDARD\n CURV -0.004\n DISZ 80\n\
508 SURF 6\n TYPE STANDARD\n CURV 0.0\n DISZ 0\n"
509 );
510 sys(&t)
511 }
512
513 #[test]
514 fn a_cemented_doublet_is_one_lens() {
515 let s = two_lenses();
516 let e = split(&s).unwrap();
517 let kinds: Vec<Kind> = e.iter().map(|x| x.kind).collect();
518 assert_eq!(kinds, vec![Kind::Lens, Kind::Air, Kind::Lens, Kind::Air]);
519 assert_eq!(e[2].surfaces.len(), 3);
520 assert_eq!((e[1].t, e[3].t), (5.0, 80.0));
521 let a = assemble(&s, &e).unwrap();
523 for (x, y) in a.surfaces.iter().zip(&s.surfaces) {
524 assert_eq!((x.c, x.t, &x.mat), (y.c, y.t, &y.mat));
525 }
526 assert_eq!(a.paraxial().efl, s.paraxial().efl);
527 }
528
529 #[test]
532 fn binary2_lens_reverses_and_zernike_does_not() {
533 let s = two_lenses();
534 let e = split(&s).unwrap();
535 let mut b = e[0].clone();
536 b.surfaces[1].set_type(crate::surface::SurfType::Binary2);
537 *b.surfaces[1].bin2_mut().unwrap() = Some(std::sync::Arc::new(crate::surface::Binary2 {
538 order: 1.0,
539 norm: 10.0,
540 coef: vec![-20.0],
541 }));
542 let efl = |x: &Element| {
544 let mut x = x.clone();
545 x.surfaces[0].stop = true;
546 assemble(&s, &[x, e[3].clone()]).unwrap().paraxial().efl
547 };
548 let r = reverse(&b).unwrap();
549 assert!((efl(&b) - efl(&e[0])).abs() > 1e-3 * efl(&e[0]).abs());
550 assert!((efl(&r) - efl(&b)).abs() < 1e-9 * efl(&b).abs());
551 assert_eq!(r.surfaces[0].bin2(), b.surfaces[1].bin2());
552 let mut q = e[0].clone();
554 q.surfaces[0].form = crate::surface::Form::Paraxial {
555 focal: 80.0,
556 opd_mode: 0,
557 };
558 assert!(reverse(&q).is_err());
559 let mut g = e[0].clone();
561 g.surfaces[0].set_type(crate::surface::SurfType::Gradium);
562 assert!(reverse(&g).is_err());
563 }
564
565 fn freeform_surfaces() -> Vec<Surface> {
568 use crate::freeform::{GridSag, ZernSag};
569 use crate::surface::SurfType as T;
570 use std::sync::Arc;
571 let zern = |fringe: bool| {
572 let coef: Vec<f64> = (1..=28)
573 .map(|j| 1e-3 * ((j * 7 % 11) as f64 - 5.0))
574 .collect();
575 let mut z = ZernSag::new(fringe, 8.0, coef, true);
576 z.dx = 0.7;
577 z.dy = -0.4;
578 z.rebuild();
579 Arc::new(z)
580 };
581 let mut v = Vec::new();
582 for (t, fringe) in [(T::ZernikeStd, false), (T::ZernikeFringe, true)] {
583 let mut s = Surface {
584 c: 0.02,
585 k: -0.5,
586 semi: 6.0,
587 ..Default::default()
588 };
589 s.set_type(t);
590 s.set_asph(vec![0.0, 1e-5, -2e-7]);
591 *s.zern_mut().unwrap() = Some(zern(fringe));
592 v.push(s);
593 }
594 let (nx, ny, d) = (9usize, 7usize, 1.5);
596 let mut g = GridSag {
597 nx,
598 ny,
599 dx: d,
600 dy: d,
601 xdec: 0.4,
602 ydec: -0.3,
603 z: Vec::new(),
604 nodata: vec![false; nx * ny],
605 linear: false,
606 };
607 for iy in 0..ny {
608 for ix in 0..nx {
609 let x = (ix as f64 - (nx - 1) as f64 / 2.0) * d;
610 let y = (iy as f64 - (ny - 1) as f64 / 2.0) * d;
611 g.z.push([
612 0.01 * x + 0.002 * x * y + 0.001 * x * x * y,
613 0.01 + 0.002 * y + 0.002 * x * y,
614 0.002 * x + 0.001 * x * x,
615 0.002 + 0.002 * x,
616 ]);
617 }
618 }
619 let mut s = Surface {
620 c: -0.01,
621 semi: 5.0,
622 ..Default::default()
623 };
624 s.set_type(T::GridSag);
625 s.set_asph(vec![0.0, 2e-5]);
626 *s.grid_mut().unwrap() = Some(Arc::new(g));
627 *s.grid_file_mut().unwrap() = "a.dat".into();
628 *s.zern_mut().unwrap() = Some(zern(false));
629 v.push(s);
630 let mut s = Surface::default();
631 s.set_type(T::TiltSurf);
632 s.set_asph(vec![0.03, -0.02]);
633 v.push(s);
634 let mut s = Surface {
635 c: 0.015,
636 k: 0.3,
637 semi: 7.0,
638 ..Default::default()
639 };
640 s.set_type(T::Irregular);
641 s.set_asph(vec![0.3, -0.2, 1.5, -2.5, 0.02, -0.03, 0.015, 25.0]);
642 v.push(s);
643 let mut s = Surface {
644 c: 0.01,
645 semi: 6.0,
646 ..Default::default()
647 };
648 s.set_type(T::CylFresnel);
649 s.set_asph(vec![1e-4, 1e-6]);
650 *s.cylf_mut().unwrap() = Some(Arc::new(crate::surface::CylFresnel {
651 c: 0.03,
652 k: -1.0,
653 coef: vec![1e-5],
654 }));
655 v.push(s);
656 v
657 }
658
659 #[test]
660 fn freeform_surfaces_turn_around_the_y_axis() {
661 use crate::freeform::sag_xy;
662 for s in freeform_surfaces() {
663 assert!(reversible(&s), "{:?}", s.typ());
664 let mut r = s.clone();
665 r.flip_z().unwrap();
666 r.mirror_x().unwrap();
667 let mut f = s.clone();
668 f.flip_z().unwrap();
669 for &(x, y) in &[(1.3, 0.7), (-2.1, 1.9), (0.4, -3.2), (-3.3, -1.1)] {
670 let (z, zx, zy) = sag_xy(&s, -x, y);
671 let (zr, zrx, zry) = sag_xy(&r, x, y);
672 let tol = 1e-12 * (1.0 + z.abs());
673 assert!((zr + z).abs() < tol, "{:?} {zr} {z}", s.typ());
675 assert!((zrx - zx).abs() < 1e-9, "{:?} {zrx} {zx}", s.typ());
676 assert!((zry + zy).abs() < 1e-9, "{:?} {zry} {zy}", s.typ());
677 let (z, zx, zy) = sag_xy(&s, x, y);
679 let (zf, zfx, zfy) = sag_xy(&f, x, y);
680 assert!((zf + z).abs() < tol && (zfx + zx).abs() < 1e-9 && (zfy + zy).abs() < 1e-9);
681 }
682 if let Some(c) = s.cylf() {
683 let rc = r.cylf().unwrap();
684 assert_eq!((rc.c, rc.coef[0]), (-c.c, -c.coef[0]));
685 }
686 r.flip_z().unwrap();
688 r.mirror_x().unwrap();
689 assert_eq!(r, s);
690 }
691 }
692
693 #[test]
694 fn a_freeform_lens_is_reversed_and_folded_back() {
695 let s = two_lenses();
696 let e = split(&s).unwrap();
697 for f in freeform_surfaces() {
698 let mut l = e[0].clone();
699 let (t, mat) = (l.surfaces[0].t, l.surfaces[0].mat.clone());
700 l.surfaces[0] = Surface {
701 t,
702 mat,
703 ..f.clone()
704 };
705 let r = reverse(&l).unwrap();
706 assert_eq!(r.surfaces[1].grid_file(), "");
708 assert_eq!(r.surfaces[1].typ(), f.typ());
709 let rr = reverse(&r).unwrap();
710 assert_eq!(rr.surfaces[0].zern(), l.surfaces[0].zern());
711 assert_eq!(rr.surfaces[0].grid(), l.surfaces[0].grid());
712 assert_eq!(rr.surfaces[0].asph(), l.surfaces[0].asph());
713 let mut b = reverse_folded(&l).unwrap();
715 b.surfaces[1].flip_z().unwrap();
716 assert_eq!(b.surfaces[1].zern(), l.surfaces[0].zern());
717 assert_eq!(b.surfaces[1].grid(), l.surfaces[0].grid());
718 assert_eq!(b.surfaces[1].asph(), l.surfaces[0].asph());
719 assert_eq!(b.surfaces[1].grid_file(), l.surfaces[0].grid_file());
720 }
721 }
722
723 fn lens(surfaces: Vec<Surface>) -> Element {
724 Element {
725 kind: Kind::Lens,
726 from: 0,
727 surfaces,
728 n: Vec::new(),
729 t: 0.0,
730 reversed: false,
731 }
732 }
733
734 fn grin_surface(t: crate::surface::SurfType, c: f64, th: f64, g: crate::grin::Grin) -> Surface {
735 let mut s = Surface {
736 c,
737 t: th,
738 ..Default::default()
739 };
740 s.set_type(t);
741 *s.grin_mut().unwrap() = Some(Arc::new(g));
742 s
743 }
744
745 #[test]
748 fn a_grin_lens_is_reversed_with_its_medium() {
749 use crate::grin::tests::gradium;
750 use crate::surface::SurfType as T;
751 let th = 4.0;
752 let e = lens(vec![
753 grin_surface(T::Gradium, 0.02, th, gradium([0.1, -0.05, 0.01, 0.02])),
754 Surface {
755 c: -0.01,
756 ..Default::default()
757 },
758 ]);
759 let g = e.surfaces[0].grin().unwrap();
760 let r = reverse(&e).unwrap();
761 assert_eq!(r.surfaces[0].typ(), T::Gradium);
762 assert_eq!((r.surfaces[0].c, r.surfaces[0].t), (0.01, th));
763 assert_eq!((r.surfaces[1].typ(), r.surfaces[1].c), (T::Standard, -0.02));
764 assert!(r.surfaces[1].grin().is_none());
765 let b = reverse_folded(&e).unwrap();
766 let rr = reverse(&r).unwrap();
767 let (gr, gb, grr) = (
768 r.surfaces[0].grin().unwrap(),
769 b.surfaces[0].grin().unwrap(),
770 rr.surfaces[0].grin().unwrap(),
771 );
772 assert_eq!((rr.surfaces[0].c, rr.surfaces[1].c), (0.02, -0.01));
773 for p in [[0.4, -0.3, 1.2], [-0.2, 0.5, 2.5], [0.1, 0.1, 3.6]] {
774 for lam in [0.48, 0.55, 0.65] {
775 let (n, d) = g.eval(lam, p).unwrap();
776 let (nr, dr) = gr.eval(lam, [-p[0], p[1], th - p[2]]).unwrap();
777 assert!((n - nr).abs() < 1e-12, "{p:?} {n} {nr}");
778 assert!((d[0] + dr[0]).abs() < 1e-10 && (d[1] - dr[1]).abs() < 1e-10);
779 assert!((d[2] + dr[2]).abs() < 1e-10, "{d:?} {dr:?}");
780 let (nb, db) = gb.eval(lam, [p[0], p[1], th - p[2]]).unwrap();
781 assert!((n - nb).abs() < 1e-12 && (d[0] - db[0]).abs() < 1e-10);
782 let (n2, d2) = grr.eval(lam, p).unwrap();
783 assert!((n - n2).abs() < 1e-12 && (d[2] - d2[2]).abs() < 1e-10);
784 }
785 }
786 let mut bad = e.clone();
788 bad.surfaces[1] = grin_surface(T::Gradium, -0.01, 0.0, gradium([0.0; 4]));
789 assert!(reverse(&bad).is_err());
790 }
791
792 #[test]
795 fn a_gradient9_lens_keeps_the_surface_tilts() {
796 use crate::grin::{tests::g9, GrinKind};
797 use crate::surface::SurfType as T;
798 let tilted = |c: f64, tan: [f64; 2]| {
799 let mut g = g9();
800 if let GrinKind::Grad9 { tan: t, .. } = &mut g.kind {
801 *t = tan;
802 }
803 grin_surface(T::Gradient9, c, 5.0, g)
804 };
805 let mut s1 = Surface {
806 c: 0.3,
807 ..Default::default()
808 };
809 s1.set_type(T::TiltSurf);
810 s1.set_asph(vec![0.03, 0.01]);
811 let e = lens(vec![tilted(0.0, [0.01, -0.02]), s1]);
812 let tan = |s: &Surface| match s.grin().map(|g| &g.kind) {
813 Some(GrinKind::Grad9 { tan, .. }) => *tan,
814 _ => panic!("{:?}", s.typ()),
815 };
816 let r = reverse(&e).unwrap();
817 assert_eq!(r.surfaces[0].typ(), T::Gradient9);
818 assert_eq!(tan(&r.surfaces[0]), [0.03, -0.01]);
819 assert_eq!((r.surfaces[0].c, r.surfaces[0].t), (0.0, 5.0));
820 assert_eq!(r.surfaces[1].typ(), T::TiltSurf);
821 assert_eq!(r.surfaces[1].asph(), &[0.01, 0.02]);
822 let rr = reverse(&r).unwrap();
823 assert_eq!(rr.surfaces[0].typ(), T::Gradient9);
824 assert_eq!(tan(&rr.surfaces[0]), [0.01, -0.02]);
825 assert_eq!(rr.surfaces[1].typ(), T::TiltSurf);
826 assert_eq!(rr.surfaces[1].asph(), &[0.03, 0.01]);
827 assert_eq!(rr.surfaces[0].grin(), e.surfaces[0].grin());
828 let e = lens(vec![tilted(0.02, [0.01, -0.02]), Surface::default()]);
829 assert!(reverse(&e).is_err());
830 let e = lens(vec![tilted(0.02, [0.0; 2]), Surface::default()]);
831 assert_eq!(reverse(&e).unwrap().surfaces[1].typ(), T::Standard);
832 }
833
834 #[test]
835 fn a_reversed_lens_keeps_its_focal_length() {
836 let s = two_lenses();
837 let e = split(&s).unwrap();
838 for i in [0, 2] {
839 let r = reverse(&e[i]).unwrap();
840 assert!((r.efl(0) - e[i].efl(0)).abs() < 1e-9 * e[i].efl(0).abs());
841 assert_eq!(r.length(), e[i].length());
842 let rr = reverse(&r).unwrap();
843 for (x, y) in rr.surfaces.iter().zip(&e[i].surfaces) {
844 assert_eq!((x.c, x.t, &x.mat), (y.c, y.t, &y.mat));
845 }
846 assert_eq!(rr.n, e[i].n);
847 }
848 let (n, c1, c2, d): (f64, f64, f64, f64) = (1.5168, 0.02, -0.005, 4.0);
850 let p = (n - 1.0) * (c1 - c2) + (n - 1.0).powi(2) * d * c1 * c2 / n;
851 assert!((e[0].efl(0) - 1.0 / p).abs() < 1e-9);
852 let mut v = vec![
854 reverse(&e[2]).unwrap(),
855 e[1].clone(),
856 e[0].clone(),
857 e[3].clone(),
858 ];
859 v[0].surfaces[0].stop = false;
860 v[2].surfaces[0].stop = true;
861 let a = assemble(&s, &v).unwrap();
862 assert_eq!(a.surfaces.len(), s.surfaces.len());
863 assert!(a.paraxial().efl.is_finite());
864 }
865}