1use crate::psf::Psf;
8use lensbench_core::error::Result;
9use lensbench_core::invalid;
10use lensbench_core::system::{FieldSel, System};
11use lensbench_core::Waves;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum EnergyShape {
16 #[default]
18 Circle,
19 X,
21 Y,
23 Square,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub enum EnergyCenter {
30 #[default]
32 Chief,
33 Centroid,
35 Vertex,
37 Middle,
39}
40
41#[derive(Debug, Clone)]
43pub struct Spots {
44 pts: Vec<[f64; 3]>,
45 total: f64,
46 chief: (f64, f64),
48 cell: Option<(f64, f64)>,
50}
51
52impl Spots {
53 pub fn geometric(s: &System, field: FieldSel, w: Waves, n: usize) -> Result<Spots> {
56 if n < 4 {
57 invalid!("geometric encircled energy needs a pupil grid of 4 or more ({n})");
58 }
59 let mut px = Vec::new();
60 let mut py = Vec::new();
61 for i in 0..n {
62 for j in 0..n {
63 let x = -1.0 + (2 * i + 1) as f64 / n as f64;
64 let y = -1.0 + (2 * j + 1) as f64 / n as f64;
65 if x * x + y * y <= 1.0 {
66 px.push(x);
67 py.push(y);
68 }
69 }
70 }
71 let ws: Vec<usize> = match w.one() {
72 Some(w) => vec![w],
73 None => (0..s.wavelengths.len()).collect(),
74 };
75 let mut pts = Vec::new();
76 for &wi in &ws {
77 let t = s.try_trace(field, &px, &py, Some(wi), None, false)?;
78 let ok: Vec<_> = (0..t.rays.len()).filter(|&i| t.ok(i)).collect();
79 if ok.is_empty() {
80 continue;
81 }
82 let wt = if ws.len() == 1 { 1.0 } else { s.weights[wi] } / ok.len() as f64;
83 pts.extend(ok.iter().map(|&i| [t.rays[i].xyz[0], t.rays[i].xyz[1], wt]));
84 }
85 if pts.is_empty() {
86 invalid!("no ray of the field reaches the image");
87 }
88 let total = pts.iter().map(|p| p[2]).sum();
89 let c = s.try_trace(field, &[0.0], &[0.0], Some(s.primary), None, false)?;
90 if !c.ok(0) {
91 invalid!("the chief ray doesn't reach the image");
92 }
93 Ok(Spots {
94 pts,
95 total,
96 chief: (c.rays[0].xyz[0], c.rays[0].xyz[1]),
97 cell: None,
98 })
99 }
100
101 pub fn psf(p: &Psf) -> Result<Spots> {
103 if p.plane != crate::psf::PsfPlane::Image {
104 invalid!("encircled energy needs a PSF on the image surface");
105 }
106 let (xs, ys) = (p.i.x(), p.i.y());
107 let mut pts = Vec::with_capacity(xs.len() * ys.len());
108 let mut sum = 0.0;
109 for (iy, row) in p.i.rows().enumerate() {
110 for (ix, &v) in row.iter().enumerate() {
111 if !v.is_finite() {
112 invalid!("the PSF intensity is undefined at some image grid points");
113 }
114 pts.push([p.center.0 + xs[ix], p.center.1 + ys[iy], v]);
115 sum += v;
116 }
117 }
118 if !(sum > 0.0) || !(p.enclosed > 0.0) {
119 invalid!("the PSF has no light");
120 }
121 Ok(Spots {
122 pts,
123 total: sum / p.enclosed.min(1.0),
124 chief: p.center,
125 cell: Some(p.pixel),
126 })
127 }
128
129 pub fn center(&self, c: EnergyCenter) -> (f64, f64) {
131 match c {
132 EnergyCenter::Chief => self.chief,
133 EnergyCenter::Vertex => (0.0, 0.0),
134 EnergyCenter::Centroid => {
135 let w: f64 = self.pts.iter().map(|p| p[2]).sum();
136 let x = self.pts.iter().map(|p| p[0] * p[2]).sum::<f64>() / w;
137 let y = self.pts.iter().map(|p| p[1] * p[2]).sum::<f64>() / w;
138 (x, y)
139 }
140 EnergyCenter::Middle => {
141 let lit = self.pts.iter().filter(|p| p[2] > 0.0);
142 let (mut x0, mut x1, mut y0, mut y1) = (f64::MAX, f64::MIN, f64::MAX, f64::MIN);
143 for p in lit {
144 x0 = x0.min(p[0]);
145 x1 = x1.max(p[0]);
146 y0 = y0.min(p[1]);
147 y1 = y1.max(p[1]);
148 }
149 ((x0 + x1) / 2.0, (y0 + y1) / 2.0)
150 }
151 }
152 }
153
154 pub fn curve(&self, at: (f64, f64), shape: EnergyShape) -> Curve {
156 let (cx, cy) = at;
157 let mut d: Vec<(f64, f64)> = self
158 .pts
159 .iter()
160 .map(|p| {
161 let (dx, dy) = ((p[0] - cx).abs(), (p[1] - cy).abs());
162 (dist(shape, dx, dy), p[2])
163 })
164 .collect();
165 d.sort_by(|a, b| a.0.total_cmp(&b.0));
166 let mut out = Vec::with_capacity(d.len() + 1);
167 out.push((0.0, 0.0));
168 let mut acc = 0.0;
169 for (r, w) in d {
170 acc += w;
171 out.push((r, acc / self.total));
172 }
173 Curve(out)
174 }
175
176 pub fn fraction(&self, at: (f64, f64), shape: EnergyShape, r: f64) -> f64 {
178 match self.cell {
179 Some(cell) => self.fraction_cells(at, shape, r, cell),
180 None => self.curve(at, shape).fraction(r),
181 }
182 }
183
184 fn fraction_cells(&self, at: (f64, f64), shape: EnergyShape, r: f64, cell: (f64, f64)) -> f64 {
187 let (cx, cy) = at;
188 let (hx, hy) = (cell.0 / 2.0, cell.1 / 2.0);
189 let mut acc = 0.0;
190 for p in &self.pts {
191 let (dx, dy) = ((p[0] - cx).abs(), (p[1] - cy).abs());
192 let (d, h) = match shape {
193 EnergyShape::X => (dx, hx),
194 EnergyShape::Y => (dy, hy),
195 EnergyShape::Square if dx >= dy => (dx, hx),
196 EnergyShape::Square => (dy, hy),
197 EnergyShape::Circle => {
198 let d = dx.hypot(dy);
199 if d > 0.0 {
200 (d, (dx * hx + dy * hy) / d)
201 } else {
202 (0.0, hx.max(hy))
203 }
204 }
205 };
206 let (lo, hi) = (d - h, d + h);
207 let f = if r >= hi {
208 1.0
209 } else if lo < 0.0 {
210 r.max(0.0) / hi
212 } else if r <= lo {
213 0.0
214 } else {
215 (r - lo) / (2.0 * h)
216 };
217 acc += p[2] * f;
218 }
219 acc / self.total
220 }
221
222 pub fn size(&self, at: (f64, f64), shape: EnergyShape, frac: f64) -> Result<f64> {
224 let r = self.curve(at, shape).size(frac)?;
225 let Some(cell) = self.cell else {
226 return Ok(r);
227 };
228 let w = cell.0.max(cell.1);
230 let (mut lo, mut hi) = ((r - 2.0 * w).max(0.0), r + 2.0 * w);
231 while lo > 0.0 && self.fraction(at, shape, lo) > frac {
232 lo = (lo - 2.0 * w).max(0.0);
233 }
234 while self.fraction(at, shape, hi) < frac {
235 hi += 2.0 * w;
236 }
237 Ok(bisect(lo, hi, |m| self.fraction(at, shape, m) >= frac))
238 }
239}
240
241fn dist(shape: EnergyShape, dx: f64, dy: f64) -> f64 {
243 match shape {
244 EnergyShape::Circle => dx.hypot(dy),
245 EnergyShape::X => dx,
246 EnergyShape::Y => dy,
247 EnergyShape::Square => dx.max(dy),
248 }
249}
250
251#[derive(Debug, Clone)]
253pub struct Curve(Vec<(f64, f64)>);
254
255impl Curve {
256 pub fn fraction(&self, r: f64) -> f64 {
258 let cv = &self.0;
259 let k = cv.partition_point(|p| p.0 <= r);
260 if k >= cv.len() {
261 return cv[cv.len() - 1].1;
262 }
263 let (a, b) = (cv[k - 1], cv[k]);
264 a.1 + (b.1 - a.1) * (r - a.0) / (b.0 - a.0)
265 }
266
267 pub fn size(&self, frac: f64) -> Result<f64> {
269 if !(frac > 0.0 && frac < 1.0) {
270 invalid!("fraction {frac} (between 0 and 1)");
271 }
272 let cv = &self.0;
273 let k = cv.partition_point(|p| p.1 < frac);
274 if k >= cv.len() {
275 invalid!(
276 "the energy reaches only {:.4} of the total, not {frac}",
277 cv[cv.len() - 1].1
278 );
279 }
280 let (a, b) = (cv[k - 1], cv[k]);
281 Ok(a.0 + (b.0 - a.0) * (frac - a.1) / (b.1 - a.1))
282 }
283}
284
285#[derive(Debug, Clone)]
289pub struct AiryEnergy {
290 parts: Vec<(f64, Curve, f64)>,
291}
292
293impl AiryEnergy {
294 pub fn new(
296 s: &System,
297 field: FieldSel,
298 w: Waves,
299 n: usize,
300 c: EnergyCenter,
301 ) -> Result<AiryEnergy> {
302 let at = Spots::geometric(s, field, w, n)?.center(c);
303 let ws: Vec<usize> = match w.one() {
304 Some(w) => vec![w],
305 None => (0..s.wavelengths.len())
306 .filter(|&i| s.weights[i] > 0.0)
307 .collect(),
308 };
309 let wsum: f64 = ws.iter().map(|&i| s.weights[i]).sum();
310 let mut parts = Vec::with_capacity(ws.len());
311 for wi in ws {
312 let sp = Spots::geometric(s, field, Waves::all_or(Some(wi)), n)?;
313 let cut = crate::analysis::mtf_cutoff(s, field, wi)?;
314 let lam_f = 1.0 / (cut.tan * cut.sag).sqrt();
315 let om = if w.one().is_some() {
316 1.0
317 } else {
318 s.weights[wi] / wsum
319 };
320 parts.push((om, sp.curve(at, EnergyShape::Circle), lam_f));
321 }
322 Ok(AiryEnergy { parts })
323 }
324
325 pub fn fraction(&self, r: f64) -> f64 {
327 self.parts
328 .iter()
329 .map(|(om, cv, lf)| om * cv.fraction(r) * airy_energy(std::f64::consts::PI * r / lf))
330 .sum()
331 }
332
333 pub fn size(&self, frac: f64) -> Result<f64> {
335 if !(frac > 0.0 && frac < 1.0) {
336 invalid!("fraction {frac} (between 0 and 1)");
337 }
338 let mut hi = self.parts.iter().map(|p| p.2).fold(0.0, f64::max);
339 let mut n = 0;
340 while self.fraction(hi) < frac {
341 hi *= 2.0;
342 n += 1;
343 if n > 60 {
344 invalid!("the energy doesn't reach {frac}");
345 }
346 }
347 Ok(bisect(0.0, hi, |m| self.fraction(m) >= frac))
348 }
349}
350
351fn bisect(mut lo: f64, mut hi: f64, ok: impl Fn(f64) -> bool) -> f64 {
353 for _ in 0..100 {
354 let m = 0.5 * (lo + hi);
355 if ok(m) {
356 hi = m;
357 } else {
358 lo = m;
359 }
360 if hi - lo <= 1e-15 * hi {
361 break;
362 }
363 }
364 0.5 * (lo + hi)
365}
366
367pub fn strehl(s: &System, field: FieldSel, w: Waves, pupil: Option<usize>) -> Result<f64> {
370 let ws: Vec<usize> = match w.one() {
371 Some(w) => vec![w],
372 None => (0..s.wavelengths.len()).collect(),
373 };
374 let mut top = 0.0f64;
375 for wi in ws {
376 let c = crate::analysis::mtf_cutoff(s, field, wi)?;
377 top = top.max(c.tan).max(c.sag);
378 }
379 if !(top > 0.0 && top.is_finite()) {
380 invalid!("the diffraction cutoff of the field is not finite");
381 }
382 let o = crate::psf::PsfOpts {
383 pupil,
384 image: 128,
385 pixel: Some(0.25 / top),
386 plane: crate::psf::PsfPlane::Image,
387 };
388 let p = crate::psf::psf(s, field, w, o)?;
389 let (nx, ny) = (p.i.nx(), p.i.ny());
390 let mut best = (0, 0, f64::NEG_INFINITY);
391 for iy in 0..ny {
392 for ix in 0..nx {
393 let v = *p.i.get(ix, iy);
394 if v > best.2 {
395 best = (ix, iy, v);
396 }
397 }
398 }
399 let (ix, iy, v) = best;
400 if !v.is_finite() {
401 invalid!("the PSF has no finite peak");
402 }
403 if ix == 0 || iy == 0 || ix + 1 == nx || iy + 1 == ny {
404 return Ok(v);
405 }
406 let g = |a: usize, b: usize| *p.i.get(a, b);
408 let up = |m: f64, c: f64, q: f64| -> f64 {
409 let (d1, d2) = ((q - m) / 2.0, q - 2.0 * c + m);
410 if d2 < 0.0 {
411 -d1 * d1 / (2.0 * d2)
412 } else {
413 0.0
414 }
415 };
416 Ok(v + up(g(ix - 1, iy), v, g(ix + 1, iy)) + up(g(ix, iy - 1), v, g(ix, iy + 1)))
417}
418
419pub fn airy_energy(v: f64) -> f64 {
421 let v = v.abs();
422 if v > 400.0 {
423 return 1.0 - 2.0 / (std::f64::consts::PI * v);
425 }
426 let (j0, j1) = bessel01(v);
427 1.0 - j0 * j0 - j1 * j1
428}
429
430fn bessel01(x: f64) -> (f64, f64) {
433 let m = (x as usize + 40) * 2;
434 let (mut j0, mut j1) = (0.0, 0.0);
435 for k in 0..m {
436 let t = std::f64::consts::PI * (k as f64 + 0.5) / m as f64;
437 let ph = x * t.sin();
438 j0 += ph.cos();
439 j1 += (t - ph).cos();
440 }
441 (j0 / m as f64, j1 / m as f64)
442}
443
444#[cfg(test)]
445mod tests {
446 use super::*;
447
448 #[test]
449 fn airy_energy_known_values() {
450 let ring = |j0: f64| 1.0 - j0 * j0;
452 assert!((airy_energy(3.831_705_970_207_512) - ring(-0.402_759_395_702_553)).abs() < 1e-13);
453 assert!((airy_energy(7.015_586_669_815_619) - ring(0.300_115_752_526_133)).abs() < 1e-13);
454 assert!(airy_energy(0.0).abs() < 1e-15);
455 let (j0, j1) = bessel01(10.0);
456 assert!((j0 - (-0.245_935_764_451_348_3)).abs() < 1e-14);
457 assert!((j1 - 0.043_472_746_168_861_44).abs() < 1e-14);
458 }
459}