1use crate::analysis::{lens_quad, mtf_cutoff_axes, pupil_jacobian, LensGl, MtfAxes};
16use lensbench_core::coating::C64;
17use lensbench_core::error::Result;
18use lensbench_core::grid::Grid2;
19use lensbench_core::invalid;
20use lensbench_core::par::scoped;
21pub use lensbench_core::pupil::{cell_frac, cell_frac_mapped};
22use lensbench_core::pupil::{PupilAmp, PupilFunction, PupilGrid};
23use lensbench_core::system::{FieldSel, System};
24use lensbench_core::{TanSag, Waves};
25
26#[derive(Debug, Clone)]
28#[non_exhaustive]
29pub struct Psf {
30 pub i: Grid2,
34 pub plane: PsfPlane,
36 pub center: (f64, f64),
38 pub pixel: (f64, f64),
39 pub axes: [[f64; 3]; 2],
43 pub peak: f64,
45 pub pupil: usize,
47 pub phase_step: f64,
50 pub enclosed: f64,
52 pub warnings: Vec<String>,
54 pub device: Option<String>,
56}
57
58pub const PHASE_STEP_WARN: f64 = std::f64::consts::FRAC_PI_2;
60pub const ENCLOSED_WARN: f64 = 0.95;
62
63#[doc(hidden)]
67pub fn auto_pupil(
68 s: &System,
69 field: FieldSel,
70 ws: &[usize],
71 need: usize,
72 cap: usize,
73) -> Result<usize> {
74 let mut g: f64 = 0.0;
75 for &wi in ws {
76 g = g.max(crate::analysis::opd_slope_max(s, field, wi)?);
77 }
78 let n = if g.is_finite() {
79 ((8.0 * g).ceil() as usize).next_multiple_of(16)
80 } else {
81 cap
82 };
83 Ok(n.max(need).clamp(64, cap.max(need)))
84}
85
86#[doc(hidden)]
88pub fn phase_step(np: usize, w: &[(usize, usize, f64)]) -> f64 {
89 let mut g = vec![f64::NAN; np * np];
90 for &(ix, iy, v) in w {
91 g[iy * np + ix] = v;
92 }
93 let row = |iy: &usize| -> f64 {
95 let iy = *iy;
96 let mut m: f64 = 0.0;
97 for ix in 0..np {
98 let v = g[iy * np + ix];
99 if !v.is_finite() {
100 continue;
101 }
102 if ix + 1 < np && g[iy * np + ix + 1].is_finite() {
103 m = m.max((g[iy * np + ix + 1] - v).abs());
104 }
105 if iy + 1 < np && g[(iy + 1) * np + ix].is_finite() {
106 m = m.max((g[(iy + 1) * np + ix] - v).abs());
107 }
108 }
109 m
110 };
111 let iys: Vec<usize> = (0..np).collect();
112 let rows: Vec<f64> = if np * np >= 1 << 16 {
113 lensbench_core::par::map(&iys, row)
114 } else {
115 iys.iter().map(row).collect()
116 };
117 let m = rows.into_iter().fold(0.0, f64::max);
118 2.0 * std::f64::consts::PI * m
119}
120
121#[doc(hidden)]
123pub fn sampling_warnings(what: &str, np: usize, step: f64, enclosed: f64) -> Vec<String> {
124 let mut w = Vec::new();
125 if step > PHASE_STEP_WARN {
126 w.push(format!(
127 "{what}: the phase changes by up to {step:.2} rad between neighboring pupil samples (pupil grid {np}); above π/2 the value depends on the pupil grid (increase the pupil grid)"
128 ));
129 }
130 if enclosed < ENCLOSED_WARN {
131 w.push(format!(
132 "{what}: the image grid holds {:.1} % of the light; the grid does not cover the PSF (increase the image grid or spacing)",
133 enclosed * 100.0
134 ));
135 }
136 w
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
141pub enum PsfPlane {
142 #[default]
144 Image,
145 ChiefPerp,
148}
149
150#[derive(Debug, Clone, Copy)]
152pub struct PsfOpts {
153 pub pupil: Option<usize>,
156 pub image: usize,
158 pub pixel: Option<f64>,
162 pub plane: PsfPlane,
164}
165
166impl Default for PsfOpts {
167 fn default() -> Self {
168 PsfOpts {
169 pupil: None,
170 image: 128,
171 pixel: None,
172 plane: PsfPlane::Image,
173 }
174 }
175}
176
177fn perp_basis(k: [f64; 3]) -> ([f64; 3], [f64; 3]) {
179 let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
180 let unit = |a: [f64; 3]| {
181 let n = dot(a, a).sqrt();
182 [a[0] / n, a[1] / n, a[2] / n]
183 };
184 let e2 = unit([-k[1] * k[0], 1.0 - k[1] * k[1], -k[1] * k[2]]);
186 let e1 = [
187 e2[1] * k[2] - e2[2] * k[1],
188 e2[2] * k[0] - e2[0] * k[2],
189 e2[0] * k[1] - e2[1] * k[0],
190 ];
191 (e1, e2)
192}
193
194#[doc(hidden)]
198pub fn perp_slopes_of(s: &System, jm: [[f64; 2]; 2], k: [f64; 3]) -> (f64, f64) {
199 if s.afocal {
200 (jm[0][0], jm[1][1])
201 } else {
202 perp_slopes(jm, k)
203 }
204}
205
206#[doc(hidden)]
210pub fn plane_slopes(s: &System, jm: [[f64; 2]; 2], k: [f64; 3], plane: PsfPlane) -> (f64, f64) {
211 match plane {
212 PsfPlane::Image => (
213 jm[0][0].signum() * jm[0][0].hypot(jm[0][1]),
214 jm[1][1].signum() * jm[1][0].hypot(jm[1][1]),
215 ),
216 PsfPlane::ChiefPerp => perp_slopes_of(s, jm, k),
217 }
218}
219
220#[doc(hidden)]
226pub fn image_shear(jm: [[f64; 2]; 2]) -> Option<[[f64; 2]; 2]> {
227 let [[a, b], [c, d]] = jm;
228 let r = lensbench_core::tol::JACOBIAN_REL;
229 if b.abs() <= r * a.abs() && c.abs() <= r * d.abs() {
230 return None;
231 }
232 let det = a * d - b * c;
233 let (ga, gb) = (a.signum() * a.hypot(b), d.signum() * c.hypot(d));
234 Some([[d * ga / det, -b * gb / det], [-c * ga / det, a * gb / det]])
235}
236
237fn perp_slopes(jm: [[f64; 2]; 2], k: [f64; 3]) -> (f64, f64) {
238 let (e1, e2) = perp_basis(k);
239 let v = |c: usize| {
240 let (dl, dm) = (jm[0][c], jm[1][c]);
241 [dl, dm, -(k[0] * dl + k[1] * dm) / k[2]]
242 };
243 let (vx, vy) = (v(0), v(1));
244 (
245 vx[0] * e1[0] + vx[1] * e1[1] + vx[2] * e1[2],
246 vy[0] * e2[0] + vy[1] * e2[1] + vy[2] * e2[2],
247 )
248}
249
250pub fn psf(s: &System, field: FieldSel, w: Waves, o: PsfOpts) -> Result<Psf> {
253 psf_with(s, field, w, o, None)
254}
255
256pub fn psf_with(
259 s: &System,
260 field: FieldSel,
261 w: Waves,
262 o: PsfOpts,
263 extra: Option<&dyn PupilAmp>,
264) -> Result<Psf> {
265 let w = w.one();
266 retry_auto(o.pupil, PSF_PUPIL_CAP, |np| {
267 psf_once(s, field, w, PsfOpts { pupil: np, ..o }, extra)
268 })
269}
270
271const PSF_PUPIL_CAP: usize = 2048;
273
274#[doc(hidden)]
278pub fn retry_auto(
279 pupil: Option<usize>,
280 cap: usize,
281 run: impl Fn(Option<usize>) -> Result<Psf>,
282) -> Result<Psf> {
283 let mut r = run(pupil)?;
284 if pupil.is_some() {
285 return Ok(r);
286 }
287 for _ in 0..3 {
288 if r.phase_step <= PHASE_STEP_WARN || r.pupil >= cap {
289 break;
290 }
291 let n = ((r.pupil as f64 * r.phase_step / PHASE_STEP_WARN * 1.2).ceil() as usize)
292 .next_multiple_of(16)
293 .min(cap);
294 r = run(Some(n))?;
295 }
296 Ok(r)
297}
298
299fn psf_once(
300 s: &System,
301 field: FieldSel,
302 w: Option<usize>,
303 o: PsfOpts,
304 extra: Option<&dyn PupilAmp>,
305) -> Result<Psf> {
306 let ni = o.image;
307 if o.pupil.is_some_and(|np| np < 4) || ni < 2 {
308 invalid!(
309 "the PSF pupil grid {:?} must be 4 or more and the image grid {ni} 2 or more",
310 o.pupil
311 );
312 }
313 let ws: Vec<usize> = match w {
314 None => (0..s.wavelengths.len()).collect(),
315 Some(w) => vec![w],
316 };
317 let c = s.try_trace(field, &[0.0], &[0.0], Some(s.primary), None, false)?;
319 let (center, kc) = if c.traced(0) {
321 (s.image_point(c.rays[0].xyz, c.rays[0].lmn), c.rays[0].lmn)
322 } else {
323 ((f64::NAN, f64::NAN), [0.0, 0.0, 1.0])
324 };
325 if !(kc[2].abs() > 1e-9) {
326 invalid!("PSF: the chief ray is parallel to the image surface");
327 }
328 let axes = match o.plane {
329 PsfPlane::Image => [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
330 PsfPlane::ChiefPerp => {
331 let (e1, e2) = perp_basis(kc);
332 [e1, e2]
333 }
334 };
335 let mut cut: (f64, f64) = (0.0, 0.0);
337 for &wi in &ws {
338 if ws.len() > 1 && !(s.weights[wi] > 0.0) {
339 continue;
340 }
341 let (ga, gb) = plane_slopes(s, pupil_jacobian(s, field, wi)?, kc, o.plane);
342 let lam = s.wave(wi).mm();
343 cut.0 = cut.0.max(2.0 * (ga / lam).abs());
344 cut.1 = cut.1.max(2.0 * (gb / lam).abs());
345 }
346 let pixel = match o.pixel {
347 Some(d) if d > 0.0 => (d, d),
348 Some(d) => invalid!("PSF image grid spacing {d}"),
349 None => (0.5 / cut.0, 0.5 / cut.1),
350 };
351 let half = (ni / 2) as f64;
352 let xs: Vec<f64> = (0..ni).map(|m| (m as f64 - half) * pixel.0).collect();
353 let ys: Vec<f64> = (0..ni).map(|m| (m as f64 - half) * pixel.1).collect();
354 let np = match o.pupil {
355 Some(n) => n,
356 None => {
357 let ws: Vec<usize> = ws
358 .iter()
359 .copied()
360 .filter(|&wi| ws.len() == 1 || s.weights[wi] > 0.0)
361 .collect();
362 let need = (ni as f64 * (pixel.0 * cut.0).max(pixel.1 * cut.1)).ceil() as usize;
364 auto_pupil(s, field, &ws, need, PSF_PUPIL_CAP)?
365 }
366 };
367
368 let h = 2.0 / np as f64;
370
371 let mut tot = vec![vec![0.0; ni]; ni];
372 let (mut norm, mut wsum) = (0.0, 0.0);
373 let (mut step, mut encl): (f64, f64) = (0.0, 0.0);
374 for &wi in &ws {
375 lensbench_core::par::check_cancel()?;
376 let k = lensbench_core::pupil::wave_weight(s, field, wi, ws.len() > 1, extra)?;
377 if !(k > 0.0) {
378 continue;
379 }
380 let jm = pupil_jacobian(s, field, wi)?;
381 let (ga, gb) = plane_slopes(s, jm, kc, o.plane);
382 let grid = match (o.plane, image_shear(jm)) {
383 (PsfPlane::Image, Some(q)) => PupilGrid::Sheared { n: np, q },
384 _ => PupilGrid::Cells(np),
385 };
386 let lam = s.wave(wi).mm();
387 let (a, b) = (ga / lam, gb / lam);
389 if ni as f64 * pixel.0 * a.abs() * h > 1.0 + 1e-9
392 || ni as f64 * pixel.1 * b.abs() * h > 1.0 + 1e-9
393 {
394 invalid!(
395 "PSF: the image grid is wider than the period of the pupil sampling (wavelength {}; add pupil grid points or reduce the image grid or spacing)",
396 wi + 1
397 );
398 }
399 let op = PupilFunction::trace_amp(s, field, Some(wi), grid, true, extra)?;
400 let mut ph = vec![C64::new(0.0, 0.0); op.len()];
403 let phasor = |q: usize| match op.get(q) {
404 Some(o) => {
405 let ph = 2.0 * std::f64::consts::PI * o;
406 C64::new(ph.cos(), ph.sin()) * (op.samples.wt[q] * op.amp[q])
407 }
408 None => C64::new(0.0, 0.0),
409 };
410 if op.len() >= 1 << 14 {
411 lensbench_core::par::for_each_chunk_mut(&mut ph, 1 << 12, |c, v| {
412 for (k, z) in v.iter_mut().enumerate() {
413 *z = phasor((c << 12) + k);
414 }
415 });
416 } else {
417 ph.iter_mut().enumerate().for_each(|(q, z)| *z = phasor(q));
418 }
419 let mut p = vec![vec![C64::new(0.0, 0.0); np]; np];
420 let (mut s1, mut s2) = (0.0, 0.0);
421 let mut w_ok: Vec<(usize, usize, f64)> = Vec::with_capacity(op.len());
422 for q in 0..op.len() {
423 if let Some(o) = op.get(q) {
424 let ((ix, iy), f) = (op.samples.cell[q], op.samples.wt[q]);
425 let (fa, am) = (f * op.amp[q], op.amp[q]);
426 p[iy][ix] = ph[q];
427 s1 += fa;
428 s2 += fa * am;
429 w_ok.push((ix, iy, o));
430 }
431 }
432 if !(s2 > 0.0) {
433 invalid!(code = lensbench_core::error::code::ALL_VIGNETTED; "PSF: no valid rays (all vignetted)");
434 }
435 step = step.max(phase_step(np, &w_ok));
436 let (n0, m0) = (0.5 - 0.5 * np as f64, -half);
440 let cx = Czt::new(a * h * pixel.0, np, n0, ni, m0);
441 let cy = Czt::new(b * h * pixel.1, np, n0, ni, m0);
442 let big = np * ni >= 1 << 14 && !lensbench_core::par::sequential();
443 let stage1 = |row: &Vec<C64>| -> Vec<C64> { cx.apply(row) };
445 let g: Vec<Vec<C64>> = if big {
446 use rayon::prelude::*;
447 p.par_iter().map(scoped(stage1)).collect()
448 } else {
449 p.iter().map(stage1).collect()
450 };
451 let one = |mx: usize| -> Vec<f64> {
453 let col: Vec<C64> = g.iter().map(|r| r[mx]).collect();
454 cy.apply(&col).iter().map(|u| u.norm_sqr()).collect()
455 };
456 let cols: Vec<Vec<f64>> = if big {
457 use rayon::prelude::*;
458 (0..ni).into_par_iter().map(scoped(one)).collect()
459 } else {
460 (0..ni).map(one).collect()
461 };
462 let iw: Vec<Vec<f64>> = (0..ni)
463 .map(|my| cols.iter().map(|c| c[my]).collect())
464 .collect();
465 let e_w = s2 / (a * b * h * h).abs();
468 let dl = s1 * s1 / e_w;
470 for (t, r) in tot.iter_mut().zip(&iw) {
471 for (a, v) in t.iter_mut().zip(r) {
472 *a += k * v / e_w;
473 }
474 }
475 encl += k * iw.iter().flatten().sum::<f64>() * pixel.0 * pixel.1 / e_w;
477 norm += k * dl;
478 wsum += k;
479 }
480 if !(wsum > 0.0) {
481 invalid!("no weighted wavelength");
482 }
483 for r in tot.iter_mut() {
484 for v in r.iter_mut() {
485 *v /= norm;
486 }
487 }
488 let peak = tot.iter().flatten().cloned().fold(0.0, f64::max);
489 let enclosed = encl / wsum;
490 Ok(Psf {
491 i: Grid2::from_rows(xs, ys, tot),
492 plane: o.plane,
493 center,
494 pixel,
495 axes,
496 peak,
497 pupil: np,
498 phase_step: step,
499 enclosed,
500 warnings: sampling_warnings("PSF", np, step, enclosed),
501 device: None,
502 })
503}
504
505struct Czt {
509 l: usize,
510 pre: Vec<C64>,
512 post: Vec<C64>,
514 kern: Vec<C64>,
516 fwd: std::sync::Arc<dyn rustfft::Fft<f64>>,
517 inv: std::sync::Arc<dyn rustfft::Fft<f64>>,
518}
519
520impl Czt {
521 fn new(alpha: f64, n_in: usize, n0: f64, n_out: usize, m0: f64) -> Czt {
522 let l = (n_in + n_out).next_power_of_two();
523 let chirp = |t: f64| -> C64 {
525 let v = alpha * t;
526 let v = v - 2.0 * (0.5 * v).floor();
527 let (sn, cs) = (std::f64::consts::PI * v).sin_cos();
528 C64::new(cs, sn)
529 };
530 let pre = (0..n_in)
531 .map(|n| {
532 let n = n as f64;
533 chirp(-(n * n + 2.0 * n * m0))
534 })
535 .collect();
536 let post = (0..n_out)
537 .map(|m| {
538 let m = m as f64;
539 chirp(-(m * m + 2.0 * n0 * m + 2.0 * n0 * m0)) / l as f64
540 })
541 .collect();
542 let mut kern = vec![C64::new(0.0, 0.0); l];
543 for (k, v) in kern.iter_mut().enumerate().take(n_out) {
544 *v = chirp((k * k) as f64);
545 }
546 for k in 1..n_in {
547 kern[l - k] = chirp((k * k) as f64);
548 }
549 let mut planner = rustfft::FftPlanner::<f64>::new();
550 let (fwd, inv) = (planner.plan_fft_forward(l), planner.plan_fft_inverse(l));
551 fwd.process(&mut kern);
552 Czt {
553 l,
554 pre,
555 post,
556 kern,
557 fwd,
558 inv,
559 }
560 }
561
562 fn apply(&self, x: &[C64]) -> Vec<C64> {
564 let mut buf = vec![C64::new(0.0, 0.0); self.l];
565 for ((o, v), p) in buf.iter_mut().zip(x).zip(&self.pre) {
566 *o = v * p;
567 }
568 self.fwd.process(&mut buf);
569 for (o, k) in buf.iter_mut().zip(&self.kern) {
570 *o *= k;
571 }
572 self.inv.process(&mut buf);
573 buf.iter().zip(&self.post).map(|(v, p)| v * p).collect()
574 }
575}
576
577pub use crate::analysis::Mtf;
580
581pub fn diffraction_limit(v: f64) -> f64 {
583 let v = v.abs();
584 if v >= 1.0 {
585 return 0.0;
586 }
587 2.0 / std::f64::consts::PI * (v.acos() - v * (1.0 - v * v).sqrt())
588}
589
590pub fn geometric_mtf(
594 s: &System,
595 field: FieldSel,
596 w: Waves,
597 n: usize,
598 freqs: &[f64],
599 diff_limit: bool,
600) -> Result<Mtf> {
601 geometric_mtf_axes(s, field, w, n, freqs, diff_limit, MtfAxes::default())
602}
603
604thread_local! {
605 static GEO_BUF: std::cell::RefCell<(Vec<f64>, Vec<C64>)> = const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
607}
608
609#[allow(clippy::too_many_arguments)]
611pub fn geometric_mtf_axes(
612 s: &System,
613 field: FieldSel,
614 w: Waves,
615 n: usize,
616 freqs: &[f64],
617 diff_limit: bool,
618 axes: MtfAxes,
619) -> Result<Mtf> {
620 let w = w.one();
621 let tdir = crate::analysis::mtf_tangential(s, field, axes)?;
623 if n < 4 {
624 invalid!("geometric MTF needs 4 or more quadrature points ({n})");
625 }
626 let ws: Vec<usize> = match w {
627 None => (0..s.wavelengths.len()).collect(),
628 Some(w) => vec![w],
629 };
630 let gl = LensGl::new(n);
631 let (t, u, wq) = lens_quad(0.0, &gl);
632 let wa = crate::analysis::apodized(s, field, &u, &t, &wq)?;
634 let mut sets = Vec::new();
636 for &wi in &ws {
637 lensbench_core::par::check_cancel()?;
638 let k = if ws.len() == 1 { 1.0 } else { s.weights[wi] };
639 if !(k > 0.0) {
640 continue;
641 }
642 let r = s.try_trace(field, &u, &t, Some(wi), None, false)?;
643 let pts: Vec<(f64, f64, f64)> = (0..t.len())
644 .filter(|&i| r.ok(i))
645 .map(|i| {
646 let (x, y) = s.image_point(r.rays[i].xyz, r.rays[i].lmn);
647 let (x, y) = match tdir {
649 None => (x, y),
650 Some(t) => (x * t[1] - y * t[0], x * t[0] + y * t[1]),
651 };
652 (x, y, wa[i])
653 })
654 .collect();
655 let e: f64 = pts.iter().map(|p| p.2).sum();
656 if pts.is_empty() || !(e > 0.0) {
657 invalid!(code = lensbench_core::error::code::ALL_VIGNETTED; "geometric MTF: no valid rays (all vignetted)");
658 }
659 let cut = if diff_limit {
660 mtf_cutoff_axes(s, field, wi, axes)?
661 } else {
662 TanSag::new(f64::INFINITY, f64::INFINITY)
663 };
664 sets.push((k / e, pts, cut));
665 }
666 let wsum: f64 = sets
667 .iter()
668 .map(|x| x.0 * x.1.iter().map(|p| p.2).sum::<f64>())
669 .sum();
670 if sets.is_empty() || !(wsum > 0.0) {
671 invalid!("no weighted wavelength");
672 }
673 let (mut mx, mut my) = (0.0, 0.0);
675 for (k, pts, _) in &sets {
676 for p in pts {
677 mx += k * p.2 * p.0;
678 my += k * p.2 * p.1;
679 }
680 }
681 let (mx, my) = (mx / wsum, my / wsum);
682 let cols: Vec<[Vec<f64>; 3]> = sets
684 .iter()
685 .map(|(_, pts, _)| {
686 [
687 pts.iter().map(|p| p.0 - mx).collect(),
688 pts.iter().map(|p| p.1 - my).collect(),
689 pts.iter().map(|p| p.2).collect(),
690 ]
691 })
692 .collect();
693 let one = |f: f64| -> (f64, f64) {
696 let ph = 2.0 * std::f64::consts::PI * f;
697 let (mut a, mut b) = (C64::new(0.0, 0.0), C64::new(0.0, 0.0));
698 let sum = |pos: &[f64], wq: &[f64]| -> C64 {
700 GEO_BUF.with_borrow_mut(|(arg, out)| {
701 arg.clear();
702 arg.extend(pos.iter().map(|&x| ph * x));
703 out.clear();
704 out.resize(pos.len(), C64::new(0.0, 0.0));
705 lensbench_core::trig::cis_scaled(arg, wq, out);
706 let mut acc = C64::new(0.0, 0.0);
707 for &c in out.iter() {
708 acc += c;
709 }
710 acc
711 })
712 };
713 for ((k, _, cut), [xs, ys, wq]) in sets.iter().zip(&cols) {
714 let (aw, bw) = (sum(xs, wq), sum(ys, wq));
715 let (ds, dt) = if diff_limit {
716 (
717 diffraction_limit(f / cut.sag),
718 diffraction_limit(f / cut.tan),
719 )
720 } else {
721 (1.0, 1.0)
722 };
723 a += aw * (k * ds);
724 b += bw * (k * dt);
725 }
726 (a.norm() / wsum, b.norm() / wsum)
727 };
728 let npts: usize = sets.iter().map(|x| x.1.len()).sum();
729 let st: Vec<(f64, f64)> = if freqs.len() * npts >= 1 << 16 && !lensbench_core::par::sequential()
730 {
731 use rayon::prelude::*;
732 freqs.par_iter().map(scoped(|&f: &f64| one(f))).collect()
733 } else {
734 freqs.iter().map(|&f| one(f)).collect()
735 };
736 let (sag, tan): (Vec<f64>, Vec<f64>) = st.into_iter().unzip();
737 Ok(Mtf {
738 freqs: freqs.to_vec(),
739 tan,
740 sag,
741 cutoff: mtf_cutoff_axes(s, field, w.unwrap_or(s.primary), axes)?,
742 })
743}
744
745#[cfg(test)]
746mod tests {
747 use super::*;
748
749 #[test]
750 fn diffraction_limit_ends() {
751 assert!((diffraction_limit(0.0) - 1.0).abs() < 1e-15);
752 assert_eq!(diffraction_limit(1.0), 0.0);
753 assert_eq!(diffraction_limit(-1.0), 0.0);
755 assert_eq!(diffraction_limit(-2.5), 0.0);
756 assert_eq!(diffraction_limit(-0.5), diffraction_limit(0.5));
757 assert!((diffraction_limit(0.5) - 0.391_002_218_955_6).abs() < 1e-12);
758 }
759
760 #[test]
762 fn czt_matches_the_direct_sum() {
763 for &(alpha, n_in, n_out) in &[
764 (0.0137, 64usize, 33usize),
765 (0.25, 7, 12),
766 (1.0 / 96.0, 96, 200),
767 ] {
768 let (n0, m0) = (0.5 - 0.5 * n_in as f64, -0.5 * (n_out as f64 - 1.0));
769 let x: Vec<C64> = (0..n_in)
770 .map(|n| {
771 let t = n as f64;
772 C64::new((0.37 * t).cos(), (0.11 * t * t).sin())
773 })
774 .collect();
775 let got = Czt::new(alpha, n_in, n0, n_out, m0).apply(&x);
776 assert_eq!(got.len(), n_out);
777 for (m, g) in got.iter().enumerate() {
778 let mut want = C64::new(0.0, 0.0);
779 for (n, v) in x.iter().enumerate() {
780 let ph =
781 -2.0 * std::f64::consts::PI * alpha * (n as f64 + n0) * (m as f64 + m0);
782 want += v * C64::new(ph.cos(), ph.sin());
783 }
784 assert!(
785 (g - want).norm() < 1e-12 * n_in as f64,
786 "α={alpha} m={m}: {g} vs {want}"
787 );
788 }
789 }
790 }
791
792 #[test]
793 fn cell_fraction_sums_to_pi() {
794 let n = 64;
795 let h = 2.0 / n as f64;
796 let mut a = 0.0;
797 for iy in 0..n {
798 for ix in 0..n {
799 let cx = -1.0 + h * (ix as f64 + 0.5);
800 let cy = -1.0 + h * (iy as f64 + 0.5);
801 a += cell_frac(cx, cy, h).0 * h * h;
802 }
803 }
804 assert!((a - std::f64::consts::PI).abs() < 2e-4, "{a}");
805 }
806}
807
808#[cfg(test)]
809mod perp_tests {
810 use super::*;
811
812 #[test]
813 fn perp_slopes_divide_by_cos_for_a_tilted_chief_ray() {
814 let jm = [[0.1, 0.0], [0.0, 0.2]];
816 let (a, b) = perp_slopes(jm, [0.0, 0.0, 1.0]);
817 assert!((a - 0.1).abs() < 1e-15 && (b - 0.2).abs() < 1e-15);
818 let t: f64 = 0.35;
820 let (a, b) = perp_slopes(jm, [0.0, t.sin(), t.cos()]);
821 assert!((a - 0.1).abs() < 1e-15);
822 assert!((b - 0.2 / t.cos()).abs() < 1e-14);
823 let k = [0.2, -0.3, (1.0f64 - 0.13).sqrt()];
825 let (e1, e2) = perp_basis(k);
826 let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
827 for (u, v) in [(e1, k), (e2, k), (e1, e2)] {
828 assert!(dot(u, v).abs() < 1e-15);
829 }
830 assert!(e1[0] > 0.9 && e2[1] > 0.9);
831 }
832}