1use lensbench_core::seidel::{self, DistComp};
6use lensbench_core::system::FieldType;
7use lensbench_core::{Error, FieldSel, Result, System};
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use super::{fields, spot_unit, wave, Axis};
12use crate::aber;
13use crate::registry::{Analysis, Cx, Meta};
14use crate::sweep::steps01;
15
16fn waves(s: &System, w: Option<usize>) -> Result<Vec<usize>> {
18 Ok(match wave(s, w)? {
19 Some(w) => vec![w],
20 None => (0..s.wavelengths.len()).collect(),
21 })
22}
23
24fn f3(x: f64) -> String {
26 format!("{x:.3}")
27}
28
29fn len_unit() -> String {
31 "mm".into()
32}
33
34fn shift_unit(s: &System) -> String {
36 if s.afocal { "diopters" } else { "mm" }.into()
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
43#[serde(default, deny_unknown_fields)]
44pub(super) struct FanParams {
45 pub field: Option<usize>,
47 pub wave: Option<usize>,
49 #[schemars(extend("x-min" = 1))]
51 pub rays: usize,
52}
53
54impl Default for FanParams {
55 fn default() -> Self {
56 FanParams {
57 field: None,
58 wave: None,
59 rays: 20,
60 }
61 }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
66pub struct FanRow {
67 pub field: usize,
69 pub wave: usize,
71 #[serde(deserialize_with = "crate::nan::v")]
73 pub p: Vec<f64>,
74 #[serde(deserialize_with = "crate::nan::v")]
76 pub tangential: Vec<f64>,
77 #[serde(deserialize_with = "crate::nan::v")]
79 pub sagittal: Vec<f64>,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
84pub struct FanOut {
85 pub unit: String,
87 pub fans: Vec<FanRow>,
88 pub warnings: Vec<String>,
90}
91
92fn fans(
93 s: &System,
94 p: &FanParams,
95 unit: String,
96 f: fn(&System, FieldSel, usize, &[f64]) -> Result<aber::Fan>,
97) -> Result<FanOut> {
98 let pts = aber::fan_points(p.rays);
99 let mut out = Vec::new();
100 let mut warnings = Vec::new();
101 for i in fields(s, p.field)? {
102 for w in waves(s, p.wave)? {
103 match f(s, FieldSel::Index(i), w, &pts) {
104 Ok(v) => out.push(FanRow {
105 field: i + 1,
106 wave: w + 1,
107 p: v.p,
108 tangential: v.tan,
109 sagittal: v.sag,
110 }),
111 Err(e) => warnings.push(format!("field {}, wavelength {}: {e}", i + 1, w + 1)),
112 }
113 }
114 }
115 if out.is_empty() {
116 return Err(Error::Invalid(warnings.join("; ")));
117 }
118 Ok(FanOut {
119 unit,
120 fans: out,
121 warnings,
122 })
123}
124
125pub(super) struct RayFan;
126
127impl Analysis for RayFan {
128 type Params = FanParams;
129 type Output = FanOut;
130 fn meta(&self) -> Meta {
131 Meta {
132 name: "ray-fan",
133 about: "Ray aberration fans: transverse ray error versus pupil coordinate (tangential ey vs Py, sagittal ex vs Px)",
134 help: "Ray aberration fans (OpticStudio's Ray Fan): for each field and wavelength, the image position of the rays along the pupil y axis (tangential) and x axis (sagittal), relative to the chief ray of the primary wavelength (the TRAY and TRAX operands). Vignetted rays are null. In afocal image space the values are direction angles",
135 }
136 }
137 fn run(&self, cx: &Cx<'_>, p: &FanParams) -> Result<FanOut> {
138 let s = cx.system;
139 fans(s, p, spot_unit(s), aber::ray_fan)
140 }
141}
142
143pub(super) struct OpdFan;
144
145impl Analysis for OpdFan {
146 type Params = FanParams;
147 type Output = FanOut;
148 fn meta(&self) -> Meta {
149 Meta {
150 name: "opd-fan",
151 about: "OPD fans: optical path difference [waves] versus pupil coordinate (tangential and sagittal)",
152 help: "OPD fans (OpticStudio's OPD Fan): for each field and wavelength, the optical path difference in waves along the pupil y axis (tangential) and x axis (sagittal). The reference sphere is centered on the chief ray of the primary wavelength and the path is referenced to the chief ray of each wavelength (the OPDC operand). Vignetted rays are null",
153 }
154 }
155 fn run(&self, cx: &Cx<'_>, p: &FanParams) -> Result<FanOut> {
156 fans(cx.system, p, "waves".into(), aber::opd_fan)
157 }
158}
159
160pub(super) struct PupilFan;
161
162impl Analysis for PupilFan {
163 type Params = FanParams;
164 type Output = FanOut;
165 fn meta(&self) -> Meta {
166 Meta {
167 name: "pupil-fan",
168 about: "Pupil aberration fans: where real rays cross the stop against the paraxial point [% of the stop radius]",
169 help: "Pupil aberration fans (OpticStudio's Pupil Aberration Fan): for each field and wavelength, real rays aimed at the paraxial entrance pupil coordinates along the pupil y axis (tangential) and x axis (sagittal) without ray aiming, and the y (tangential) or x (sagittal) of the point where they cross the stop surface, as the paraxial point (pupil coordinate × paraxial stop radius of the primary wavelength) minus the real point in percent of the stop radius. Rays vignetted before the stop are null",
170 }
171 }
172 fn run(&self, cx: &Cx<'_>, p: &FanParams) -> Result<FanOut> {
173 let mut s = cx.system.clone();
175 if s.aiming != lensbench_core::system::Aiming::Off {
176 s.edit(|q| {
177 q.aiming = lensbench_core::system::Aiming::Off;
178 Ok(())
179 })?;
180 }
181 fans(&s, p, "%".into(), aber::pupil_fan)
182 }
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
189#[serde(rename_all = "kebab-case")]
190pub enum DistKind {
191 #[default]
193 FTan,
194 FTheta,
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
200#[serde(default, deny_unknown_fields)]
201pub(super) struct FieldCurvParams {
202 pub wave: Option<usize>,
204 #[schemars(extend("x-min" = 2))]
206 pub points: usize,
207 pub axis: Axis,
209 pub distortion: DistKind,
211}
212
213impl Default for FieldCurvParams {
214 fn default() -> Self {
215 FieldCurvParams {
216 wave: None,
217 points: 21,
218 axis: Axis::Y,
219 distortion: DistKind::FTan,
220 }
221 }
222}
223
224#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
226pub struct CurvWave {
227 pub wave: usize,
229 #[serde(deserialize_with = "crate::nan::v")]
231 pub tangential: Vec<f64>,
232 #[serde(deserialize_with = "crate::nan::v")]
234 pub sagittal: Vec<f64>,
235 #[serde(deserialize_with = "crate::nan::v")]
237 pub distortion: Vec<f64>,
238}
239
240#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
242pub struct FieldCurvOut {
243 pub unit: String,
245 #[serde(deserialize_with = "crate::nan::v")]
247 pub h: Vec<f64>,
248 #[serde(deserialize_with = "crate::nan::v")]
250 pub field_value: Vec<f64>,
251 pub distortion_kind: DistKind,
252 pub waves: Vec<CurvWave>,
253 #[serde(deserialize_with = "crate::nan::f")]
255 pub max_distortion: f64,
256 pub warnings: Vec<String>,
257}
258
259pub(super) struct FieldCurv;
260
261impl Analysis for FieldCurv {
262 type Params = FieldCurvParams;
263 type Output = FieldCurvOut;
264 fn meta(&self) -> Meta {
265 Meta {
266 name: "field-curvature",
267 about: "Field curvature and distortion versus field (tangential and sagittal focus, distortion %)",
268 help: "Field curvature and distortion (OpticStudio's Field Curvature/Distortion): for points steps of the normalized field 0 to 1, the z of the tangential and sagittal focus of the rays near the chief ray measured from the image surface (the FCGT and FCGS operands), and the distortion of the real chief ray against the paraxial ideal height f tan θ (or f θ). Every wavelength if wave is omitted. Vignetting factors are not used, as in OpticStudio. In afocal image space the focus is in diopters (the inverse of the distance in meters along the chief ray, negative for a virtual focus before the image surface) and the distortion compares the direction tangents of the chief ray with the paraxial angular magnification, as in OpticStudio",
269 }
270 }
271 fn run(&self, cx: &Cx<'_>, p: &FieldCurvParams) -> Result<FieldCurvOut> {
272 let (s, vig) = crate::sweep::without_vig(cx.system);
273 let s = &*s;
274 if p.distortion == DistKind::FTheta && s.field_type != FieldType::Angle {
275 return Err(Error::Invalid(
276 "the f-theta distortion needs angle fields".into(),
277 ));
278 }
279 let ax = p.axis.core();
280 let h = steps01(p.points.max(2));
281 let k = usize::from(p.axis == Axis::Y);
282 let mut warnings: Vec<String> = vig.into_iter().collect();
283 let mut out = Vec::new();
284 let mut max_distortion = f64::NAN;
285 for w in waves(s, p.wave)? {
286 let (mut tan, mut sag, mut dist) = (Vec::new(), Vec::new(), Vec::new());
287 let r = match seidel::distortion_ref(s, w, None) {
288 Ok(r) => Some(r),
289 Err(e) => {
290 warnings.push(format!("wavelength {}: distortion: {e}", w + 1));
291 None
292 }
293 };
294 for &hh in &h {
295 let f = ax.sel(hh);
296 let focus = if s.afocal {
297 aber::field_focus_diopters
298 } else {
299 aber::field_focus
300 };
301 let mut get = |t: bool| match focus(s, f, w, s.image(), t) {
302 Ok(z) => z,
303 Err(e) => {
304 warnings.push(format!("wavelength {}, field {}: {e}", w + 1, f3(hh)));
305 f64::NAN
306 }
307 };
308 tan.push(get(true));
309 sag.push(get(false));
310 let d = match &r {
311 _ if hh == 0.0 => Ok(0.0),
312 None => Ok(f64::NAN),
313 Some(r) => distortion_pct(s, w, ax.sel(hh), r, k, p.distortion),
314 };
315 dist.push(d.unwrap_or_else(|e| {
316 warnings.push(format!("wavelength {}, field {}: {e}", w + 1, f3(hh)));
317 f64::NAN
318 }));
319 }
320 if w == s.primary || p.wave.is_some() {
321 max_distortion = dist
322 .iter()
323 .filter(|d| d.is_finite())
324 .fold(0.0_f64, |m, d| m.max(d.abs()));
325 }
326 out.push(CurvWave {
327 wave: w + 1,
328 tangential: tan,
329 sagittal: sag,
330 distortion: dist,
331 });
332 }
333 warnings.dedup();
334 Ok(FieldCurvOut {
335 unit: shift_unit(s),
336 field_value: h.iter().map(|&x| ax.value(s, x)).collect(),
337 h,
338 distortion_kind: p.distortion,
339 waves: out,
340 max_distortion,
341 warnings,
342 })
343 }
344}
345
346fn distortion_pct(
348 s: &System,
349 w: usize,
350 f: FieldSel,
351 r: &seidel::DistRef,
352 k: usize,
353 kind: DistKind,
354) -> Result<f64> {
355 let h = s.field_sel_norm(f, w)?;
356 match kind {
357 DistKind::FTan => Ok(seidel::distortion_against(s, w, h, r, DistComp::Radial)?.1),
358 DistKind::FTheta => {
359 let (real, ideal) = seidel::distortion_points(s, w, h, r)?;
360 let m = r.j[k][k];
362 let th = m * (ideal[k] / m).atan();
363 Ok(100.0 * (real[k] - th) / th)
364 }
365 }
366}
367
368#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
372#[serde(default, deny_unknown_fields)]
373pub(super) struct LongParams {
374 pub wave: Option<usize>,
376 #[schemars(extend("x-min" = 2))]
378 pub points: usize,
379}
380
381impl Default for LongParams {
382 fn default() -> Self {
383 LongParams {
384 wave: None,
385 points: 21,
386 }
387 }
388}
389
390#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
392pub struct LongWave {
393 pub wave: usize,
395 #[serde(deserialize_with = "crate::nan::v")]
397 pub z: Vec<f64>,
398}
399
400#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
402pub struct LongOut {
403 pub unit: String,
404 #[serde(deserialize_with = "crate::nan::v")]
406 pub zones: Vec<f64>,
407 pub waves: Vec<LongWave>,
408 pub warnings: Vec<String>,
409}
410
411pub(super) struct Longitudinal;
412
413impl Analysis for Longitudinal {
414 type Params = LongParams;
415 type Output = LongOut;
416 fn meta(&self) -> Meta {
417 Meta {
418 name: "longitudinal",
419 about: "Longitudinal aberration versus pupil height (where on-axis rays cross the axis)",
420 help: "Longitudinal aberration (OpticStudio's Longitudinal Aberration): for points zones of the normalized pupil height 0 to 1, the distance from the image surface vertex to where the on-axis ray crosses the optical axis (the LONA operand; zone 0 is the paraxial marginal ray). Every wavelength if wave is omitted",
421 }
422 }
423 fn run(&self, cx: &Cx<'_>, p: &LongParams) -> Result<LongOut> {
424 let s = cx.system;
425 let zones = steps01(p.points.max(2));
426 let mut warnings = Vec::new();
427 let mut out = Vec::new();
428 for w in waves(s, p.wave)? {
429 let z = zones
430 .iter()
431 .map(|&z| {
432 seidel::longitudinal(s, w, z).unwrap_or_else(|e| {
433 warnings.push(format!("wavelength {}: {e}", w + 1));
434 f64::NAN
435 })
436 })
437 .collect();
438 out.push(LongWave { wave: w + 1, z });
439 }
440 Ok(LongOut {
441 unit: len_unit(),
442 zones,
443 waves: out,
444 warnings,
445 })
446 }
447}
448
449#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
453#[serde(default, deny_unknown_fields)]
454pub(super) struct LatParams {
455 #[schemars(extend("x-min" = 2))]
457 pub points: usize,
458 pub axis: Axis,
460}
461
462impl Default for LatParams {
463 fn default() -> Self {
464 LatParams {
465 points: 21,
466 axis: Axis::Y,
467 }
468 }
469}
470
471#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
473pub struct LatWave {
474 pub wave: usize,
476 #[serde(deserialize_with = "crate::nan::v")]
478 pub d: Vec<f64>,
479}
480
481#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
483pub struct LatOut {
484 pub unit: String,
485 #[serde(deserialize_with = "crate::nan::v")]
486 pub h: Vec<f64>,
487 #[serde(deserialize_with = "crate::nan::v")]
488 pub field_value: Vec<f64>,
489 pub waves: Vec<LatWave>,
491 #[serde(deserialize_with = "crate::nan::f")]
493 pub airy: f64,
494 pub warnings: Vec<String>,
495}
496
497pub(super) struct LateralColor;
498
499impl Analysis for LateralColor {
500 type Params = LatParams;
501 type Output = LatOut;
502 fn meta(&self) -> Meta {
503 Meta {
504 name: "lateral-color",
505 about: "Lateral color versus field (real chief ray height of each wavelength minus the primary wavelength)",
506 help: "Lateral color (OpticStudio's Lateral Color): for points steps of the normalized field 0 to 1, the difference of the real chief ray image height (the component along the field direction) of each wavelength from the primary wavelength, with the Airy radius of the primary wavelength. In afocal image space the values are direction angles",
507 }
508 }
509 fn run(&self, cx: &Cx<'_>, p: &LatParams) -> Result<LatOut> {
510 let s = cx.system;
511 if s.wavelengths.len() < 2 {
512 return Err(Error::Invalid(
513 "lateral color needs two or more wavelengths".into(),
514 ));
515 }
516 let ax = p.axis.core();
517 let h = steps01(p.points.max(2));
518 let mut warnings = Vec::new();
519 let mut out = Vec::new();
520 for w in (0..s.wavelengths.len()).filter(|&w| w != s.primary) {
521 let d = h
522 .iter()
523 .map(|&hh| match aber::lateral_color(s, ax.sel(hh), w) {
524 Ok((dx, dy)) => {
525 if p.axis == Axis::Y {
526 dy
527 } else {
528 dx
529 }
530 }
531 Err(e) => {
532 warnings.push(format!("wavelength {}, field {}: {e}", w + 1, f3(hh)));
533 f64::NAN
534 }
535 })
536 .collect();
537 out.push(LatWave { wave: w + 1, d });
538 }
539 let airy = if s.afocal {
540 f64::NAN
541 } else {
542 1.22 * s.wave(s.primary).mm() * lensbench_core::report::system_data(s).wfno
543 };
544 Ok(LatOut {
545 unit: spot_unit(s),
546 field_value: h.iter().map(|&x| ax.value(s, x)).collect(),
547 h,
548 waves: out,
549 airy,
550 warnings,
551 })
552 }
553}
554
555#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
559#[serde(default, deny_unknown_fields)]
560pub(super) struct ShiftParams {
561 pub min: Option<f64>,
563 pub max: Option<f64>,
565 #[schemars(extend("x-min" = 2))]
567 pub points: usize,
568}
569
570impl Default for ShiftParams {
571 fn default() -> Self {
572 ShiftParams {
573 min: None,
574 max: None,
575 points: 41,
576 }
577 }
578}
579
580#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
582pub struct ShiftOut {
583 pub unit: String,
584 #[serde(deserialize_with = "crate::nan::v")]
586 pub wavelengths: Vec<f64>,
587 #[serde(deserialize_with = "crate::nan::v")]
589 pub shift: Vec<f64>,
590 #[serde(deserialize_with = "crate::nan::f")]
592 pub range: f64,
593 #[serde(deserialize_with = "crate::nan::f")]
595 pub diffraction_depth: f64,
596 pub warnings: Vec<String>,
597}
598
599pub(super) struct FocalShift;
600
601impl Analysis for FocalShift {
602 type Params = ShiftParams;
603 type Output = ShiftOut;
604 fn meta(&self) -> Meta {
605 Meta {
606 name: "focal-shift",
607 about: "Chromatic focal shift versus wavelength (paraxial focus relative to the primary wavelength)",
608 help: "Chromatic focal shift (OpticStudio's Chromatic Focal Shift): for points wavelengths from min to max, the shift of the paraxial focus from the paraxial focus of the primary wavelength (the difference of the LONA zone 0 operand, as AXCL), with the diffraction-limited depth 4 λ (F/#)². In afocal image space the shift is in diopters (the difference of the inverse distances of the paraxial focus from the image surface in meters) and the depth is 0, as in OpticStudio",
609 }
610 }
611 fn run(&self, cx: &Cx<'_>, p: &ShiftParams) -> Result<ShiftOut> {
612 let s = cx.system;
613 let lo = p
614 .min
615 .unwrap_or_else(|| s.wavelengths.iter().copied().fold(f64::INFINITY, f64::min));
616 let hi = p
617 .max
618 .unwrap_or_else(|| s.wavelengths.iter().copied().fold(0.0, f64::max));
619 if !(lo > 0.0 && hi >= lo) {
620 return Err(Error::Invalid(format!("wavelength range {lo} to {hi} µm")));
621 }
622 let n = p.points.max(2);
623 let wl: Vec<f64> = (0..n)
624 .map(|k| lo + (hi - lo) * k as f64 / (n - 1) as f64)
625 .collect();
626 let mut warnings = Vec::new();
627 let shift: Vec<f64> = wl
628 .iter()
629 .map(|&l| {
630 let f = if s.afocal {
631 aber::focal_shift_diopters
632 } else {
633 aber::focal_shift
634 };
635 f(s, l).unwrap_or_else(|e| {
636 warnings.push(format!("{l} µm: {e}"));
637 f64::NAN
638 })
639 })
640 .collect();
641 let fin = shift.iter().filter(|v| v.is_finite());
642 let range = fin.clone().fold(f64::NEG_INFINITY, |a, &b| a.max(b))
643 - fin.fold(f64::INFINITY, |a, &b| a.min(b));
644 let f = lensbench_core::report::system_data(s).wfno;
645 Ok(ShiftOut {
646 unit: shift_unit(s),
647 wavelengths: wl,
648 shift,
649 range,
650 diffraction_depth: if s.afocal {
652 0.0
653 } else {
654 4.0 * s.wave(s.primary).mm() * f * f
655 },
656 warnings,
657 })
658 }
659}
660
661#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
665#[serde(default, deny_unknown_fields)]
666pub(super) struct GridParams {
667 pub wave: Option<usize>,
669 #[schemars(extend("x-min" = 3))]
671 pub grid: usize,
672}
673
674impl Default for GridParams {
675 fn default() -> Self {
676 GridParams {
677 wave: None,
678 grid: 9,
679 }
680 }
681}
682
683#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
685pub struct GridPoint {
686 #[serde(deserialize_with = "crate::nan::f")]
688 pub hx: f64,
689 #[serde(deserialize_with = "crate::nan::f")]
690 pub hy: f64,
691 #[serde(deserialize_with = "crate::nan::a2")]
693 pub real: [f64; 2],
694 #[serde(deserialize_with = "crate::nan::a2")]
696 pub ideal: [f64; 2],
697 #[serde(deserialize_with = "crate::nan::f")]
699 pub distortion: f64,
700}
701
702#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
704pub struct GridOut {
705 pub unit: String,
706 pub wave: usize,
708 pub grid: usize,
709 pub points: Vec<GridPoint>,
710 #[serde(deserialize_with = "crate::nan::f")]
712 pub max_distortion: f64,
713 #[serde(deserialize_with = "crate::nan::a2")]
714 pub max_at: [f64; 2],
715 pub warnings: Vec<String>,
716}
717
718pub(super) struct GridDistortion;
719
720impl Analysis for GridDistortion {
721 type Params = GridParams;
722 type Output = GridOut;
723 fn meta(&self) -> Meta {
724 Meta {
725 name: "grid-distortion",
726 about: "Grid distortion: real chief ray image points of a square grid of fields against the paraxial ideal grid",
727 help: "Grid distortion (OpticStudio's Grid Distortion): for a grid × grid square inscribed in the circle of the largest field (evenly spaced in tan θ for angle fields), the real chief ray image point and the ideal point from the paraxial magnification, with the distortion % (the DISG operand against the axis). In afocal image space the points are the direction tangents (l/n, m/n) of the image space ray and the ideal points come from the paraxial angular magnification, as in OpticStudio. Needs a rotationally symmetric system",
728 }
729 }
730 fn run(&self, cx: &Cx<'_>, p: &GridParams) -> Result<GridOut> {
731 let s = cx.system;
732 let w = wave(s, p.wave)?.unwrap_or(s.primary);
733 seidel::grid_field(s, 1.0, 1.0)?;
735 let r = seidel::distortion_ref(s, w, None)?;
736 let n = p.grid.max(3);
737 let mut points = Vec::with_capacity(n * n);
738 let mut warnings = Vec::new();
739 let (mut max_distortion, mut max_at) = (0.0_f64, [0.0, 0.0]);
740 for j in 0..n {
741 for i in 0..n {
742 let u = -1.0 + 2.0 * i as f64 / (n - 1) as f64;
743 let v = 1.0 - 2.0 * j as f64 / (n - 1) as f64;
744 let (hx, hy) = seidel::grid_field(s, u, v)?;
745 let pt = seidel::distortion_points(s, w, (hx, hy), &r).and_then(|(re, id)| {
746 let d = if u == 0.0 && v == 0.0 {
747 0.0
748 } else {
749 seidel::distortion_against(s, w, (hx, hy), &r, DistComp::Radial)?.1
750 };
751 Ok((re, id, d))
752 });
753 match pt {
754 Ok((real, ideal, d)) => {
755 if d.abs() > max_distortion.abs() {
756 (max_distortion, max_at) = (d, [hx, hy]);
757 }
758 points.push(GridPoint {
759 hx,
760 hy,
761 real,
762 ideal,
763 distortion: d,
764 });
765 }
766 Err(e) => warnings.push(format!("field ({}, {}): {e}", f3(hx), f3(hy))),
767 }
768 }
769 }
770 Ok(GridOut {
771 unit: if s.afocal { "tan".into() } else { len_unit() },
773 wave: w + 1,
774 grid: n,
775 points,
776 max_distortion,
777 max_at,
778 warnings,
779 })
780 }
781}
782
783#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
787#[serde(default, deny_unknown_fields)]
788pub(super) struct SeidelParams {
789 pub wave: Option<usize>,
791}
792
793#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
795pub struct SeidelRow {
796 pub surf: usize,
798 #[serde(deserialize_with = "crate::nan::f")]
800 pub spha: f64,
801 #[serde(deserialize_with = "crate::nan::f")]
803 pub coma: f64,
804 #[serde(deserialize_with = "crate::nan::f")]
806 pub asti: f64,
807 #[serde(deserialize_with = "crate::nan::f")]
809 pub fcur: f64,
810 #[serde(deserialize_with = "crate::nan::f")]
812 pub dist: f64,
813 #[serde(deserialize_with = "crate::nan::f")]
815 pub cla: f64,
816 #[serde(deserialize_with = "crate::nan::f")]
818 pub ctr: f64,
819}
820
821#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
823pub struct SeidelWaves {
824 pub surf: usize,
825 #[serde(deserialize_with = "crate::nan::f")]
826 pub w040: f64,
827 #[serde(deserialize_with = "crate::nan::f")]
828 pub w131: f64,
829 #[serde(deserialize_with = "crate::nan::f")]
830 pub w222: f64,
831 #[serde(deserialize_with = "crate::nan::f")]
832 pub w220: f64,
833 #[serde(deserialize_with = "crate::nan::f")]
834 pub w311: f64,
835}
836
837#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
839pub struct SeidelOut {
840 pub unit: String,
841 pub wave: usize,
843 pub surfaces: Vec<SeidelRow>,
845 pub sum: SeidelRow,
847 pub waves: Vec<SeidelWaves>,
849}
850
851pub(super) struct SeidelCoef;
852
853impl Analysis for SeidelCoef {
854 type Params = SeidelParams;
855 type Output = SeidelOut;
856 fn meta(&self) -> Meta {
857 Meta {
858 name: "seidel",
859 about: "Seidel coefficients per surface (S_I to S_V, axial and lateral color) and wavefront coefficients [waves]",
860 help: "Seidel coefficients (OpticStudio's Seidel Coefficients and Seidel Diagram): the third-order sums S_I to S_V per surface in lens units (Welford), the first-order axial color C_L and lateral color C_T between the shortest and longest wavelengths, and the wavefront coefficients W040, W131, W222, W220 and W311 in waves (the SPHA, COMA, ASTI, FCUR and DIST operands). Needs a rotationally symmetric system without mirrors",
861 }
862 }
863 fn run(&self, cx: &Cx<'_>, p: &SeidelParams) -> Result<SeidelOut> {
864 let s = cx.system;
865 let w = wave(s, p.wave)?.unwrap_or(s.primary);
866 let sd = seidel::seidel(s, w)?;
867 let by = |f: fn(&f64, &f64) -> bool| {
868 let mut k = 0;
869 for (i, l) in s.wavelengths.iter().enumerate() {
870 if f(l, &s.wavelengths[k]) {
871 k = i;
872 }
873 }
874 k
875 };
876 let (short, long) = (by(|a, b| a < b), by(|a, b| a > b));
877 let col = seidel::chromatic(s, w, short, long)?;
878 let row = |j: usize, v: [f64; 5], c: [f64; 2]| SeidelRow {
879 surf: j,
880 spha: v[0],
881 coma: v[1],
882 asti: v[2],
883 fcur: v[3],
884 dist: v[4],
885 cla: c[0],
886 ctr: c[1],
887 };
888 let wrow = |j: usize| {
889 let v = sd.waves(j);
890 SeidelWaves {
891 surf: j,
892 w040: v[0],
893 w131: v[1],
894 w222: v[2],
895 w220: v[3],
896 w311: v[4],
897 }
898 };
899 let used = |j: usize| {
900 let f = &s.surfaces[j];
901 !(f.ignore || f.is_coord_break())
902 };
903 let js: Vec<usize> = (1..s.image()).filter(|&j| used(j)).collect();
904 let csum = col.iter().fold([0.0; 2], |a, c| [a[0] + c[0], a[1] + c[1]]);
905 let mut waves = vec![wrow(0)];
906 waves.extend(js.iter().map(|&j| wrow(j)));
907 Ok(SeidelOut {
908 unit: len_unit(),
909 wave: w + 1,
910 surfaces: js.iter().map(|&j| row(j, sd.at(j), col[j])).collect(),
911 sum: row(0, sd.at(0), csum),
912 waves,
913 })
914 }
915}