Skip to main content

lensbench_analysis/defs/
mtfs.rs

1//! 回折 MTF・スルーフォーカス・フィールド MTF・幾何 MTF・Huygens MTF
2
3use crate::analysis::{self, MtfMethod};
4use crate::huygens::{self, HuygensDevice, HuygensOpts};
5use crate::{psf, sweep};
6use lensbench_core::Waves;
7use lensbench_core::{Error, FieldSel, Result};
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use super::{
12    coat_notes, fields, freq_unit, freqs_for, pol_amp, skip_vignetted, wave, Axis, MtfDirs, MtfRow,
13    WaveMtf,
14};
15use crate::registry::{Analysis, Cx, Meta};
16use lensbench_core::pupil::PupilAmp;
17
18// ----------------------------------------------------------------------------------------- mtf
19
20/// 回折 MTF の求め方
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
22#[serde(rename_all = "lowercase")]
23pub(super) enum MtfHow {
24    /// 瞳の格子を 1 度追跡して補間の求積。求積点が 1024 を超え周波数が 8 個以上なら FFT(n を省いたとき)
25    #[default]
26    Auto,
27    /// 求積点の数が多い系でも FFT に切り替えず、補間の求積で求める
28    Interp,
29    /// 求積点の OPD をすべて直接追跡する(遅い、確かめ用)
30    Direct,
31    /// 瞳関数の自己相関を FFT で全周波数まとめて求める(既定との差は 1e-4 程度)
32    Fft,
33}
34
35/// 回折 MTF の設定
36#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
37#[serde(default, deny_unknown_fields)]
38pub(super) struct MtfParams {
39    /// Field number (from 1; all fields if omitted)
40    pub field: Option<usize>,
41    /// Wavelength number (from 1; polychromatic if omitted)
42    pub wave: Option<usize>,
43    /// Frequencies [cycles/mm; cycles per angle unit in afocal image space]. If omitted, freq_steps equal steps from 0 to the limit (max_freq, 0.95 times the cutoff by default)
44    pub freqs: Option<Vec<f64>>,
45    /// Upper limit when frequencies are omitted [cycles/mm; cycles per angle unit in afocal image space]. 0.95 times the cutoff if omitted
46    pub max_freq: Option<f64>,
47    /// Number of steps when frequencies are omitted (equal steps from 0 to the limit; steps + 1 points)
48    #[schemars(extend("x-min" = 1))]
49    pub freq_steps: usize,
50    /// Approximate number of quadrature points for the pupil overlap (about n² points). Chosen automatically from the OPD slope if omitted
51    pub n: Option<usize>,
52    /// Method: auto, interp, direct or fft
53    pub method: MtfHow,
54    /// Also output the MTF of each wavelength besides the polychromatic one ("waves"; faster than separate runs because the per-wavelength computation is reused). Can't be used with wave
55    pub each_wave: bool,
56    /// 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
57    pub polarization: bool,
58    /// Tangential and sagittal directions: field (default; tangential along the field direction, the physical tangential plane) or pupil (tangential along the pupil y and sagittal along x, as in OpticStudio's FFT MTF). They differ only for fields with an x component
59    pub axes: MtfDirs,
60}
61
62impl Default for MtfParams {
63    fn default() -> Self {
64        MtfParams {
65            field: None,
66            wave: None,
67            freqs: None,
68            max_freq: None,
69            freq_steps: 20,
70            n: None,
71            method: MtfHow::Auto,
72            each_wave: false,
73            polarization: false,
74            axes: MtfDirs::Field,
75        }
76    }
77}
78
79/// MTF の結果(mtf・huygens-mtf)
80#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
81pub struct MtfOut {
82    pub unit: String,
83    /// 求め方(huygens-mtf は huygens)
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub method: Option<String>,
86    pub mtf: Vec<MtfRow>,
87    /// 注意(polarization のときの系の膜の注意など)
88    #[serde(default, skip_serializing_if = "Vec::is_empty")]
89    pub warnings: Vec<String>,
90    /// huygens-mtf の和を計算した装置: cpu か「gpu: アダプタの名前」(視野で違えば , で並べる)
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub device: Option<String>,
93}
94
95pub(super) struct Mtf;
96
97impl Analysis for Mtf {
98    type Params = MtfParams;
99    type Output = MtfOut;
100    fn meta(&self) -> Meta {
101        Meta {
102            name: "mtf",
103            about: "Diffraction MTF (modulation, tangential and sagittal). Polychromatic if wave is omitted",
104            help: "",
105        }
106    }
107    fn run(&self, cx: &Cx<'_>, p: &MtfParams) -> Result<MtfOut> {
108        let s = cx.system;
109        let w = wave(s, p.wave)?;
110        if p.each_wave && w.is_some() {
111            return Err(Error::Invalid("each_wave can't be used with wave".into()));
112        }
113        let method = match p.method {
114            MtfHow::Auto => MtfMethod::Auto,
115            MtfHow::Interp => MtfMethod::Interp,
116            MtfHow::Direct => MtfMethod::Direct,
117            MtfHow::Fft => MtfMethod::Fft,
118        };
119        // 視野ごとに独立なので並列に(視野の中も波長・周波数ごとに並列。値はスレッド数によらず同じ)
120        let fl = fields(s, p.field)?;
121        let mtf_row = |i: usize| -> Result<MtfRow> {
122            let fs = freqs_for(s, i, w, &p.freqs, p.max_freq, p.freq_steps, p.axes)?;
123            let f = FieldSel::Index(i);
124            let pa = pol_amp(s, i, w, p.polarization)?;
125            let pa = pa.as_ref().map(|a| a as &dyn PupilAmp);
126            let row = if p.each_wave {
127                let mw = analysis::mtf_waves_amp(s, f, p.n, &fs, method, pa, p.axes.core())?;
128                let mut r = MtfRow::of(i, mw.poly);
129                r.waves = Some(
130                    mw.waves
131                        .into_iter()
132                        .enumerate()
133                        .map(|(k, m)| WaveMtf {
134                            wave: k + 1,
135                            tangential: m.tan,
136                            sagittal: m.sag,
137                        })
138                        .collect(),
139                );
140                r
141            } else {
142                MtfRow::of(
143                    i,
144                    analysis::mtf_amp(
145                        s,
146                        f,
147                        Waves::all_or(w),
148                        p.n,
149                        &fs,
150                        method,
151                        None,
152                        pa,
153                        p.axes.core(),
154                    )?,
155                )
156            };
157            Ok(row)
158        };
159        let rows = lensbench_core::par::try_map(&fl, |&i| -> Result<(usize, Result<MtfRow>)> {
160            Ok((i, mtf_row(i)))
161        })?;
162        let mut warnings = coat_notes(s, p.polarization)?;
163        let v = skip_vignetted(rows, &mut warnings)?;
164        Ok(MtfOut {
165            unit: freq_unit(s),
166            method: None,
167            mtf: v,
168            warnings,
169            device: None,
170        })
171    }
172}
173
174// ----------------------------------------------------------------------------------- mtf-focus
175
176/// スルーフォーカス MTF の設定
177#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
178#[serde(default, deny_unknown_fields)]
179pub(super) struct MtfFocusParams {
180    /// Field number (from 1; all fields if omitted)
181    pub field: Option<usize>,
182    /// Wavelength number (from 1; polychromatic if omitted)
183    pub wave: Option<usize>,
184    /// Frequency [cycles/mm; cycles per angle unit in afocal image space] (required)
185    pub freqs: Vec<f64>,
186    /// Image shift range ±range [lens units]
187    pub range: f64,
188    /// Number of shift points (from −range to +range)
189    #[schemars(extend("x-min" = 1))]
190    pub points: usize,
191    /// Approximate number of quadrature points for the pupil overlap (as in mtf; automatic if omitted)
192    pub n: Option<usize>,
193    /// Tangential and sagittal directions: field (default; tangential along the field direction, the physical tangential plane) or pupil (tangential along the pupil y and sagittal along x, as in OpticStudio's FFT MTF). They differ only for fields with an x component
194    pub axes: MtfDirs,
195}
196
197impl Default for MtfFocusParams {
198    fn default() -> Self {
199        MtfFocusParams {
200            field: None,
201            wave: None,
202            freqs: Vec::new(),
203            range: 0.1,
204            points: 11,
205            n: None,
206            axes: MtfDirs::Field,
207        }
208    }
209}
210
211/// スルーフォーカス MTF の 1 点
212#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
213pub struct FocusRow {
214    pub field: usize,
215    #[serde(deserialize_with = "crate::nan::f")]
216    pub freq: f64,
217    #[serde(deserialize_with = "crate::nan::f")]
218    pub dz: f64,
219    #[serde(deserialize_with = "crate::nan::f")]
220    pub tangential: f64,
221    #[serde(deserialize_with = "crate::nan::f")]
222    pub sagittal: f64,
223}
224
225/// スルーフォーカス MTF の結果
226#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
227pub struct MtfFocusOut {
228    pub unit: String,
229    pub through_focus: Vec<FocusRow>,
230    pub warnings: Vec<String>,
231}
232
233pub(super) struct MtfFocus;
234
235impl Analysis for MtfFocus {
236    type Params = MtfFocusParams;
237    type Output = MtfFocusOut;
238    fn meta(&self) -> Meta {
239        Meta {
240            name: "mtf-focus",
241            about: "Through-focus MTF (diffraction MTF with the image shifted over ±range in points steps). Polychromatic if wave is omitted",
242            help: "",
243        }
244    }
245    fn run(&self, cx: &Cx<'_>, p: &MtfFocusParams) -> Result<MtfFocusOut> {
246        if p.freqs.is_empty() {
247            return Err(Error::Invalid("freqs (frequencies) are needed".into()));
248        }
249        let s = cx.system;
250        let w = wave(s, p.wave)?;
251        Waves::all_or(w).weighted(s)?;
252        let dz = sweep::steps_sym(p.range, p.points);
253        let (mut v, mut warn) = (Vec::new(), Vec::new());
254        for i in fields(s, p.field)? {
255            let m = sweep::through_focus_mtf(
256                s,
257                FieldSel::Index(i),
258                Waves::all_or(w),
259                p.n,
260                &p.freqs,
261                &dz,
262                p.axes.core(),
263            );
264            for (k, &f) in p.freqs.iter().enumerate() {
265                for (j, &z) in dz.iter().enumerate() {
266                    v.push(FocusRow {
267                        field: i + 1,
268                        freq: f,
269                        dz: z,
270                        tangential: m.tan[k][j],
271                        sagittal: m.sag[k][j],
272                    });
273                }
274            }
275            warn.extend(
276                m.warnings
277                    .iter()
278                    .map(|x| format!("field {}: {e}", i + 1, e = x)),
279            );
280        }
281        Ok(MtfFocusOut {
282            unit: freq_unit(s),
283            through_focus: v,
284            warnings: warn,
285        })
286    }
287}
288
289// ----------------------------------------------------------------------------------- mtf-field
290
291/// フィールド MTF の設定
292#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
293#[serde(default, deny_unknown_fields)]
294pub(super) struct MtfFieldParams {
295    /// Wavelength number (from 1; polychromatic if omitted)
296    pub wave: Option<usize>,
297    /// Frequency [cycles/mm; cycles per angle unit in afocal image space] (required)
298    pub freqs: Vec<f64>,
299    /// Number of field points (normalized field 0 to 1)
300    #[schemars(extend("x-min" = 1))]
301    pub points: usize,
302    /// Field direction (y or x)
303    pub axis: Axis,
304    /// Approximate number of quadrature points for the pupil overlap (as in mtf; automatic if omitted)
305    pub n: Option<usize>,
306    /// Tangential and sagittal directions: field (default; tangential along the field direction, the physical tangential plane) or pupil (tangential along the pupil y and sagittal along x, as in OpticStudio's FFT MTF). They differ only for fields with an x component
307    pub axes: MtfDirs,
308}
309
310impl Default for MtfFieldParams {
311    fn default() -> Self {
312        MtfFieldParams {
313            wave: None,
314            freqs: Vec::new(),
315            points: 11,
316            axis: Axis::Y,
317            n: None,
318            axes: MtfDirs::Field,
319        }
320    }
321}
322
323/// フィールド MTF の 1 点
324#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
325pub struct FieldRow {
326    #[serde(deserialize_with = "crate::nan::f")]
327    pub freq: f64,
328    /// 正規化視野
329    #[serde(deserialize_with = "crate::nan::f")]
330    pub h: f64,
331    /// 視野の値(系の視野の単位)
332    #[serde(deserialize_with = "crate::nan::f")]
333    pub field_value: f64,
334    #[serde(deserialize_with = "crate::nan::f")]
335    pub tangential: f64,
336    #[serde(deserialize_with = "crate::nan::f")]
337    pub sagittal: f64,
338}
339
340/// フィールド MTF の結果
341#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
342pub struct MtfFieldOut {
343    pub unit: String,
344    pub field_mtf: Vec<FieldRow>,
345    pub warnings: Vec<String>,
346}
347
348pub(super) struct MtfField;
349
350impl Analysis for MtfField {
351    type Params = MtfFieldParams;
352    type Output = MtfFieldOut;
353    fn meta(&self) -> Meta {
354        Meta {
355            name: "mtf-field",
356            about:
357                "Field MTF (diffraction MTF at points steps of the normalized field 0 to 1). Polychromatic if wave is omitted",
358            help: "",
359        }
360    }
361    fn run(&self, cx: &Cx<'_>, p: &MtfFieldParams) -> Result<MtfFieldOut> {
362        if p.freqs.is_empty() {
363            return Err(Error::Invalid("freqs (frequencies) are needed".into()));
364        }
365        let s = cx.system;
366        let w = wave(s, p.wave)?;
367        let ax = p.axis.core();
368        let h = sweep::steps01(p.points);
369        let ws = Waves::all_or(w).weighted(s)?;
370        let m = sweep::field_mtf(s, ax, &h, ws, p.n, &p.freqs, p.axes.core());
371        let mut v = Vec::new();
372        for (k, &f) in p.freqs.iter().enumerate() {
373            for (j, &hh) in h.iter().enumerate() {
374                v.push(FieldRow {
375                    freq: f,
376                    h: hh,
377                    field_value: ax.value(s, hh),
378                    tangential: m.tan[k][j],
379                    sagittal: m.sag[k][j],
380                });
381            }
382        }
383        Ok(MtfFieldOut {
384            unit: freq_unit(s),
385            field_mtf: v,
386            warnings: m.warnings,
387        })
388    }
389}
390
391// ------------------------------------------------------------------------------------- geo-mtf
392
393/// 幾何 MTF の設定
394#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
395#[serde(default, deny_unknown_fields)]
396pub(super) struct GeoMtfParams {
397    /// Field number (from 1; all fields if omitted)
398    pub field: Option<usize>,
399    /// Wavelength number (from 1; polychromatic if omitted)
400    pub wave: Option<usize>,
401    /// Frequencies [cycles/mm; cycles per angle unit in afocal image space]. If omitted, freq_steps equal steps from 0 to the limit (max_freq, 0.95 times the cutoff by default)
402    pub freqs: Option<Vec<f64>>,
403    /// Upper limit when frequencies are omitted. 0.95 times the cutoff if omitted
404    pub max_freq: Option<f64>,
405    /// Number of steps when frequencies are omitted (equal steps from 0 to the limit; steps + 1 points)
406    #[schemars(extend("x-min" = 1))]
407    pub freq_steps: usize,
408    /// Approximate number of pupil quadrature points (about n² points)
409    #[schemars(extend("x-min" = 4))]
410    pub n: usize,
411    /// Multiply by the diffraction-limited MTF
412    pub diff_limit: bool,
413    /// Tangential and sagittal directions: field (default; tangential along the field direction, the physical tangential plane) or pupil (tangential along the pupil y and sagittal along x, as in OpticStudio's FFT MTF). They differ only for fields with an x component
414    pub axes: MtfDirs,
415}
416
417impl Default for GeoMtfParams {
418    fn default() -> Self {
419        GeoMtfParams {
420            field: None,
421            wave: None,
422            freqs: None,
423            max_freq: None,
424            freq_steps: 20,
425            n: 128,
426            diff_limit: false,
427            axes: MtfDirs::Field,
428        }
429    }
430}
431
432/// 幾何 MTF の結果
433#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
434pub struct GeoMtfOut {
435    pub unit: String,
436    pub geometric_mtf: Vec<MtfRow>,
437    /// 注意(全部けられて飛ばした視野など)
438    #[serde(default, skip_serializing_if = "Vec::is_empty")]
439    pub warnings: Vec<String>,
440}
441
442pub(super) struct GeoMtf;
443
444impl Analysis for GeoMtf {
445    type Params = GeoMtfParams;
446    type Output = GeoMtfOut;
447    fn meta(&self) -> Meta {
448        Meta {
449            name: "geo-mtf",
450            about: "Geometric MTF (from the distribution of ray positions). Polychromatic if wave is omitted",
451            help: "",
452        }
453    }
454    fn run(&self, cx: &Cx<'_>, p: &GeoMtfParams) -> Result<GeoMtfOut> {
455        let s = cx.system;
456        let w = wave(s, p.wave)?;
457        let mut rows = Vec::new();
458        for i in fields(s, p.field)? {
459            let r = freqs_for(s, i, w, &p.freqs, p.max_freq, p.freq_steps, p.axes).and_then(|fs| {
460                psf::geometric_mtf_axes(
461                    s,
462                    FieldSel::Index(i),
463                    Waves::all_or(w),
464                    p.n,
465                    &fs,
466                    p.diff_limit,
467                    p.axes.core(),
468                )
469            });
470            rows.push((i, r.map(|m| MtfRow::of(i, m))));
471        }
472        let mut warnings = Vec::new();
473        let v = skip_vignetted(rows, &mut warnings)?;
474        Ok(GeoMtfOut {
475            unit: freq_unit(s),
476            geometric_mtf: v,
477            warnings,
478        })
479    }
480}
481
482// --------------------------------------------------------------------------------- huygens-mtf
483
484/// Huygens MTF の設定
485#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
486#[serde(default, deny_unknown_fields)]
487pub(super) struct HuygensMtfParams {
488    /// Field number (from 1; all fields if omitted)
489    pub field: Option<usize>,
490    /// Wavelength number (from 1; polychromatic if omitted)
491    pub wave: Option<usize>,
492    /// Frequencies [cycles/mm]. If omitted, freq_steps equal steps from 0 to the limit (max_freq, 0.95 times the cutoff by default)
493    pub freqs: Option<Vec<f64>>,
494    /// Upper limit when frequencies are omitted [cycles/mm]. 0.95 times the cutoff if omitted
495    pub max_freq: Option<f64>,
496    /// Number of steps when frequencies are omitted (equal steps from 0 to the limit; steps + 1 points)
497    #[schemars(extend("x-min" = 1))]
498    pub freq_steps: usize,
499    /// Pupil grid side (automatic if omitted: large enough that neighboring samples differ by π/2 or less in phase)
500    pub pupil: Option<usize>,
501    /// Image grid side (up to twice the pupil grid at the default spacing). If it doesn't cover the PSF, the low-frequency MTF drops
502    #[schemars(extend("x-min" = 1))]
503    pub image: usize,
504    /// Image grid spacing [mm] (1 / (2 × cutoff) if omitted)
505    pub pixel: Option<f64>,
506    /// 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)
507    pub exact: bool,
508    /// 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
509    pub device: HuygensDevice,
510    /// 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
511    pub polarization: bool,
512    /// Tangential and sagittal directions: field (default; tangential along the field direction, the physical tangential plane) or pupil (tangential along the pupil y and sagittal along x, as in OpticStudio's FFT MTF). They differ only for fields with an x component
513    pub axes: MtfDirs,
514}
515
516impl Default for HuygensMtfParams {
517    fn default() -> Self {
518        HuygensMtfParams {
519            field: None,
520            wave: None,
521            freqs: None,
522            max_freq: None,
523            freq_steps: 20,
524            pupil: None,
525            image: 128,
526            pixel: None,
527            exact: false,
528            device: HuygensDevice::Auto,
529            polarization: false,
530            axes: MtfDirs::Field,
531        }
532    }
533}
534
535pub(super) struct HuygensMtf;
536
537impl Analysis for HuygensMtf {
538    type Params = HuygensMtfParams;
539    type Output = MtfOut;
540    fn meta(&self) -> Meta {
541        Meta {
542            name: "huygens-mtf",
543            about: "Huygens MTF (Fourier transform of the Huygens PSF, frequencies on the image surface). Polychromatic if wave is omitted. The output has the same form as mtf",
544            help: "",
545        }
546    }
547    fn run(&self, cx: &Cx<'_>, p: &HuygensMtfParams) -> Result<MtfOut> {
548        let s = cx.system;
549        let w = wave(s, p.wave)?;
550        let o = HuygensOpts {
551            pupil: p.pupil,
552            image: p.image,
553            pixel: p.pixel,
554            exact: p.exact,
555            device: p.device,
556        };
557        let (mut rows, mut dev) = (Vec::new(), Vec::new());
558        for i in fields(s, p.field)? {
559            let r = (|| {
560                let fs = freqs_for(s, i, w, &p.freqs, p.max_freq, p.freq_steps, p.axes)?;
561                let pa = pol_amp(s, i, w, p.polarization)?;
562                let pa = pa.as_ref().map(|a| a as &dyn PupilAmp);
563                let f = FieldSel::Index(i);
564                let (m, d) =
565                    huygens::huygens_mtf_device(s, f, Waves::all_or(w), o, &fs, pa, p.axes.core())?;
566                huygens::push_device(&mut dev, Some(&d));
567                Ok(MtfRow::of(i, m))
568            })();
569            rows.push((i, r));
570        }
571        let mut warnings = coat_notes(s, p.polarization)?;
572        let v = skip_vignetted(rows, &mut warnings)?;
573        Ok(MtfOut {
574            unit: freq_unit(s),
575            method: Some("huygens".into()),
576            mtf: v,
577            warnings,
578            device: Some(dev.join(", ")),
579        })
580    }
581}