1use lensbench_core::Waves;
4use std::path::PathBuf;
5
6use crate::analysis::{self, ZernKind};
7use lensbench_core::coating::Coatings;
8use lensbench_core::{FieldSel, Result};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use super::{fields, skip_vignetted, spot_unit, wave};
13use crate::registry::{Analysis, Cx, Meta};
14
15#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
19#[serde(default, deny_unknown_fields)]
20pub(super) struct SpotParams {
21 pub field: Option<usize>,
23 pub wave: Option<usize>,
25 #[schemars(extend("x-min" = 1))]
27 pub rings: usize,
28}
29
30impl Default for SpotParams {
31 fn default() -> Self {
32 SpotParams {
33 field: None,
34 wave: None,
35 rings: 6,
36 }
37 }
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
42pub struct SpotRow {
43 pub field: usize,
44 #[serde(deserialize_with = "crate::nan::f")]
45 pub rms_centroid: f64,
46 #[serde(deserialize_with = "crate::nan::f")]
47 pub rms_chief: f64,
48 #[serde(deserialize_with = "crate::nan::f")]
49 pub geo: f64,
50 #[serde(deserialize_with = "crate::nan::a2")]
51 pub centroid: [f64; 2],
52 #[serde(deserialize_with = "crate::nan::a2")]
53 pub chief: [f64; 2],
54 pub rays: RayCountsOut,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
60pub struct RayCountsOut {
61 pub total: usize,
63 pub vignetted: usize,
65 pub missed: usize,
67 pub tir: usize,
69 pub aim_failed: usize,
71}
72
73impl From<lensbench_core::trace::RayCounts> for RayCountsOut {
74 fn from(c: lensbench_core::trace::RayCounts) -> Self {
75 RayCountsOut {
76 total: c.total,
77 vignetted: c.vignetted,
78 missed: c.missed,
79 tir: c.tir,
80 aim_failed: c.aim_failed,
81 }
82 }
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
87pub struct SpotOut {
88 pub unit: String,
90 pub spot: Vec<SpotRow>,
91}
92
93pub(super) struct Spot;
94
95impl Analysis for Spot {
96 type Params = SpotParams;
97 type Output = SpotOut;
98 fn meta(&self) -> Meta {
99 Meta {
100 name: "spot",
101 about: "Spot (RMS and GEO radius)",
102 help: "",
103 }
104 }
105 fn run(&self, cx: &Cx<'_>, p: &SpotParams) -> Result<SpotOut> {
106 let s = cx.system;
107 let w = wave(s, p.wave)?;
108 let mut v = Vec::new();
109 for i in fields(s, p.field)? {
110 let sp = analysis::spot(s, FieldSel::Index(i), Waves::all_or(w), p.rings)?;
111 v.push(SpotRow {
112 field: i + 1,
113 rms_centroid: sp.rms_centroid,
114 rms_chief: sp.rms_chief,
115 geo: sp.geo,
116 centroid: [sp.centroid.0, sp.centroid.1],
117 chief: [sp.chief.0, sp.chief.1],
118 rays: sp.rays.into(),
119 });
120 }
121 Ok(SpotOut {
122 unit: spot_unit(s),
123 spot: v,
124 })
125 }
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
132#[serde(default, deny_unknown_fields)]
133pub(super) struct WavefrontParams {
134 pub field: Option<usize>,
136 pub wave: Option<usize>,
138 #[schemars(extend("x-min" = 1))]
140 pub n: usize,
141 pub map: bool,
143}
144
145impl Default for WavefrontParams {
146 fn default() -> Self {
147 WavefrontParams {
148 field: None,
149 wave: None,
150 n: 64,
151 map: false,
152 }
153 }
154}
155
156#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
158pub struct WavefrontRow {
159 pub field: usize,
160 #[serde(deserialize_with = "crate::nan::f")]
161 pub pv: f64,
162 #[serde(deserialize_with = "crate::nan::f")]
163 pub rms: f64,
164 #[serde(
166 skip_serializing_if = "Option::is_none",
167 deserialize_with = "crate::nan::ov",
168 default
169 )]
170 pub p: Option<Vec<f64>>,
171 #[serde(
173 skip_serializing_if = "Option::is_none",
174 deserialize_with = "crate::nan::ovv",
175 default
176 )]
177 pub map: Option<Vec<Vec<f64>>>,
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
182pub struct WavefrontOut {
183 pub unit: String,
184 pub wavefront: Vec<WavefrontRow>,
185 #[serde(default, skip_serializing_if = "Vec::is_empty")]
187 pub warnings: Vec<String>,
188}
189
190pub(super) struct Wavefront;
191
192impl Analysis for Wavefront {
193 type Params = WavefrontParams;
194 type Output = WavefrontOut;
195 fn meta(&self) -> Meta {
196 Meta {
197 name: "wavefront",
198 about: "Wavefront aberration (OPD relative to the chief ray, P-V and RMS [waves])",
199 help: "",
200 }
201 }
202 fn run(&self, cx: &Cx<'_>, p: &WavefrontParams) -> Result<WavefrontOut> {
203 let s = cx.system;
204 let w = wave(s, p.wave)?;
205 let mut rows = Vec::new();
206 for i in fields(s, p.field)? {
207 let r =
209 analysis::wavefront(s, FieldSel::Index(i), w, p.n, false).map(|wf| WavefrontRow {
210 field: i + 1,
211 pv: wf.pv,
212 rms: wf.rms,
213 p: p.map.then(|| wf.w.x().to_vec()),
214 map: p.map.then(|| wf.w.to_rows()),
215 });
216 rows.push((i, r));
217 }
218 let mut warnings = Vec::new();
219 let v = skip_vignetted(rows, &mut warnings)?;
220 Ok(WavefrontOut {
221 unit: "waves".into(),
222 wavefront: v,
223 warnings,
224 })
225 }
226}
227
228#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
232#[serde(rename_all = "lowercase")]
233pub enum ZKind {
234 #[default]
236 Standard,
237 Fringe,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
243#[serde(default, deny_unknown_fields)]
244pub(super) struct ZernikeParams {
245 pub field: Option<usize>,
247 pub wave: Option<usize>,
249 pub kind: ZKind,
251 #[schemars(extend("x-min" = 1))]
253 pub terms: usize,
254 #[schemars(extend("x-min" = 1))]
256 pub n: usize,
257}
258
259impl Default for ZernikeParams {
260 fn default() -> Self {
261 ZernikeParams {
262 field: None,
263 wave: None,
264 kind: ZKind::Standard,
265 terms: 37,
266 n: 64,
267 }
268 }
269}
270
271#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
273pub struct ZernikeRow {
274 pub field: usize,
275 #[serde(deserialize_with = "crate::nan::v")]
277 pub coef: Vec<f64>,
278 #[serde(deserialize_with = "crate::nan::f")]
279 pub pv: f64,
280 #[serde(deserialize_with = "crate::nan::f")]
281 pub rms_chief: f64,
282 #[serde(deserialize_with = "crate::nan::f")]
283 pub rms_centroid: f64,
284 #[serde(deserialize_with = "crate::nan::f")]
285 pub rms_fit: f64,
286 #[serde(deserialize_with = "crate::nan::f")]
287 pub strehl: f64,
288}
289
290#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
292pub struct ZernikeOut {
293 pub unit: String,
294 pub kind: ZKind,
295 pub zernike: Vec<ZernikeRow>,
296 #[serde(default, skip_serializing_if = "Vec::is_empty")]
298 pub warnings: Vec<String>,
299}
300
301pub(super) struct Zernike;
302
303impl Analysis for Zernike {
304 type Params = ZernikeParams;
305 type Output = ZernikeOut;
306 fn meta(&self) -> Meta {
307 Meta {
308 name: "zernike",
309 about: "Zernike coefficients [waves]",
310 help: "",
311 }
312 }
313 fn run(&self, cx: &Cx<'_>, p: &ZernikeParams) -> Result<ZernikeOut> {
314 let k = match p.kind {
315 ZKind::Standard => ZernKind::Standard,
316 ZKind::Fringe => ZernKind::Fringe,
317 };
318 if k == ZernKind::Fringe && p.terms > 37 {
319 return Err(lensbench_core::Error::Invalid(
320 "Fringe has at most 37 terms".into(),
321 ));
322 }
323 let s = cx.system;
324 let w = wave(s, p.wave)?;
325 let mut rows = Vec::new();
326 for i in fields(s, p.field)? {
327 let r = analysis::zernike(s, FieldSel::Index(i), w, k, p.terms, p.n, false).map(|z| {
328 ZernikeRow {
329 field: i + 1,
330 coef: z.coef,
331 pv: z.pv,
332 rms_chief: z.rms_chief,
333 rms_centroid: z.rms_centroid,
334 rms_fit: z.rms_fit,
335 strehl: z.strehl,
336 }
337 });
338 rows.push((i, r));
339 }
340 let mut warnings = Vec::new();
341 let v = skip_vignetted(rows, &mut warnings)?;
342 Ok(ZernikeOut {
343 unit: "waves".into(),
344 kind: p.kind,
345 zernike: v,
346 warnings,
347 })
348 }
349}
350
351#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
355#[serde(default, deny_unknown_fields)]
356pub(super) struct GhostParams {
357 pub first: usize,
359 pub last: Option<usize>,
361 #[schemars(extend("x-kind" = "path"))]
363 pub coatings: Vec<PathBuf>,
364 #[schemars(extend("x-kind" = "path", "x-write" = true))]
366 pub out: Option<PathBuf>,
367}
368
369impl Default for GhostParams {
370 fn default() -> Self {
371 GhostParams {
372 first: 1,
373 last: None,
374 coatings: Vec::new(),
375 out: None,
376 }
377 }
378}
379
380#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
382pub struct GhostRow {
383 pub a: usize,
385 pub b: usize,
387 #[serde(deserialize_with = "crate::nan::f")]
388 pub marginal_y: f64,
389 #[serde(deserialize_with = "crate::nan::f")]
390 pub marginal_u: f64,
391 pub focus: Option<f64>,
393 #[serde(deserialize_with = "crate::nan::f")]
394 pub wfno: f64,
395 #[serde(skip_serializing_if = "Option::is_none")]
397 pub intensity: Option<f64>,
398 #[serde(skip_serializing_if = "Option::is_none")]
400 pub intensity_error: Option<String>,
401}
402
403#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
405pub struct GhostOut {
406 pub first: usize,
407 pub last: usize,
408 pub ghosts: Vec<GhostRow>,
409 pub written: Vec<String>,
411 pub warnings: Vec<String>,
413}
414
415pub(super) struct Ghost;
416
417impl Analysis for Ghost {
418 type Params = GhostParams;
419 type Output = GhostOut;
420 fn meta(&self) -> Meta {
421 Meta {
422 name: "ghost",
423 about: "Ghosts (double reflections): focus position, blur at the image and intensity ratio",
424 help: "List of ghosts (reflected at surface a then at surface b, the double bounce of OpticStudio's Ghost Focus Generator): paraxial ghost focus position, blur radius at the image and on-axis chief ray intensity ratio (with coatings). out writes the expanded systems to .zmx files in a folder",
425 }
426 }
427 fn run(&self, cx: &Cx<'_>, p: &GhostParams) -> Result<GhostOut> {
428 let s = cx.system;
429 let last = p.last.unwrap_or(s.image());
430 let mut co = Coatings::for_system(s)?;
431 for f in &p.coatings {
432 co.load_file(f)?;
433 }
434 let v = crate::ghost::survey(s, p.first, last, &co)?;
435 let (mut written, mut warnings) = (Vec::new(), co.notes.clone());
436 if let Some(dir) = &p.out {
437 lensbench_core::vfs::create_dir_all(dir)
438 .map_err(|x| lensbench_core::Error::Io(format!("{}: {x}", dir.display())))?;
439 for g in &v {
440 let gs = crate::ghost::ghost_system(s, g.par.a, g.par.b)?;
441 let f = dir.join(format!("ghost_{}_{}.zmx", g.par.a, g.par.b));
442 warnings.extend(lensbench_formats::zmx_write::save(&f, &gs.sys)?);
443 written.push(f.display().to_string());
444 }
445 }
446 let ghosts = v
447 .iter()
448 .map(|g| {
449 let q = &g.par;
450 let (intensity, intensity_error) = match &g.intensity {
451 Ok(x) => (Some(*x), None),
452 Err(m) => (None, Some(m.to_string())),
453 };
454 GhostRow {
455 a: q.a,
456 b: q.b,
457 marginal_y: q.marginal_y,
458 marginal_u: q.marginal_u,
459 focus: q.focus.is_finite().then_some(q.focus),
460 wfno: q.wfno,
461 intensity,
462 intensity_error,
463 }
464 })
465 .collect();
466 Ok(GhostOut {
467 first: p.first,
468 last,
469 ghosts,
470 written,
471 warnings,
472 })
473 }
474}