1use lensbench_analysis::analysis::ZernKind;
36use lensbench_analysis::fiber::FiberOpts;
37use lensbench_analysis::sweep::RmsRef;
38use lensbench_core::seidel::DistComp;
39use lensbench_core::{FieldSel, System};
40use lensbench_optim::zplm::ZplmTerm;
41use lensbench_optim::{
42 CalcArg, CalcOp, CardQ, DistMode, Each, EdgeAxis, EnergyMethod, EnergyQ, Medium, MtfDir,
43 MtfKind, ParaxQ, Quad, RayQ, SeidelQ, Side, SpotAxis, SurfQ, Term, TermKind,
44};
45use serde_json::Value;
46
47use crate::term_spec::{
48 AxisName, CalcArgSpec, CalcName, DirName, EachName, EdgeAxisName, FieldRef, MacroRef,
49 MtfKindName, Nums, QuadName, RefName, RmsSpec, TermSpec, Xy, ZernName, ZplmSpec,
50};
51
52pub fn is_comment(v: &Value) -> bool {
54 v.get("type")
55 .and_then(Value::as_str)
56 .is_some_and(|t| t.eq_ignore_ascii_case("comment"))
57}
58
59pub fn terms_from_json(v: &Value, configs: &[System]) -> lensbench_core::Result<Vec<Term>> {
61 match v {
62 Value::Array(a) => a
63 .iter()
64 .enumerate()
65 .filter(|(_, t)| !is_comment(t))
66 .map(|(i, t)| {
67 term_from_json(t, configs)
68 .map_err(|e| e.map_message(|e| format!("term {}: {e}", i + 1)))
69 })
70 .collect(),
71 _ => Ok(vec![term_from_json(v, configs)?]),
72 }
73}
74
75fn field(f: FieldRef, s: &System) -> lensbench_core::Result<FieldSel> {
76 match f {
77 FieldRef::Norm([x, y]) => Ok(FieldSel::Norm(x, y)),
78 FieldRef::Index(i) if i >= 1 && i <= s.fields.len() => Ok(FieldSel::Index(i - 1)),
79 FieldRef::Index(i) => Err(format!("no field {i} (1 to {})", s.fields.len()).into()),
80 }
81}
82
83fn wave(w: Option<usize>, s: &System) -> lensbench_core::Result<Option<usize>> {
84 Ok(lensbench_core::waves::index_opt(w, s.wavelengths.len()).map_err(String::from)?)
85}
86
87fn reference(r: Option<RefName>) -> RmsRef {
88 match r.unwrap_or_default() {
89 RefName::Centroid => RmsRef::Centroid,
90 RefName::Chief => RmsRef::Chief,
91 }
92}
93
94fn quad(r: &RmsSpec) -> lensbench_core::Result<Quad> {
95 let q = r.quadrature.unwrap_or_default();
96 let pos = |k: &str, v: usize| -> lensbench_core::Result<usize> {
97 if v == 0 {
98 return Err(format!("{k} must be 1 or more").into());
99 }
100 Ok(v)
101 };
102 if r.arms.is_some() && !matches!(q, QuadName::Opticstudio) {
103 return Err("arms goes with quadrature opticstudio".to_string().into());
104 }
105 if r.n.is_some() && !matches!(q, QuadName::Grid) {
106 return Err("n goes with quadrature grid".to_string().into());
107 }
108 Ok(match (q, r.arms, r.n) {
109 (QuadName::Lensbench, ..) => Quad::Lensbench,
110 (QuadName::Opticstudio, None, _) => Quad::OpticStudio,
111 (QuadName::Opticstudio, Some(a), _) => Quad::Arms(pos("arms", a)?),
112 (QuadName::Grid, _, Some(n)) => Quad::Grid(pos("n", n)?),
113 (QuadName::Grid, _, None) => return Err("quadrature grid needs n".into()),
114 })
115}
116
117fn calc_kind(c: crate::term_spec::CalcSpec, s: &System) -> lensbench_core::Result<TermKind> {
119 let k = TermKind::Calc {
120 op: match c.op {
121 CalcName::Sum => CalcOp::Sum,
122 CalcName::Diff => CalcOp::Diff,
123 CalcName::Prod => CalcOp::Prod,
124 CalcName::Div => CalcOp::Div,
125 CalcName::Abs => CalcOp::Abs,
126 CalcName::Sqrt => CalcOp::Sqrt,
127 CalcName::Reci => CalcOp::Reci,
128 CalcName::Max => CalcOp::Max,
129 CalcName::Min => CalcOp::Min,
130 CalcName::Qsum => CalcOp::Qsum,
131 CalcName::Sin => CalcOp::Sin,
132 CalcName::Cos => CalcOp::Cos,
133 CalcName::Tan => CalcOp::Tan,
134 CalcName::Asin => CalcOp::Asin,
135 CalcName::Acos => CalcOp::Acos,
136 CalcName::Atan => CalcOp::Atan,
137 },
138 args: c
139 .args
140 .into_iter()
141 .map(|a| match a {
142 CalcArgSpec::Num(x) => Ok(CalcArg::Const(x)),
143 CalcArgSpec::Term(t) => Ok(CalcArg::Term(Box::new(kind_of(*t, s)?))),
144 })
145 .collect::<lensbench_core::Result<_>>()?,
146 target: c.target.unwrap_or(0.0),
147 };
148 if let TermKind::Calc { op, args, .. } = &k {
149 let (lo, hi) = op.arity();
150 if args.len() < lo || args.len() > hi {
151 let (op, n) = (op.name(), args.len());
152 if lo == hi {
153 return Err(format!("the {op} calc term takes {lo} arguments ({n})").into());
154 }
155 return Err(format!("the {op} calc term takes {lo} or more arguments ({n})").into());
156 }
157 if args
158 .iter()
159 .any(|a| matches!(a, CalcArg::Term(t) if t.target().is_none()))
160 {
161 return Err("an argument of a calc term must be a term with a single value".into());
162 }
163 }
164 Ok(k)
165}
166
167fn num(k: &str, v: &Value) -> lensbench_core::Result<f64> {
168 Ok(v.as_f64()
169 .ok_or_else(|| format!("{k} must be a number ({v})"))?)
170}
171
172pub fn term_from_json(v: &Value, configs: &[System]) -> lensbench_core::Result<Term> {
174 let mut m = v
175 .as_object()
176 .ok_or_else(|| format!("a term is an object {{\"type\": ...}} ({v})"))?
177 .clone();
178 m.retain(|_, x| !x.is_null());
179 let mut side = Side::Eq;
181 for (k, sd) in [("min", Side::Min), ("max", Side::Max)] {
182 if let Some(b) = m.remove(k) {
183 if side != Side::Eq || m.contains_key("target") {
184 return Err("exactly one of target, min and max".into());
185 }
186 m.insert("target".into(), b);
187 side = sd;
188 }
189 }
190 let weight = m.remove("weight").map_or(Ok(1.0), |x| num("weight", &x))?;
191 let config = match m.remove("config").map(|c| c.as_u64().ok_or(c)) {
192 None => 0,
193 Some(Ok(c)) if c >= 1 && c as usize <= configs.len() => c as usize - 1,
194 Some(Ok(c)) => return Err(format!("no configuration {c} (1 to {})", configs.len()).into()),
195 Some(Err(c)) => return Err(format!("config must be an integer 1 or more ({c})").into()),
196 };
197 if let Some(Value::String(t)) = m.get_mut("type") {
198 *t = t.to_ascii_lowercase();
199 }
200 let ty = m
201 .get("type")
202 .and_then(|t| t.as_str())
203 .unwrap_or("")
204 .to_string();
205 if ty.is_empty() {
206 return Err("no type".into());
207 }
208 const TYPES: [&str; 31] = [
209 "spot",
210 "wavefront",
211 "mtf",
212 "paraxial",
213 "ray",
214 "centroid",
215 "opd",
216 "zernike",
217 "coupling",
218 "thickness",
219 "surface",
220 "volume",
221 "tsag",
222 "bfs",
223 "cardinal",
224 "fnum",
225 "seidel",
226 "distortion",
227 "energy",
228 "strehl",
229 "param",
230 "illum",
231 "longitudinal",
232 "lateral_color",
233 "semi",
234 "zplm",
235 "plugin",
236 "calc",
237 "spread",
238 "diff",
239 "comment",
240 ];
241 if !TYPES.contains(&ty.as_str()) {
242 return Err(format!("type {ty} (one of {})", TYPES.join(", ")).into());
243 }
244 if side != Side::Eq && ["spot", "wavefront", "zplm", "plugin"].contains(&ty.as_str()) {
245 return Err(format!(
246 "{ty} terms can't use min or max (only terms with a single target value)"
247 )
248 .into());
249 }
250 let spec: TermSpec =
251 serde_json::from_value(Value::Object(m)).map_err(|e| format!("{ty} term: {e}"))?;
252 let s = configs.get(config).ok_or("no configurations")?;
253 let kind = kind_of(spec, s)?;
254 let single = matches!(
255 kind,
256 TermKind::Mtf {
257 dir: MtfDir::Tan | MtfDir::Sag | MtfDir::Avg,
258 ..
259 } | TermKind::Paraxial { .. }
260 | TermKind::Ray { .. }
261 | TermKind::RayPath { .. }
262 | TermKind::ParaxRay { .. }
263 | TermKind::Centroid { .. }
264 | TermKind::Opd { .. }
265 | TermKind::Zernike { .. }
266 | TermKind::Coupling { .. }
267 | TermKind::Thickness { .. }
268 | TermKind::Surface { .. }
269 | TermKind::Volume { .. }
270 | TermKind::Shape { .. }
271 | TermKind::Cardinal { .. }
272 | TermKind::FNum { .. }
273 | TermKind::Seidel { .. }
274 | TermKind::Distortion { .. }
275 | TermKind::Energy { .. }
276 | TermKind::Strehl { .. }
277 | TermKind::Param { .. }
278 | TermKind::Spread { .. }
279 | TermKind::Diff { .. }
280 | TermKind::Illum { .. }
281 | TermKind::Longitudinal { .. }
282 | TermKind::LateralColor { .. }
283 | TermKind::SurfEach { .. }
284 | TermKind::Calc { .. }
285 );
286 let mut kind = kind;
288 if let TermKind::Thickness { each: Some(e), .. } = &mut kind {
289 if side == Side::Eq {
290 return Err("a thickness term with each needs min or max".into());
291 }
292 e.upper = side == Side::Max;
293 }
294 if let TermKind::SurfEach { upper, .. } = &mut kind {
295 if side == Side::Eq {
296 return Err("a semi term or a surface term with to needs min or max".into());
297 }
298 *upper = side == Side::Max;
299 }
300 if let TermKind::RayPath {
302 q: RayQ::Aoi | RayQ::Aoe,
303 upper,
304 ..
305 } = &mut kind
306 {
307 if side == Side::Eq {
308 return Err("a ray term with to and aoi or aoe needs min or max".into());
309 }
310 *upper = Some(side == Side::Max);
311 }
312 if side != Side::Eq && !single {
313 return Err(format!(
314 "{ty} terms can't use min or max (only terms with a single target value)"
315 )
316 .into());
317 }
318 Ok(Term {
319 side,
320 config,
321 weight,
322 kind,
323 })
324}
325
326fn kind_of(spec: TermSpec, s: &System) -> lensbench_core::Result<TermKind> {
328 let user = |t: std::sync::Arc<dyn lensbench_optim::UserTerm>| {
329 TermKind::User(lensbench_optim::UserTermRef(t))
330 };
331 Ok(match spec {
332 TermSpec::Spot(r) => TermKind::Spot {
333 field: field(r.field, s)?,
334 wave: wave(r.wave, s)?,
335 rings: r.rings.unwrap_or(3),
336 reference: reference(r.reference),
337 quad: quad(&r)?,
338 axis: match r.axis.unwrap_or_default() {
339 AxisName::Xy => SpotAxis::Both,
340 AxisName::X => SpotAxis::X,
341 AxisName::Y => SpotAxis::Y,
342 },
343 },
344 TermSpec::Wavefront(r) => {
345 if r.axis.is_some() {
346 return Err("axis goes with spot".to_string().into());
347 }
348 TermKind::Wavefront {
349 field: field(r.field, s)?,
350 wave: wave(r.wave, s)?,
351 rings: r.rings.unwrap_or(3),
352 reference: reference(r.reference),
353 quad: quad(&r)?,
354 }
355 }
356 TermSpec::Mtf(t) => TermKind::Mtf {
357 field: field(t.field, s)?,
358 wave: wave(t.wave, s)?,
359 n: t.n,
360 freq: t.freq,
361 dir: match t.dir.unwrap_or_default() {
362 DirName::Tan => MtfDir::Tan,
363 DirName::Sag => MtfDir::Sag,
364 DirName::Both => MtfDir::Both,
365 DirName::Avg => MtfDir::Avg,
366 },
367 kind: match (t.kind.unwrap_or_default(), t.diff_limit) {
368 (MtfKindName::Geometric, d) => MtfKind::Geometric {
369 diff_limit: d.unwrap_or(true),
370 },
371 (_, Some(_)) => {
372 return Err("diff_limit of an mtf term goes with kind geometric"
373 .to_string()
374 .into())
375 }
376 (MtfKindName::Diffraction, None) => MtfKind::Diffraction,
377 (MtfKindName::Square, None) => MtfKind::SquareWave,
378 (MtfKindName::Huygens, None) => MtfKind::Huygens,
379 },
380 target: t.target.unwrap_or(1.0),
381 },
382 TermSpec::Paraxial(t) => TermKind::Paraxial {
383 q: ParaxQ::parse(&t.q)?,
384 wave: wave(t.wave, s)?,
385 target: t
386 .target
387 .ok_or("paraxial term has no target (or min and max)")?,
388 },
389 TermSpec::Ray(t) if t.paraxial == Some(true) => {
390 if t.to.is_some() {
391 return Err("to does not go with paraxial".to_string().into());
392 }
393 TermKind::ParaxRay {
394 field: field(t.field, s)?,
395 wave: wave(t.wave, s)?,
396 px: t.px.unwrap_or(0.0),
397 py: t.py.unwrap_or(0.0),
398 surf: t.surf.unwrap_or(s.image()),
399 q: RayQ::parse(&t.q)?,
400 target: t.target.unwrap_or(0.0),
401 }
402 }
403 TermSpec::Ray(t) => match t.to {
404 Some(to) => TermKind::RayPath {
405 field: field(t.field, s)?,
406 wave: wave(t.wave, s)?,
407 px: t.px.unwrap_or(0.0),
408 py: t.py.unwrap_or(0.0),
409 surf: t.surf.ok_or("to goes with surf")?,
410 to,
411 q: RayQ::parse(&t.q)?,
412 upper: None,
413 target: t.target.unwrap_or(0.0),
414 },
415 None => TermKind::Ray {
416 field: field(t.field, s)?,
417 wave: wave(t.wave, s)?,
418 px: t.px.unwrap_or(0.0),
419 py: t.py.unwrap_or(0.0),
420 surf: t.surf,
421 q: RayQ::parse(&t.q)?,
422 target: t.target.unwrap_or(0.0),
423 },
424 },
425 TermSpec::Centroid(t) => TermKind::Centroid {
426 field: field(t.field, s)?,
427 wave: wave(t.wave, s)?,
428 rings: t.rings.unwrap_or(3),
429 y: matches!(t.q, Xy::Y),
430 target: t.target.unwrap_or(0.0),
431 },
432 TermSpec::Opd(t) => TermKind::Opd {
433 field: field(t.field, s)?,
434 wave: wave(t.wave, s)?,
435 px: t.px.unwrap_or(0.0),
436 py: t.py.unwrap_or(0.0),
437 target: t.target.unwrap_or(0.0),
438 },
439 TermSpec::Zernike(t) => TermKind::Zernike {
440 field: field(t.field, s)?,
441 wave: wave(t.wave, s)?,
442 kind: match t.kind.unwrap_or_default() {
443 ZernName::Fringe => ZernKind::Fringe,
444 ZernName::Standard => ZernKind::Standard,
445 },
446 term: t.term,
447 fit: t.fit,
448 n: t.n.unwrap_or(64),
449 target: t.target.unwrap_or(0.0),
450 },
451 TermSpec::Coupling(t) => {
452 let d = FiberOpts::default();
453 let opts = FiberOpts {
454 na_source: t.na_source.or(t.na).unwrap_or(d.na_source),
455 na_receiver: t.na_receiver.or(t.na).unwrap_or(d.na_receiver),
456 source: t.source.unwrap_or(d.source),
457 receiver: t.receiver.unwrap_or(d.receiver),
458 grid: t.grid.unwrap_or(d.grid),
459 na_max: t.na_max,
460 clip_stop: t.clip_stop.unwrap_or(d.clip_stop),
461 };
462 TermKind::Coupling {
463 wave: wave(t.wave, s)?,
464 opts,
465 target: t.target.unwrap_or(1.0),
466 }
467 }
468 TermSpec::Thickness(t) => {
469 let zone = t.zone.unwrap_or(1.0);
470 if t.zone.is_some() && t.edge != Some(true) {
471 return Err("zone goes with edge".to_string().into());
472 }
473 if t.clear.is_some() && t.edge != Some(true) {
474 return Err("clear goes with edge".to_string().into());
475 }
476 if t.axis.is_some() && t.edge != Some(true) {
477 return Err("axis goes with edge".to_string().into());
478 }
479 if !(zone > 0.0 && zone <= 1.0) {
480 return Err(format!("zone {zone} (more than 0, up to 1)").into());
481 }
482 TermKind::Thickness {
483 surf: t.surf,
484 to: t.to.unwrap_or(t.surf),
485 target: t.target.unwrap_or(0.0),
486 edge: (t.edge == Some(true)).then_some(zone),
487 clear: t.clear == Some(true),
488 axis: match t.axis {
489 None | Some(EdgeAxisName::PosY) => EdgeAxis::PosY,
490 Some(EdgeAxisName::PosX) => EdgeAxis::PosX,
491 Some(EdgeAxisName::NegY) => EdgeAxis::NegY,
492 Some(EdgeAxisName::NegX) => EdgeAxis::NegX,
493 },
494 each: t.each.map(|e| Each {
495 medium: match e {
496 EachName::All => Medium::All,
497 EachName::Air => Medium::Air,
498 EachName::Glass => Medium::Glass,
499 },
500 upper: false,
501 }),
502 }
503 }
504 TermSpec::Surface(t) => {
505 let mut q = SurfQ::parse(&t.q)?;
506 if (t.x.is_some() || t.y.is_some())
507 && !matches!(
508 q,
509 SurfQ::Sag | SurfQ::Thick | SurfQ::Total | SurfQ::TotalClear
510 )
511 {
512 return Err("x and y go with sag, thick, total and total_clear"
513 .to_string()
514 .into());
515 }
516 match (q, t.param) {
517 (SurfQ::Parm(_), Some(n)) => q = SurfQ::Parm(n),
518 (SurfQ::Parm(_), None) => {
519 return Err("q param needs param (the parameter number)"
520 .to_string()
521 .into())
522 }
523 (_, Some(_)) => return Err("param goes with q param".to_string().into()),
524 _ => {}
525 }
526 if let Some(to) = t.to {
527 if t.wave.is_some() || t.x.is_some() || t.y.is_some() {
528 return Err("a surface term with to has no wave, x or y"
529 .to_string()
530 .into());
531 }
532 return Ok(TermKind::SurfEach {
533 q,
534 surf: t.surf,
535 to,
536 upper: false,
537 target: t.target.ok_or("surface term with to has no min or max")?,
538 });
539 }
540 if q == SurfQ::Semi {
541 return Err("q semi goes with to (or use the semi term)"
542 .to_string()
543 .into());
544 }
545 TermKind::Surface {
546 surf: t.surf,
547 q,
548 x: t.x.unwrap_or(0.0),
549 y: t.y.unwrap_or(0.0),
550 wave: wave(t.wave, s)?,
551 target: t
552 .target
553 .ok_or("surface term has no target (or min and max)")?,
554 }
555 }
556 TermSpec::Volume(t) => TermKind::Volume {
557 surf: t.surf,
558 to: t.to.unwrap_or(t.surf),
559 mass: t.mass.unwrap_or(false),
560 clear: t.clear.unwrap_or(false),
561 cylinder: t.cylinder.unwrap_or(false),
562 target: t
563 .target
564 .ok_or("volume term has no target (or min and max)")?,
565 },
566 TermSpec::Tsag(t) => TermKind::Shape {
567 surf: t.surf,
568 q: lensbench_optim::ShapeQ::Tsag {
569 p: t.point.unwrap_or([0.0; 3]),
570 tilt: t.tilt.unwrap_or([0.0; 3]),
571 flat: t.flat.unwrap_or(false),
572 },
573 target: t.target.ok_or("tsag term has no target (or min and max)")?,
574 },
575 TermSpec::Bfs(t) => TermKind::Shape {
576 surf: t.surf,
577 q: lensbench_optim::ShapeQ::Bfs {
578 data: lensbench_optim::BfsData::parse(&t.q).ok_or_else(|| {
579 format!(
580 "bfs q {} ({})",
581 t.q,
582 lensbench_optim::BfsData::ALL.map(|d| d.name()).join(", ")
583 )
584 })?,
585 rmin: t.rmin.unwrap_or(0.0),
586 rmax: t.rmax.unwrap_or(0.0),
587 },
588 target: t.target.ok_or("bfs term has no target (or min and max)")?,
589 },
590 TermSpec::Cardinal(t) => {
591 let last = (1..s.image())
592 .rev()
593 .find(|&j| !s.surfaces[j].ignore)
594 .unwrap_or(1);
595 TermKind::Cardinal {
596 from: t.from.unwrap_or(1),
597 to: t.to.unwrap_or(last),
598 q: CardQ::parse(&t.q)?,
599 wave: wave(t.wave, s)?,
600 target: t
601 .target
602 .ok_or("cardinal term has no target (or min and max)")?,
603 }
604 }
605 TermSpec::Fnum(t) => TermKind::FNum {
606 field: field(t.field, s)?,
607 wave: wave(t.wave, s)?,
608 sag: match t.dir {
609 None | Some(DirName::Tan) => false,
610 Some(DirName::Sag) => true,
611 Some(DirName::Both | DirName::Avg) => {
612 return Err("dir of an fnum term is tan or sag".to_string().into())
613 }
614 },
615 target: t.target.ok_or("fnum term has no target (or min and max)")?,
616 },
617 TermSpec::Seidel(t) => TermKind::Seidel {
618 surf: t.surf.unwrap_or(0),
619 q: SeidelQ::parse(&t.q)?,
620 wave: wave(t.wave, s)?,
621 target: t
622 .target
623 .ok_or("seidel term has no target (or min and max)")?,
624 },
625 TermSpec::Energy(t) => {
626 use lensbench_analysis::energy::{EnergyCenter, EnergyShape};
627 let airy = t.airy.unwrap_or(false);
628 let method = match t.method.as_deref().unwrap_or("geometric") {
629 "geometric" => EnergyMethod::Geometric { airy },
630 m @ ("fft" | "huygens") => {
631 if airy {
632 return Err("airy of an energy term goes with method geometric"
633 .to_string()
634 .into());
635 }
636 if m == "fft" {
637 EnergyMethod::Fft
638 } else {
639 EnergyMethod::Huygens
640 }
641 }
642 m => return Err(format!("energy method {m} (geometric, fft or huygens)").into()),
643 };
644 let shape = match t.shape.as_deref().unwrap_or("circle") {
645 "circle" => EnergyShape::Circle,
646 "x" => EnergyShape::X,
647 "y" => EnergyShape::Y,
648 "square" => EnergyShape::Square,
649 v => return Err(format!("energy shape {v} (circle, x, y or square)").into()),
650 };
651 let center = match t.center.as_deref().unwrap_or("chief") {
652 "chief" => EnergyCenter::Chief,
653 "centroid" => EnergyCenter::Centroid,
654 "vertex" => EnergyCenter::Vertex,
655 "middle" => EnergyCenter::Middle,
656 v => {
657 return Err(
658 format!("energy center {v} (chief, centroid, vertex or middle)").into(),
659 )
660 }
661 };
662 let q = match (t.size_at, t.fraction_at) {
663 (Some(f), None) => EnergyQ::Size(f),
664 (None, Some(r)) => EnergyQ::Fraction(r),
665 _ => {
666 return Err("an energy term needs one of size_at and fraction_at"
667 .to_string()
668 .into())
669 }
670 };
671 TermKind::Energy {
672 field: field(t.field, s)?,
673 wave: wave(t.wave, s)?,
674 n: t.n,
675 method,
676 shape,
677 center,
678 q,
679 target: t
680 .target
681 .ok_or("energy term has no target (or min and max)")?,
682 }
683 }
684 TermSpec::Param(t) => TermKind::Param {
685 param: s.param(&t.name)?,
686 target: t
687 .target
688 .ok_or("param term has no target (or min and max)")?,
689 },
690 TermSpec::Strehl(t) => TermKind::Strehl {
691 field: field(t.field, s)?,
692 wave: wave(t.wave, s)?,
693 n: t.n,
694 target: t
695 .target
696 .ok_or("strehl term has no target (or min and max)")?,
697 },
698 TermSpec::Illum(t) => TermKind::Illum {
699 field: field(t.field, s)?,
700 wave: wave(t.wave, s)?,
701 n: t.n,
702 relative: match t.q.as_str() {
703 "relative" => true,
704 "fno" => false,
705 q => return Err(format!("illum q {q} (relative or fno)").into()),
706 },
707 target: t
708 .target
709 .ok_or("illum term has no target (or min and max)")?,
710 },
711 TermSpec::Distortion(t) => TermKind::Distortion {
712 wave: wave(t.wave, s)?,
713 absolute: t.absolute.unwrap_or(false),
714 field: t.field.map(|f| field(f, s)).transpose()?,
715 reference: t.reference.map(|f| field(f, s)).transpose()?,
716 abcd: t.abcd,
717 component: match t.component.as_deref().unwrap_or("radial") {
718 "radial" => DistComp::Radial,
719 "x" => DistComp::X,
720 "y" => DistComp::Y,
721 c => return Err(format!("distortion component {c} (radial, x, y)").into()),
722 },
723 mode: match (t.peak.unwrap_or(false), t.ftheta.unwrap_or(false)) {
724 _ if t.coef.is_some()
725 && (t.peak == Some(true) || t.ftheta == Some(true) || t.abcd.is_some()) =>
726 {
727 return Err("a distortion coefficient term has no peak, ftheta or abcd".into())
728 }
729 _ if t.coef.is_some() => match t.coef.as_deref().unwrap_or("") {
730 "a" => DistMode::Coef(0),
731 "b" => DistMode::Coef(1),
732 "c" => DistMode::Coef(2),
733 "d" => DistMode::Coef(3),
734 c => return Err(format!("distortion coefficient {c} (a, b, c, d)").into()),
735 },
736 (_, _) if t.abcd.is_some() && (t.peak == Some(true) || t.ftheta == Some(true)) => {
737 return Err("a distortion term with abcd has no peak or ftheta".into())
738 }
739 (false, false) => DistMode::At,
740 (true, false) if t.reference.is_none() => DistMode::Max,
741 (false, true) if t.field.is_none() && t.reference.is_none() => DistMode::FTheta,
742 (true, false) => {
743 return Err("a peak distortion term is against the axis (no reference)".into())
744 }
745 _ => {
746 return Err("an f-theta distortion term has no field, reference or peak".into())
747 }
748 },
749 target: t
750 .target
751 .ok_or("distortion term has no target (or min and max)")?,
752 },
753 TermSpec::Longitudinal(t) => TermKind::Longitudinal {
754 wave: wave(t.wave, s)?,
755 wave2: wave(t.wave2, s)?,
756 zone: t.zone.unwrap_or(0.0),
757 target: t
758 .target
759 .ok_or("longitudinal term has no target (or min and max)")?,
760 },
761 TermSpec::LateralColor(t) => TermKind::LateralColor {
762 wave: wave(t.wave, s)?,
763 wave2: wave(Some(t.wave2), s)?.unwrap_or(s.primary),
764 target: t
765 .target
766 .ok_or("lateral_color term has no target (or min and max)")?,
767 },
768 TermSpec::Semi(t) => TermKind::SurfEach {
769 q: SurfQ::Semi,
770 surf: t.surf,
771 to: t.to.unwrap_or(t.surf),
772 upper: false,
773 target: t.target.ok_or("semi term has no min or max")?,
774 },
775 TermSpec::Calc(c) => calc_kind(c, s)?,
776 TermSpec::Spread(t) => {
777 let inner = kind_of(*t.term, s)?;
778 if inner.target().is_none() || matches!(inner, TermKind::Spread { .. }) {
779 return Err("the term of a spread term must be a term with a single value".into());
780 }
781 TermKind::Spread {
782 term: Box::new(inner),
783 target: t
784 .target
785 .ok_or("spread term has no target (or min and max)")?,
786 }
787 }
788 TermSpec::Diff(t) => {
789 let inner = kind_of(*t.term, s)?;
790 if inner.target().is_none()
791 || matches!(inner, TermKind::Spread { .. } | TermKind::Diff { .. })
792 {
793 return Err(
794 "the term of a difference term must be a term with a single value".into(),
795 );
796 }
797 if t.a == 0 || t.b == 0 {
798 return Err("difference term: a and b are configuration numbers from 1".into());
799 }
800 TermKind::Diff {
801 a: t.a - 1,
802 b: t.b - 1,
803 term: Box::new(inner),
804 target: t.target.unwrap_or(0.0),
805 }
806 }
807 TermSpec::Comment(_) => {
808 return Err("a comment is not a term (it is skipped in a list of terms)".into())
809 }
810 TermSpec::Zplm(t) => {
811 let m = zplm_macro(&t, s)?;
812 let pv = [t.hx, t.hy, t.px, t.py].map(|x| x.unwrap_or(0.0));
813 let data = t.data.unwrap_or(0);
814 let z = ZplmTerm::new(&m, data, pv, t.target.unwrap_or(0.0))?;
815 user(std::sync::Arc::new(z))
816 }
817 TermSpec::Plugin(t) => {
818 if t.name.is_empty() {
819 return Err("no name (the plugin name)".into());
820 }
821 let args = crate::plugin_term::config_of(t.args.as_ref())?;
822 let mut inputs = crate::plugin_term::arrays_of(t.inputs.as_ref())?;
823 if let Some(f) = &t.field {
824 if inputs.contains_key("field") {
825 return Err("only one of field and the field in inputs".into());
826 }
827 inputs.insert("field".into(), crate::plugin_term::array_of("field", f)?);
828 }
829 if t.output.is_empty() {
830 return Err("no output (the output name)".into());
831 }
832 let target = match t.target {
833 None => vec![],
834 Some(Nums::One(x)) => vec![x],
835 Some(Nums::Many(v)) => v,
836 };
837 let p = crate::plugin_term::PluginTerm::new(
838 &t.name, &args, inputs, &t.output, t.index, target, s,
839 )?;
840 user(std::sync::Arc::new(p))
841 }
842 })
843}
844
845fn zplm_macro(
847 t: &ZplmSpec,
848 s: &System,
849) -> lensbench_core::Result<lensbench_core::zpl_solve::Macro> {
850 use lensbench_core::zpl_solve::{find_macro, macro_dirs, Macro};
851 use std::path::{Path, PathBuf};
852 if let Some(f) = &t.file {
853 if t.macro_.is_some() {
854 return Err("only one of macro and file".into());
855 }
856 let p = Path::new(f);
857 let src =
858 lensbench_core::vfs::read(p).map_err(lensbench_core::Error::io_at(f.to_string()))?;
859 let name = p
860 .file_stem()
861 .map(|x| x.to_string_lossy().into_owned())
862 .unwrap_or_default();
863 let mut m = Macro::from_source(&name, &String::from_utf8_lossy(&src))?;
864 m.path = p.to_path_buf();
865 return Ok(m);
866 }
867 let name = match &t.macro_ {
868 None => return Err("no macro (number or name) or file".into()),
869 Some(MacroRef::Name(n)) => n.clone(),
870 Some(MacroRef::No(n)) if *n <= 99 => format!("ZPL{n:02}"),
871 Some(MacroRef::No(n)) => {
872 return Err(format!("macro must be a number 0 to 99 or a name ({n})").into())
873 }
874 };
875 let extra: Vec<PathBuf> = t.macro_dirs.iter().flatten().map(PathBuf::from).collect();
876 if !extra.is_empty() {
877 if let Ok(m) = find_macro(&name, &extra) {
878 return Ok(m);
879 }
880 }
881 if let Some(m) = s.macros.iter().find(|m| m.name.eq_ignore_ascii_case(&name)) {
882 return Ok(m.clone());
883 }
884 if !t.default_dirs.unwrap_or(true) {
885 return find_macro(&name, &extra);
886 }
887 let mut dirs = macro_dirs(&extra, None);
888 dirs.push(PathBuf::from("."));
889 find_macro(&name, &dirs)
890}
891
892#[cfg(test)]
893mod tests {
894 use super::*;
895
896 fn sys() -> System {
897 let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
898 lensbench_formats::zmx::load_with(
899 &root.join("tests/refs/A0/system.zmx"),
900 &lensbench_formats::zmx::LoadOptions {
901 cfg: 1,
902 catalog_dirs: vec![root.join("tests/glass")],
903 ..Default::default()
904 },
905 )
906 .unwrap()
907 }
908
909 #[test]
910 fn parse_terms() {
911 let s = sys();
912 let v: Value = serde_json::from_str(
913 r#"[
914 {"type": "ray", "field": 1, "py": 1, "q": "y", "target": 0.1, "weight": 2},
915 {"type": "paraxial", "q": "EFFL", "target": 50},
916 {"type": "opd", "field": [0, 0.5], "wave": 1, "px": 0.5},
917 {"type": "zernike", "field": 1, "term": 9},
918 {"type": "spot", "field": 1, "wave": null, "reference": "chief"},
919 {"type": "mtf", "field": 1, "freq": 30, "dir": "tan"}
920 ]"#,
921 )
922 .unwrap();
923 let t = terms_from_json(&v, std::slice::from_ref(&s)).unwrap();
924 assert_eq!(t.len(), 6);
925 assert_eq!(t[0].weight, 2.0);
926 assert_eq!(
927 t[0].kind,
928 TermKind::Ray {
929 field: FieldSel::Index(0),
930 wave: None,
931 px: 0.0,
932 py: 1.0,
933 surf: None,
934 q: RayQ::Y,
935 target: 0.1
936 }
937 );
938 assert_eq!(
939 t[1].kind,
940 TermKind::Paraxial {
941 q: ParaxQ::Efl,
942 wave: None,
943 target: 50.0
944 }
945 );
946 assert!(matches!(
947 t[2].kind,
948 TermKind::Opd {
949 field: FieldSel::Norm(_, _),
950 wave: Some(0),
951 ..
952 }
953 ));
954 assert!(matches!(t[5].kind, TermKind::Mtf { target, .. } if target == 1.0));
955 let w = serde_json::json!({"type": "spot", "field": 1, "quadrature": "opticstudio", "arms": 6, "axis": "y"});
957 assert!(matches!(
958 term_from_json(&w, std::slice::from_ref(&s)).unwrap().kind,
959 TermKind::Spot {
960 quad: Quad::Arms(6),
961 axis: SpotAxis::Y,
962 ..
963 }
964 ));
965 let w = serde_json::json!({"type": "wavefront", "field": 1, "quadrature": "grid", "n": 4});
966 assert!(matches!(
967 term_from_json(&w, std::slice::from_ref(&s)).unwrap().kind,
968 TermKind::Wavefront {
969 quad: Quad::Grid(4),
970 ..
971 }
972 ));
973 let mut p = lensbench_optim::Problem::single(s.clone());
974 p.terms = t;
975 p.check().unwrap();
976 for bad in [
978 r#"{"type": "ray", "field": 1, "q": "y", "taget": 1}"#,
979 r#"{"type": "ray", "field": 9, "q": "y"}"#,
980 r#"{"type": "paraxial", "q": "foo", "target": 1}"#,
981 r#"{"type": "nope"}"#,
982 r#"{"field": 1}"#,
983 r#"{"type": "spot", "field": 1, "arms": 6}"#,
984 r#"{"type": "spot", "field": 1, "quadrature": "opticstudio", "arms": 0}"#,
985 r#"{"type": "spot", "field": 1, "quadrature": "grid"}"#,
986 r#"{"type": "spot", "field": 1, "n": 4}"#,
987 r#"{"type": "wavefront", "field": 1, "axis": "x"}"#,
988 r#"{"type": "calc", "op": "diff", "args": [1]}"#,
989 r#"{"type": "calc", "op": "abs", "args": [{"type": "spot", "field": 1}]}"#,
990 r#"{"type": "calc", "op": "sum", "args": []}"#,
991 r#"{"type": "calc", "op": "sum", "args": [{"type": "paraxial", "q": "efl", "target": 0, "weight": 2}]}"#,
992 r#"{"type": "thickness", "surf": 1, "to": 3, "each": "air", "target": 1}"#,
993 r#"{"type": "thickness", "surf": 1, "zone": 0.5, "target": 1}"#,
994 r#"{"type": "thickness", "surf": 1, "edge": true, "zone": 0, "target": 1}"#,
995 r#"{"type": "ray", "field": 1, "to": 3, "q": "opth"}"#,
996 r#"{"type": "ray", "field": 1, "surf": 1, "to": 3, "paraxial": true, "q": "y"}"#,
997 r#"{"type": "ray", "field": 1, "surf": 1, "to": 3, "q": "aoi", "target": 10}"#,
998 r#"{"type": "cardinal", "q": "focal", "target": 0}"#,
999 r#"{"type": "cardinal", "q": "efl"}"#,
1000 r#"{"type": "fnum", "field": 1, "dir": "both", "target": 3}"#,
1001 r#"{"type": "fnum", "field": 1}"#,
1002 r#"{"type": "seidel", "q": "petz", "target": 0}"#,
1003 r#"{"type": "distortion"}"#,
1004 r#"{"type": "longitudinal", "zone": 0.5}"#,
1005 r#"{"type": "lateral_color", "target": 0}"#,
1006 r#"{"type": "semi", "surf": 1, "target": 5}"#,
1007 ] {
1008 let v: Value = serde_json::from_str(bad).unwrap();
1009 assert!(
1010 term_from_json(&v, std::slice::from_ref(&s)).is_err(),
1011 "{bad}"
1012 );
1013 }
1014 }
1015
1016 #[test]
1018 fn mirror_terms_rejected() {
1019 let raw = lensbench_formats::zmx::parse_text(
1020 "VERS 260327 42\nMODE SEQ\nUNIT MM X W X CM MR CPMM\nENPD 8\nFTYP 0 0 1 1 0 0 0\n\
1021YFLN 0\nFWGN 1\nWAVM 1 0.5876 1\nPWAV 1\nSURF 0\n TYPE STANDARD\n CURV 0.0\n DISZ INFINITY\n\
1022SURF 1\n STOP\n TYPE STANDARD\n CURV -0.01\n DISZ -50\n GLAS MIRROR 0 0 1.5 40 0 0 0 0 0 0\n\
1023SURF 2\n TYPE STANDARD\n CURV 0.0\n DISZ 0\n",
1024 )
1025 .unwrap();
1026 let s = lensbench_formats::zmx::build(&raw, &Default::default(), &[], None).unwrap();
1027 let check = |v: Value| {
1028 let mut p = lensbench_optim::Problem::single(s.clone());
1029 p.terms = terms_from_json(&serde_json::json!([v]), std::slice::from_ref(&s)).unwrap();
1030 p.check()
1031 };
1032 for v in [
1033 serde_json::json!({"type": "paraxial", "q": "petc", "target": 0}),
1034 serde_json::json!({"type": "paraxial", "q": "petz", "target": 0}),
1035 serde_json::json!({"type": "paraxial", "q": "linv", "target": 0}),
1036 serde_json::json!({"type": "surface", "surf": 1, "q": "power", "target": 0}),
1037 serde_json::json!({"type": "surface", "surf": 2, "q": "ynip", "target": 0}),
1038 ] {
1039 assert!(check(v.clone()).is_err(), "{v}");
1040 }
1041 check(serde_json::json!({"type": "paraxial", "q": "efl", "target": 0})).unwrap();
1042 }
1043
1044 #[test]
1045 fn zplm_term() {
1046 let s = sys();
1047 let d = std::env::temp_dir().join(format!("lb_zplm_{}", std::process::id()));
1048 lensbench_core::vfs::create_dir_all(&d).unwrap();
1049 lensbench_core::vfs::write(d.join("ZPL07.ZPL"), "OPTRETURN 2, THIC(1) + PVHY()\n").unwrap();
1050 lensbench_core::vfs::write(d.join("lbEfl.zpl"), "OPTRETURN 0, CURV(1)\n").unwrap();
1051 let dirs = d.to_string_lossy().into_owned();
1052 let v = serde_json::json!([
1053 {"type": "zplm", "macro": 7, "data": 2, "hy": 0.5, "target": 1.0, "macro_dirs": [dirs], "weight": 3},
1054 {"type": "zplm", "file": d.join("lbEfl.zpl").to_string_lossy()}
1055 ]);
1056 let t = terms_from_json(&v, std::slice::from_ref(&s)).unwrap();
1057 assert_eq!(t[0].weight, 3.0);
1058 let mut p = lensbench_optim::Problem::single(s.clone());
1059 p.terms = t;
1060 p.check().unwrap();
1061 let r = p.residuals(&[]).unwrap();
1062 let want = [3f64.sqrt() * (s.surfaces[1].t + 0.5 - 1.0), s.surfaces[1].c];
1063 assert!((r[0] - want[0]).abs() < 1e-14 && r[1] == want[1], "{r:?}");
1064 for bad in [
1066 serde_json::json!({"type": "zplm"}),
1067 serde_json::json!({"type": "zplm", "macro": 100}),
1068 serde_json::json!({"type": "zplm", "macro": "NOPE_NOT_THERE"}),
1069 serde_json::json!({"type": "zplm", "macro": 7, "field": 1, "macro_dirs": [dirs]}),
1070 serde_json::json!({"type": "zplm", "macro": 7, "default_dirs": false}),
1071 ] {
1072 assert!(
1073 term_from_json(&bad, std::slice::from_ref(&s)).is_err(),
1074 "{bad}"
1075 );
1076 }
1077 }
1078
1079 #[test]
1080 fn plugin_term() {
1081 let s = sys();
1082 let v = serde_json::json!([
1083 {"type": "plugin", "name": "rms", "field": 1, "output": "wfe", "args": {"rings": 4}},
1084 {"type": "plugin", "name": "rms", "inputs": {"field": [0.0, 1.0]}, "output": "wfe", "target": 1e-3, "weight": 4},
1085 {"type": "plugin", "name": "zernike", "field": 1, "output": "coef", "args": {"terms": 9}, "index": 3}
1086 ]);
1087 let t = terms_from_json(&v, std::slice::from_ref(&s)).unwrap();
1088 let mut p = lensbench_optim::Problem::single(s.clone());
1089 p.terms = t;
1090 p.check().unwrap();
1091 let r = p.residuals(&[]).unwrap();
1092 assert_eq!(r.len(), 3);
1093 let reg = crate::plugins::builtin();
1094 let ctx_sys = std::sync::Arc::new(s.clone());
1095 let ctx = lensbench_core::plugin::Context::with_system(&ctx_sys);
1096 let f1 = lensbench_core::plugin::Arrays::from([(
1097 "field".into(),
1098 lensbench_core::plugin::Array::scalar(1.0),
1099 )]);
1100 let cfg = |k: &str, x: f64| {
1101 lensbench_core::plugin::Config::from([(
1102 k.to_string(),
1103 lensbench_core::plugin::Value::Num(x),
1104 )])
1105 };
1106 let wfe = reg
1107 .prepare("rms", &cfg("rings", 4.0))
1108 .unwrap()
1109 .run(&ctx, &f1)
1110 .unwrap()["wfe"]
1111 .as_f64()
1112 .unwrap()[0];
1113 assert_eq!(r[0], wfe);
1114 let z = reg
1115 .prepare("zernike", &cfg("terms", 9.0))
1116 .unwrap()
1117 .run(&ctx, &f1)
1118 .unwrap()["coef"]
1119 .as_f64()
1120 .unwrap()[3];
1121 assert_eq!(r[2], z);
1122 let fn1 = lensbench_core::plugin::Arrays::from([(
1123 "field".into(),
1124 lensbench_core::plugin::Array::f64(vec![2], vec![0.0, 1.0]).unwrap(),
1125 )]);
1126 let a = reg
1127 .prepare("rms", &lensbench_core::plugin::Config::new())
1128 .unwrap()
1129 .run(&ctx, &fn1)
1130 .unwrap()["wfe"]
1131 .as_f64()
1132 .unwrap()[0];
1133 assert!((r[1] - 2.0 * (a - 1e-3)).abs() < 1e-15);
1134 for bad in [
1136 serde_json::json!({"type": "plugin", "name": "nope", "field": 1, "output": "x"}),
1137 serde_json::json!({"type": "plugin", "name": "rms", "field": 1}),
1138 serde_json::json!({"type": "plugin", "name": "rms", "field": 1, "output": "nope"}),
1139 serde_json::json!({"type": "plugin", "name": "rms", "output": "wfe"}),
1140 serde_json::json!({"type": "plugin", "name": "rms", "field": 1, "output": "wfe", "target": [1, 2]}),
1141 serde_json::json!({"type": "plugin", "name": "rms", "field": 1, "inputs": {"field": 1}, "output": "wfe"}),
1142 ] {
1143 assert!(
1144 term_from_json(&bad, std::slice::from_ref(&s)).is_err(),
1145 "{bad}"
1146 );
1147 }
1148 }
1149}