1use crate::error::Result;
11use crate::invalid;
12use crate::math::V3;
13use crate::opd::{opd_chief, to_ref_plane_point};
14use crate::system::{FieldSel, RayBuf, System, Trace};
15use std::sync::{Arc, Mutex};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Rim {
20 Closed,
22 Padded,
24}
25
26impl Rim {
27 #[inline]
29 pub fn inside(self, x: f64, y: f64) -> bool {
30 match self {
31 Rim::Closed => x * x + y * y <= 1.0,
32 Rim::Padded => x * x + y * y <= 1.0 + crate::tol::PUPIL_RIM,
33 }
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq)]
39pub enum PupilGrid {
40 WavefrontMap(usize),
42 Interferogram(usize),
45 Linear { n: usize, rim: Rim },
47 Cells(usize),
51 Sheared { n: usize, q: [[f64; 2]; 2] },
54 Gauss { rings: usize, arms: Option<usize> },
56}
57
58#[derive(Debug, Clone, Default)]
60pub struct PupilSamples {
61 pub px: Vec<f64>,
62 pub py: Vec<f64>,
63 pub cell: Vec<(usize, usize)>,
65 pub wt: Vec<f64>,
67}
68
69impl PupilSamples {
70 pub fn len(&self) -> usize {
71 self.px.len()
72 }
73 pub fn is_empty(&self) -> bool {
74 self.px.is_empty()
75 }
76}
77
78impl PupilGrid {
79 pub fn side(&self) -> Option<usize> {
81 match *self {
82 PupilGrid::WavefrontMap(n)
83 | PupilGrid::Interferogram(n)
84 | PupilGrid::Linear { n, .. }
85 | PupilGrid::Cells(n)
86 | PupilGrid::Sheared { n, .. } => Some(n),
87 PupilGrid::Gauss { .. } => None,
88 }
89 }
90
91 pub fn check(&self) -> Result<()> {
93 match *self {
94 PupilGrid::WavefrontMap(n) | PupilGrid::Interferogram(n) => {
95 if n < 4 || !n.is_multiple_of(2) {
96 invalid!("grid side {n} must be an even number 4 or more");
97 }
98 }
99 PupilGrid::Linear { n, .. } => {
100 if n < 2 {
101 invalid!("the pupil grid must be 2 or more");
102 }
103 }
104 PupilGrid::Cells(n) | PupilGrid::Sheared { n, .. } => {
105 if n < 1 {
106 invalid!("the pupil grid must be 1 or more");
107 }
108 }
109 PupilGrid::Gauss { rings, .. } => {
110 if rings == 0 {
111 invalid!("the number of rings must be 1 or more");
112 }
113 }
114 }
115 Ok(())
116 }
117
118 pub fn axis(&self) -> Option<Vec<f64>> {
120 Some(match *self {
121 PupilGrid::WavefrontMap(n) => {
122 let h = (n / 2) as f64;
123 (0..n).map(|i| (i as f64 - h) / (h - 1.0)).collect()
124 }
125 PupilGrid::Interferogram(n) => {
126 let h = (n / 2) as f64 - 1.0;
127 (0..n).map(|i| (i as f64 - h) / h).collect()
128 }
129 PupilGrid::Linear { n, .. } => (0..n)
130 .map(|i| -1.0 + 2.0 * i as f64 / (n - 1) as f64)
131 .collect(),
132 PupilGrid::Cells(n) | PupilGrid::Sheared { n, .. } => {
133 let h = 2.0 / n as f64;
134 (0..n).map(|i| -1.0 + h * (i as f64 + 0.5)).collect()
135 }
136 PupilGrid::Gauss { .. } => return None,
137 })
138 }
139
140 pub fn samples(&self) -> PupilSamples {
142 let mut s = PupilSamples::default();
143 match *self {
144 PupilGrid::WavefrontMap(_) | PupilGrid::Interferogram(_) | PupilGrid::Linear { .. } => {
145 let rim = match *self {
146 PupilGrid::Linear { rim, .. } => rim,
147 _ => Rim::Closed,
148 };
149 let g = self.axis().unwrap_or_default();
150 for (iy, &y) in g.iter().enumerate() {
151 for (ix, &x) in g.iter().enumerate() {
152 if rim.inside(x, y) {
153 s.px.push(x);
154 s.py.push(y);
155 s.cell.push((ix, iy));
156 s.wt.push(1.0);
157 }
158 }
159 }
160 }
161 PupilGrid::Cells(n) | PupilGrid::Sheared { n, .. } => {
162 let h = 2.0 / n as f64;
163 let g = self.axis().unwrap_or_default();
164 let row = |iy: &usize| -> PupilSamples {
166 let (iy, cy) = (*iy, g[*iy]);
167 let mut r = PupilSamples::default();
168 for (ix, &cx) in g.iter().enumerate() {
169 let (f, qx, qy) = match *self {
170 PupilGrid::Sheared { q, .. } => cell_frac_mapped(q, cx, cy, h),
171 _ => cell_frac(cx, cy, h),
172 };
173 if f > 0.0 {
174 r.px.push(qx);
175 r.py.push(qy);
176 r.cell.push((ix, iy));
177 r.wt.push(f);
178 }
179 }
180 r
181 };
182 let iys: Vec<usize> = (0..n).collect();
183 let rows: Vec<PupilSamples> = if n * n >= 1 << 16 {
184 crate::par::map(&iys, row)
185 } else {
186 iys.iter().map(row).collect()
187 };
188 let m: usize = rows.iter().map(|r| r.len()).sum();
189 s.px.reserve_exact(m);
190 s.py.reserve_exact(m);
191 s.cell.reserve_exact(m);
192 s.wt.reserve_exact(m);
193 for r in rows {
194 s.px.extend_from_slice(&r.px);
195 s.py.extend_from_slice(&r.py);
196 s.cell.extend_from_slice(&r.cell);
197 s.wt.extend_from_slice(&r.wt);
198 }
199 }
200 PupilGrid::Gauss { rings, arms } => {
201 let arms = arms.unwrap_or(4 * rings + 2);
202 let (u, wu) = crate::opd::gauss_legendre(rings);
203 for i in 0..rings {
204 let r = ((u[i] + 1.0) / 2.0).sqrt();
205 for a in 0..arms {
206 let ang = (a as f64 + 0.5) * 2.0 * std::f64::consts::PI / arms as f64;
207 s.px.push(r * ang.cos());
208 s.py.push(r * ang.sin());
209 s.cell.push((a, i));
210 s.wt.push(wu[i] / 2.0 / arms as f64);
211 }
212 }
213 }
214 }
215 s
216 }
217}
218
219#[derive(Debug, Clone, Copy, PartialEq)]
221pub enum RefSurface {
222 Sphere { center: V3, radius: f64, sign: f64 },
224 Plane { point: V3, normal: V3 },
226 Far { center: V3 },
230 Image,
232}
233
234#[inline]
236pub fn exit_pupil_near(expp: f64) -> bool {
237 expp.is_finite() && expp.abs() <= crate::tol::EXPP_FAR
238}
239
240pub fn check_ropd(s: &System) -> Result<()> {
242 if !s.afocal && s.ropd != 1 && s.ropd != 2 {
243 crate::notimpl!("OPD reference {} (exit pupil or infinity only)", s.ropd);
244 }
245 Ok(())
246}
247
248pub fn check_opd_reference(s: &System) -> Result<()> {
250 check_ropd(s)?;
251 if !s.afocal && s.ropd != 1 && s.exit_pupil().is_nan() {
252 invalid!(
253 "the exit pupil can't be found (the pupil helper rays can't be solved); no OPD reference"
254 );
255 }
256 Ok(())
257}
258
259impl RefSurface {
260 pub fn far_for(s: &System) -> bool {
262 !s.afocal && (s.ropd == 1 || !exit_pupil_near(s.exit_pupil()))
263 }
264
265 pub fn of(s: &System, pc: V3, kc: V3) -> RefSurface {
267 let expp = s.exit_pupil();
268 if s.afocal {
269 if s.ropd == 3 {
272 return RefSurface::Image;
273 }
274 let point = if s.ropd == 0 {
275 pc
276 } else {
277 to_ref_plane_point(expp, pc, kc)
278 };
279 return RefSurface::Plane { point, normal: kc };
280 }
281 if RefSurface::far_for(s) {
282 return RefSurface::Far { center: pc };
283 }
284 let sc = (expp - pc[2]) / kc[2];
285 RefSurface::Sphere {
286 center: pc,
287 radius: sc.abs(),
288 sign: if sc < 0.0 { 1.0 } else { -1.0 },
289 }
290 }
291
292 #[inline]
295 pub fn opl(&self, ni: f64, q: V3, k: V3, opl: f64) -> f64 {
296 use crate::math::{dot, sub};
297 match *self {
298 RefSurface::Plane { point, normal } => {
299 opl + ni * dot(sub(point, q), normal) / dot(k, normal)
300 }
301 RefSurface::Far { center } => opl - ni * dot(sub(q, center), k),
302 RefSurface::Image => opl,
303 RefSurface::Sphere {
304 center,
305 radius,
306 sign,
307 } => {
308 let dd = sub(q, center);
309 let b = dot(dd, k);
310 let c = dot(dd, dd) - radius * radius;
311 let disc = (b * b - c).sqrt();
312 let t = if sign > 0.0 { -b - disc } else { -b + disc };
313 opl + ni * t
314 }
315 }
316 }
317}
318
319#[derive(Debug)]
321pub struct PupilFunction {
322 pub field: FieldSel,
323 pub wave: usize,
325 pub ref_primary: bool,
327 pub grid: PupilGrid,
328 pub samples: PupilSamples,
329 pub opd: Vec<f64>,
331 pub mask: Vec<bool>,
333 pub rays: RayBuf,
335 pub chief: Trace,
337 pub reference: RefSurface,
339 pub amp: Vec<f64>,
342}
343
344impl PupilFunction {
345 pub fn trace(
348 s: &System,
349 field: FieldSel,
350 wave: Option<usize>,
351 grid: PupilGrid,
352 ref_primary: bool,
353 ) -> Result<Arc<PupilFunction>> {
354 Self::trace_amp(s, field, wave, grid, ref_primary, None)
355 }
356
357 pub fn trace_amp(
359 s: &System,
360 field: FieldSel,
361 wave: Option<usize>,
362 grid: PupilGrid,
363 ref_primary: bool,
364 extra: Option<&dyn PupilAmp>,
365 ) -> Result<Arc<PupilFunction>> {
366 grid.check()?;
367 if extra.is_some() {
368 return Ok(Arc::new(Self::trace_new(
369 s,
370 field,
371 wave,
372 grid,
373 ref_primary,
374 extra,
375 )?));
376 }
377 let key = PupilKey {
378 field,
379 wave: wave.unwrap_or(s.primary),
380 grid,
381 ref_primary,
382 };
383 let cache = s.pupil_cache();
384 if let Some(p) = cache.get(&key) {
385 return Ok(p);
386 }
387 let p = Arc::new(Self::trace_new(s, field, wave, grid, ref_primary, None)?);
388 cache.put(key, &p);
389 Ok(p)
390 }
391
392 fn trace_new(
394 s: &System,
395 field: FieldSel,
396 wave: Option<usize>,
397 grid: PupilGrid,
398 ref_primary: bool,
399 extra: Option<&dyn PupilAmp>,
400 ) -> Result<PupilFunction> {
401 let samples = grid.samples();
402 let (op, chief) = opd_chief(s, field, &samples.px, &samples.py, wave, ref_primary)?;
403 let mask = (0..samples.len())
404 .map(|q| op.ok(q) && op.opd[q].is_finite())
405 .collect();
406 let reference = RefSurface::of(s, chief.rays[0].xyz, chief.rays[0].lmn);
407 let wa = WaveAmp::new(s, field, wave.unwrap_or(s.primary), extra)?;
408 let amp = if wa.is_uniform() {
409 vec![1.0; samples.len()]
410 } else {
411 (0..samples.len())
412 .map(|q| wa.at(samples.px[q], samples.py[q]))
413 .collect()
414 };
415 Ok(PupilFunction {
416 amp,
417 field,
418 wave: wave.unwrap_or(s.primary),
419 ref_primary,
420 grid,
421 samples,
422 opd: op.opd,
423 mask,
424 rays: op.rays,
425 chief,
426 reference,
427 })
428 }
429
430 pub fn len(&self) -> usize {
432 self.samples.len()
433 }
434
435 pub fn is_empty(&self) -> bool {
436 self.samples.is_empty()
437 }
438
439 #[inline]
441 pub fn get(&self, q: usize) -> Option<f64> {
442 self.mask[q].then(|| self.opd[q])
443 }
444
445 pub fn map(&self) -> Vec<Vec<f64>> {
447 let Some(n) = self.grid.side() else {
448 return Vec::new();
449 };
450 let mut g = vec![vec![f64::NAN; n]; n];
451 for (q, &(ix, iy)) in self.samples.cell.iter().enumerate() {
452 if self.mask[q] {
453 g[iy][ix] = self.opd[q];
454 }
455 }
456 g
457 }
458}
459
460#[derive(Debug, Clone, Copy, PartialEq)]
462struct PupilKey {
463 field: FieldSel,
464 wave: usize,
465 grid: PupilGrid,
466 ref_primary: bool,
467}
468
469#[derive(Default)]
474pub(crate) struct PupilCache {
475 entries: Mutex<Vec<(PupilKey, Arc<PupilFunction>)>>,
476}
477
478impl std::fmt::Debug for PupilCache {
479 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480 let n = self.entries.lock().map_or(0, |e| e.len());
481 write!(f, "PupilCache({n})")
482 }
483}
484
485impl PupilCache {
486 const MAX_SAMPLES: usize = 1 << 18;
488 #[cfg(not(target_arch = "wasm32"))]
490 const MAX_TOTAL: usize = 1 << 20;
491 #[cfg(target_arch = "wasm32")]
492 const MAX_TOTAL: usize = 1 << 18;
493 const MAX_ENTRIES: usize = 8;
495
496 fn get(&self, k: &PupilKey) -> Option<Arc<PupilFunction>> {
497 let mut e = self.entries.lock().ok()?;
498 let i = e.iter().position(|(q, _)| q == k)?;
499 let hit = e.remove(i);
501 let p = hit.1.clone();
502 e.push(hit);
503 Some(p)
504 }
505
506 fn put(&self, k: PupilKey, p: &Arc<PupilFunction>) {
507 if p.len() > Self::MAX_SAMPLES {
508 return;
509 }
510 let Ok(mut e) = self.entries.lock() else {
511 return;
512 };
513 e.retain(|(q, _)| *q != k);
514 e.push((k, p.clone()));
515 while e.len() > Self::MAX_ENTRIES
516 || e.iter().map(|(_, p)| p.len()).sum::<usize>() > Self::MAX_TOTAL
517 {
518 e.remove(0);
519 }
520 }
521
522 pub(crate) fn clear(&self) {
523 if let Ok(mut e) = self.entries.lock() {
524 e.clear();
525 }
526 }
527}
528
529#[derive(Debug, Clone, Copy, PartialEq, Default, serde::Serialize, serde::Deserialize)]
545#[serde(rename_all = "snake_case")]
546#[derive(schemars::JsonSchema)]
547pub enum Apodization {
548 #[default]
550 Uniform,
551 Gaussian(f64),
553 CosineCubed,
555}
556
557impl Apodization {
558 pub fn from_zmx(kind: &str, g: f64) -> crate::Result<Apodization> {
561 let t = kind.to_ascii_uppercase();
562 Ok(match t.as_str() {
563 "0" | "UNIFORM" => Apodization::Uniform,
564 "1" | "GAUSSIAN" => {
565 if !g.is_finite() || g < 0.0 {
566 crate::invalid!(
567 "zmx apodization factor {g}: the Gaussian factor must be 0 or more"
568 );
569 }
570 Apodization::Gaussian(g)
571 }
572 "2" | "COSINE" | "COSINE_CUBED" => Apodization::CosineCubed,
573 _ => crate::notimpl!("zmx apodization type {t} (0, 1 or 2)"),
574 })
575 }
576
577 pub fn os_code(&self) -> i64 {
579 match self {
580 Apodization::Uniform => 0,
581 Apodization::Gaussian(_) => 1,
582 Apodization::CosineCubed => 2,
583 }
584 }
585
586 pub fn factor(&self) -> f64 {
588 match *self {
589 Apodization::Gaussian(g) => g,
590 _ => 0.0,
591 }
592 }
593
594 pub fn from_os_code(n: i64, g: f64) -> Apodization {
596 match n {
597 1 => Apodization::Gaussian(g),
598 2 => Apodization::CosineCubed,
599 _ => Apodization::Uniform,
600 }
601 }
602
603 pub fn is_uniform(&self) -> bool {
604 match *self {
605 Apodization::Uniform => true,
606 Apodization::Gaussian(g) => g == 0.0,
607 Apodization::CosineCubed => false,
608 }
609 }
610}
611
612pub trait PupilAmp: Sync {
615 fn amp(&self, w: usize, px: f64, py: f64) -> f64;
616}
617
618#[derive(Debug, Clone, Copy, PartialEq)]
620pub struct ApodMap {
621 kind: ApodKind,
622}
623
624#[derive(Debug, Clone, Copy, PartialEq)]
625enum ApodKind {
626 Uniform,
627 Gauss(f64),
628 Cos3 {
631 l: f64,
632 r: f64,
633 ox: f64,
634 oy: f64,
635 c0: f64,
636 },
637}
638
639impl ApodMap {
640 pub fn new(s: &System, field: FieldSel) -> Result<ApodMap> {
642 let kind = match s.apodization {
643 a if a.is_uniform() => ApodKind::Uniform,
644 Apodization::Gaussian(g) => ApodKind::Gauss(g),
645 Apodization::CosineCubed if s.infinite() => ApodKind::Uniform,
646 _ => {
647 let p = s.paraxial();
648 let l = (p.enpp + s.surfaces[0].t).abs();
649 let c = s.try_trace(field, &[0.0], &[0.0], Some(s.primary), None, false)?;
650 if !c.traced(0) {
651 invalid!("cosine cubed apodization: the chief ray can't be traced");
652 }
653 let k = c.k0[0];
655 let (ox, oy) = (-l * k[0] / k[2], -l * k[1] / k[2]);
656 let c0 = l / (ox * ox + oy * oy + l * l).sqrt();
657 if !(l > 0.0 && c0 > 0.0 && p.epd > 0.0) {
658 invalid!("cosine cubed apodization: the object or entrance pupil position is undefined");
659 }
660 ApodKind::Cos3 {
661 l,
662 r: 0.5 * p.epd,
663 ox,
664 oy,
665 c0,
666 }
667 }
668 };
669 Ok(ApodMap { kind })
670 }
671
672 pub fn is_uniform(&self) -> bool {
674 self.kind == ApodKind::Uniform
675 }
676
677 pub fn amp(&self, px: f64, py: f64) -> f64 {
679 match self.kind {
680 ApodKind::Uniform => 1.0,
681 ApodKind::Gauss(g) => (-g * (px * px + py * py)).exp(),
682 ApodKind::Cos3 { l, r, ox, oy, c0 } => {
683 let (dx, dy) = (px * r - ox, py * r - oy);
684 let c = l / (dx * dx + dy * dy + l * l).sqrt();
685 (c / c0).powf(1.5)
687 }
688 }
689 }
690}
691
692#[derive(Clone, Copy)]
694pub struct WaveAmp<'a> {
695 pub apod: ApodMap,
696 pub extra: Option<&'a dyn PupilAmp>,
697 pub wave: usize,
698}
699
700impl<'a> WaveAmp<'a> {
701 pub fn new(
702 s: &System,
703 field: FieldSel,
704 wave: usize,
705 extra: Option<&'a dyn PupilAmp>,
706 ) -> Result<WaveAmp<'a>> {
707 Ok(WaveAmp {
708 apod: ApodMap::new(s, field)?,
709 extra,
710 wave,
711 })
712 }
713
714 pub fn is_uniform(&self) -> bool {
716 self.extra.is_none() && self.apod.is_uniform()
717 }
718
719 pub fn rotationally_symmetric(&self) -> bool {
721 self.extra.is_none() && matches!(self.apod.kind, ApodKind::Uniform | ApodKind::Gauss(_))
722 }
723
724 #[inline]
726 pub fn at(&self, px: f64, py: f64) -> f64 {
727 let a = match self.extra {
728 Some(e) => self.apod.amp(px, py) * e.amp(self.wave, px, py),
729 None => self.apod.amp(px, py),
730 };
731 if a.is_finite() {
732 a
733 } else {
734 0.0
735 }
736 }
737}
738
739pub const TRANSMISSION_GRID: usize = 33;
741
742pub fn wave_weight(
750 s: &System,
751 field: FieldSel,
752 w: usize,
753 multi: bool,
754 extra: Option<&dyn PupilAmp>,
755) -> Result<f64> {
756 if !multi {
757 return Ok(1.0);
758 }
759 let k = s.weights[w];
760 let Some(e) = extra else {
761 return Ok(k);
762 };
763 if !(k > 0.0) {
764 return Ok(k);
765 }
766 let apod = ApodMap::new(s, field)?;
767 let sm = PupilGrid::Cells(TRANSMISSION_GRID).samples();
768 let (mut num, mut den) = (0.0, 0.0);
769 for q in 0..sm.len() {
770 let (px, py) = (sm.px[q], sm.py[q]);
771 let t = e.amp(w, px, py);
772 if t.is_finite() {
773 let fa = sm.wt[q] * apod.amp(px, py).powi(2);
774 num += fa * t * t;
775 den += fa;
776 }
777 }
778 Ok(if den > 0.0 { k * num / den } else { 0.0 })
779}
780
781#[doc(hidden)]
783pub fn cell_frac(cx: f64, cy: f64, h: f64) -> (f64, f64, f64) {
784 let r0 = cx.hypot(cy);
785 let half = 0.5 * h * std::f64::consts::SQRT_2;
786 if r0 + half <= 1.0 {
787 return (1.0, cx, cy);
788 }
789 if r0 - half >= 1.0 {
790 return (0.0, cx, cy);
791 }
792 let k = 8;
793 let (mut n, mut sx, mut sy) = (0usize, 0.0, 0.0);
794 for a in 0..k {
795 for b in 0..k {
796 let x = cx + h * ((a as f64 + 0.5) / k as f64 - 0.5);
797 let y = cy + h * ((b as f64 + 0.5) / k as f64 - 0.5);
798 if x * x + y * y <= 1.0 {
799 n += 1;
800 sx += x;
801 sy += y;
802 }
803 }
804 }
805 if n == 0 {
806 return (0.0, cx, cy);
807 }
808 let f = n as f64 / (k * k) as f64;
809 (f, sx / n as f64, sy / n as f64)
810}
811
812#[doc(hidden)]
815pub fn cell_frac_mapped(q: [[f64; 2]; 2], cx: f64, cy: f64, h: f64) -> (f64, f64, f64) {
816 let map = |x: f64, y: f64| (q[0][0] * x + q[0][1] * y, q[1][0] * x + q[1][1] * y);
817 let (px, py) = map(cx, cy);
818 let r0 = px.hypot(py);
819 let (u, v) = map(0.5 * h, 0.5 * h);
820 let (u2, v2) = map(0.5 * h, -0.5 * h);
821 let half = u.hypot(v).max(u2.hypot(v2));
822 if r0 + half <= 1.0 {
823 return (1.0, px, py);
824 }
825 if r0 - half >= 1.0 {
826 return (0.0, px, py);
827 }
828 let k = 8;
829 let (mut n, mut sx, mut sy) = (0usize, 0.0, 0.0);
830 for a in 0..k {
831 for b in 0..k {
832 let x = cx + h * ((a as f64 + 0.5) / k as f64 - 0.5);
833 let y = cy + h * ((b as f64 + 0.5) / k as f64 - 0.5);
834 let (x, y) = map(x, y);
835 if x * x + y * y <= 1.0 {
836 n += 1;
837 sx += x;
838 sy += y;
839 }
840 }
841 }
842 if n == 0 {
843 return (0.0, px, py);
844 }
845 let f = n as f64 / (k * k) as f64;
846 (f, sx / n as f64, sy / n as f64)
847}
848
849#[cfg(test)]
850mod tests {
851 use super::*;
852
853 #[test]
854 fn grids_keep_their_formulas() {
855 let w = PupilGrid::WavefrontMap(8).axis().unwrap();
857 let f = PupilGrid::Interferogram(8).axis().unwrap();
858 assert_eq!(w[4], 0.0);
859 assert_eq!(f[3], 0.0);
860 assert_eq!(w[1], -1.0);
861 assert_eq!(f[0], -1.0);
862 let l = PupilGrid::Linear {
863 n: 5,
864 rim: Rim::Closed,
865 }
866 .axis()
867 .unwrap();
868 assert_eq!(l, vec![-1.0, -0.5, 0.0, 0.5, 1.0]);
869 let c = PupilGrid::Cells(4).axis().unwrap();
870 assert_eq!(c, vec![-0.75, -0.25, 0.25, 0.75]);
871 let s = PupilGrid::Cells(64).samples();
873 let h = 2.0 / 64.0;
874 let a: f64 = s.wt.iter().sum::<f64>() * h * h;
875 assert!((a - std::f64::consts::PI).abs() < 2e-4, "{a}");
876 let g = PupilGrid::Gauss {
878 rings: 6,
879 arms: None,
880 }
881 .samples();
882 assert_eq!(g.len(), 6 * 26);
883 assert!((g.wt.iter().sum::<f64>() - 1.0).abs() < 1e-14);
884 }
885
886 #[test]
887 fn rim_padding_keeps_points_rounded_off_the_circle() {
888 let l = PupilGrid::Linear {
890 n: 11,
891 rim: Rim::Closed,
892 }
893 .axis()
894 .unwrap();
895 let (x, y) = (l[1], l[8]);
896 assert!(x * x + y * y > 1.0);
897 assert!(!Rim::Closed.inside(x, y) && Rim::Padded.inside(x, y));
898 let n = |rim| PupilGrid::Linear { n: 11, rim }.samples().len();
899 assert_eq!(n(Rim::Padded), n(Rim::Closed) + 4);
900 assert!(Rim::Closed.inside(1.0, 0.0) && Rim::Padded.inside(1.0, 0.0));
901 }
902
903 #[test]
904 fn grid_sizes_are_checked() {
905 assert!(PupilGrid::WavefrontMap(6).check().is_ok());
906 assert!(PupilGrid::WavefrontMap(5).check().is_err());
907 assert!(PupilGrid::Interferogram(2).check().is_err());
908 assert!(PupilGrid::Linear {
909 n: 1,
910 rim: Rim::Padded
911 }
912 .check()
913 .is_err());
914 assert!(PupilGrid::Gauss {
915 rings: 0,
916 arms: None
917 }
918 .check()
919 .is_err());
920 }
921}