1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
19#[serde(rename_all = "lowercase")]
20pub enum Vs {
21 #[default]
23 Field,
24 Focus,
26 Wavelength,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
32#[serde(rename_all = "lowercase")]
33pub enum Reference {
34 #[default]
36 Centroid,
37 Chief,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
43#[serde(default, deny_unknown_fields)]
44pub(super) struct RmsParams {
45 pub field: Option<usize>,
47 pub wave: Option<usize>,
49 pub vs: Vs,
51 #[schemars(extend("x-min" = 1))]
53 pub points: usize,
54 pub range: f64,
56 pub axis: Axis,
58 pub reference: Reference,
60 #[schemars(extend("x-min" = 1))]
62 pub rings: usize,
63 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
86pub struct RmsRow {
87 #[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 #[serde(deserialize_with = "crate::nan::f")]
96 pub wfe: f64,
97 #[serde(deserialize_with = "crate::nan::f")]
99 pub strehl: f64,
100 #[serde(skip_serializing_if = "Option::is_none")]
102 pub h: Option<f64>,
103 #[serde(skip_serializing_if = "Option::is_none")]
105 pub field_value: Option<f64>,
106 #[serde(skip_serializing_if = "Option::is_none")]
108 pub dz: Option<f64>,
109 #[serde(skip_serializing_if = "Option::is_none")]
111 pub wavelength: Option<f64>,
112 #[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
242#[serde(rename_all = "lowercase")]
243pub enum Plane {
244 #[default]
246 Image,
247 Chief,
249}
250
251#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
253#[serde(default, deny_unknown_fields)]
254pub(super) struct PsfParams {
255 pub field: Option<usize>,
257 pub wave: Option<usize>,
259 pub huygens: bool,
261 pub pupil: Option<usize>,
263 #[schemars(extend("x-min" = 1))]
265 pub image: usize,
266 pub pixel: Option<f64>,
268 pub exact: bool,
270 pub device: HuygensDevice,
272 pub plane: Plane,
274 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#[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 #[serde(deserialize_with = "crate::nan::f")]
305 pub i: f64,
306}
307
308#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
310pub struct PsfAxes {
311 pub field: usize,
312 #[serde(deserialize_with = "crate::nan::a2")]
314 pub center: [f64; 2],
315 pub plane: Plane,
317 #[serde(deserialize_with = "crate::nan::a3")]
319 pub e1: [f64; 3],
320 #[serde(deserialize_with = "crate::nan::a3")]
322 pub e2: [f64; 3],
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
327pub struct PsfSampling {
328 pub field: usize,
329 pub pupil: usize,
331 #[serde(deserialize_with = "crate::nan::f")]
333 pub phase_step: f64,
334 #[serde(deserialize_with = "crate::nan::f")]
336 pub enclosed: f64,
337 #[serde(deserialize_with = "crate::nan::f")]
339 pub peak: f64,
340 #[serde(deserialize_with = "crate::nan::a2")]
342 pub pixel: [f64; 2],
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
347pub struct PsfOut {
348 pub unit: String,
349 pub method: String,
351 pub psf: Vec<PsfPoint>,
352 pub axes: Vec<PsfAxes>,
353 pub sampling: Vec<PsfSampling>,
354 pub warnings: Vec<String>,
355 #[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}