1use crate::error::Result;
4use crate::linalg::Lu;
5use crate::param::{Kind, Param};
6use crate::surface::{After, SurfType};
7use crate::system::{Keep, System};
8use crate::{invalid, notimpl};
9
10#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
12#[serde(tag = "type", rename_all = "snake_case")]
13#[derive(schemars::JsonSchema)]
14pub enum SolveKind {
15 MarginalHeight { height: f64 },
17 MarginalHeightZone { height: f64, zone: f64 },
19 ChiefHeight { height: f64 },
21 Opd { opd: f64, zone: f64 },
24 PupilPosition,
26 Edge { thickness: f64, radius: f64 },
28 Position { other: usize, length: f64 },
31 Compensator { other: usize, sum: f64 },
33 CenterOfCurvature { other: usize },
35 MarginalAngle { angle: f64 },
37 ChiefAngle { angle: f64 },
39 MarginalNormal,
41 ChiefNormal,
43 Aplanatic,
45 ElementPower { power: f64 },
47 ConcentricSurface { other: usize },
49 ConcentricRadius { other: usize },
51 FNumber { fnum: f64 },
53 MacroCurv { index: u16 },
55 MacroThick { index: u16 },
57}
58
59impl Default for SolveKind {
60 fn default() -> SolveKind {
61 SolveKind::MarginalHeight { height: 0.0 }
62 }
63}
64
65impl SolveKind {
66 pub fn is_curv(&self) -> bool {
68 matches!(
69 self,
70 SolveKind::MarginalAngle { .. }
71 | SolveKind::ChiefAngle { .. }
72 | SolveKind::MarginalNormal
73 | SolveKind::ChiefNormal
74 | SolveKind::Aplanatic
75 | SolveKind::ElementPower { .. }
76 | SolveKind::ConcentricSurface { .. }
77 | SolveKind::ConcentricRadius { .. }
78 | SolveKind::FNumber { .. }
79 | SolveKind::MacroCurv { .. }
80 )
81 }
82
83 pub fn param_kind(&self) -> Kind {
85 if self.is_curv() {
86 Kind::Curv
87 } else {
88 Kind::Thick
89 }
90 }
91
92 pub fn other_surface(&self) -> Option<usize> {
94 match *self {
95 SolveKind::Position { other, .. }
96 | SolveKind::Compensator { other, .. }
97 | SolveKind::CenterOfCurvature { other }
98 | SolveKind::ConcentricSurface { other }
99 | SolveKind::ConcentricRadius { other } => Some(other),
100 _ => None,
101 }
102 }
103
104 pub fn with_other_surface(mut self, s: usize) -> SolveKind {
106 match &mut self {
107 SolveKind::Position { other, .. }
108 | SolveKind::Compensator { other, .. }
109 | SolveKind::CenterOfCurvature { other }
110 | SolveKind::ConcentricSurface { other }
111 | SolveKind::ConcentricRadius { other } => *other = s,
112 _ => {}
113 }
114 self
115 }
116
117 pub fn value(&self) -> f64 {
119 match *self {
120 SolveKind::MarginalHeight { height }
121 | SolveKind::MarginalHeightZone { height, .. }
122 | SolveKind::ChiefHeight { height } => height,
123 SolveKind::Opd { opd, .. } => opd,
124 SolveKind::Edge { thickness, .. } => thickness,
125 SolveKind::Position { length, .. } => length,
126 SolveKind::Compensator { sum, .. } => sum,
127 SolveKind::MarginalAngle { angle } | SolveKind::ChiefAngle { angle } => angle,
128 SolveKind::ElementPower { power } => power,
129 SolveKind::FNumber { fnum } => fnum,
130 _ => 0.0,
131 }
132 }
133
134 pub fn with_value(mut self, v: f64) -> SolveKind {
136 match &mut self {
137 SolveKind::MarginalHeight { height }
138 | SolveKind::MarginalHeightZone { height, .. }
139 | SolveKind::ChiefHeight { height } => *height = v,
140 SolveKind::Opd { opd, .. } => *opd = v,
141 SolveKind::Edge { thickness, .. } => *thickness = v,
142 SolveKind::Position { length, .. } => *length = v,
143 SolveKind::Compensator { sum, .. } => *sum = v,
144 SolveKind::MarginalAngle { angle } | SolveKind::ChiefAngle { angle } => *angle = v,
145 SolveKind::ElementPower { power } => *power = v,
146 SolveKind::FNumber { fnum } => *fnum = v,
147 _ => {}
148 }
149 self
150 }
151}
152
153#[derive(
155 Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
156)]
157pub struct Solve {
158 pub surf: usize,
159 #[serde(flatten)]
160 pub kind: SolveKind,
161}
162
163impl System {
164 pub(crate) fn drop_unsolvable_on_load(&mut self) {
171 let is_macro = |k: &SolveKind| {
172 matches!(
173 k,
174 SolveKind::MacroCurv { .. } | SolveKind::MacroThick { .. }
175 )
176 };
177 let n = self.solves.len();
178 let with = |keep: &[bool]| {
179 let mut c = self.clone();
180 let mut i = 0;
181 let r = c.rx_mut();
182 r.solves.retain(|_| {
183 i += 1;
184 keep[i - 1]
185 });
186 r.macro_parms.clear();
187 c
188 };
189 let plain: Vec<bool> = self.solves.iter().map(|q| !is_macro(&q.kind)).collect();
190 if !plain.contains(&true) || with(&plain).solve_thickness().is_ok() {
191 return;
192 }
193 let mut keep = vec![false; n];
194 if with(&keep).solve_thickness().is_err() {
195 return;
196 }
197 let mut notes = Vec::new();
198 for j in 0..n {
199 if !plain[j] {
200 continue;
201 }
202 keep[j] = true;
203 if let Err(e) = with(&keep).solve_thickness() {
204 keep[j] = false;
205 let q = &self.solves[j];
206 let what = if q.kind.is_curv() {
207 "curvature"
208 } else {
209 "thickness"
210 };
211 let (kind, k) = (solve_kind_info(q.kind).0, q.surf);
212 notes.push(format!(
213 "removed the {what} solve {kind} of surface {k} and fixed the saved value: can't solve it ({e})"
214 ));
215 }
216 }
217 let mut i = 0;
219 let r = self.rx_mut();
220 r.solves.retain(|q| {
221 i += 1;
222 keep[i - 1] || is_macro(&q.kind)
223 });
224 r.import_notes.extend(notes);
225 }
226
227 pub(crate) fn solve_thickness(&mut self) -> Result<()> {
232 let ns = self.surfaces.len();
233 for q in &self.solves {
234 let what = if q.kind.is_curv() {
235 Kind::Curv
236 } else {
237 Kind::Thick
238 };
239 if q.surf == 0 || q.surf + 1 >= ns {
240 let surf = q.surf;
241 invalid!(
242 "surface {surf}: solve on the object or image surface (or a missing surface)"
243 );
244 }
245 if let Some(o) = q.kind.other_surface() {
246 if o >= ns {
247 invalid!("surface {}: no reference surface {o} for the solve", q.surf);
248 }
249 }
250 if self
251 .pickups
252 .iter()
253 .any(|p| p.dst == q.surf && p.what == what)
254 {
255 invalid!("surface {}: both a solve and a pickup ({:?})", q.surf, what);
256 }
257 if q.kind.is_curv() && self.surfaces[q.surf].is_coord_break() {
258 invalid!("surface {}: curvature solve on a coordinate break", q.surf);
259 }
260 if matches!(q.kind, SolveKind::Position { other: 0, .. }) {
261 let surf = q.surf;
262 invalid!("surface {surf}: the position solve refers to the object surface");
263 }
264 }
265 let solves: Vec<Solve> = self
266 .solves
267 .iter()
268 .filter(|q| !self.surfaces[q.surf].ignore)
269 .copied()
270 .collect();
271 if solves.is_empty() && self.macro_parms.is_empty() {
272 return Ok(());
273 }
274 for _ in 0..100 {
275 let mut moved = false;
276 for q in &solves {
277 moved |= self.solve_one(q)?;
278 }
279 if !self.macro_parms.is_empty() {
280 moved |= self.solve_macro_parms()?;
281 }
282 if !moved {
283 return Ok(());
284 }
285 }
286 invalid!("the solve doesn't converge")
287 }
288
289 pub(crate) fn active_solves(&self) -> Vec<Solve> {
291 self.solves
292 .iter()
293 .filter(|q| !self.surfaces[q.surf].ignore)
294 .copied()
295 .collect()
296 }
297
298 pub(crate) fn solves_still_hold(&self) -> bool {
302 self.active_solves().iter().all(|q| {
303 if matches!(
304 q.kind,
305 SolveKind::MarginalHeightZone { .. }
306 | SolveKind::Opd { .. }
307 | SolveKind::CenterOfCurvature { .. }
308 | SolveKind::ConcentricSurface { .. }
309 | SolveKind::ConcentricRadius { .. }
310 | SolveKind::MacroCurv { .. }
311 | SolveKind::MacroThick { .. }
312 ) {
313 return false;
314 }
315 let v = self.solved_value(q);
316 match q.kind {
317 SolveKind::MarginalHeight { .. }
318 | SolveKind::ChiefHeight { .. }
319 | SolveKind::PupilPosition => self
320 .paraxial_height_residual(q)
321 .is_ok_and(|(r, du)| (r / du).abs() <= 1e-13 * (1.0 + v.abs())),
322 _ => self.closed_value(q).is_ok_and(|c| c == v),
323 }
324 })
325 }
326
327 pub(crate) fn solve_sensitivity(&self, ps: &[Param]) -> Result<Vec<Vec<f64>>> {
333 let qs = self.active_solves();
334 let ns = qs.len();
335 if ns == 0 {
336 return Ok(vec![Vec::new(); ps.len()]);
337 }
338 let resid = |s: &System| -> Result<Vec<f64>> {
339 let r: Vec<f64> = qs
340 .iter()
341 .map(|q| s.solve_residual(q))
342 .collect::<Result<_>>()?;
343 if r.iter().any(|x| !x.is_finite()) {
344 invalid!("the solve residual is not finite");
345 }
346 Ok(r)
347 };
348 let step = |v: f64| 1e-6 * (1.0 + v.abs());
349 let mut js = vec![0.0; ns * ns];
351 for (j, q) in qs.iter().enumerate() {
352 let v = self.solved_value(q);
353 let h = step(v);
354 let mut r = [Vec::new(), Vec::new()];
355 for (i, x) in [v + h, v - h].into_iter().enumerate() {
356 let mut s = self.clone_keep(Keep {
357 frames: false,
358 paraxial: false,
359 });
360 s.put_solved(q.surf, q.kind.is_curv(), x)?;
361 r[i] = resid(&s)?;
362 }
363 for i in 0..ns {
364 js[i * ns + j] = (r[0][i] - r[1][i]) / (2.0 * h);
365 }
366 }
367 let lu = Lu::new(js, ns).ok_or_else(|| {
368 crate::error::Error::Invalid(
369 "the solve target doesn't change with the solved value (no derivative)".into(),
370 )
371 })?;
372 ps.iter()
373 .map(|&p| {
374 let v = self.get_param(p)?;
375 let h = step(v);
376 let a = resid(&self.with_params_solve(&[(p, v + h)], false)?)?;
377 let b = resid(&self.with_params_solve(&[(p, v - h)], false)?)?;
378 let jp: Vec<f64> = a
379 .iter()
380 .zip(&b)
381 .map(|(x, y)| -(x - y) / (2.0 * h))
382 .collect();
383 Ok(lu.solve(&jp))
384 })
385 .collect()
386 }
387
388 fn chief_scale(&self) -> Result<f64> {
391 let (_, ny) = self.field_norm_values();
392 Ok(match self.field_type {
393 crate::system::FieldType::Angle => crate::quantity::Angle::from_deg(ny).tan(),
394 crate::system::FieldType::ObjH => ny,
395 crate::system::FieldType::ParH => ny / self.paraxial().chief_parimage_per_unit,
396 t => notimpl!("chief ray solve with field type {t:?}"),
397 })
398 }
399
400 fn put_solved(&mut self, k: usize, curv: bool, v: f64) -> Result<()> {
402 if curv {
403 self.rx_mut().surfaces[k].c = v;
404 } else {
405 self.rx_mut().surfaces[k].t = v;
406 }
407 if !self.pickups.is_empty() {
408 self.resolve_pickups()?;
409 }
410 self.changed()
411 }
412
413 fn prev_live(&self, k: usize) -> usize {
415 (1..k)
416 .rev()
417 .find(|&j| !self.surfaces[j].ignore)
418 .unwrap_or(0)
419 }
420
421 fn axial(&self, a: usize, b: usize) -> Result<f64> {
423 let mut z = 0.0;
424 for j in a..b {
425 let d = &self.surfaces[j];
426 if d.ignore {
427 continue;
428 }
429 let tilted = (d.is_coord_break() && d.cb().iter().any(|&v| v != 0.0))
430 || d.before.is_some()
431 || matches!(d.after, After::Tilt(_));
432 if d.is_mirror() || tilted {
433 notimpl!("solve distance across a mirror or a tilt or decenter (surface {j})");
434 }
435 z += d.t;
436 }
437 Ok(z)
438 }
439
440 fn solve_one(&mut self, q: &Solve) -> Result<bool> {
442 let k = q.surf;
443 let curv = q.kind.is_curv();
444 match q.kind {
445 SolveKind::MarginalHeight { .. }
446 | SolveKind::ChiefHeight { .. }
447 | SolveKind::PupilPosition => {
448 return self.solve_paraxial_height(q);
449 }
450 SolveKind::MarginalHeightZone { zone: z, .. } => {
451 return self.solve_real_height(k, q.kind.value(), z)
452 }
453 SolveKind::Opd { zone: z, .. } => return self.solve_opd(k, q.kind.value(), z),
454 _ => {}
455 }
456 let old = self.solved_value(q);
457 let tol = |v: f64| 1e-14 * (1.0 + v.abs());
458 let v = self.closed_value(q)?;
459 if v != old {
461 self.put_solved(k, curv, v)?;
462 }
463 Ok((v - old).abs() > tol(v))
464 }
465
466 fn solved_value(&self, q: &Solve) -> f64 {
468 let d = &self.surfaces[q.surf];
469 if q.kind.is_curv() {
470 d.c
471 } else {
472 d.t
473 }
474 }
475
476 pub(crate) fn solve_residual(&self, q: &Solve) -> Result<f64> {
479 Ok(match q.kind {
480 SolveKind::MarginalHeight { .. }
481 | SolveKind::ChiefHeight { .. }
482 | SolveKind::PupilPosition => self.paraxial_height_residual(q)?.0,
483 SolveKind::MarginalHeightZone { zone: z, .. } => {
484 self.real_height_residual(q.surf, q.kind.value(), z)?
485 }
486 SolveKind::Opd { zone: z, .. } => self.opd_residual(q.kind.value(), z)?,
487 _ => self.solved_value(q) - self.closed_value(q)?,
488 })
489 }
490
491 fn closed_value(&self, q: &Solve) -> Result<f64> {
493 let k = q.surf;
494 let h = q.kind.value();
495 let radius = |c: f64| if c == 0.0 { 1e10 } else { 1.0 / c };
496 let closed: Option<f64> = match q.kind {
497 SolveKind::MarginalHeight { .. }
498 | SolveKind::ChiefHeight { .. }
499 | SolveKind::PupilPosition
500 | SolveKind::MarginalHeightZone { .. }
501 | SolveKind::Opd { .. } => unreachable!(),
502 SolveKind::Edge { radius: r, .. } => {
503 let d = &self.surfaces[k];
504 let n = &self.surfaces[k + 1];
505 for (j, x) in [(k, d), (k + 1, n)] {
506 if !matches!(
507 x.typ(),
508 SurfType::Standard | SurfType::EvenAsph | SurfType::OddAsph
509 ) {
510 notimpl!("edge thickness solve on surface {j} ({:?})", x.typ());
511 }
512 }
513 let r = if r == 0.0 { d.semi } else { r };
514 let r2 = r * r;
515 let sag_r = |x: &crate::surface::Surface| match x.typ() {
517 SurfType::OddAsph => crate::freeform::sag_xy(x, 0.0, r).0,
518 _ => crate::trace::sag(x.c, x.k, x.asph(), r2).0,
519 };
520 let z1 = sag_r(d);
521 let z2 = sag_r(n);
522 Some(h + z1 - z2)
523 }
524 SolveKind::Position { other: f, .. } => {
525 let rest = if f <= k { f..k } else { k + 1..f };
528 let t = h - self.surfaces[rest].iter().map(|d| d.t).sum::<f64>();
529 if !t.is_finite() {
530 invalid!("surface {k}: the position solve thickness is not finite (sum from surface {f})");
531 }
532 Some(t)
533 }
534 SolveKind::Compensator { other: s0, .. } => {
535 if s0 == k {
536 invalid!("surface {k}: compensator solve referring to itself");
537 }
538 Some(h - self.surfaces[s0].t)
539 }
540 SolveKind::CenterOfCurvature { other: s0 } => {
541 if s0 > k {
542 notimpl!("surface {k}: center of curvature solve on the later surface {s0}");
543 }
544 Some(radius(self.surfaces[s0].c) - self.axial(s0, k)?)
545 }
546 SolveKind::ConcentricSurface { other: j } => {
547 let z = if j >= k {
548 self.axial(k, j)?
549 } else {
550 -self.axial(j, k)?
551 };
552 Some(if z == 0.0 { 0.0 } else { 1.0 / z })
553 }
554 SolveKind::ConcentricRadius { other: j } => {
555 let z = if j >= k {
556 self.axial(k, j)?
557 } else {
558 -self.axial(j, k)?
559 };
560 let cj = self.surfaces[j].c;
562 let r = z + if cj == 0.0 { -1e10 } else { 1.0 / cj };
563 Some(if r == 0.0 { 0.0 } else { 1.0 / r })
564 }
565 SolveKind::ElementPower { .. } => Some(self.element_power_curv(k, h)?),
566 SolveKind::MacroCurv { index: i } | SolveKind::MacroThick { index: i } => {
567 let Some(m) = self.macros.get(i as usize) else {
568 invalid!("surface {k}: no macro {i} ({} in all)", self.macros.len());
569 };
570 Some(self.run_macro(m, k)?.unwrap_or(self.solved_value(q)))
572 }
573 _ => Some(self.paraxial_curv(q)?),
574 };
575 let v = closed.expect("closed form exists");
576 if !v.is_finite() {
577 invalid!(
578 "surface {k}: solve {} can't be solved ({v})",
579 solve_kind_info(q.kind).0
580 );
581 }
582 Ok(v)
583 }
584
585 fn paraxial_curv(&self, q: &Solve) -> Result<f64> {
587 let k = q.surf;
588 let d = &self.surfaces[k];
589 if d.is_mirror()
590 || self.surfaces[1..k]
591 .iter()
592 .any(|x| x.is_mirror() && !x.ignore)
593 {
594 notimpl!("surface {k}: ray curvature solve on a mirror or a surface after a mirror");
595 }
596 if !matches!(
597 d.typ(),
598 SurfType::Standard | SurfType::EvenAsph | SurfType::Toroidal
599 ) {
600 notimpl!("curvature solve on surface {k} ({:?})", d.typ());
601 }
602 let pw = self.primary;
603 let par = self.paraxial();
604 let chief = matches!(
605 q.kind,
606 SolveKind::ChiefAngle { .. } | SolveKind::ChiefNormal
607 );
608 let (y, u) = if chief { &par.chief } else { &par.marginal };
609 let f = if chief { self.chief_scale()? } else { 1.0 };
611 let (y, u) = (f * y[k], f * u[self.prev_live(k)]);
612 let n = self.index_before(k, pw);
613 let n2 = self.n(k)[pw];
614 let a1 = d.shape().paraxial_extra().unwrap_or(0.0);
616 if y == 0.0 {
617 invalid!("surface {k}: the ray height is 0, so the curvature solve can't be solved");
618 }
619 let ce = match q.kind {
620 SolveKind::MarginalAngle { .. }
622 | SolveKind::ChiefAngle { .. }
623 | SolveKind::FNumber { .. } => {
624 if n2 == n {
625 invalid!("surface {k}: the same index on both sides, so the ray angle solve can't be solved");
626 }
627 let a = if matches!(q.kind, SolveKind::FNumber { .. }) {
628 if q.kind.value() == 0.0 {
629 invalid!("surface {k}: F/# 0 solve");
630 }
631 -1.0 / (2.0 * q.kind.value())
632 } else {
633 q.kind.value()
634 };
635 (n * u - n2 * a) / (y * (n2 - n))
636 }
637 SolveKind::MarginalNormal | SolveKind::ChiefNormal => -u / y,
638 SolveKind::Aplanatic => -u * (n2 + n) / (n * y),
639 _ => unreachable!(),
640 };
641 Ok(ce - a1)
642 }
643
644 fn element_power_curv(&self, k: usize, p: f64) -> Result<f64> {
647 let pw = self.primary;
648 let (a, b) = (self.prev_live(k), k);
649 if a == 0 {
650 invalid!("surface {k}: surface pair of the lens power solve (surfaces {a} and {b})");
651 }
652 for j in [a, b] {
653 let d = &self.surfaces[j];
654 if d.is_mirror() || !matches!(d.typ(), SurfType::Standard | SurfType::EvenAsph) {
655 notimpl!(
656 "lens power solve on a lens with surface {j} ({:?})",
657 d.typ()
658 );
659 }
660 }
661 let n0 = self.index_before(a, pw);
662 let ng = self.n(a)[pw];
663 let n1 = self.n(b)[pw];
664 let t = self.axial(a, b)?;
665 let ce = |j: usize| {
666 let d = &self.surfaces[j];
667 let a1 = d.shape().paraxial_extra().unwrap_or(0.0);
668 (d.c + a1, a1)
669 };
670 let (fa, fb) = (ng - n0, n1 - ng);
672 let c = if k == a {
673 let (cb, _) = ce(b);
674 let pb = cb * fb;
675 let den = fa * (1.0 - t / ng * pb);
676 (p - pb) / den
677 } else {
678 let (ca, _) = ce(a);
679 let pa = ca * fa;
680 let den = fb * (1.0 - t / ng * pa);
681 (p - pa) / den
682 };
683 Ok(c - ce(k).1)
684 }
685
686 fn solve_paraxial_height(&mut self, q: &Solve) -> Result<bool> {
689 let k = q.surf;
690 let chief = !matches!(q.kind, SolveKind::MarginalHeight { .. });
691 if q.kind == SolveKind::PupilPosition && k < self.stop() {
692 notimpl!("surface {k}: pupil position solve on a surface before the stop");
694 }
695 let eval = |s: &mut System, t: f64| -> Result<(f64, f64)> {
697 s.put_solved(k, false, t)?;
698 s.paraxial_height_residual(q)
699 };
700 let old = self.surfaces[k].t;
702 let (f0, du) = eval(self, 0.0)?;
703 if !(du.abs() > 0.0) || !f0.is_finite() {
704 self.put_solved(k, false, old)?;
705 if chief {
706 invalid!("surface {k}: the chief ray is parallel to the axis (thickness solve)");
707 }
708 invalid!("surface {k}: the marginal ray is parallel to the axis (thickness solve)");
709 }
710 let t = self.secant(k, 0.0, f0, -f0 / du, |s, t| Ok(eval(s, t)?.0))?;
711 self.finish_thick(k, old, t)
712 }
713
714 fn paraxial_height_residual(&self, q: &Solve) -> Result<(f64, f64)> {
717 let k = q.surf;
718 let (chief, h) = match q.kind {
719 SolveKind::MarginalHeight { .. } => (false, q.kind.value()),
720 SolveKind::ChiefHeight { .. } => (true, q.kind.value()),
721 _ => (true, 0.0),
722 };
723 let t = self.surfaces[k].t;
724 let par = self.paraxial();
725 let (y, u) = if chief { &par.chief } else { &par.marginal };
726 let (y, u) = (y[k], u[k]);
727 let f = if chief && h != 0.0 {
729 self.chief_scale()?
730 } else {
731 1.0
732 };
733 let nmir = self.surfaces[1..=k]
735 .iter()
736 .filter(|d| d.is_mirror() && !d.ignore)
737 .count();
738 let du = f * if nmir % 2 == 1 { -u } else { u };
739 Ok((f * y + du * t - h, du))
740 }
741
742 fn solve_real_height(&mut self, k: usize, h: f64, zone: f64) -> Result<bool> {
744 let (d, n) = (&self.surfaces[k], &self.surfaces[k + 1]);
745 if d.is_mirror()
746 || d.is_coord_break()
747 || d.after != After::None
748 || n.before.is_some()
749 || n.is_coord_break()
750 || n.ignore
751 {
752 notimpl!(
753 "surface {k}: real ray height thickness solve next to a mirror, tilt or decenter, coordinate break or ignored surface"
754 );
755 }
756 let eval = |s: &mut System, t: f64| -> Result<f64> {
757 s.put_solved(k, false, t)?;
758 s.real_height_residual(k, h, zone)
759 };
760 let old = self.surfaces[k].t;
762 let t0 = 0.0;
763 let f0 = eval(self, t0)?;
764 if !f0.is_finite() {
765 self.put_solved(k, false, old)?;
766 invalid!("surface {k}: the real ray (pupil zone {zone}) doesn't pass, so the thickness solve can't be solved");
767 }
768 let dt = 1e-6;
770 let f1 = eval(self, t0 + dt)?;
771 let slope = (f1 - f0) / dt;
772 if !(slope.abs() > 0.0) {
773 self.put_solved(k, false, old)?;
774 invalid!("surface {k}: the real ray height doesn't change with thickness, so the thickness solve can't be solved");
775 }
776 let t = self.secant(k, t0, f0, t0 - f0 / slope, eval)?;
777 self.finish_thick(k, old, t)
778 }
779
780 fn real_height_residual(&self, k: usize, h: f64, zone: f64) -> Result<f64> {
782 let t = self.surfaces[k].t;
783 let tr = self.try_trace(
785 crate::system::FieldSel::Norm(0.0, 0.0),
786 &[0.0],
787 &[zone],
788 None,
789 Some(k),
790 false,
791 )?;
792 let r = &tr.rays[0];
793 if r.status.surf().is_some() || r.lmn[2] == 0.0 {
794 return Ok(f64::NAN);
795 }
796 Ok(r.xyz[1] + r.lmn[1] / r.lmn[2] * (t - r.xyz[2]) - h)
797 }
798
799 fn solve_opd(&mut self, k: usize, opd: f64, zone: f64) -> Result<bool> {
806 if self.surfaces[k].is_mirror() || self.surfaces[k].is_coord_break() {
807 notimpl!("surface {k}: OPD thickness solve on a mirror or coordinate break");
808 }
809 if k + 1 >= self.surfaces.len() {
810 invalid!("surface {k}: OPD thickness solve on the image surface");
811 }
812 let others: Vec<Solve> = self
813 .active_solves()
814 .into_iter()
815 .filter(|q| !matches!(q.kind, SolveKind::Opd { .. }))
816 .collect();
817 let eval = |s: &mut System, t: f64| -> Result<f64> {
818 s.put_solved(k, false, t)?;
819 if !others.is_empty() || !s.macro_parms.is_empty() {
820 let mut done = false;
821 for _ in 0..100 {
822 let mut moved = false;
823 for q in &others {
824 moved |= s.solve_one(q)?;
825 }
826 if !s.macro_parms.is_empty() {
827 moved |= s.solve_macro_parms()?;
828 }
829 if !moved {
830 done = true;
831 break;
832 }
833 }
834 if !done {
835 invalid!("surface {k}: another solve doesn't converge inside the OPD thickness solve");
836 }
837 }
838 s.opd_residual(opd, zone)
839 };
840 let old = self.surfaces[k].t;
841 let f0 = eval(self, old)?;
842 if !f0.is_finite() {
843 self.put_solved(k, false, old)?;
844 invalid!("surface {k}: the real ray (pupil zone {zone}) doesn't pass, so the OPD thickness solve can't be solved");
845 }
846 if f0.abs() <= OPD_SOLVE_TOL {
849 return Ok(false);
850 }
851 let dt = 1e-6 * (1.0 + old.abs());
852 let f1 = eval(self, old + dt)?;
853 let slope = (f1 - f0) / dt;
854 if !(slope.abs() > 0.0) || !slope.is_finite() {
855 self.put_solved(k, false, old)?;
856 invalid!("surface {k}: the OPD doesn't change with thickness, so the OPD thickness solve can't be solved");
857 }
858 let t = self.secant(k, old, f0, old - f0 / slope, eval)?;
859 self.finish_thick(k, old, t)
860 }
861
862 fn opd_residual(&self, opd: f64, zone: f64) -> Result<f64> {
864 let o = crate::opd::opd(
865 self,
866 crate::system::FieldSel::Norm(0.0, 0.0),
867 &[0.0],
868 &[zone],
869 None,
870 true,
871 )?;
872 if !o.ok(0) {
873 return Ok(f64::NAN);
874 }
875 Ok(o.opd[0] - opd)
876 }
877
878 fn finish_thick(&mut self, k: usize, old: f64, t: f64) -> Result<bool> {
880 self.put_solved(k, false, t)?;
881 Ok((t - old).abs() > 1e-14 * (1.0 + t.abs()))
882 }
883
884 fn secant(
886 &mut self,
887 k: usize,
888 t0: f64,
889 f0: f64,
890 t1: f64,
891 mut eval: impl FnMut(&mut System, f64) -> Result<f64>,
892 ) -> Result<f64> {
893 let tol = |t: f64| 1e-14 * (1.0 + t.abs());
894 let (mut t0, mut f0, mut t1) = (t0, f0, t1);
895 let mut done = false;
896 for _ in 0..100 {
897 if (t1 - t0).abs() <= tol(t1) {
898 done = true;
899 break;
900 }
901 let f1 = eval(self, t1)?;
902 if f1 == 0.0 || f1 == f0 {
903 done = f1 == 0.0 || (t1 - t0).abs() <= 1e-9 * (1.0 + t1.abs());
904 break;
905 }
906 let t2 = t1 - f1 * (t1 - t0) / (f1 - f0);
907 (t0, f0, t1) = (t1, f1, t2);
908 if !t1.is_finite() {
909 break;
910 }
911 }
912 if !done {
913 invalid!("surface {k}: the thickness solve doesn't converge");
914 }
915 Ok(t1)
916 }
917}
918
919const OPD_SOLVE_TOL: f64 = 1e-9;
921
922pub(crate) fn solve_kind_of(w: crate::param::Kind) -> Option<Kind> {
924 use crate::param::Kind;
925 match w {
926 Kind::Thick => Some(Kind::Thick),
927 Kind::Curv => Some(Kind::Curv),
928 _ => None,
929 }
930}
931
932pub const SOLVE_KINDS: &[&str] = &[
934 "marginal_height",
935 "marginal_height_zone",
936 "chief_height",
937 "pupil_position",
938 "edge",
939 "opd",
940 "position",
941 "compensator",
942 "center_of_curvature",
943 "marginal_angle",
944 "chief_angle",
945 "marginal_normal",
946 "chief_normal",
947 "aplanatic",
948 "element_power",
949 "concentric_surface",
950 "concentric_radius",
951 "f_number",
952];
953
954pub fn solve_kind_parse(
957 name: &str,
958 value: f64,
959 param: f64,
960 other: Option<usize>,
961) -> Result<SolveKind> {
962 use SolveKind as K;
963 let n = name.trim().to_ascii_lowercase();
964 let need = || -> Result<usize> {
965 match other {
966 Some(s) => Ok(s),
967 None => invalid!("solve {n} needs another surface (other)"),
968 }
969 };
970 let v = value;
971 Ok(match n.as_str() {
972 "marginal_height" => K::MarginalHeight { height: v },
973 "marginal_height_zone" => K::MarginalHeightZone {
974 height: v,
975 zone: param,
976 },
977 "chief_height" => K::ChiefHeight { height: v },
978 "pupil_position" => K::PupilPosition,
979 "edge" => K::Edge {
980 thickness: v,
981 radius: param,
982 },
983 "opd" => K::Opd {
984 opd: v,
985 zone: param,
986 },
987 "position" => K::Position {
988 other: need()?,
989 length: v,
990 },
991 "compensator" => K::Compensator {
992 other: need()?,
993 sum: v,
994 },
995 "center_of_curvature" => K::CenterOfCurvature { other: need()? },
996 "marginal_angle" => K::MarginalAngle { angle: v },
997 "chief_angle" => K::ChiefAngle { angle: v },
998 "marginal_normal" => K::MarginalNormal,
999 "chief_normal" => K::ChiefNormal,
1000 "aplanatic" => K::Aplanatic,
1001 "element_power" => K::ElementPower { power: v },
1002 "concentric_surface" => K::ConcentricSurface { other: need()? },
1003 "concentric_radius" => K::ConcentricRadius { other: need()? },
1004 "f_number" => K::FNumber { fnum: v },
1005 "macro_curv" | "macro_thick" => {
1008 if !(param >= 0.0 && param.fract() == 0.0 && param <= u16::MAX as f64) {
1009 invalid!("macro number {param}");
1010 }
1011 let index = param as u16;
1012 if n == "macro_curv" {
1013 K::MacroCurv { index }
1014 } else {
1015 K::MacroThick { index }
1016 }
1017 }
1018 _ => invalid!("solve type {name} ({})", SOLVE_KINDS.join(" ")),
1019 })
1020}
1021
1022pub fn solve_kind_info(k: SolveKind) -> (&'static str, f64, f64, Option<usize>) {
1024 use SolveKind as K;
1025 let (o, v) = (k.other_surface(), k.value());
1026 let (name, param) = match k {
1027 K::MarginalHeight { .. } => ("marginal_height", 0.0),
1028 K::MarginalHeightZone { zone, .. } => ("marginal_height_zone", zone),
1029 K::ChiefHeight { .. } => ("chief_height", 0.0),
1030 K::PupilPosition => ("pupil_position", 0.0),
1031 K::Edge { radius, .. } => ("edge", radius),
1032 K::Opd { zone, .. } => ("opd", zone),
1033 K::Position { .. } => ("position", 0.0),
1034 K::Compensator { .. } => ("compensator", 0.0),
1035 K::CenterOfCurvature { .. } => ("center_of_curvature", 0.0),
1036 K::MarginalAngle { .. } => ("marginal_angle", 0.0),
1037 K::ChiefAngle { .. } => ("chief_angle", 0.0),
1038 K::MarginalNormal => ("marginal_normal", 0.0),
1039 K::ChiefNormal => ("chief_normal", 0.0),
1040 K::Aplanatic => ("aplanatic", 0.0),
1041 K::ElementPower { .. } => ("element_power", 0.0),
1042 K::ConcentricSurface { .. } => ("concentric_surface", 0.0),
1043 K::ConcentricRadius { .. } => ("concentric_radius", 0.0),
1044 K::FNumber { .. } => ("f_number", 0.0),
1045 K::MacroCurv { index } => ("macro_curv", index as f64),
1046 K::MacroThick { index } => ("macro_thick", index as f64),
1047 };
1048 (name, v, param, o)
1049}