1use crate::illum::exit_cone;
18use crate::psf::{psf, PsfOpts, PsfPlane};
19use lensbench_core::error::Result;
20use lensbench_core::invalid;
21use lensbench_core::system::{FieldSel, System};
22use lensbench_core::Waves;
23use rustfft::num_complex::Complex;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum Aberrations {
28 None,
30 #[default]
32 Diffraction,
33 Geometric,
35 Huygens,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum Flip {
43 #[default]
44 None,
45 TopBottom,
47 LeftRight,
49 Both,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub enum Rotate {
56 #[default]
57 R0,
58 R90,
59 R180,
60 R270,
61}
62
63pub fn flip(im: &SimImage, f: Flip) -> SimImage {
65 let (w, h) = (im.width, im.height);
66 let (fx, fy) = match f {
67 Flip::None => return im.clone(),
68 Flip::TopBottom => (false, true),
69 Flip::LeftRight => (true, false),
70 Flip::Both => (true, true),
71 };
72 let channels = im
73 .channels
74 .iter()
75 .map(|c| {
76 (0..w * h)
77 .map(|k| {
78 let (i, j) = (k % w, k / w);
79 let (i, j) = (
80 if fx { w - 1 - i } else { i },
81 if fy { h - 1 - j } else { j },
82 );
83 c[j * w + i]
84 })
85 .collect()
86 })
87 .collect();
88 SimImage {
89 width: w,
90 height: h,
91 channels,
92 }
93}
94
95pub fn rotate(im: &SimImage, r: Rotate) -> SimImage {
97 let (w, h) = (im.width, im.height);
98 let (w1, h1) = match r {
99 Rotate::R0 => return im.clone(),
100 Rotate::R180 => return flip(im, Flip::Both),
101 Rotate::R90 | Rotate::R270 => (h, w),
102 };
103 let at = |i: usize, j: usize| {
105 if r == Rotate::R90 {
106 (w - 1 - j, i)
107 } else {
108 (j, h - 1 - i)
109 }
110 };
111 let channels = im
112 .channels
113 .iter()
114 .map(|c| {
115 (0..w1 * h1)
116 .map(|k| {
117 let (i0, j0) = at(k % w1, k / w1);
118 c[j0 * w + i0]
119 })
120 .collect()
121 })
122 .collect();
123 SimImage {
124 width: w1,
125 height: h1,
126 channels,
127 }
128}
129
130#[derive(Debug, Clone)]
132pub struct ImageSimOpts {
133 pub field_height: f64,
135 pub psf_grid: (usize, usize),
137 pub map_grid: usize,
139 pub pupil: Option<usize>,
141 pub psf_points: usize,
143 pub pixel: Option<f64>,
145 pub size: Option<(usize, usize)>,
147 pub aberrations: Aberrations,
148 pub relative_illumination: bool,
150 pub channel_waves: Option<[usize; 3]>,
152 pub wave: Option<usize>,
154 pub center_field: (f64, f64),
156 pub flip_source: Flip,
158 pub rotate: Rotate,
160 pub flip_image: Flip,
162}
163
164impl Default for ImageSimOpts {
165 fn default() -> Self {
166 ImageSimOpts {
167 field_height: 0.0,
168 psf_grid: (5, 5),
169 map_grid: 17,
170 pupil: None,
171 psf_points: 64,
172 pixel: None,
173 size: None,
174 aberrations: Aberrations::Diffraction,
175 relative_illumination: true,
176 channel_waves: None,
177 wave: None,
178 center_field: (0.0, 0.0),
179 flip_source: Flip::None,
180 rotate: Rotate::R0,
181 flip_image: Flip::None,
182 }
183 }
184}
185
186#[derive(Debug, Clone, PartialEq)]
188pub struct SimImage {
189 pub width: usize,
190 pub height: usize,
191 pub channels: Vec<Vec<f64>>,
192}
193
194#[derive(Debug, Clone)]
196pub struct ImageSimOut {
197 pub image: SimImage,
199 pub pixel: f64,
201 pub center: (f64, f64),
203 pub warnings: Vec<String>,
204}
205
206pub fn default_field_height(s: &System) -> f64 {
208 s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max) * std::f64::consts::SQRT_2
209}
210
211fn bilinear<T: Copy>(
213 n: (usize, usize),
214 u: f64,
215 v: f64,
216 at: impl Fn(usize, usize) -> T,
217 mix: impl Fn(T, T, f64) -> T,
218) -> T {
219 let cell = |t: f64, n: usize| (t.floor().max(0.0) as usize).min(n.saturating_sub(2));
221 let (i0, j0) = (cell(u, n.0), cell(v, n.1));
222 let (i1, j1) = ((i0 + 1).min(n.0 - 1), (j0 + 1).min(n.1 - 1));
223 let (fu, fv) = (u - i0 as f64, v - j0 as f64);
224 let a = mix(at(i0, j0), at(i1, j0), fu);
225 let b = mix(at(i0, j1), at(i1, j1), fu);
226 mix(a, b, fv)
227}
228
229fn hat(t: f64, k: usize, n: usize) -> f64 {
231 if n == 1 {
232 return 1.0;
233 }
234 let t = t.clamp(0.0, (n - 1) as f64);
235 (1.0 - (t - k as f64).abs()).max(0.0)
236}
237
238pub fn image_sim(s: &System, src: &SimImage, o: &ImageSimOpts) -> Result<ImageSimOut> {
240 let mut r = sim(s, src, o)?;
241 r.image = flip(&r.image, o.flip_image);
242 Ok(r)
243}
244
245fn sim(s: &System, src: &SimImage, o: &ImageSimOpts) -> Result<ImageSimOut> {
246 if src.width == 0
247 || src.height == 0
248 || src
249 .channels
250 .iter()
251 .any(|c| c.len() != src.width * src.height)
252 {
253 invalid!("image simulation: the source image is empty or its channels have the wrong size");
254 }
255 let src = &rotate(&flip(src, o.flip_source), o.rotate);
256 let (w0, h0) = (src.width, src.height);
257 if !(src.channels.len() == 1 || src.channels.len() == 3) {
258 invalid!("image simulation: the source image must be gray (1 channel) or RGB (3 channels)");
259 }
260 if !(o.field_height > 0.0) {
261 invalid!(
262 "image simulation: field height {} must be positive",
263 o.field_height
264 );
265 }
266 if o.psf_grid.0 == 0 || o.psf_grid.1 == 0 || o.map_grid < 2 {
267 invalid!(
268 "image simulation: PSF grid {:?} must be 1 or more and the map grid {} 2 or more",
269 o.psf_grid,
270 o.map_grid
271 );
272 }
273 let mut warnings = Vec::new();
274 let fpx = o.field_height / h0 as f64;
276 let (nx, ny) = s.field_norm_values();
277 let (fcx, fcy) = o.center_field;
278 if !(fcx.is_finite() && fcy.is_finite()) {
279 invalid!("image simulation: center field ({fcx}, {fcy})");
280 }
281 let field_of = |i: f64, j: f64| -> (f64, f64) {
282 let fx = fcx + (i + 0.5 - w0 as f64 / 2.0) * fpx;
283 let fy = fcy + (h0 as f64 / 2.0 - (j + 0.5)) * fpx;
284 (fx / nx, fy / ny)
285 };
286 let chans: Vec<Vec<(usize, f64)>> = if let (1, Some(w)) = (src.channels.len(), o.wave) {
288 if w >= s.wavelengths.len() {
289 let (wn, nw) = (w + 1, s.wavelengths.len());
290 invalid!("wavelength number {wn} ({nw} in all)");
291 }
292 vec![vec![(w, 1.0)]]
293 } else if src.channels.len() == 1 {
294 let ws: Vec<(usize, f64)> = (0..s.wavelengths.len())
295 .filter(|&w| s.weights[w] > 0.0)
296 .map(|w| (w, s.weights[w]))
297 .collect();
298 let tot: f64 = ws.iter().map(|x| x.1).sum();
299 if !(tot > 0.0) {
300 invalid!("no weighted wavelength");
301 }
302 vec![ws.into_iter().map(|(w, k)| (w, k / tot)).collect()]
303 } else {
304 let cw = match o.channel_waves {
305 Some(c) => c,
306 None => {
307 if s.wavelengths.len() < 3 {
308 invalid!("image simulation: an RGB image needs 3 wavelengths (or give the channel wavelengths)");
309 }
310 let mut idx = [0usize, 1, 2];
311 idx.sort_by(|&a, &b| s.wave(b).mm().total_cmp(&s.wave(a).mm()));
312 idx
313 }
314 };
315 for &w in &cw {
316 if w >= s.wavelengths.len() {
317 let (wn, nw) = (w + 1, s.wavelengths.len());
318 invalid!("wavelength number {wn} ({nw} in all)");
319 }
320 }
321 cw.iter().map(|&w| vec![(w, 1.0)]).collect()
322 };
323 let m = o.map_grid;
325 let grid_field = |a: usize, b: usize, na: usize, nb: usize| -> (f64, f64) {
326 let t = |k: usize, n: usize, len: usize| {
327 if n == 1 {
328 (len as f64 - 1.0) / 2.0
329 } else {
330 k as f64 * (len as f64 - 1.0) / (n - 1) as f64
331 }
332 };
333 field_of(t(a, na, w0), t(b, nb, h0))
334 };
335 let chief = |h: (f64, f64)| -> Result<(f64, f64)> {
336 let c = s.try_trace(
337 FieldSel::Norm(h.0, h.1),
338 &[0.0],
339 &[0.0],
340 Some(s.primary),
341 None,
342 false,
343 )?;
344 if !c.traced(0) {
345 invalid!("image simulation: can't trace the chief ray of field ({:.4}, {:.4}) (normalized); reduce the field height", h.0, h.1);
346 }
347 Ok((c.rays[0].xyz[0], c.rays[0].xyz[1]))
348 };
349 let mut pos = vec![(0.0, 0.0); m * m];
350 let mut ri = vec![1.0; m * m];
351 let a0 = if o.relative_illumination {
353 exit_cone(s, FieldSel::Norm(0.0, 0.0), s.primary, 64)?
354 } else {
355 1.0
356 };
357 let (mut dark, mut dark_err) = (0, None);
359 for b in 0..m {
360 for a in 0..m {
361 let h = grid_field(a, b, m, m);
362 pos[b * m + a] = chief(h)?;
363 if o.relative_illumination {
364 ri[b * m + a] = match exit_cone(s, FieldSel::Norm(h.0, h.1), s.primary, 64) {
365 Ok(v) => v / a0,
366 Err(e) if crate::defs::field_vignetted(&e) => {
367 dark += 1;
368 dark_err.get_or_insert(e);
369 0.0
370 }
371 Err(e) => return Err(e),
372 };
373 }
374 }
375 }
376 if let Some(e) = dark_err {
377 if dark == m * m {
378 return Err(e);
379 }
380 warnings.push(format!(
381 "image simulation: the chief ray doesn't reach the image at {dark} of {} points of the field map (vignetted); they are taken as dark",
382 m * m
383 ));
384 }
385 let center = chief((fcx / nx, fcy / ny))?;
386 let pixel_img = {
388 let d = 1e-3;
389 let c0 = chief((0.0, 0.0))?;
390 let (x1, _) = chief((d * fpx / nx, 0.0))?;
391 let (_, y1) = chief((0.0, d * fpx / ny))?;
392 ((x1 - c0.0).abs() / d, (y1 - c0.1).abs() / d)
393 };
394 let pixel = match o.pixel {
395 Some(p) if p > 0.0 => p,
396 Some(p) => invalid!("image simulation: detector pixel {p}"),
397 None => pixel_img.0.max(pixel_img.1),
398 };
399 let (w1, h1) = o.size.unwrap_or((w0, h0));
400 if w1 == 0 || h1 == 0 {
401 invalid!("image simulation: detector size {w1} × {h1}");
402 }
403 let to_map = |i: f64, j: f64| -> (f64, f64) {
405 let t = |k: f64, len: usize| k * (m - 1) as f64 / (len as f64 - 1.0).max(1.0);
406 (t(i, w0), t(j, h0))
407 };
408 let q = {
411 let (sx, sy) = (
412 (w0 as f64 - 1.0).max(1.0) / (m - 1) as f64,
413 (h0 as f64 - 1.0).max(1.0) / (m - 1) as f64,
414 );
415 let d = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).hypot(a.1 - b.1);
416 let mut big = 0.0f64;
417 for b in 0..m {
418 for a in 0..m - 1 {
419 big = big.max(d(pos[b * m + a], pos[b * m + a + 1]) / sx);
420 big = big.max(d(pos[a * m + b], pos[(a + 1) * m + b]) / sy);
421 }
422 }
423 ((2.0 * big / pixel).ceil() as usize).clamp(1, 32)
424 };
425 let mix2 =
426 |a: (f64, f64), b: (f64, f64), t: f64| (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t);
427 let mix1 = |a: f64, b: f64, t: f64| a + (b - a) * t;
428 let (gx, gy) = o.psf_grid;
430 let gtx = |i: usize| {
431 if gx == 1 {
432 0.0
433 } else {
434 i as f64 * (gx - 1) as f64 / (w0 as f64 - 1.0).max(1.0)
435 }
436 };
437 let gty = |j: usize| {
438 if gy == 1 {
439 0.0
440 } else {
441 j as f64 * (gy - 1) as f64 / (h0 as f64 - 1.0).max(1.0)
442 }
443 };
444 let mut out = vec![vec![0.0; w1 * h1]; src.channels.len()];
445 for (c, ws) in chans.iter().enumerate() {
446 for &(w, kw) in ws {
447 let mut kernel = |k: usize| -> Result<Option<(usize, Vec<f64>)>> {
450 if o.aberrations == Aberrations::None {
451 return Ok(None);
452 }
453 let h = grid_field(k % gx, k / gx, gx, gy);
454 if o.aberrations == Aberrations::Geometric {
455 let n = o.pupil.unwrap_or(GEO_PUPIL);
456 return geo_kernel(s, FieldSel::Norm(h.0, h.1), w, n, pixel).map(Some);
457 }
458 let p = if o.aberrations == Aberrations::Huygens {
459 crate::huygens::huygens_psf(
460 s,
461 FieldSel::Norm(h.0, h.1),
462 Waves::One(w),
463 crate::huygens::HuygensOpts {
464 pupil: o.pupil,
465 image: o.psf_points,
466 ..Default::default()
467 },
468 )?
469 } else {
470 psf(
471 s,
472 FieldSel::Norm(h.0, h.1),
473 Waves::One(w),
474 PsfOpts {
475 pupil: o.pupil,
476 image: o.psf_points,
477 pixel: None,
478 plane: PsfPlane::Image,
479 },
480 )?
481 };
482 for wn in &p.warnings {
483 if !warnings.contains(wn) {
484 warnings.push(wn.clone());
485 }
486 }
487 Ok(Some(bin_kernel(&p, pixel)))
488 };
489 let (mut kernels, mut cut, mut cut_err) = (Vec::with_capacity(gx * gy), 0, None);
490 for k in 0..gx * gy {
491 kernels.push(match kernel(k) {
492 Ok(x) => x,
493 Err(e) if crate::defs::field_vignetted(&e) => {
494 cut += 1;
495 cut_err.get_or_insert(e);
496 Some((1, vec![0.0]))
497 }
498 Err(e) => return Err(e),
499 });
500 }
501 if let Some(e) = cut_err {
502 if cut == gx * gy {
503 return Err(e);
504 }
505 let wn = format!(
506 "image simulation: {cut} of {} PSF grid points are fully vignetted; no light is taken from them",
507 gx * gy
508 );
509 if !warnings.contains(&wn) {
510 warnings.push(wn);
511 }
512 }
513 let mut ideal = vec![vec![0.0; w1 * h1]; gx * gy];
515 let ch = &src.channels[c];
516 for j in 0..h0 {
517 for i in 0..w0 {
518 let v = ch[j * w0 + i];
519 if v == 0.0 {
520 continue;
521 }
522 let (tx, ty) = (gtx(i), gty(j));
523 for sj in 0..q {
524 for si in 0..q {
525 let fi = i as f64 + (si as f64 + 0.5) / q as f64 - 0.5;
526 let fj = j as f64 + (sj as f64 + 0.5) / q as f64 - 0.5;
527 let (u, t) = to_map(fi, fj);
528 let (x, y) = bilinear((m, m), u, t, |a, b| pos[b * m + a], mix2);
529 let r = bilinear((m, m), u, t, |a, b| ri[b * m + a], mix1);
530 let cx = (x - center.0) / pixel + w1 as f64 / 2.0 - 0.5;
532 let cy = h1 as f64 / 2.0 - 0.5 - (y - center.1) / pixel;
533 let at = |di: f64, dj: f64| {
536 let (u, t) = to_map(fi + di, fj + dj);
537 bilinear((m, m), u, t, |a, b| pos[b * m + a], mix2)
538 };
539 let (xa, xb, ya, yb) =
540 (at(-0.5, 0.0), at(0.5, 0.0), at(0.0, -0.5), at(0.0, 0.5));
541 let area = ((xb.0 - xa.0) * (yb.1 - ya.1)
542 - (xb.1 - xa.1) * (yb.0 - ya.0))
543 .abs();
544 let e = v * r * area / (pixel * pixel) / (q * q) as f64;
545 let side = area.sqrt() / pixel / q as f64;
547 for kj in 0..gy {
548 let wy = hat(ty, kj, gy);
549 if wy == 0.0 {
550 continue;
551 }
552 for ki in 0..gx {
553 let wx = hat(tx, ki, gx);
554 if wx == 0.0 {
555 continue;
556 }
557 splat_box(
558 &mut ideal[kj * gx + ki],
559 w1,
560 h1,
561 cx,
562 cy,
563 side,
564 e * wx * wy,
565 );
566 }
567 }
568 }
569 }
570 }
571 }
572 let mut items = Vec::new();
574 for (k, img) in ideal.iter().enumerate() {
575 let acc = &mut out[c];
576 match &kernels[k] {
577 None => {
578 for (a, b) in acc.iter_mut().zip(img) {
579 *a += kw * b;
580 }
581 }
582 Some((n, ker)) => {
583 if img.iter().any(|v| *v != 0.0) {
584 items.push((img.as_slice(), ker.as_slice(), *n));
585 }
586 }
587 }
588 }
589 if !items.is_empty() {
590 let conv = convolve_sum(&items, w1, h1);
591 for (a, b) in out[c].iter_mut().zip(&conv) {
592 *a += kw * b;
593 }
594 }
595 }
596 }
597 Ok(ImageSimOut {
598 image: SimImage {
599 width: w1,
600 height: h1,
601 channels: out,
602 },
603 pixel,
604 center,
605 warnings,
606 })
607}
608
609fn splat(img: &mut [f64], w: usize, h: usize, cx: f64, cy: f64, e: f64) {
611 let (x0, y0) = (cx.floor(), cy.floor());
612 let (fx, fy) = (cx - x0, cy - y0);
613 for (dx, wx) in [(0i64, 1.0 - fx), (1, fx)] {
614 for (dy, wy) in [(0i64, 1.0 - fy), (1, fy)] {
615 let (x, y) = (x0 as i64 + dx, y0 as i64 + dy);
616 if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h {
617 img[y as usize * w + x as usize] += e * wx * wy;
618 }
619 }
620 }
621}
622
623fn splat_box(img: &mut [f64], w: usize, h: usize, cx: f64, cy: f64, side: f64, e: f64) {
625 if !(side > 1e-9) {
626 return splat(img, w, h, cx, cy, e);
627 }
628 let parts = |c: f64, n: usize| -> Vec<(usize, f64)> {
630 let (a, b) = (c - side / 2.0, c + side / 2.0);
631 let (k0, k1) = (
632 (a + 0.5).floor().max(0.0) as i64,
633 (b + 0.5).floor().min(n as f64 - 1.0) as i64,
634 );
635 (k0..=k1)
636 .filter_map(|k| {
637 let o = (b.min(k as f64 + 0.5) - a.max(k as f64 - 0.5)) / side;
638 (o > 0.0).then_some((k as usize, o))
639 })
640 .collect()
641 };
642 let (px, py) = (parts(cx, w), parts(cy, h));
643 for &(y, wy) in &py {
644 for &(x, wx) in &px {
645 img[y * w + x] += e * wx * wy;
646 }
647 }
648}
649
650pub const GEO_PUPIL: usize = 64;
652
653fn geo_kernel(
657 s: &System,
658 field: FieldSel,
659 w: usize,
660 n: usize,
661 pixel: f64,
662) -> Result<(usize, Vec<f64>)> {
663 if n < 2 {
664 invalid!("image simulation: geometric PSF pupil grid {n}");
665 }
666 let c = s.try_trace(field, &[0.0], &[0.0], Some(s.primary), None, false)?;
667 if !c.traced(0) {
668 invalid!(code = lensbench_core::error::code::PUPIL_VIGNETTED; "image simulation: the chief ray doesn't reach the image (geometric PSF)");
669 }
670 let c0 = (c.rays[0].xyz[0], c.rays[0].xyz[1]);
671 let (px, py) = lensbench_core::opd::pupil_grid(n);
672 let t = s.try_trace(field, &px, &py, Some(w), None, false)?;
673 let wts = crate::analysis::apodized(s, field, &px, &py, &vec![1.0; px.len()])?;
674 let pts: Vec<(f64, f64, f64)> = (0..px.len())
675 .filter(|&i| t.ok(i) && wts[i] > 0.0)
676 .map(|i| (t.rays[i].xyz[0] - c0.0, t.rays[i].xyz[1] - c0.1, wts[i]))
677 .filter(|p| p.0.is_finite() && p.1.is_finite())
678 .collect();
679 if pts.is_empty() {
680 invalid!(code = lensbench_core::error::code::ALL_VIGNETTED; "image simulation: no ray of the pupil reaches the image (geometric PSF)");
681 }
682 let half = pts
683 .iter()
684 .fold(0.0f64, |a, p| a.max(p.0.abs()).max(p.1.abs()));
685 let r = (half / pixel).ceil() as usize + 1;
686 let m = 2 * r + 1;
687 let mut k = vec![0.0; m * m];
688 for &(x, y, wt) in &pts {
689 splat(&mut k, m, m, x / pixel + r as f64, r as f64 - y / pixel, wt);
690 }
691 let tot: f64 = k.iter().sum();
692 for v in &mut k {
693 *v /= tot;
694 }
695 Ok((m, k))
696}
697
698fn bin_kernel(p: &crate::psf::Psf, pixel: f64) -> (usize, Vec<f64>) {
701 let (xs, ys) = (p.i.x(), p.i.y());
702 let half_w = xs.iter().chain(ys).fold(0.0f64, |a, v| a.max(v.abs()));
703 let r = (half_w / pixel).ceil() as usize + 1;
704 let n = 2 * r + 1;
705 let mut k = vec![0.0; n * n];
706 let step = if xs.len() > 1 {
708 (xs[1] - xs[0]).abs()
709 } else {
710 0.0
711 };
712 let q = ((2.0 * step / pixel).ceil() as usize).clamp(1, 32);
713 for (row, &y) in p.i.rows().zip(ys) {
714 for (v, &x) in row.iter().zip(xs) {
715 if !v.is_finite() || *v == 0.0 {
716 continue;
717 }
718 for sj in 0..q {
719 for si in 0..q {
720 let ox = ((si as f64 + 0.5) / q as f64 - 0.5) * step;
721 let oy = ((sj as f64 + 0.5) / q as f64 - 0.5) * step;
722 let cx = (x + ox) / pixel + r as f64;
723 let cy = r as f64 - (y + oy) / pixel;
724 splat(&mut k, n, n, cx, cy, *v / (q * q) as f64);
725 }
726 }
727 }
728 }
729 let tot: f64 = k.iter().sum();
730 if tot > 0.0 {
731 for v in &mut k {
732 *v /= tot;
733 }
734 }
735 (n, k)
736}
737
738fn fast_len(m: usize) -> usize {
740 let mut n = m.max(1);
741 loop {
742 let mut k = n;
743 for p in [2, 3, 5] {
744 while k.is_multiple_of(p) {
745 k /= p;
746 }
747 }
748 if k == 1 {
749 return n;
750 }
751 n += 1;
752 }
753}
754
755struct Fft2 {
757 w: usize,
758 h: usize,
759 row: std::sync::Arc<dyn rustfft::Fft<f64>>,
760 col: std::sync::Arc<dyn rustfft::Fft<f64>>,
761}
762
763impl Fft2 {
764 fn new(w: usize, h: usize, inverse: bool) -> Fft2 {
765 let mut planner = rustfft::FftPlanner::<f64>::new();
766 let (row, col) = if inverse {
767 (planner.plan_fft_inverse(w), planner.plan_fft_inverse(h))
768 } else {
769 (planner.plan_fft_forward(w), planner.plan_fft_forward(h))
770 };
771 Fft2 { w, h, row, col }
772 }
773
774 fn process(&self, a: &mut [Complex<f64>]) {
775 let (w, h) = (self.w, self.h);
776 for r in a.chunks_exact_mut(w) {
777 self.row.process(r);
778 }
779 let mut col = vec![Complex::new(0.0, 0.0); h];
780 for x in 0..w {
781 for y in 0..h {
782 col[y] = a[y * w + x];
783 }
784 self.col.process(&mut col);
785 for y in 0..h {
786 a[y * w + x] = col[y];
787 }
788 }
789 }
790}
791
792fn convolve_sum(items: &[(&[f64], &[f64], usize)], w: usize, h: usize) -> Vec<f64> {
796 use rayon::prelude::*;
797 let nmax = items.iter().map(|t| t.2).max().unwrap_or(1);
798 let (pw, ph) = (fast_len(w + nmax - 1), fast_len(h + nmax - 1));
799 let (fwd, inv) = (Fft2::new(pw, ph, false), Fft2::new(pw, ph, true));
800 let zero = || vec![Complex::new(0.0, 0.0); pw * ph];
801 let spectrum = |&(img, ker, n): &(&[f64], &[f64], usize)| -> Vec<Complex<f64>> {
802 let r = n / 2;
803 let mut z = zero();
804 for y in 0..h {
805 for x in 0..w {
806 z[y * pw + x].re = img[y * w + x];
807 }
808 }
809 for y in 0..n {
811 for x in 0..n {
812 let (px, py) = ((x + pw - r) % pw, (y + ph - r) % ph);
813 z[py * pw + px].im = ker[y * n + x];
814 }
815 }
816 fwd.process(&mut z);
817 let mut out = zero();
819 for ky in 0..ph {
820 for kx in 0..pw {
821 let zk = z[ky * pw + kx];
822 let zm = z[((ph - ky) % ph) * pw + (pw - kx) % pw].conj();
823 out[ky * pw + kx] = (zk * zk - zm * zm) * Complex::new(0.0, -0.25);
824 }
825 }
826 out
827 };
828 const BATCH: usize = 8;
830 let mut acc = zero();
831 for batch in items.chunks(BATCH) {
832 let sp: Vec<Vec<Complex<f64>>> = if batch.len() > 1 && !lensbench_core::par::sequential() {
833 batch
834 .par_iter()
835 .map(lensbench_core::par::scoped(spectrum))
836 .collect()
837 } else {
838 batch.iter().map(spectrum).collect()
839 };
840 for v in sp {
841 for (u, x) in acc.iter_mut().zip(&v) {
842 *u += x;
843 }
844 }
845 }
846 inv.process(&mut acc);
847 let sc = 1.0 / (pw * ph) as f64;
848 let mut out = vec![0.0; w * h];
849 for y in 0..h {
850 for x in 0..w {
851 out[y * w + x] = acc[y * pw + x].re * sc;
852 }
853 }
854 out
855}
856
857#[cfg(test)]
859fn convolve(img: &[f64], w: usize, h: usize, ker: &[f64], n: usize) -> Vec<f64> {
860 convolve_sum(&[(img, ker, n)], w, h)
861}
862
863#[cfg(test)]
864mod tests {
865 use super::*;
866
867 #[test]
868 fn convolve_with_a_delta_is_identity() {
869 let img: Vec<f64> = (0..12).map(|v| v as f64).collect();
870 let ker = vec![0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0];
871 let out = convolve(&img, 4, 3, &ker, 3);
872 for (a, b) in img.iter().zip(&out) {
873 assert!((a - b).abs() < 1e-12);
874 }
875 }
876
877 #[test]
878 fn convolve_shifts_by_the_kernel_offset() {
879 let mut img = vec![0.0; 25];
880 img[12] = 1.0;
881 let mut ker = vec![0.0; 9];
883 ker[5] = 1.0;
884 let out = convolve(&img, 5, 5, &ker, 3);
885 assert!((out[13] - 1.0).abs() < 1e-12);
886 }
887
888 #[test]
890 fn convolve_sum_matches_direct_convolution() {
891 let mut st = 0x2545_f491_4f6c_dd1du64;
892 let mut rnd = || {
893 st ^= st << 13;
894 st ^= st >> 7;
895 st ^= st << 17;
896 (st >> 11) as f64 / (1u64 << 53) as f64
897 };
898 let (w, h) = (13, 8);
899 let imgs: Vec<Vec<f64>> = (0..3)
900 .map(|_| (0..w * h).map(|_| rnd()).collect())
901 .collect();
902 let kers: Vec<(usize, Vec<f64>)> = [3usize, 7, 5]
903 .iter()
904 .map(|&n| (n, (0..n * n).map(|_| rnd()).collect()))
905 .collect();
906 let items: Vec<(&[f64], &[f64], usize)> = imgs
907 .iter()
908 .zip(&kers)
909 .map(|(i, (n, k))| (i.as_slice(), k.as_slice(), *n))
910 .collect();
911 let got = convolve_sum(&items, w, h);
912 let mut want = vec![0.0; w * h];
913 for (img, ker, n) in &items {
914 let r = (*n / 2) as i64;
915 for y in 0..h as i64 {
916 for x in 0..w as i64 {
917 let mut v = 0.0;
918 for ky in 0..*n as i64 {
919 for kx in 0..*n as i64 {
920 let (sx, sy) = (x - (kx - r), y - (ky - r));
921 if sx >= 0 && sy >= 0 && sx < w as i64 && sy < h as i64 {
922 v += ker[(ky * *n as i64 + kx) as usize]
923 * img[(sy * w as i64 + sx) as usize];
924 }
925 }
926 }
927 want[(y * w as i64 + x) as usize] += v;
928 }
929 }
930 }
931 for (a, b) in got.iter().zip(&want) {
932 assert!((a - b).abs() < 1e-12, "{a} vs {b}");
933 }
934 }
935
936 #[test]
937 fn splat_conserves_energy_inside() {
938 let mut img = vec![0.0; 16];
939 splat(&mut img, 4, 4, 1.3, 2.6, 2.0);
940 assert!((img.iter().sum::<f64>() - 2.0).abs() < 1e-12);
941 }
942}