1use lensbench_core::coating::{Coatings, C64};
20use lensbench_core::grid::Grid2;
21use lensbench_core::interp::Spline;
22use lensbench_core::pupil::{PupilGrid, Rim};
23use lensbench_core::system::{Launch, PolIn, RecSel, System};
24use lensbench_core::{invalid, Result};
25
26pub(crate) const NV: usize = 8;
28
29pub fn obj_dir(sys: &System, d: [f64; 3]) -> [f64; 2] {
32 let r = sys.frames().obj.r;
33 let n = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
34 [0, 1].map(|c| (r[0][c] * d[0] + r[1][c] * d[1] + r[2][c] * d[2]) / n)
35}
36
37pub fn basis_coeffs(j: [C64; 2], kx: f64, ky: f64) -> [C64; 2] {
42 let s = (1.0 - kx * kx).sqrt();
43 let kz = (1.0 - kx * kx - ky * ky).max(0.0).sqrt();
44 [j[0] / s + j[1] * (kx * ky / (s * kz)), j[1] * (s / kz)]
46}
47
48pub(crate) const BAD_MARGIN: usize = 2;
51
52pub const MIN_POINTS: usize = 4;
54
55#[derive(Debug, Clone)]
57pub struct PolGrid {
58 f: Grid2<[C64; NV]>,
60 fx: Vec<[C64; NV]>,
62 fy: Vec<[C64; NV]>,
63 fxy: Vec<[C64; NV]>,
64 missing: Vec<usize>,
66 bad: Vec<bool>,
68}
69
70pub fn axis(n: usize) -> Vec<f64> {
72 PupilGrid::Linear {
73 n,
74 rim: Rim::Padded,
75 }
76 .axis()
77 .unwrap_or_default()
78}
79
80impl PolGrid {
81 pub fn trace(
84 sys: &System,
85 l: &Launch,
86 w: usize,
87 coat: &Coatings,
88 nx: usize,
89 ny: usize,
90 ) -> Result<PolGrid> {
91 if nx < MIN_POINTS || ny < MIN_POINTS {
92 invalid!("the polarization grid needs {MIN_POINTS} points or more on each axis ({nx} × {ny})");
93 }
94 let (ax, ay) = (axis(nx), axis(ny));
95 let mut gx = Vec::with_capacity(nx * ny);
96 let mut gy = Vec::with_capacity(nx * ny);
97 for &y in &ay {
98 for &x in &ax {
99 gx.push(x);
100 gy.push(y);
101 }
102 }
103 let gl = match *l {
104 Launch::Pupil {
105 spec,
106 signed,
107 vig,
108 hxy,
109 ..
110 } => Launch::Pupil {
111 spec,
112 signed,
113 px: &gx,
114 py: &gy,
115 vig,
116 hxy,
117 },
118 _ => invalid!("the polarization grid is only for rays started in pupil coordinates (normalized, signed)"),
119 };
120 let x = [C64::new(1.0, 0.0), C64::new(0.0, 0.0)];
121 let y = [C64::new(0.0, 0.0), C64::new(1.0, 0.0)];
122 let p = sys.trace_pol_launch(&gl, w, PolIn::new(&[x, y], coat).no_phase(), RecSel::Off)?;
123 let n = nx * ny;
124 let mut vals = vec![[C64::new(0.0, 0.0); NV]; n];
125 let mut good = vec![false; n];
126 for k in 0..n {
127 let e = &p.e[k];
128 let (ex, ey) = (e[0], e[1]);
129 let [kx, ky] = obj_dir(sys, p.trace.k0[k]).map(|c| C64::new(c, 0.0));
130 let v = [ex[0], ey[0], ex[1], ey[1], ex[2], ey[2], kx, ky];
131 if p.trace.ok(k) && v.iter().all(|c| c.re.is_finite() && c.im.is_finite()) {
132 vals[k] = v;
133 good[k] = true;
134 }
135 }
136 if !good.iter().any(|&g| g) {
137 invalid!("no point of the polarization grid passes");
138 }
139 let inside = |k: usize| Rim::Padded.inside(gx[k], gy[k]);
140 let missing: Vec<usize> = (0..n).filter(|&k| !good[k] && inside(k)).collect();
141 let mut bad = vec![false; n];
142 missing.iter().for_each(|&k| bad[k] = true);
143 fill_nearest(&mut vals, &good, nx, ny);
144 let (hx, hy) = (2.0 / (nx - 1) as f64, 2.0 / (ny - 1) as f64);
145 let sx = SlopeOp::new(nx, hx);
146 let sy = SlopeOp::new(ny, hy);
147 let fx = sx.along_x(&vals, nx, ny);
148 let fy = sy.along_y(&vals, nx, ny);
149 let fxy = sx.along_x(&fy, nx, ny);
150 Ok(PolGrid {
151 f: Grid2::new(ax, ay, vals),
152 fx,
153 fy,
154 fxy,
155 missing,
156 bad,
157 })
158 }
159
160 pub fn nx(&self) -> usize {
162 self.f.nx()
163 }
164
165 pub fn ny(&self) -> usize {
167 self.f.ny()
168 }
169
170 pub fn values(&self) -> &Grid2<[C64; NV]> {
172 &self.f
173 }
174
175 pub fn missing(&self) -> Vec<[f64; 2]> {
177 let (ax, ay, nx) = (self.f.x(), self.f.y(), self.nx());
178 self.missing
179 .iter()
180 .map(|&k| [ax[k % nx], ay[k / nx]])
181 .collect()
182 }
183
184 pub fn eval(&self, px: f64, py: f64) -> Option<[C64; NV]> {
187 if !(px.is_finite() && py.is_finite()) {
188 return None;
189 }
190 let (nx, ny) = (self.nx(), self.ny());
191 let f = self.f.data();
192 let (hx, hy) = (2.0 / (nx - 1) as f64, 2.0 / (ny - 1) as f64);
193 let cell = |p: f64, h: f64, n: usize| -> (usize, f64) {
194 let s = (p + 1.0) / h;
195 let i = (s.floor().max(0.0) as usize).min(n - 2);
196 (i, s - i as f64)
197 };
198 let (i, t) = cell(px, hx, nx);
199 let (j, u) = cell(py, hy, ny);
200 if !self.missing.is_empty() {
201 let m = BAD_MARGIN;
202 let (i0, i1) = (i.saturating_sub(m), (i + 1 + m).min(nx - 1));
203 let (j0, j1) = (j.saturating_sub(m), (j + 1 + m).min(ny - 1));
204 for jj in j0..=j1 {
205 for ii in i0..=i1 {
206 if self.bad[jj * nx + ii] {
207 return None;
208 }
209 }
210 }
211 }
212 let h = |s: f64| {
214 let (s2, s3) = (s * s, s * s * s);
215 (
216 [2.0 * s3 - 3.0 * s2 + 1.0, -2.0 * s3 + 3.0 * s2],
217 [s3 - 2.0 * s2 + s, s3 - s2],
218 )
219 };
220 let (ax, bx) = h(t);
221 let (ay, by) = h(u);
222 let mut out = [C64::new(0.0, 0.0); NV];
223 for (b, jj) in [j, j + 1].into_iter().enumerate() {
224 for (a, ii) in [i, i + 1].into_iter().enumerate() {
225 let k = jj * nx + ii;
226 let w0 = ax[a] * ay[b];
227 let w1 = bx[a] * ay[b] * hx;
228 let w2 = ax[a] * by[b] * hy;
229 let w3 = bx[a] * by[b] * hx * hy;
230 for c in 0..NV {
231 out[c] += f[k][c] * w0
232 + self.fx[k][c] * w1
233 + self.fy[k][c] * w2
234 + self.fxy[k][c] * w3;
235 }
236 }
237 }
238 Some(out)
239 }
240}
241
242fn fill_nearest(v: &mut [[C64; NV]], good: &[bool], nx: usize, ny: usize) {
244 let gk: Vec<usize> = (0..nx * ny).filter(|&k| good[k]).collect();
245 for k in 0..nx * ny {
246 if good[k] {
247 continue;
248 }
249 let (i, j) = ((k % nx) as i64, (k / nx) as i64);
250 let mut best = (i64::MAX, 0);
251 for &q in &gk {
252 let (a, b) = ((q % nx) as i64 - i, (q / nx) as i64 - j);
253 let d = a * a + b * b;
254 if d < best.0 {
255 best = (d, q);
256 }
257 }
258 v[k] = v[best.1];
259 }
260}
261
262struct SlopeOp {
264 n: usize,
265 m: Vec<f64>,
266}
267
268impl SlopeOp {
269 fn new(n: usize, h: f64) -> SlopeOp {
270 let x: Vec<f64> = (0..n).map(|i| i as f64 * h).collect();
272 let mut m = vec![0.0; n * n];
273 for c in 0..n {
274 let mut e = vec![0.0; n];
275 e[c] = 1.0;
276 let d = Spline::not_a_knot_slopes(&x, &e)
277 .expect("equally spaced nodes with MIN_POINTS (4) points or more");
278 for (i, v) in d.into_iter().enumerate() {
279 m[i * n + c] = v;
280 }
281 }
282 SlopeOp { n, m }
283 }
284
285 fn apply(&self, src: &[[C64; NV]], dst: &mut [[C64; NV]], idx: impl Fn(usize) -> usize) {
286 let n = self.n;
287 for i in 0..n {
288 let mut acc = [C64::new(0.0, 0.0); NV];
289 for c in 0..n {
290 let w = self.m[i * n + c];
291 if w != 0.0 {
292 let s = &src[idx(c)];
293 for q in 0..NV {
294 acc[q] += s[q] * w;
295 }
296 }
297 }
298 dst[idx(i)] = acc;
299 }
300 }
301
302 fn along_x(&self, v: &[[C64; NV]], nx: usize, ny: usize) -> Vec<[C64; NV]> {
304 let mut d = vec![[C64::new(0.0, 0.0); NV]; nx * ny];
305 for j in 0..ny {
306 self.apply(v, &mut d, |i| j * nx + i);
307 }
308 d
309 }
310
311 fn along_y(&self, v: &[[C64; NV]], nx: usize, ny: usize) -> Vec<[C64; NV]> {
313 let mut d = vec![[C64::new(0.0, 0.0); NV]; nx * ny];
314 for i in 0..nx {
315 self.apply(v, &mut d, |j| j * nx + i);
316 }
317 d
318 }
319}
320
321#[cfg(test)]
322mod tests {
323 use super::*;
324
325 #[test]
327 fn slope_exact_for_cubic() {
328 let n = 7;
329 let h = 2.0 / (n - 1) as f64;
330 let op = SlopeOp::new(n, h);
331 let xs = axis(n);
332 let f = |x: f64| 0.3 - 1.2 * x + 0.7 * x * x + 2.1 * x * x * x;
333 let df = |x: f64| -1.2 + 1.4 * x + 6.3 * x * x;
334 for i in 0..n {
335 let d: f64 = (0..n).map(|c| op.m[i * n + c] * f(xs[c])).sum();
336 assert!((d - df(xs[i])).abs() < 1e-12, "{i}: {d} {}", df(xs[i]));
337 }
338 }
339
340 #[test]
342 fn eval_exact_for_bicubic() {
343 let (nx, ny) = (6, 5);
344 let g = |x: f64, y: f64| {
345 C64::new(
346 1.0 + x - 0.5 * y + 0.3 * x * y * y + 0.8 * x * x * x * y,
347 0.2 * y * y * y - x * x,
348 )
349 };
350 let (ax, ay) = (axis(nx), axis(ny));
351 let mut f = Vec::new();
352 for &y in &ay {
353 for &x in &ax {
354 f.push([g(x, y); NV]);
355 }
356 }
357 let (hx, hy) = (2.0 / (nx - 1) as f64, 2.0 / (ny - 1) as f64);
358 let (sx, sy) = (SlopeOp::new(nx, hx), SlopeOp::new(ny, hy));
359 let fy = sy.along_y(&f, nx, ny);
360 let pg = PolGrid {
361 fx: sx.along_x(&f, nx, ny),
362 fxy: sx.along_x(&fy, nx, ny),
363 fy,
364 f: Grid2::new(ax, ay, f),
365 missing: vec![],
366 bad: vec![false; nx * ny],
367 };
368 for &(x, y) in &[
369 (0.13, -0.77),
370 (-0.99, 0.5),
371 (1.0, 1.0),
372 (0.0, 0.0),
373 (1.02, -1.01),
374 ] {
375 let v = pg.eval(x, y).unwrap()[3];
376 assert!((v - g(x, y)).norm() < 1e-12, "({x}, {y}): {v} {}", g(x, y));
377 }
378 }
379
380 #[test]
381 fn fill_nearest_picks_closest() {
382 let (nx, ny) = (4, 4);
383 let mut v = vec![[C64::new(0.0, 0.0); NV]; 16];
384 let mut good = vec![false; 16];
385 v[5][0] = C64::new(1.0, 0.0);
386 good[5] = true;
387 v[15][0] = C64::new(2.0, 0.0);
388 good[15] = true;
389 fill_nearest(&mut v, &good, nx, ny);
390 assert_eq!(v[0][0].re, 1.0);
391 assert_eq!(v[14][0].re, 2.0);
392 assert_eq!(v[10][0].re, 1.0); }
394}