1use crate::error::{Error, Result};
14use crate::invalid;
15use crate::system::{FieldCond, Launch, ObjSpec, RecSel, Trace};
16use crate::System;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Unknown {
21 Object,
23 Pupil,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq)]
29pub enum Residual {
30 Position { surf: usize, target: [f64; 2] },
32 DirSum { s1: usize, s2: usize },
34 DirDiff { s1: usize, s2: usize },
36}
37
38impl Residual {
39 fn quantity(self) -> FieldCond {
41 match self {
42 Residual::Position { surf, .. } => FieldCond::Position { surf },
43 Residual::DirSum { s1, s2 } => FieldCond::DirSum { s1, s2 },
44 Residual::DirDiff { s1, s2 } => FieldCond::DirDiff { s1, s2 },
45 }
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq)]
51pub struct RayProblem {
52 pub unknown: Unknown,
53 pub residual: Residual,
54 pub object: ObjSpec,
56 pub pupil: [f64; 2],
58 pub wave: usize,
60 pub tol: f64,
62 pub max_iter: usize,
63}
64
65impl RayProblem {
66 pub fn new(unknown: Unknown, residual: Residual, object: ObjSpec, wave: usize) -> RayProblem {
67 RayProblem {
68 unknown,
69 residual,
70 object,
71 pupil: [0.0, 0.0],
72 wave,
73 tol: 1e-12,
74 max_iter: 50,
75 }
76 }
77}
78
79#[derive(Debug, Clone)]
81pub struct RaySolution {
82 pub object: ObjSpec,
83 pub pupil: [f64; 2],
84 pub residual: [f64; 2],
85 pub iterations: usize,
86 pub trace: Trace,
88}
89
90impl System {
91 pub fn solve_ray(&self, prob: &RayProblem) -> Result<RaySolution> {
93 let needs = match prob.residual {
94 Residual::Position { surf, .. } => vec![surf],
95 Residual::DirSum { s1, s2 } | Residual::DirDiff { s1, s2 } => vec![s1, s2],
96 };
97 for &j in &needs {
98 if j == 0 || j > self.image() || self.surfaces[j].ignore {
99 invalid!(
100 "residual surface {j} (surfaces not ignored, 1 to {})",
101 self.image()
102 );
103 }
104 }
105 if prob.unknown == Unknown::Object && !matches!(prob.object, ObjSpec::Point(_)) {
106 invalid!("only a finite object can be an unknown");
107 }
108 let w = prob.wave;
109 if w >= self.wavelengths.len() {
110 invalid!("wavelength {w}");
111 }
112 let start = match (prob.unknown, prob.object) {
113 (Unknown::Object, ObjSpec::Point(p)) => p,
114 _ => prob.pupil,
115 };
116 let run = |u: [f64; 2], rec_all: bool| -> (Trace, [f64; 2]) {
117 let (spec, pp) = match prob.unknown {
118 Unknown::Object => (ObjSpec::Point(u), prob.pupil),
119 Unknown::Pupil => (prob.object, u),
120 };
121 let (t, q) = self.ray_quantity(spec, pp, w, prob.residual.quantity(), rec_all);
122 let r = match prob.residual {
123 Residual::Position { target, .. } => [q[0] - target[0], q[1] - target[1]],
124 _ => q,
125 };
126 (t, r)
127 };
128 let norm = |r: [f64; 2]| r[0].abs().max(r[1].abs());
129 if !norm(run(start, false).1).is_finite() {
130 invalid!("the starting ray doesn't pass ({:?})", prob.unknown);
131 }
132 let nw = crate::newton2::Newton2 {
133 tol: prob.tol,
134 max_it: prob.max_iter,
135 diff: crate::newton2::Diff {
136 h: 1e-6,
137 rel: prob.unknown == Unknown::Object,
138 central: true,
139 },
140 line: crate::newton2::Line::Decrease { min: 1e-4 },
142 };
143 let sol = nw.solve(|u| run(u, false).1, start, [0.0; 2]);
144 let (u, r, it) = (sol.v, sol.r, sol.it);
145 if sol.end == crate::newton2::End::Singular {
146 return Err(Error::Invalid(format!(
147 "ray solve: singular Jacobian (iteration {it}, residual {:e})",
148 norm(r)
149 )));
150 }
151 if !(norm(r) <= prob.tol) {
152 invalid!(
153 "the ray solve doesn't converge (iteration {it}, residual {:e}, tolerance {:e})",
154 norm(r),
155 prob.tol
156 );
157 }
158 let t = run(u, true).0;
159 let (object, pupil) = match prob.unknown {
160 Unknown::Object => (ObjSpec::Point(u), prob.pupil),
161 Unknown::Pupil => (prob.object, u),
162 };
163 Ok(RaySolution {
164 object,
165 pupil,
166 residual: r,
167 iterations: it,
168 trace: t,
169 })
170 }
171}
172
173impl System {
174 pub(crate) fn ray_quantity(
178 &self,
179 spec: ObjSpec,
180 pupil: [f64; 2],
181 w: usize,
182 c: FieldCond,
183 rec_all: bool,
184 ) -> (Trace, [f64; 2]) {
185 let last = match c {
186 FieldCond::Position { surf } => surf,
187 FieldCond::DirSum { s1, s2 } | FieldCond::DirDiff { s1, s2 } => s1.max(s2),
188 };
189 let surfs = match c {
191 FieldCond::Position { surf } => [surf, surf],
192 FieldCond::DirSum { s1, s2 } | FieldCond::DirDiff { s1, s2 } => [s1, s2],
193 };
194 let l = Launch::Pupil {
195 spec,
196 signed: false,
197 px: &[pupil[0]],
198 py: &[pupil[1]],
199 vig: Some([0.0; 5]),
200 hxy: Some((0.0, 0.0)),
201 };
202 let rec = if rec_all {
203 RecSel::All
204 } else {
205 RecSel::Surfs(&surfs)
206 };
207 let mut t = self.trace_launch(&l, w, Some(last), rec);
208 t.hx_hy = (0.0, 0.0);
209 if t.rays[0].status.surf().is_some() {
210 return (t, [f64::NAN; 2]);
211 }
212 let q = match c {
213 FieldCond::Position { surf } => t.rec_at(surf).map(|a| [a.xyz[0][0], a.xyz[0][1]]),
214 FieldCond::DirSum { s1, s2 } | FieldCond::DirDiff { s1, s2 } => {
215 t.rec_at(s1).zip(t.rec_at(s2)).map(|(a, b)| {
216 let (a, b) = (a.lmn[0], b.lmn[0]);
217 if matches!(c, FieldCond::DirSum { .. }) {
218 [a[0] + b[0], a[1] + b[1]]
219 } else {
220 [a[0] - b[0], a[1] - b[1]]
221 }
222 })
223 }
224 };
225 (t, q.unwrap_or([f64::NAN; 2]))
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
235 fn ray_quantity_of_a_stopped_ray_is_nan() {
236 let txt =
238 "VERS 260327 42\nMODE SEQ\nUNIT MM X W X CM MR CPMM\nENPD 10\nFTYP 0 0 1 1 0 0 0\n\
239 XFLN 0\nYFLN 0\nFWGN 1\nWAVM 1 0.55 1\nPWAV 1\n\
240 SURF 0\n TYPE STANDARD\n CURV 0.0\n DISZ INFINITY\n\
241 SURF 1\n STOP\n TYPE STANDARD\n CURV 0.2\n DISZ 10\n\
242 SURF 2\n TYPE STANDARD\n CURV 0.0\n DISZ 0\n";
243 let raw = crate::test_zmx::parse_text(txt).unwrap();
244 let s = crate::test_zmx::build(&raw, &Default::default(), &[], None).unwrap();
245 let spec = ObjSpec::Dir([0.0, 0.0, 1.0]);
246 for c in [
247 FieldCond::Position { surf: 2 },
248 FieldCond::DirSum { s1: 1, s2: 2 },
249 FieldCond::DirDiff { s1: 1, s2: 2 },
250 ] {
251 let (t, q) = s.ray_quantity(spec, [3.0, 0.0], 0, c, false);
252 assert!(t.rays[0].status.surf().is_some(), "{c:?}");
253 assert!(q[0].is_nan() && q[1].is_nan(), "{c:?}: {q:?}");
254 let (_, q) = s.ray_quantity(spec, [0.3, 0.0], 0, c, false);
256 assert!(q[0].is_finite() && q[1].is_finite(), "{c:?}: {q:?}");
257 }
258 }
259}