Skip to main content

lensbench_analysis/defs/
illum.rs

1//! フットプリント図・相対照度・けられの図(Footprint Diagram・Relative Illumination・Vignetting Plot)
2
3use lensbench_core::{Error, FieldSel, Result, System};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use super::{coat_notes, fields, wave, Axis};
8use crate::footprint;
9use crate::registry::{Analysis, Cx, Meta};
10use crate::sweep::steps01;
11
12// ----------------------------------------------------------------------------------- footprint
13
14/// フットプリントの設定
15#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
16#[serde(default, deny_unknown_fields)]
17pub(super) struct FootprintParams {
18    /// Surface number (the stop surface if omitted)
19    pub surface: Option<usize>,
20    /// Field number (from 1; all fields if omitted)
21    pub field: Option<usize>,
22    /// Wavelength number (from 1; every wavelength if omitted)
23    pub wave: Option<usize>,
24    /// Pupil ray grid (rays across the pupil diameter)
25    #[schemars(extend("x-min" = 2))]
26    pub rays: usize,
27    /// Ignore the vignetting factors of the fields (only the surface apertures clip the full pupil)
28    pub no_vignetting_factors: bool,
29}
30
31impl Default for FootprintParams {
32    fn default() -> Self {
33        FootprintParams {
34            surface: None,
35            field: None,
36            wave: None,
37            rays: 21,
38            no_vignetting_factors: false,
39        }
40    }
41}
42
43/// フットプリントの 1 視野・1 波長
44#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
45pub struct FootprintRow {
46    /// Field number (from 1)
47    pub field: usize,
48    /// 波長の番号(1 始まり)
49    pub wave: usize,
50    /// 面に届いた光線の交点 (x, y)(面の局所座標)
51    pub points: Vec<[f64; 2]>,
52    /// 瞳の縁の光線の交点(面より前でけられた光線は null)
53    pub edge: Vec<[Option<f64>; 2]>,
54    /// 交点の x・y の最小・最大
55    #[serde(deserialize_with = "crate::nan::a2")]
56    pub x: [f64; 2],
57    #[serde(deserialize_with = "crate::nan::a2")]
58    pub y: [f64; 2],
59    /// 面の頂点からの交点の距離の最大
60    #[serde(deserialize_with = "crate::nan::f")]
61    pub max_radius: f64,
62    /// max_radius の、面の半直径に対する割合(半直径が 0 なら null)
63    #[serde(deserialize_with = "crate::nan::f")]
64    pub fill: f64,
65    /// 像面までけられずに通った光線の割合
66    #[serde(deserialize_with = "crate::nan::f")]
67    pub through: f64,
68    /// この面でけられた光線の割合
69    #[serde(deserialize_with = "crate::nan::f")]
70    pub clipped: f64,
71}
72
73/// フットプリントの結果
74#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
75pub struct FootprintOut {
76    /// 面の番号
77    pub surface: usize,
78    pub unit: String,
79    /// 面の半直径
80    #[serde(deserialize_with = "crate::nan::f")]
81    pub semi: f64,
82    /// 面の開口の輪郭(閉じた折れ線の並び、面の局所座標)
83    pub aperture: Vec<Vec<[f64; 2]>>,
84    pub rows: Vec<FootprintRow>,
85    /// 全部の視野・波長の max_radius の最大と、その半直径に対する割合
86    #[serde(deserialize_with = "crate::nan::f")]
87    pub max_radius: f64,
88    #[serde(deserialize_with = "crate::nan::f")]
89    pub fill: f64,
90    pub warnings: Vec<String>,
91}
92
93pub(super) struct Footprint;
94
95impl Analysis for Footprint {
96    type Params = FootprintParams;
97    type Output = FootprintOut;
98    fn meta(&self) -> Meta {
99        Meta {
100            name: "footprint",
101            about: "Footprint diagram: where the beam of each field and wavelength crosses a surface, against its aperture",
102            help: "Footprint diagram (OpticStudio's Footprint Diagram): the local intersections on a surface of a grid of pupil rays for each field and wavelength, with the outline of the surface aperture, the largest radius and its fraction of the semi-diameter, the fraction of rays that reach the image unvignetted and the fraction clipped at this surface. Rays clipped before the surface are not drawn. The vignetting factors of the fields are used unless no_vignetting_factors",
103        }
104    }
105    fn run(&self, cx: &Cx<'_>, p: &FootprintParams) -> Result<FootprintOut> {
106        let s = cx.system;
107        let j = match p.surface {
108            Some(j) => j,
109            None => s.surfaces.iter().position(|d| d.stop).unwrap_or(1),
110        };
111        if j == 0 || j > s.image() {
112            return Err(Error::Invalid(format!("surface {j} (1 to {})", s.image())));
113        }
114        let ws: Vec<usize> = match wave(s, p.wave)? {
115            Some(w) => vec![w],
116            None => (0..s.wavelengths.len()).collect(),
117        };
118        let semi = s.surfaces[j].semi.abs();
119        let frac = |r: f64| if semi > 0.0 { r / semi } else { f64::NAN };
120        let mut rows = Vec::new();
121        let mut warnings = Vec::new();
122        for i in fields(s, p.field)? {
123            for &w in &ws {
124                match footprint::footprint(
125                    s,
126                    FieldSel::Index(i),
127                    w,
128                    j,
129                    p.rays,
130                    !p.no_vignetting_factors,
131                ) {
132                    Ok(f) => {
133                        let n = f.rays.max(1) as f64;
134                        rows.push(FootprintRow {
135                            field: i + 1,
136                            wave: w + 1,
137                            edge: f
138                                .edge
139                                .iter()
140                                .map(|q| {
141                                    [
142                                        q[0].is_finite().then_some(q[0]),
143                                        q[1].is_finite().then_some(q[1]),
144                                    ]
145                                })
146                                .collect(),
147                            points: f.points,
148                            x: f.x,
149                            y: f.y,
150                            max_radius: f.max_radius,
151                            fill: frac(f.max_radius),
152                            through: f.through as f64 / n,
153                            clipped: f.clipped as f64 / n,
154                        });
155                    }
156                    Err(e) => warnings.push(format!("field {}, wavelength {}: {e}", i + 1, w + 1)),
157                }
158            }
159        }
160        if rows.is_empty() {
161            return Err(Error::Invalid(warnings.join("; ")));
162        }
163        let max_radius = rows
164            .iter()
165            .map(|r| r.max_radius)
166            .filter(|r| r.is_finite())
167            .fold(f64::NAN, f64::max);
168        Ok(FootprintOut {
169            surface: j,
170            unit: "mm".into(),
171            semi,
172            aperture: footprint::aperture_outline(s, j),
173            rows,
174            max_radius,
175            fill: frac(max_radius),
176            warnings,
177        })
178    }
179}
180
181// ------------------------------------------------------------------------ relative-illumination
182
183/// 相対照度の設定
184#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
185#[serde(default, deny_unknown_fields)]
186pub(super) struct RelIllumParams {
187    /// Wavelength number (from 1; the primary wavelength if omitted)
188    pub wave: Option<usize>,
189    /// Number of field points (normalized field 0 to 1)
190    #[schemars(extend("x-min" = 2))]
191    pub points: usize,
192    /// Field direction (y or x)
193    pub axis: Axis,
194    /// Number of points on the rim of the beam (even, 8 or more)
195    #[schemars(extend("x-min" = 8))]
196    pub rim: usize,
197    /// Include the coating transmission and Fresnel losses (the system input polarization, unpolarized by default, and coatings; the pupil-averaged transmission relative to the axis)
198    pub polarization: bool,
199    /// Replace the vignetting factors with floating apertures at the current semi-diameters (OpticStudio's default Remove Vignetting Factors); off ignores the vignetting factors and keeps the surface apertures as they are
200    pub remove_vignetting_factors: bool,
201}
202
203impl Default for RelIllumParams {
204    fn default() -> Self {
205        RelIllumParams {
206            wave: None,
207            points: 21,
208            axis: Axis::Y,
209            rim: crate::illum::RIM_POINTS,
210            polarization: false,
211            remove_vignetting_factors: true,
212        }
213    }
214}
215
216/// 相対照度の結果
217#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
218pub struct RelIllumOut {
219    /// 波長の番号(1 始まり)
220    pub wave: usize,
221    #[serde(deserialize_with = "crate::nan::v")]
222    pub h: Vec<f64>,
223    #[serde(deserialize_with = "crate::nan::v")]
224    pub field_value: Vec<f64>,
225    /// 相対照度(軸上の像点を 1、演算子 RELI と同じ。polarization なら透過率の比も掛ける)
226    #[serde(deserialize_with = "crate::nan::v")]
227    pub relative: Vec<f64>,
228    /// 実効 F ナンバー(演算子 EFNO と同じ)
229    #[serde(deserialize_with = "crate::nan::v")]
230    pub effective_fno: Vec<f64>,
231    /// 瞳の上で平均した膜・フレネルの透過率(polarization のときだけ)
232    #[serde(default, skip_serializing_if = "Option::is_none")]
233    #[serde(deserialize_with = "crate::nan::ov")]
234    pub transmission: Option<Vec<f64>>,
235    pub warnings: Vec<String>,
236}
237
238/// 視野 f の瞳の上で平均した強度の透過率(膜・フレネル、系の入射偏光。偏光なし = 光線に垂直な面の正規直交の基底の 2 つの偏光の平均、
239/// [`crate::polgrid::basis_coeffs`])。入力の偏光の強度を 1 にそろえる(斜めの光線で射影の分だけ小さく出さない。
240/// OpticStudio の Relative Illumination の Use Polarization と同じく、軸外でも透過率だけの比になる)
241pub fn mean_transmission(s: &System, f: FieldSel, w: usize) -> Result<f64> {
242    use lensbench_core::coating::C64;
243    use lensbench_core::system::{Launch, PolIn, RecSel};
244    let co = lensbench_core::coating::Coatings::for_system(s)?;
245    let c = s.try_trace(f, &[0.0], &[0.0], Some(w), None, false)?;
246    let (hx, hy) = c.hx_hy;
247    let (px, py) = lensbench_core::opd::pupil_grid(21);
248    let l = Launch::Pupil {
249        spec: s.object_spec(hx, hy)?,
250        signed: false,
251        px: &px,
252        py: &py,
253        vig: Some(s.vig_factors(hx, hy)?),
254        hxy: Some((hx, hy)),
255    };
256    let (one, zero) = (C64::new(1.0, 0.0), C64::new(0.0, 0.0));
257    let pol = s.input_pol.jones();
258    if pol.is_some_and(|j| !(j[0].norm_sqr() + j[1].norm_sqr() > 0.0)) {
259        return Err(Error::Invalid(
260            "the input polarization (Ex, Ey) must not be zero".into(),
261        ));
262    }
263    let p = s.trace_pol_launch(
264        &l,
265        w,
266        PolIn::new(&[[one, zero], [zero, one]], &co).no_phase(),
267        RecSel::Off,
268    )?;
269    let (mut sum, mut n) = (0.0, 0usize);
270    for k in 0..px.len() {
271        if !p.trace.ok(k) {
272            continue;
273        }
274        let [kx, ky] = crate::polgrid::obj_dir(s, p.trace.k0[k]);
275        let e = &p.e[k];
276        // 正規直交の基底 e_x'・e_y' の 2 つの偏光の平均(OpticStudio の系の偏光と同じ基底)
277        let i = |j: [C64; 2]| {
278            let c = crate::polgrid::basis_coeffs(j, kx, ky);
279            (0..3)
280                .map(|q| (e[0][q] * c[0] + e[1][q] * c[1]).norm_sqr())
281                .sum::<f64>()
282        };
283        // 系の入射偏光(強度を 1 にそろえる)、偏光なしは 2 つの偏光の平均
284        let t = match pol {
285            Some(j) => i(j) / (j[0].norm_sqr() + j[1].norm_sqr()),
286            None => 0.5 * (i([one, zero]) + i([zero, one])),
287        };
288        if t.is_finite() {
289            sum += t;
290            n += 1;
291        }
292    }
293    if n == 0 {
294        return Err(Error::Invalid(
295            "no ray of the pupil has a transmission".into(),
296        ));
297    }
298    Ok(sum / n as f64)
299}
300
301pub(super) struct RelIllum;
302
303impl Analysis for RelIllum {
304    type Params = RelIllumParams;
305    type Output = RelIllumOut;
306    fn meta(&self) -> Meta {
307        Meta {
308            name: "relative-illumination",
309            about: "Relative illumination versus field (image irradiance relative to the axis) and effective F-number",
310            help: "Relative illumination (OpticStudio's Relative Illumination): for points steps of the normalized field 0 to 1, the irradiance at the image point of the chief ray relative to the axis, from the projected solid angle of the beam that reaches that image point (the RELI operand), and the effective F-number (EFNO). By default the vignetting factors are replaced with floating apertures at the current semi-diameters on the surfaces where the medium changes (OpticStudio's Remove Vignetting Factors); with remove_vignetting_factors off the vignetting factors are ignored and the surface apertures are kept as they are. With polarization the ratio of the pupil-averaged coating and Fresnel transmission to the axis is multiplied in, and the effective F-number includes the transmission (F/√T)",
311        }
312    }
313    fn run(&self, cx: &Cx<'_>, p: &RelIllumParams) -> Result<RelIllumOut> {
314        let replaced = if p.remove_vignetting_factors {
315            Some(crate::illum::replace_vignetting(cx.system)?)
316        } else {
317            None
318        };
319        let s = replaced.as_ref().unwrap_or(cx.system);
320        let w = wave(s, p.wave)?.unwrap_or(s.primary);
321        let ax = p.axis.core();
322        if !has_off_axis(s, ax) {
323            return Err(Error::Invalid(
324                "the relative illumination needs a field off the axis (in the field direction)"
325                    .into(),
326            ));
327        }
328        let h = steps01(p.points.max(2));
329        let mut warnings = Vec::new();
330        let a0 = crate::illum::exit_cone(s, FieldSel::Norm(0.0, 0.0), w, p.rim)?;
331        let t0 = if p.polarization {
332            Some(mean_transmission(s, FieldSel::Norm(0.0, 0.0), w)?)
333        } else {
334            None
335        };
336        let (mut rel, mut fno, mut trans) = (Vec::new(), Vec::new(), Vec::new());
337        for &hh in &h {
338            let f = ax.sel(hh);
339            match crate::illum::exit_cone(s, f, w, p.rim) {
340                Ok(a) => {
341                    rel.push(a / a0);
342                    fno.push(1.0 / (2.0 * (a / std::f64::consts::PI).sqrt()));
343                }
344                Err(e) => {
345                    warnings.push(format!("field {}: {e}", f3(hh)));
346                    rel.push(f64::NAN);
347                    fno.push(f64::NAN);
348                }
349            }
350            if let Some(t0) = t0 {
351                let t = mean_transmission(s, f, w).unwrap_or_else(|e| {
352                    warnings.push(format!("field {}: {e}", f3(hh)));
353                    f64::NAN
354                });
355                trans.push(t);
356                if let Some(r) = rel.last_mut() {
357                    *r *= t / t0;
358                }
359                // 透過を含めた実効 F ナンバー F/√T(T ナンバー。OpticStudio の Use Polarization と同じ)
360                if let Some(n) = fno.last_mut() {
361                    *n /= t.sqrt();
362                }
363            }
364        }
365        warnings.extend(coat_notes(s, p.polarization)?);
366        Ok(RelIllumOut {
367            wave: w + 1,
368            field_value: h.iter().map(|&x| ax.value(s, x)).collect(),
369            h,
370            relative: rel,
371            effective_fno: fno,
372            transmission: t0.map(|_| trans),
373            warnings,
374        })
375    }
376}
377
378/// 視野を振る向きに軸外の視野があるか(無ければ正規化視野に大きさが無く、横軸の視野の値が意味を持たない)
379fn has_off_axis(s: &System, ax: crate::sweep::FieldAxis) -> bool {
380    let along = |f: &lensbench_core::system::Field| match (s.field_norm, ax) {
381        (lensbench_core::system::FieldNorm::Radial, _) => f.x.hypot(f.y),
382        (_, crate::sweep::FieldAxis::X) => f.x.abs(),
383        (_, crate::sweep::FieldAxis::Y) => f.y.abs(),
384    };
385    s.fields.iter().map(along).fold(0.0, f64::max) > 0.0
386}
387
388/// 注意の文の視野の値(小数 3 桁)
389fn f3(x: f64) -> String {
390    format!("{x:.3}")
391}
392
393// ----------------------------------------------------------------------------------- vignetting
394
395/// けられの図の設定
396#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
397#[serde(default, deny_unknown_fields)]
398pub(super) struct VignettingParams {
399    /// Wavelength number (from 1; the primary wavelength if omitted)
400    pub wave: Option<usize>,
401    /// Number of field points (normalized field 0 to 1)
402    #[schemars(extend("x-min" = 2))]
403    pub points: usize,
404    /// Field direction (y or x)
405    pub axis: Axis,
406    /// Pupil ray grid (rays across the pupil diameter)
407    #[schemars(extend("x-min" = 2))]
408    pub rays: usize,
409    /// Ignore the vignetting factors of the fields (only the surface apertures clip the full pupil; when remove_vignetting_factors is off)
410    pub no_vignetting_factors: bool,
411    /// Replace the vignetting factors with floating apertures at the current semi-diameters (OpticStudio's default Remove Vignetting Factors)
412    pub remove_vignetting_factors: bool,
413}
414
415impl Default for VignettingParams {
416    fn default() -> Self {
417        VignettingParams {
418            wave: None,
419            points: 21,
420            axis: Axis::Y,
421            rays: 64,
422            no_vignetting_factors: false,
423            remove_vignetting_factors: true,
424        }
425    }
426}
427
428/// けられの図の結果
429#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
430pub struct VignettingOut {
431    /// 波長の番号(1 始まり)
432    pub wave: usize,
433    #[serde(deserialize_with = "crate::nan::v")]
434    pub h: Vec<f64>,
435    #[serde(deserialize_with = "crate::nan::v")]
436    pub field_value: Vec<f64>,
437    /// けられずに像面まで通る光線の割合
438    #[serde(deserialize_with = "crate::nan::v")]
439    pub unvignetted: Vec<f64>,
440    pub warnings: Vec<String>,
441}
442
443pub(super) struct Vignetting;
444
445impl Analysis for Vignetting {
446    type Params = VignettingParams;
447    type Output = VignettingOut;
448    fn meta(&self) -> Meta {
449        Meta {
450            name: "vignetting",
451            about: "Vignetting plot: fraction of unvignetted rays versus field",
452            help: "Vignetting plot (OpticStudio's Vignetting Plot): for points steps of the normalized field 0 to 1, the fraction of a grid of pupil rays (rays across the diameter) that reach the image unvignetted. By default the vignetting factors are replaced with floating apertures at the current semi-diameters on the surfaces where the medium changes (OpticStudio's Remove Vignetting Factors). With remove_vignetting_factors off, the vignetting factors of the fields are used unless no_vignetting_factors (then the full pupil is clipped only by the surface apertures)",
453        }
454    }
455    fn run(&self, cx: &Cx<'_>, p: &VignettingParams) -> Result<VignettingOut> {
456        let replaced = if p.remove_vignetting_factors {
457            Some(crate::illum::replace_vignetting(cx.system)?)
458        } else {
459            None
460        };
461        let s = replaced.as_ref().unwrap_or(cx.system);
462        let w = wave(s, p.wave)?.unwrap_or(s.primary);
463        let ax = p.axis.core();
464        if !has_off_axis(s, ax) {
465            return Err(Error::Invalid(
466                "the vignetting plot needs a field off the axis (in the field direction)".into(),
467            ));
468        }
469        let h = steps01(p.points.max(2));
470        let mut warnings = Vec::new();
471        let unvignetted = h
472            .iter()
473            .map(|&hh| {
474                footprint::unvignetted(s, ax.sel(hh), w, p.rays, !p.no_vignetting_factors)
475                    .unwrap_or_else(|e| {
476                        warnings.push(format!("field {}: {e}", f3(hh)));
477                        f64::NAN
478                    })
479            })
480            .collect();
481        Ok(VignettingOut {
482            wave: w + 1,
483            field_value: h.iter().map(|&x| ax.value(s, x)).collect(),
484            h,
485            unvignetted,
486            warnings,
487        })
488    }
489}