1use lensbench_core::{Error, FieldSel, Result, System};
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6
7use super::{coat_notes, fields, wave, Axis};
8use crate::footprint;
9use crate::registry::{Analysis, Cx, Meta};
10use crate::sweep::steps01;
11
12#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
16#[serde(default, deny_unknown_fields)]
17pub(super) struct FootprintParams {
18 pub surface: Option<usize>,
20 pub field: Option<usize>,
22 pub wave: Option<usize>,
24 #[schemars(extend("x-min" = 2))]
26 pub rays: usize,
27 pub no_vignetting_factors: bool,
29}
30
31impl Default for FootprintParams {
32 fn default() -> Self {
33 FootprintParams {
34 surface: None,
35 field: None,
36 wave: None,
37 rays: 21,
38 no_vignetting_factors: false,
39 }
40 }
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
45pub struct FootprintRow {
46 pub field: usize,
48 pub wave: usize,
50 pub points: Vec<[f64; 2]>,
52 pub edge: Vec<[Option<f64>; 2]>,
54 #[serde(deserialize_with = "crate::nan::a2")]
56 pub x: [f64; 2],
57 #[serde(deserialize_with = "crate::nan::a2")]
58 pub y: [f64; 2],
59 #[serde(deserialize_with = "crate::nan::f")]
61 pub max_radius: f64,
62 #[serde(deserialize_with = "crate::nan::f")]
64 pub fill: f64,
65 #[serde(deserialize_with = "crate::nan::f")]
67 pub through: f64,
68 #[serde(deserialize_with = "crate::nan::f")]
70 pub clipped: f64,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
75pub struct FootprintOut {
76 pub surface: usize,
78 pub unit: String,
79 #[serde(deserialize_with = "crate::nan::f")]
81 pub semi: f64,
82 pub aperture: Vec<Vec<[f64; 2]>>,
84 pub rows: Vec<FootprintRow>,
85 #[serde(deserialize_with = "crate::nan::f")]
87 pub max_radius: f64,
88 #[serde(deserialize_with = "crate::nan::f")]
89 pub fill: f64,
90 pub warnings: Vec<String>,
91}
92
93pub(super) struct Footprint;
94
95impl Analysis for Footprint {
96 type Params = FootprintParams;
97 type Output = FootprintOut;
98 fn meta(&self) -> Meta {
99 Meta {
100 name: "footprint",
101 about: "Footprint diagram: where the beam of each field and wavelength crosses a surface, against its aperture",
102 help: "Footprint diagram (OpticStudio's Footprint Diagram): the local intersections on a surface of a grid of pupil rays for each field and wavelength, with the outline of the surface aperture, the largest radius and its fraction of the semi-diameter, the fraction of rays that reach the image unvignetted and the fraction clipped at this surface. Rays clipped before the surface are not drawn. The vignetting factors of the fields are used unless no_vignetting_factors",
103 }
104 }
105 fn run(&self, cx: &Cx<'_>, p: &FootprintParams) -> Result<FootprintOut> {
106 let s = cx.system;
107 let j = match p.surface {
108 Some(j) => j,
109 None => s.surfaces.iter().position(|d| d.stop).unwrap_or(1),
110 };
111 if j == 0 || j > s.image() {
112 return Err(Error::Invalid(format!("surface {j} (1 to {})", s.image())));
113 }
114 let ws: Vec<usize> = match wave(s, p.wave)? {
115 Some(w) => vec![w],
116 None => (0..s.wavelengths.len()).collect(),
117 };
118 let semi = s.surfaces[j].semi.abs();
119 let frac = |r: f64| if semi > 0.0 { r / semi } else { f64::NAN };
120 let mut rows = Vec::new();
121 let mut warnings = Vec::new();
122 for i in fields(s, p.field)? {
123 for &w in &ws {
124 match footprint::footprint(
125 s,
126 FieldSel::Index(i),
127 w,
128 j,
129 p.rays,
130 !p.no_vignetting_factors,
131 ) {
132 Ok(f) => {
133 let n = f.rays.max(1) as f64;
134 rows.push(FootprintRow {
135 field: i + 1,
136 wave: w + 1,
137 edge: f
138 .edge
139 .iter()
140 .map(|q| {
141 [
142 q[0].is_finite().then_some(q[0]),
143 q[1].is_finite().then_some(q[1]),
144 ]
145 })
146 .collect(),
147 points: f.points,
148 x: f.x,
149 y: f.y,
150 max_radius: f.max_radius,
151 fill: frac(f.max_radius),
152 through: f.through as f64 / n,
153 clipped: f.clipped as f64 / n,
154 });
155 }
156 Err(e) => warnings.push(format!("field {}, wavelength {}: {e}", i + 1, w + 1)),
157 }
158 }
159 }
160 if rows.is_empty() {
161 return Err(Error::Invalid(warnings.join("; ")));
162 }
163 let max_radius = rows
164 .iter()
165 .map(|r| r.max_radius)
166 .filter(|r| r.is_finite())
167 .fold(f64::NAN, f64::max);
168 Ok(FootprintOut {
169 surface: j,
170 unit: "mm".into(),
171 semi,
172 aperture: footprint::aperture_outline(s, j),
173 rows,
174 max_radius,
175 fill: frac(max_radius),
176 warnings,
177 })
178 }
179}
180
181#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
185#[serde(default, deny_unknown_fields)]
186pub(super) struct RelIllumParams {
187 pub wave: Option<usize>,
189 #[schemars(extend("x-min" = 2))]
191 pub points: usize,
192 pub axis: Axis,
194 #[schemars(extend("x-min" = 8))]
196 pub rim: usize,
197 pub polarization: bool,
199 pub remove_vignetting_factors: bool,
201}
202
203impl Default for RelIllumParams {
204 fn default() -> Self {
205 RelIllumParams {
206 wave: None,
207 points: 21,
208 axis: Axis::Y,
209 rim: crate::illum::RIM_POINTS,
210 polarization: false,
211 remove_vignetting_factors: true,
212 }
213 }
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
218pub struct RelIllumOut {
219 pub wave: usize,
221 #[serde(deserialize_with = "crate::nan::v")]
222 pub h: Vec<f64>,
223 #[serde(deserialize_with = "crate::nan::v")]
224 pub field_value: Vec<f64>,
225 #[serde(deserialize_with = "crate::nan::v")]
227 pub relative: Vec<f64>,
228 #[serde(deserialize_with = "crate::nan::v")]
230 pub effective_fno: Vec<f64>,
231 #[serde(default, skip_serializing_if = "Option::is_none")]
233 #[serde(deserialize_with = "crate::nan::ov")]
234 pub transmission: Option<Vec<f64>>,
235 pub warnings: Vec<String>,
236}
237
238pub fn mean_transmission(s: &System, f: FieldSel, w: usize) -> Result<f64> {
242 use lensbench_core::coating::C64;
243 use lensbench_core::system::{Launch, PolIn, RecSel};
244 let co = lensbench_core::coating::Coatings::for_system(s)?;
245 let c = s.try_trace(f, &[0.0], &[0.0], Some(w), None, false)?;
246 let (hx, hy) = c.hx_hy;
247 let (px, py) = lensbench_core::opd::pupil_grid(21);
248 let l = Launch::Pupil {
249 spec: s.object_spec(hx, hy)?,
250 signed: false,
251 px: &px,
252 py: &py,
253 vig: Some(s.vig_factors(hx, hy)?),
254 hxy: Some((hx, hy)),
255 };
256 let (one, zero) = (C64::new(1.0, 0.0), C64::new(0.0, 0.0));
257 let pol = s.input_pol.jones();
258 if pol.is_some_and(|j| !(j[0].norm_sqr() + j[1].norm_sqr() > 0.0)) {
259 return Err(Error::Invalid(
260 "the input polarization (Ex, Ey) must not be zero".into(),
261 ));
262 }
263 let p = s.trace_pol_launch(
264 &l,
265 w,
266 PolIn::new(&[[one, zero], [zero, one]], &co).no_phase(),
267 RecSel::Off,
268 )?;
269 let (mut sum, mut n) = (0.0, 0usize);
270 for k in 0..px.len() {
271 if !p.trace.ok(k) {
272 continue;
273 }
274 let [kx, ky] = crate::polgrid::obj_dir(s, p.trace.k0[k]);
275 let e = &p.e[k];
276 let i = |j: [C64; 2]| {
278 let c = crate::polgrid::basis_coeffs(j, kx, ky);
279 (0..3)
280 .map(|q| (e[0][q] * c[0] + e[1][q] * c[1]).norm_sqr())
281 .sum::<f64>()
282 };
283 let t = match pol {
285 Some(j) => i(j) / (j[0].norm_sqr() + j[1].norm_sqr()),
286 None => 0.5 * (i([one, zero]) + i([zero, one])),
287 };
288 if t.is_finite() {
289 sum += t;
290 n += 1;
291 }
292 }
293 if n == 0 {
294 return Err(Error::Invalid(
295 "no ray of the pupil has a transmission".into(),
296 ));
297 }
298 Ok(sum / n as f64)
299}
300
301pub(super) struct RelIllum;
302
303impl Analysis for RelIllum {
304 type Params = RelIllumParams;
305 type Output = RelIllumOut;
306 fn meta(&self) -> Meta {
307 Meta {
308 name: "relative-illumination",
309 about: "Relative illumination versus field (image irradiance relative to the axis) and effective F-number",
310 help: "Relative illumination (OpticStudio's Relative Illumination): for points steps of the normalized field 0 to 1, the irradiance at the image point of the chief ray relative to the axis, from the projected solid angle of the beam that reaches that image point (the RELI operand), and the effective F-number (EFNO). By default the vignetting factors are replaced with floating apertures at the current semi-diameters on the surfaces where the medium changes (OpticStudio's Remove Vignetting Factors); with remove_vignetting_factors off the vignetting factors are ignored and the surface apertures are kept as they are. With polarization the ratio of the pupil-averaged coating and Fresnel transmission to the axis is multiplied in, and the effective F-number includes the transmission (F/√T)",
311 }
312 }
313 fn run(&self, cx: &Cx<'_>, p: &RelIllumParams) -> Result<RelIllumOut> {
314 let replaced = if p.remove_vignetting_factors {
315 Some(crate::illum::replace_vignetting(cx.system)?)
316 } else {
317 None
318 };
319 let s = replaced.as_ref().unwrap_or(cx.system);
320 let w = wave(s, p.wave)?.unwrap_or(s.primary);
321 let ax = p.axis.core();
322 if !has_off_axis(s, ax) {
323 return Err(Error::Invalid(
324 "the relative illumination needs a field off the axis (in the field direction)"
325 .into(),
326 ));
327 }
328 let h = steps01(p.points.max(2));
329 let mut warnings = Vec::new();
330 let a0 = crate::illum::exit_cone(s, FieldSel::Norm(0.0, 0.0), w, p.rim)?;
331 let t0 = if p.polarization {
332 Some(mean_transmission(s, FieldSel::Norm(0.0, 0.0), w)?)
333 } else {
334 None
335 };
336 let (mut rel, mut fno, mut trans) = (Vec::new(), Vec::new(), Vec::new());
337 for &hh in &h {
338 let f = ax.sel(hh);
339 match crate::illum::exit_cone(s, f, w, p.rim) {
340 Ok(a) => {
341 rel.push(a / a0);
342 fno.push(1.0 / (2.0 * (a / std::f64::consts::PI).sqrt()));
343 }
344 Err(e) => {
345 warnings.push(format!("field {}: {e}", f3(hh)));
346 rel.push(f64::NAN);
347 fno.push(f64::NAN);
348 }
349 }
350 if let Some(t0) = t0 {
351 let t = mean_transmission(s, f, w).unwrap_or_else(|e| {
352 warnings.push(format!("field {}: {e}", f3(hh)));
353 f64::NAN
354 });
355 trans.push(t);
356 if let Some(r) = rel.last_mut() {
357 *r *= t / t0;
358 }
359 if let Some(n) = fno.last_mut() {
361 *n /= t.sqrt();
362 }
363 }
364 }
365 warnings.extend(coat_notes(s, p.polarization)?);
366 Ok(RelIllumOut {
367 wave: w + 1,
368 field_value: h.iter().map(|&x| ax.value(s, x)).collect(),
369 h,
370 relative: rel,
371 effective_fno: fno,
372 transmission: t0.map(|_| trans),
373 warnings,
374 })
375 }
376}
377
378fn has_off_axis(s: &System, ax: crate::sweep::FieldAxis) -> bool {
380 let along = |f: &lensbench_core::system::Field| match (s.field_norm, ax) {
381 (lensbench_core::system::FieldNorm::Radial, _) => f.x.hypot(f.y),
382 (_, crate::sweep::FieldAxis::X) => f.x.abs(),
383 (_, crate::sweep::FieldAxis::Y) => f.y.abs(),
384 };
385 s.fields.iter().map(along).fold(0.0, f64::max) > 0.0
386}
387
388fn f3(x: f64) -> String {
390 format!("{x:.3}")
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
397#[serde(default, deny_unknown_fields)]
398pub(super) struct VignettingParams {
399 pub wave: Option<usize>,
401 #[schemars(extend("x-min" = 2))]
403 pub points: usize,
404 pub axis: Axis,
406 #[schemars(extend("x-min" = 2))]
408 pub rays: usize,
409 pub no_vignetting_factors: bool,
411 pub remove_vignetting_factors: bool,
413}
414
415impl Default for VignettingParams {
416 fn default() -> Self {
417 VignettingParams {
418 wave: None,
419 points: 21,
420 axis: Axis::Y,
421 rays: 64,
422 no_vignetting_factors: false,
423 remove_vignetting_factors: true,
424 }
425 }
426}
427
428#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
430pub struct VignettingOut {
431 pub wave: usize,
433 #[serde(deserialize_with = "crate::nan::v")]
434 pub h: Vec<f64>,
435 #[serde(deserialize_with = "crate::nan::v")]
436 pub field_value: Vec<f64>,
437 #[serde(deserialize_with = "crate::nan::v")]
439 pub unvignetted: Vec<f64>,
440 pub warnings: Vec<String>,
441}
442
443pub(super) struct Vignetting;
444
445impl Analysis for Vignetting {
446 type Params = VignettingParams;
447 type Output = VignettingOut;
448 fn meta(&self) -> Meta {
449 Meta {
450 name: "vignetting",
451 about: "Vignetting plot: fraction of unvignetted rays versus field",
452 help: "Vignetting plot (OpticStudio's Vignetting Plot): for points steps of the normalized field 0 to 1, the fraction of a grid of pupil rays (rays across the diameter) that reach the image unvignetted. By default the vignetting factors are replaced with floating apertures at the current semi-diameters on the surfaces where the medium changes (OpticStudio's Remove Vignetting Factors). With remove_vignetting_factors off, the vignetting factors of the fields are used unless no_vignetting_factors (then the full pupil is clipped only by the surface apertures)",
453 }
454 }
455 fn run(&self, cx: &Cx<'_>, p: &VignettingParams) -> Result<VignettingOut> {
456 let replaced = if p.remove_vignetting_factors {
457 Some(crate::illum::replace_vignetting(cx.system)?)
458 } else {
459 None
460 };
461 let s = replaced.as_ref().unwrap_or(cx.system);
462 let w = wave(s, p.wave)?.unwrap_or(s.primary);
463 let ax = p.axis.core();
464 if !has_off_axis(s, ax) {
465 return Err(Error::Invalid(
466 "the vignetting plot needs a field off the axis (in the field direction)".into(),
467 ));
468 }
469 let h = steps01(p.points.max(2));
470 let mut warnings = Vec::new();
471 let unvignetted = h
472 .iter()
473 .map(|&hh| {
474 footprint::unvignetted(s, ax.sel(hh), w, p.rays, !p.no_vignetting_factors)
475 .unwrap_or_else(|e| {
476 warnings.push(format!("field {}: {e}", f3(hh)));
477 f64::NAN
478 })
479 })
480 .collect();
481 Ok(VignettingOut {
482 wave: w + 1,
483 field_value: h.iter().map(|&x| ax.value(s, x)).collect(),
484 h,
485 unvignetted,
486 warnings,
487 })
488 }
489}