Skip to main content

lensbench_analysis/defs/
image.rs

1//! RMS の掃引・PSF
2
3use crate::huygens::{self, HuygensDevice, HuygensOpts};
4use crate::psf::{self, PsfOpts, PsfPlane};
5use crate::sweep::{self, RmsOpts, RmsRef};
6use lensbench_core::pupil::PupilAmp;
7use lensbench_core::Waves;
8use lensbench_core::{Error, FieldSel, Result};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use super::{coat_notes, fields, pol_amp, skip_vignetted, spot_unit, wave, Axis};
13use crate::registry::{Analysis, Cx, Meta};
14
15// ----------------------------------------------------------------------------------------- rms
16
17/// RMS の横軸
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
19#[serde(rename_all = "lowercase")]
20pub enum Vs {
21    /// 正規化視野 0〜1
22    #[default]
23    Field,
24    /// 像面のずらし ±range
25    Focus,
26    /// 系の波長の最小〜最大(単色)
27    Wavelength,
28}
29
30/// RMS の基準
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
32#[serde(rename_all = "lowercase")]
33pub enum Reference {
34    /// 重心
35    #[default]
36    Centroid,
37    /// 主光線
38    Chief,
39}
40
41/// RMS の設定
42#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
43#[serde(default, deny_unknown_fields)]
44pub(super) struct RmsParams {
45    /// Field number (from 1; all fields if omitted; not used with vs field)
46    pub field: Option<usize>,
47    /// Wavelength number (from 1; polychromatic if omitted; not used with vs wavelength)
48    pub wave: Option<usize>,
49    /// Horizontal axis: field (normalized field 0 to 1), focus (image shift ±range), wavelength (system wavelength minimum to maximum, monochromatic)
50    pub vs: Vs,
51    /// Number of points on the horizontal axis
52    #[schemars(extend("x-min" = 1))]
53    pub points: usize,
54    /// Shift range of focus ±range [lens units]
55    pub range: f64,
56    /// Field direction for field (y or x)
57    pub axis: Axis,
58    /// Reference: centroid or chief (chief ray)
59    pub reference: Reference,
60    /// Number of rings of the Gaussian pupil quadrature
61    #[schemars(extend("x-min" = 1))]
62    pub rings: usize,
63    /// In monochromatic field and wavelength sweeps, solve fields given by real image height (and fields defined by conditions) with the chief ray of the analysis wavelength
64    /// (Same as OpticStudio's monochromatic RMS vs Field and vs Wavelength; solved at the primary wavelength if omitted)
65    pub field_wave: bool,
66}
67
68impl Default for RmsParams {
69    fn default() -> Self {
70        RmsParams {
71            field: None,
72            wave: None,
73            vs: Vs::Field,
74            points: 11,
75            range: 0.1,
76            axis: Axis::Y,
77            reference: Reference::Centroid,
78            rings: 6,
79            field_wave: false,
80        }
81    }
82}
83
84/// RMS の 1 点
85#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
86pub struct RmsRow {
87    /// スポット半径の RMS
88    #[serde(deserialize_with = "crate::nan::f")]
89    pub spot: f64,
90    #[serde(deserialize_with = "crate::nan::f")]
91    pub spot_x: f64,
92    #[serde(deserialize_with = "crate::nan::f")]
93    pub spot_y: f64,
94    /// 波面収差の RMS [波]
95    #[serde(deserialize_with = "crate::nan::f")]
96    pub wfe: f64,
97    /// ストレール比の近似
98    #[serde(deserialize_with = "crate::nan::f")]
99    pub strehl: f64,
100    /// 正規化視野(vs field)
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub h: Option<f64>,
103    /// 視野の値(vs field)
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub field_value: Option<f64>,
106    /// 像面のずらし(vs focus)
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub dz: Option<f64>,
109    /// 波長 [µm](vs wavelength)
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub wavelength: Option<f64>,
112    /// 視野の番号(vs focus・wavelength)
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub field: Option<usize>,
115}
116
117impl RmsRow {
118    fn of(r: &sweep::Rms) -> RmsRow {
119        RmsRow {
120            spot: r.spot,
121            spot_x: r.spot_x,
122            spot_y: r.spot_y,
123            wfe: r.wfe,
124            strehl: r.strehl,
125            h: None,
126            field_value: None,
127            dz: None,
128            wavelength: None,
129            field: None,
130        }
131    }
132}
133
134/// RMS の結果
135#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
136pub struct RmsOut {
137    pub unit: String,
138    pub wfe_unit: String,
139    pub vs: Vs,
140    pub reference: Reference,
141    pub rms: Vec<RmsRow>,
142    pub warnings: Vec<String>,
143}
144
145pub(super) struct Rms;
146
147impl Analysis for Rms {
148    type Params = RmsParams;
149    type Output = RmsOut;
150    fn meta(&self) -> Meta {
151        Meta {
152            name: "rms",
153            about: "RMS (spot radius, x, y, wavefront, approximate Strehl ratio) against field, focus or wavelength",
154            help: "",
155        }
156    }
157    fn run(&self, cx: &Cx<'_>, p: &RmsParams) -> Result<RmsOut> {
158        let s = cx.system;
159        let w = wave(s, p.wave)?;
160        let o = RmsOpts {
161            rings: p.rings,
162            field_wave: p.field_wave,
163            reference: match p.reference {
164                Reference::Centroid => RmsRef::Centroid,
165                Reference::Chief => RmsRef::Chief,
166            },
167        };
168        let (mut v, mut warn) = (Vec::new(), Vec::new());
169        match p.vs {
170            Vs::Field => {
171                if p.field.is_some() {
172                    return Err(Error::Invalid("field is not used with vs field".into()));
173                }
174                let ax = p.axis.core();
175                let r = sweep::rms_vs_field(s, ax, &sweep::steps01(p.points), Waves::all_or(w), o);
176                for (x, q) in r.x.iter().zip(&r.rms) {
177                    let mut e = RmsRow::of(q);
178                    e.h = Some(*x);
179                    e.field_value = Some(ax.value(s, *x));
180                    v.push(e);
181                }
182                warn = r.warnings;
183            }
184            Vs::Focus => {
185                for i in fields(s, p.field)? {
186                    let r = sweep::rms_vs_focus(
187                        s,
188                        FieldSel::Index(i),
189                        &sweep::steps_sym(p.range, p.points),
190                        Waves::all_or(w),
191                        o,
192                    );
193                    for (x, q) in r.x.iter().zip(&r.rms) {
194                        let mut e = RmsRow::of(q);
195                        e.dz = Some(*x);
196                        e.field = Some(i + 1);
197                        v.push(e);
198                    }
199                    warn.extend(
200                        r.warnings
201                            .iter()
202                            .map(|x| format!("field {}: {e}", i + 1, e = x)),
203                    );
204                }
205            }
206            Vs::Wavelength => {
207                if p.wave.is_some() {
208                    return Err(Error::Invalid("wave is not used with vs wavelength".into()));
209                }
210                let lams = sweep::wavelength_steps(s, p.points);
211                for i in fields(s, p.field)? {
212                    let r = sweep::rms_vs_wavelength(s, FieldSel::Index(i), &lams, o);
213                    for (x, q) in r.x.iter().zip(&r.rms) {
214                        let mut e = RmsRow::of(q);
215                        e.wavelength = Some(*x);
216                        e.field = Some(i + 1);
217                        v.push(e);
218                    }
219                    warn.extend(
220                        r.warnings
221                            .iter()
222                            .map(|x| format!("field {}: {e}", i + 1, e = x)),
223                    );
224                }
225            }
226        }
227        Ok(RmsOut {
228            unit: spot_unit(s),
229            wfe_unit: "waves".into(),
230            vs: p.vs,
231            reference: p.reference,
232            rms: v,
233            warnings: warn,
234        })
235    }
236}
237
238// ----------------------------------------------------------------------------------------- psf
239
240/// PSF の像の面
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
242#[serde(rename_all = "lowercase")]
243pub enum Plane {
244    /// 像面の上(像面の局所座標)
245    #[default]
246    Image,
247    /// 主光線に垂直な面(OpticStudio の FFT PSF と同じ)
248    Chief,
249}
250
251/// PSF の設定
252#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
253#[serde(default, deny_unknown_fields)]
254pub(super) struct PsfParams {
255    /// Field number (from 1; all fields if omitted)
256    pub field: Option<usize>,
257    /// Wavelength number (from 1; polychromatic if omitted)
258    pub wave: Option<usize>,
259    /// Huygens PSF (on the image surface; for tilted image surfaces and strongly aberrated systems; slower than FFT)
260    pub huygens: bool,
261    /// Pupil grid side (automatic if omitted: large enough that neighboring samples differ by π/2 or less in phase)
262    pub pupil: Option<usize>,
263    /// Image grid side (up to twice the pupil grid at the default spacing)
264    #[schemars(extend("x-min" = 1))]
265    pub image: usize,
266    /// Image grid spacing [lens units; angle units in afocal image space] (1 / (2 × cutoff) if omitted)
267    pub pixel: Option<f64>,
268    /// Huygens PSF only: sum every pupil sample exactly at every image point (several times slower). By default each pupil sample's phase and amplitude are approximated by a quadratic over small blocks of the image grid; the block size is chosen so that the phase differs from the exact value by at most 1e-6 rad, checked on the corner and center blocks of the grid (the intensity typically agrees with the exact sum to 1e-7 of the unaberrated peak)
269    pub exact: bool,
270    /// Huygens PSF only: where to compute the Huygens sum: auto (default; a GPU if one is present, otherwise the CPU), cpu, or gpu (use the GPU path even on a software adapter; falls back to the CPU with a warning). The GPU sums in single precision (the intensity agrees with the exact sum to about 5e-7 of the unaberrated peak). Not used with exact
271    pub device: HuygensDevice,
272    /// Plane of the FFT PSF grid (image: the image surface; chief: perpendicular to the chief ray, as in OpticStudio's FFT PSF)
273    pub plane: Plane,
274    /// Include coating transmission and Fresnel losses in the pupil amplitude (with the system's input polarization, unpolarized by default, and coatings; like OpticStudio's Use Polarization). The system's pupil apodization is always included
275    pub polarization: bool,
276}
277
278impl Default for PsfParams {
279    fn default() -> Self {
280        PsfParams {
281            field: None,
282            wave: None,
283            huygens: false,
284            pupil: None,
285            image: 128,
286            pixel: None,
287            exact: false,
288            device: HuygensDevice::Auto,
289            plane: Plane::Image,
290            polarization: false,
291        }
292    }
293}
294
295/// PSF の格子の 1 点
296#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
297pub struct PsfPoint {
298    pub field: usize,
299    #[serde(deserialize_with = "crate::nan::f")]
300    pub x: f64,
301    #[serde(deserialize_with = "crate::nan::f")]
302    pub y: f64,
303    /// 強度(収差のない同じ瞳の中心の値を 1)
304    #[serde(deserialize_with = "crate::nan::f")]
305    pub i: f64,
306}
307
308/// PSF の格子の向き
309#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
310pub struct PsfAxes {
311    pub field: usize,
312    /// 主波長の主光線の像点(像面の局所座標)
313    #[serde(deserialize_with = "crate::nan::a2")]
314    pub center: [f64; 2],
315    /// 格子の面(image か chief)
316    pub plane: Plane,
317    /// 格子の x の向き(像空間の単位ベクトル)
318    #[serde(deserialize_with = "crate::nan::a3")]
319    pub e1: [f64; 3],
320    /// 格子の y の向き
321    #[serde(deserialize_with = "crate::nan::a3")]
322    pub e2: [f64; 3],
323}
324
325/// PSF の標本化
326#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
327pub struct PsfSampling {
328    pub field: usize,
329    /// 使った瞳の格子の一辺
330    pub pupil: usize,
331    /// 瞳の隣り合う標本の位相差の最大 [rad]
332    #[serde(deserialize_with = "crate::nan::f")]
333    pub phase_step: f64,
334    /// 像の格子に入った光量の割合
335    #[serde(deserialize_with = "crate::nan::f")]
336    pub enclosed: f64,
337    /// 格子の最大値(ストレール比の目安)
338    #[serde(deserialize_with = "crate::nan::f")]
339    pub peak: f64,
340    /// 像の格子の間隔(x, y)
341    #[serde(deserialize_with = "crate::nan::a2")]
342    pub pixel: [f64; 2],
343}
344
345/// PSF の結果
346#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
347pub struct PsfOut {
348    pub unit: String,
349    /// fft か huygens
350    pub method: String,
351    pub psf: Vec<PsfPoint>,
352    pub axes: Vec<PsfAxes>,
353    pub sampling: Vec<PsfSampling>,
354    pub warnings: Vec<String>,
355    /// huygens の和を計算した装置: cpu か「gpu: アダプタの名前」(視野で違えば , で並べる)
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub device: Option<String>,
358}
359
360pub(super) struct Psf;
361
362impl Analysis for Psf {
363    type Params = PsfParams;
364    type Output = PsfOut;
365    fn meta(&self) -> Meta {
366        Meta {
367            name: "psf",
368            about: "Diffraction PSF (DFT of the pupil function). Intensity is 1 at the center of the same pupil without aberrations. Polychromatic if wave is omitted",
369            help: "Diffraction PSF (DFT of the pupil function). Intensity is 1 at the center of the same pupil without aberrations. Polychromatic if wave is omitted. huygens gives the Huygens PSF (secondary waves from each point of the reference sphere summed on the image surface). x and y are local image surface coordinates relative to the chief ray; with plane chief, coordinates in the plane perpendicular to the chief ray (along e1 and e2, as in OpticStudio's FFT PSF)",
370        }
371    }
372    fn run(&self, cx: &Cx<'_>, p: &PsfParams) -> Result<PsfOut> {
373        let s = cx.system;
374        let w = wave(s, p.wave)?;
375        let (mut v, mut axes, mut warn, mut samp) =
376            (Vec::new(), Vec::new(), Vec::new(), Vec::new());
377        let mut dev: Vec<String> = Vec::new();
378        if p.exact && !p.huygens {
379            lensbench_core::invalid!("setting exact is for the Huygens PSF (give huygens too)");
380        }
381        if p.device != HuygensDevice::Auto && !p.huygens {
382            lensbench_core::invalid!("setting device is for the Huygens PSF (give huygens too)");
383        }
384        let mut rows = Vec::new();
385        for i in fields(s, p.field)? {
386            let pa = pol_amp(s, i, w, p.polarization)?;
387            let pa = pa.as_ref().map(|a| a as &dyn PupilAmp);
388            let r = if p.huygens {
389                let o = HuygensOpts {
390                    pupil: p.pupil,
391                    image: p.image,
392                    pixel: p.pixel,
393                    exact: p.exact,
394                    device: p.device,
395                };
396                huygens::huygens_psf_with(s, FieldSel::Index(i), Waves::all_or(w), o, pa)
397            } else {
398                let o = PsfOpts {
399                    pupil: p.pupil,
400                    image: p.image,
401                    pixel: p.pixel,
402                    plane: match p.plane {
403                        Plane::Image => PsfPlane::Image,
404                        Plane::Chief => PsfPlane::ChiefPerp,
405                    },
406                };
407                psf::psf_with(s, FieldSel::Index(i), Waves::all_or(w), o, pa)
408            };
409            rows.push((i, r.map(|r| (i, r))));
410        }
411        for (i, r) in skip_vignetted(rows, &mut warn)? {
412            crate::huygens::push_device(&mut dev, r.device.as_deref());
413            axes.push(PsfAxes {
414                field: i + 1,
415                center: [r.center.0, r.center.1],
416                plane: match r.plane {
417                    PsfPlane::Image => Plane::Image,
418                    PsfPlane::ChiefPerp => Plane::Chief,
419                },
420                e1: r.axes[0],
421                e2: r.axes[1],
422            });
423            for (iy, row) in r.i.rows().enumerate() {
424                for (ix, val) in row.iter().enumerate() {
425                    v.push(PsfPoint {
426                        field: i + 1,
427                        x: r.i.x()[ix],
428                        y: r.i.y()[iy],
429                        i: *val,
430                    });
431                }
432            }
433            warn.extend(
434                r.warnings
435                    .iter()
436                    .map(|m| format!("field {}: {e}", i + 1, e = m)),
437            );
438            samp.push(PsfSampling {
439                field: i + 1,
440                pupil: r.pupil,
441                phase_step: r.phase_step,
442                enclosed: r.enclosed,
443                peak: r.peak,
444                pixel: [r.pixel.0, r.pixel.1],
445            });
446        }
447        warn.extend(coat_notes(s, p.polarization)?);
448        Ok(PsfOut {
449            unit: spot_unit(s),
450            method: if p.huygens { "huygens" } else { "fft" }.into(),
451            psf: v,
452            axes,
453            sampling: samp,
454            warnings: warn,
455            device: (!dev.is_empty()).then(|| dev.join(", ")),
456        })
457    }
458}