Skip to main content

lensbench_analysis/
energy.rs

1//! 包囲エネルギー: 像面の上の円・x の帯・y の帯・正方形の中の光量の割合と、割合を与えたときの大きさ
2//!
3//! 光量の分布は重みつきの点の集まり([`Spots`])で表す。幾何(瞳の格子の光線の像面の点)と回折(PSF の格子の点)のどちらも
4//! 同じ形にする。中心からの距離(円は半径、x・y の帯は半幅、正方形は半幅 max(|dx|, |dy|))で並べた累積の割合を、点の
5//! 距離の間で直線に補う(大きさに対して連続)。
6
7use crate::psf::Psf;
8use lensbench_core::error::Result;
9use lensbench_core::invalid;
10use lensbench_core::system::{FieldSel, System};
11use lensbench_core::Waves;
12
13/// 光量を数える形
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum EnergyShape {
16    /// 円(半径)
17    #[default]
18    Circle,
19    /// x の帯 |dx| ≤ r(半幅)
20    X,
21    /// y の帯 |dy| ≤ r(半幅)
22    Y,
23    /// 正方形 max(|dx|, |dy|) ≤ r(半幅)
24    Square,
25}
26
27/// 形の中心
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
29pub enum EnergyCenter {
30    /// 主波長の主光線の像点
31    #[default]
32    Chief,
33    /// 光量の重心
34    Centroid,
35    /// 像面の局所座標の原点
36    Vertex,
37    /// 点の広がりの外接長方形の中心
38    Middle,
39}
40
41/// 像面の上の重みつきの点(像面の局所座標)と、全光量(点の重みの和より大きいことがある: PSF の格子の外の光)
42#[derive(Debug, Clone)]
43pub struct Spots {
44    pts: Vec<[f64; 3]>,
45    total: f64,
46    /// 主波長の主光線の像点
47    chief: (f64, f64),
48    /// PSF の升の大きさ (x, y)。Some なら各点の光量を升の中に一様に広げて数える(升の幅より細かい大きさでも連続)
49    cell: Option<(f64, f64)>,
50}
51
52impl Spots {
53    /// 瞳の n × n の格子の升の中心のうち瞳の中の点の光線(波長 w、None なら全部の波長を波長の重みで)の像面の点。
54    /// 波長ごとに、届いた光線の重みの和を波長の重みにそろえる。けられ係数は系のとおり
55    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    /// PSF の格子の点(強度 × 升の面積、全光量は格子の中の光量 / [`Psf::enclosed`])。格子は像面の上([`crate::psf::PsfPlane::Image`])
102    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    /// 中心の点
130    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    /// 中心 at からの距離の累積の割合([`Curve`]、升に広げない)
155    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    /// 中心 at、大きさ r(半径・半幅)の形の中の光量の割合
177    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    /// 升の中に一様に広げた光量の割合: 升の中心の距離 d の前後 ±h に一様に広がるとして数える(h は升の半幅の、距離の
185    /// 向きへの射影。x・y の帯では厳密、円と正方形では近似)
186    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                // 中心をまたぐ升(距離は 0 から hi まで)
211                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    /// 中心 at で光量の割合 frac(0 < frac < 1)を含む形の大きさ。届かなければ誤り
223    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        // 升に広げた割合(増える関数)を二分法で。点の曲線の値の前後 2 升分から
229        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
241/// 形の大きさの向きの距離
242fn 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/// 距離の昇順の (距離, 累積の割合)(最初は (0, 0))。割合は点の距離の間で直線に補う
252#[derive(Debug, Clone)]
253pub struct Curve(Vec<(f64, f64)>);
254
255impl Curve {
256    /// 大きさ r の中の割合
257    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    /// 割合 frac(0 < frac < 1)になる大きさ
268    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/// 幾何の円の包囲エネルギーに、波長ごとにエアリー像の円の割合をかけたもの(回折をおおまかに入れる):
286/// Σ ω_w F_w(r) A(π r / (λF)_w)。F_w は波長 w の光線の円の割合、ω_w は波長の重み、(λF)_w は視野のその波長の回折の
287/// 遮断周波数(子午・球欠の相乗平均)の逆数([`crate::psf::geometric_mtf`] の回折限界と同じ遮断周波数)
288#[derive(Debug, Clone)]
289pub struct AiryEnergy {
290    parts: Vec<(f64, Curve, f64)>,
291}
292
293impl AiryEnergy {
294    /// 視野 field・波長 w(None は全部の波長)の瞳の n × n の格子の光線で、中心 c(重心・広がりの中心は全部の波長の点で)
295    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    /// 半径 r の中の割合
326    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    /// 割合 frac になる半径(増える関数の二分法)
334    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
351/// 増える条件 ok の境目(lo で偽・hi で真)を二分法で
352fn 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
367/// ストレール比: 像面の上の FFT の回折 PSF(波長 w、瞳の格子 pupil、None は自動)の最大の値(収差のない同じ瞳の PSF の
368/// 中心を 1)。格子の間隔は既定の半分(使う波長の回折の遮断周波数の最大の 4 倍の逆数)で、最大の点の周りを 2 次式で補う
369pub 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    // 頂点の 2 次式(x・y 別)の最大
407    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
419/// 円形の無収差の瞳の像(エアリー像)の、半径 v = π r / (λ F) の円の中の光量の割合 1 − J0(v)² − J1(v)²
420pub fn airy_energy(v: f64) -> f64 {
421    let v = v.abs();
422    if v > 400.0 {
423        // 漸近形(J0² + J1² ≈ 2 / (π v)、v = 400 で相対 1e-6 以下の差)
424        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
430/// J0(x)・J1(x)(積分表示 Jn(x) = (1/π) ∫₀^π cos(nτ − x sin τ) dτ の台形則。被積分関数が周期的で滑らかなので点の数が
431/// x + 40 を超えれば丸めの誤差まで収束する)
432fn 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        // 暗輪(J1 の零点)では 1 − J0²: J0 = −0.402 759 395 702 553・0.300 115 752 526 133
451        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}