1use super::*;
4
5pub fn opd_slope_max(s: &System, field: FieldSel, w: usize) -> Result<f64> {
8 Ok(PupilInterp::new(s, field, w, T.slope_grid - 1, &MtfFrame::IDENTITY)?.slope_max())
9}
10
11pub(super) fn pupil_points(
16 s: &System,
17 field: FieldSel,
18 wi: usize,
19 n: Option<usize>,
20 fr: &MtfFrame,
21) -> Result<(usize, Option<PupilInterp>)> {
22 Ok(match n {
23 Some(n) => (n, None),
24 None => {
25 let ip = PupilInterp::new(s, field, wi, T.slope_grid - 1, &MtfFrame::IDENTITY)?;
26 let n = mtf_points(ip.slope_max());
27 (n, fr.is_identity().then_some(ip))
28 }
29 })
30}
31
32pub(super) fn mtf_interp(
39 s: &System,
40 field: FieldSel,
41 wi: usize,
42 n: usize,
43 fr: &MtfFrame,
44 mut first: Option<PupilInterp>,
45) -> Result<PupilInterp> {
46 let n = n.max(T.points_min);
47 let mut g = n.min(T.interp_grid_start);
48 loop {
49 let mut ip = match first.take() {
50 Some(ip) if ip.cells == g => ip,
51 _ => PupilInterp::new(s, field, wi, g, fr)?,
52 };
53 let cells = ((2.0 / ip.h).round() as usize).max(1);
54 if g < n {
55 let e = interp_errors(s, field, wi, &ip, cells.div_ceil(48).max(1))?
56 .iter()
57 .fold(0.0_f64, |m, &(_, _, e)| m.max(e));
58 if e <= T.interp_tol {
59 return Ok(ip);
60 }
61 g = (2 * g).min(n);
62 continue;
63 }
64 let errs = interp_errors(s, field, wi, &ip, cells.div_ceil(16).max(1))?;
66 let nb = errs.iter().filter(|x| x.2 > T.interp_mask_tol).count();
67 if 2 * nb >= errs.len() && nb > 0 {
68 ip.w.fill(f64::NAN);
71 } else if nb > 0 {
72 let bad: Vec<(usize, usize)> = interp_errors(s, field, wi, &ip, 1)?
73 .into_iter()
74 .filter(|&(_, _, e)| e > T.interp_mask_tol)
75 .map(|(ix, iy, _)| (ix, iy))
76 .collect();
77 ip.mask_cells(&bad);
78 }
79 return Ok(ip);
80 }
81}
82
83pub(super) fn interp_errors(
86 s: &System,
87 field: FieldSel,
88 wi: usize,
89 ip: &PupilInterp,
90 step: usize,
91) -> Result<Vec<(usize, usize, f64)>> {
92 let cells = ((2.0 / ip.h).round() as usize).max(1);
93 let lim = if step == 1 { (1.0 + ip.h).powi(2) } else { 1.0 };
94 let (mut px, mut py, mut id) = (Vec::new(), Vec::new(), Vec::new());
95 for iy in (0..cells).step_by(step) {
96 for ix in (0..cells).step_by(step) {
97 let x = -1.0 + (ix as f64 + 0.5) * ip.h;
98 let y = -1.0 + (iy as f64 + 0.5) * ip.h;
99 if x * x + y * y < lim {
100 px.push(x);
101 py.push(y);
102 id.push((ix, iy));
103 }
104 }
105 }
106 let o = frame_opd(s, field, wi, &ip.fr, &px, &py)?;
107 let mut out = Vec::new();
108 for k in 0..px.len() {
109 if let (Some(v), true) = (ip.eval(px[k], py[k]), o.ok(k) && o.opd[k].is_finite()) {
110 out.push((id[k].0, id[k].1, (v - o.opd[k]).abs()));
111 }
112 }
113 Ok(out)
114}
115
116pub(super) fn frame_opd(
119 s: &System,
120 field: FieldSel,
121 w: usize,
122 fr: &MtfFrame,
123 u: &[f64],
124 v: &[f64],
125) -> Result<crate::analysis::Opd> {
126 if fr.is_identity() {
127 return opd(s, field, u, v, Some(w), true);
128 }
129 let (px, py): (Vec<f64>, Vec<f64>) = u.iter().zip(v).map(|(&a, &b)| fr.pupil_xy(a, b)).unzip();
130 opd(s, field, &px, &py, Some(w), true)
131}
132
133pub(super) struct PupilInterp {
136 m: usize,
138 cells: usize,
139 pub(super) h: f64,
140 x0: f64,
141 pub(super) w: Vec<f64>,
143 pub(super) fr: MtfFrame,
145}
146
147pub(super) const LAG: usize = 6;
148
149impl PupilInterp {
150 fn new(s: &System, field: FieldSel, w: usize, n: usize, fr: &MtfFrame) -> Result<PupilInterp> {
152 lensbench_core::par::check_cancel()?;
153 let h = 2.0 / n as f64;
154 let pad = LAG / 2;
155 let m = n + 1 + 2 * pad;
156 let x0 = -1.0 - pad as f64 * h;
157 let mut ip = PupilInterp {
158 m,
159 cells: n,
160 h,
161 x0,
162 w: vec![f64::NAN; m * m],
163 fr: *fr,
164 };
165 let idx: Vec<usize> = (0..m * m).filter(|&i| ip.sampled(i)).collect();
166 let px: Vec<f64> = idx.iter().map(|&i| ip.node(i).0).collect();
167 let py: Vec<f64> = idx.iter().map(|&i| ip.node(i).1).collect();
168 let o = frame_opd(s, field, w, fr, &px, &py)?;
169 for (k, &i) in idx.iter().enumerate() {
170 if o.ok(k) && o.opd[k].is_finite() {
171 ip.w[i] = o.opd[k];
172 }
173 }
174 Ok(ip)
175 }
176
177 #[inline]
179 fn node(&self, i: usize) -> (f64, f64) {
180 (
181 self.x0 + (i % self.m) as f64 * self.h,
182 self.x0 + (i / self.m) as f64 * self.h,
183 )
184 }
185
186 #[inline]
190 fn sampled(&self, i: usize) -> bool {
191 let (x, y) = self.node(i);
192 x.hypot(y) <= 1.0 + 5.5 * self.h
193 }
194
195 pub(super) fn all_finite(&self) -> bool {
197 (0..self.w.len()).all(|i| !self.sampled(i) || self.w[i].is_finite())
198 }
199
200 fn slope_max(&self) -> f64 {
203 let m = self.m;
204 let ok = |i: usize| {
205 let (x, y) = self.node(i);
206 x.hypot(y) <= 1.0 + lensbench_core::tol::PUPIL_RIM && self.w[i].is_finite()
207 };
208 let mut g: f64 = 0.0;
209 for iy in 0..m {
210 for ix in 0..m {
211 let k = iy * m + ix;
212 if !ok(k) {
213 continue;
214 }
215 if ix + 1 < m && ok(k + 1) {
216 g = g.max((self.w[k + 1] - self.w[k]).abs() / self.h);
217 }
218 if iy + 1 < m && ok(k + m) {
219 g = g.max((self.w[k + m] - self.w[k]).abs() / self.h);
220 }
221 }
222 }
223 g
224 }
225
226 fn eval(&self, x: f64, y: f64) -> Option<f64> {
228 let (wx, ix) = self.weights(x)?;
229 let (wy, iy) = self.weights(y)?;
230 let mut acc = 0.0;
231 for (a, &cy) in wy.iter().enumerate() {
232 let o = (iy + a) * self.m + ix;
233 let row: &[f64; LAG] = self.w[o..o + LAG].try_into().expect("slice of LAG");
234 let mut r = 0.0;
235 for k in 0..LAG {
236 r += row[k] * wx[k];
237 }
238 acc += r * cy;
239 }
240 acc.is_finite().then_some(acc)
241 }
242
243 fn weights(&self, x: f64) -> Option<([f64; LAG], usize)> {
245 let t = (x - self.x0) / self.h;
246 let lo = (LAG / 2 - 1) as f64;
249 if !(t >= lo && t < self.m as f64 - (LAG / 2) as f64) {
250 return None;
251 }
252 let i = t as isize - (LAG as isize / 2 - 1);
253 debug_assert!(i >= 0 && i as usize + LAG <= self.m);
254 let u = t - i as f64; let wv = lensbench_core::interp::lagrange::<LAG>(u);
256 Some((wv, i as usize))
257 }
258}
259
260impl PupilInterp {
261 fn mask_cells(&mut self, cells: &[(usize, usize)]) {
263 let pad = LAG / 2;
264 for &(ix, iy) in cells {
265 for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
266 let (gx, gy) = (pad + ix + dx, pad + iy + dy);
267 if gx < self.m && gy < self.m {
268 self.w[gy * self.m + gx] = f64::NAN;
269 }
270 }
271 }
272 }
273}
274
275pub(super) fn opd_at(
277 s: &System,
278 field: FieldSel,
279 w: usize,
280 fr: &MtfFrame,
281 ip: Option<&PupilInterp>,
282 x: &[f64],
283 y: &[f64],
284) -> Result<Vec<f64>> {
285 let mut out = vec![f64::NAN; x.len()];
286 let mut miss = Vec::new();
287 match ip {
288 Some(ip) => {
289 use rayon::prelude::*;
291 let f = |(i, o): (usize, &mut f64)| {
292 if let Some(v) = ip.eval(x[i], y[i]) {
293 *o = v;
294 }
295 };
296 if x.len() >= 4096 && !lensbench_core::par::sequential() {
297 out.par_iter_mut()
298 .enumerate()
299 .with_min_len(1024)
300 .for_each(scoped(f));
301 } else {
302 out.iter_mut().enumerate().for_each(f);
303 }
304 miss.extend((0..x.len()).filter(|&i| out[i].is_nan()));
305 }
306 None => miss.extend(0..x.len()),
307 }
308 if !miss.is_empty() {
309 let mx: Vec<f64> = miss.iter().map(|&i| x[i]).collect();
310 let my: Vec<f64> = miss.iter().map(|&i| y[i]).collect();
311 let o = frame_opd(s, field, w, fr, &mx, &my)?;
312 for (k, &i) in miss.iter().enumerate() {
313 if o.ok(k) && o.opd[k].is_finite() {
314 out[i] = o.opd[k];
315 }
316 }
317 }
318 Ok(out)
319}
320
321impl PupilInterp {
322 #[allow(clippy::too_many_arguments)]
326 pub(super) fn eval_lines(
327 &self,
328 fixed_x: bool,
329 ca: f64,
330 cb: f64,
331 v: &[f64],
332 oa: &mut [f64],
333 ob: &mut [f64],
334 col: &mut [Vec<f64>; 2],
335 ) {
336 let m = self.m;
337 let mut have = [false; 2];
338 for (j, c) in [ca, cb].into_iter().enumerate() {
339 let Some((wc, ic)) = self.weights(c) else {
340 continue;
341 };
342 have[j] = true;
343 let cj = &mut col[j];
344 cj.clear();
345 if fixed_x {
346 cj.extend((0..m).map(|iy| {
347 let o = iy * m + ic;
348 let row: &[f64; LAG] = self.w[o..o + LAG].try_into().expect("slice of LAG");
349 let mut r = 0.0;
350 for k in 0..LAG {
351 r += row[k] * wc[k];
352 }
353 r
354 }));
355 } else {
356 cj.resize(m, 0.0);
357 for (a, &wa) in wc.iter().enumerate() {
358 let row = &self.w[(ic + a) * m..(ic + a + 1) * m];
359 for (o, &r) in cj.iter_mut().zip(row) {
360 *o += r * wa;
361 }
362 }
363 }
364 }
365 if !have[0] && !have[1] {
366 return;
367 }
368 if have[0] && have[1] {
369 let (c0, c1) = (&col[0][..], &col[1][..]);
371 for (i, &x) in v.iter().enumerate() {
372 let Some((wv, iv)) = self.weights(x) else {
373 continue;
374 };
375 let a0: &[f64; LAG] = c0[iv..iv + LAG].try_into().expect("slice of LAG");
376 let a1: &[f64; LAG] = c1[iv..iv + LAG].try_into().expect("slice of LAG");
377 let mut acc = [0.0f64; 2];
378 for a in 0..LAG {
379 acc[0] += a0[a] * wv[a];
380 acc[1] += a1[a] * wv[a];
381 }
382 if acc[0].is_finite() {
383 oa[i] = acc[0];
384 }
385 if acc[1].is_finite() {
386 ob[i] = acc[1];
387 }
388 }
389 return;
390 }
391 for (i, &x) in v.iter().enumerate() {
392 let Some((wv, iv)) = self.weights(x) else {
393 continue;
394 };
395 for (j, o) in [&mut oa[i], &mut ob[i]].into_iter().enumerate() {
396 if !have[j] {
397 continue;
398 }
399 let c: &[f64; LAG] = col[j][iv..iv + LAG].try_into().expect("slice of LAG");
400 let mut acc = 0.0;
401 for a in 0..LAG {
402 acc += c[a] * wv[a];
403 }
404 if acc.is_finite() {
405 *o = acc;
406 }
407 }
408 }
409 }
410
411 fn symmetric(&self) -> bool {
414 let m = self.m;
415 let same = |a: f64, b: f64| (a.is_nan() && b.is_nan()) || (a - b).abs() <= 1e-9;
416 (0..m).all(|iy| {
417 (0..m).all(|ix| {
418 let v = self.w[iy * m + ix];
419 same(v, self.w[ix * m + iy]) && same(v, self.w[(m - 1 - iy) * m + ix])
420 })
421 })
422 }
423}
424
425pub(super) fn axis_symmetric(jm: &[[f64; 2]; 2], ip: &PupilInterp) -> bool {
428 let a = jm[0][0].abs() * lensbench_core::tol::JACOBIAN_REL;
429 (jm[0][0] - jm[1][1]).abs() <= a && jm[0][1].abs() <= a && jm[1][0].abs() <= a && ip.symmetric()
430}
431
432pub(super) fn fill_direct(
434 s: &System,
435 field: FieldSel,
436 w: usize,
437 fr: &MtfFrame,
438 x: &[f64],
439 y: &[f64],
440 out: &mut [f64],
441) -> Result<()> {
442 let miss: Vec<usize> = (0..x.len()).filter(|&i| out[i].is_nan()).collect();
443 if !miss.is_empty() {
444 let mx: Vec<f64> = miss.iter().map(|&i| x[i]).collect();
445 let my: Vec<f64> = miss.iter().map(|&i| y[i]).collect();
446 let o = frame_opd(s, field, w, fr, &mx, &my)?;
447 for (k, &i) in miss.iter().enumerate() {
448 if o.ok(k) && o.opd[k].is_finite() {
449 out[i] = o.opd[k];
450 }
451 }
452 }
453 Ok(())
454}
455
456pub(super) fn shift_points(ip: &PupilInterp, dx: f64, dy: f64) -> usize {
463 let m = T.shift_grid;
464 let d = dx.hypot(dy);
465 let a = 1.0 - 0.5 * d;
466 if a <= 0.0 {
467 return T.points_min;
468 }
469 let (ex, ey) = if d > 0.0 {
470 (dx / d, dy / d)
471 } else {
472 (1.0, 0.0)
473 };
474 let mut dv = vec![f64::NAN; m * m];
477 let mut pt = vec![(0.0, 0.0); m * m];
478 for i in 0..m {
479 let t = a * (-1.0 + (2 * i + 1) as f64 / m as f64);
480 let x = (1.0 - (t.abs() + 0.5 * d).powi(2)).max(0.0).sqrt();
481 for j in 0..m {
482 let u = x * (-1.0 + (2 * j + 1) as f64 / m as f64);
483 let (px, py) = (t * ex - u * ey, t * ey + u * ex);
484 pt[i * m + j] = (px, py);
485 if let (Some(va), Some(vb)) = (
486 ip.eval(px + 0.5 * dx, py + 0.5 * dy),
487 ip.eval(px - 0.5 * dx, py - 0.5 * dy),
488 ) {
489 dv[i * m + j] = va - vb;
490 }
491 }
492 }
493 let mut g: f64 = 0.0;
494 let mut slope = |k: usize, k2: usize| {
495 let (v, v2) = (dv[k], dv[k2]);
496 let dist = (pt[k2].0 - pt[k].0).hypot(pt[k2].1 - pt[k].1);
497 if v.is_finite() && v2.is_finite() && dist > 0.0 {
498 g = g.max((v2 - v).abs() / dist);
499 }
500 };
501 for i in 0..m {
502 for j in 0..m {
503 let k = i * m + j;
504 if j + 1 < m {
505 slope(k, k + 1);
506 }
507 if i + 1 < m {
508 slope(k, k + m);
509 }
510 }
511 }
512 ((T.shift_fac * g).ceil() as usize + T.points_pad).clamp(T.points_min, T.points_max)
513}