1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
22#[serde(rename_all = "lowercase")]
23pub(super) enum MtfHow {
24 #[default]
26 Auto,
27 Interp,
29 Direct,
31 Fft,
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
37#[serde(default, deny_unknown_fields)]
38pub(super) struct MtfParams {
39 pub field: Option<usize>,
41 pub wave: Option<usize>,
43 pub freqs: Option<Vec<f64>>,
45 pub max_freq: Option<f64>,
47 #[schemars(extend("x-min" = 1))]
49 pub freq_steps: usize,
50 pub n: Option<usize>,
52 pub method: MtfHow,
54 pub each_wave: bool,
56 pub polarization: bool,
58 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
81pub struct MtfOut {
82 pub unit: String,
83 #[serde(skip_serializing_if = "Option::is_none")]
85 pub method: Option<String>,
86 pub mtf: Vec<MtfRow>,
87 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 pub warnings: Vec<String>,
90 #[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 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
178#[serde(default, deny_unknown_fields)]
179pub(super) struct MtfFocusParams {
180 pub field: Option<usize>,
182 pub wave: Option<usize>,
184 pub freqs: Vec<f64>,
186 pub range: f64,
188 #[schemars(extend("x-min" = 1))]
190 pub points: usize,
191 pub n: Option<usize>,
193 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#[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#[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
293#[serde(default, deny_unknown_fields)]
294pub(super) struct MtfFieldParams {
295 pub wave: Option<usize>,
297 pub freqs: Vec<f64>,
299 #[schemars(extend("x-min" = 1))]
301 pub points: usize,
302 pub axis: Axis,
304 pub n: Option<usize>,
306 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
325pub struct FieldRow {
326 #[serde(deserialize_with = "crate::nan::f")]
327 pub freq: f64,
328 #[serde(deserialize_with = "crate::nan::f")]
330 pub h: f64,
331 #[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#[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
395#[serde(default, deny_unknown_fields)]
396pub(super) struct GeoMtfParams {
397 pub field: Option<usize>,
399 pub wave: Option<usize>,
401 pub freqs: Option<Vec<f64>>,
403 pub max_freq: Option<f64>,
405 #[schemars(extend("x-min" = 1))]
407 pub freq_steps: usize,
408 #[schemars(extend("x-min" = 4))]
410 pub n: usize,
411 pub diff_limit: bool,
413 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
434pub struct GeoMtfOut {
435 pub unit: String,
436 pub geometric_mtf: Vec<MtfRow>,
437 #[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
486#[serde(default, deny_unknown_fields)]
487pub(super) struct HuygensMtfParams {
488 pub field: Option<usize>,
490 pub wave: Option<usize>,
492 pub freqs: Option<Vec<f64>>,
494 pub max_freq: Option<f64>,
496 #[schemars(extend("x-min" = 1))]
498 pub freq_steps: usize,
499 pub pupil: Option<usize>,
501 #[schemars(extend("x-min" = 1))]
503 pub image: usize,
504 pub pixel: Option<f64>,
506 pub exact: bool,
508 pub device: HuygensDevice,
510 pub polarization: bool,
512 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}