1use crate::error::Result;
4use crate::invalid;
5use crate::shape::{Base, Shape};
6use crate::system::{FieldSel, FieldType, System};
7
8#[derive(Debug, Clone, PartialEq)]
11pub struct Seidel {
12 pub surf: Vec<[f64; 5]>,
13 pub wavelength: f64,
15}
16
17impl Seidel {
18 pub fn at(&self, j: usize) -> [f64; 5] {
20 if j == 0 {
21 self.surf.iter().fold([0.0; 5], |mut a, v| {
22 for i in 0..5 {
23 a[i] += v[i];
24 }
25 a
26 })
27 } else {
28 self.surf.get(j).copied().unwrap_or([0.0; 5])
29 }
30 }
31
32 pub fn waves(&self, j: usize) -> [f64; 5] {
35 let s = self.at(j);
36 let l = self.wavelength;
37 [
38 s[0] / (8.0 * l),
39 s[1] / (2.0 * l),
40 s[2] / (2.0 * l),
41 s[3] / (4.0 * l),
42 s[4] / (2.0 * l),
43 ]
44 }
45}
46
47pub fn chief_scale(s: &System) -> f64 {
49 let hmax = s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max);
50 match s.field_type {
51 FieldType::Angle => hmax.to_radians().tan(),
52 FieldType::ObjH => hmax,
53 _ => {
55 let p = s.paraxial();
56 let pimh = crate::report::system_data(s).pimh;
57 (pimh / p.chief_parimage_per_unit).abs()
58 }
59 }
60}
61
62fn quartic_excess(sh: Shape, c0: f64) -> Option<f64> {
64 let (c, k, a4) = match sh {
65 Shape::Plane => return Some(0.0),
66 Shape::Conic { c, k } => (c, k, 0.0),
67 Shape::EvenAsphere(Base { c, k, a }) => (c, k, a.get(1).copied().unwrap_or(0.0)),
68 _ => return None,
69 };
70 Some((1.0 + k) * c.powi(3) / 8.0 + a4 - c0.powi(3) / 8.0)
71}
72
73pub fn seidel(s: &System, w: usize) -> Result<Seidel> {
75 if !s.symmetric() {
76 invalid!("Seidel coefficients need a rotationally symmetric system");
77 }
78 let sf = &s.surfaces;
79 let img = s.image();
80 let p = s.paraxial();
81 let k = chief_scale(s);
82 let (ym, um) = s.ptrace(p.marginal.0[1], p.marginal.1[0], w, None);
83 let (yc, uc) = s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None);
84 let h = s.n(0)[w] * (uc[0] * ym[1] - um[0] * yc[1]);
87 let mut out = vec![[0.0; 5]; sf.len()];
88 for j in 1..img {
89 let f = &sf[j];
90 if f.ignore || f.is_coord_break() {
91 continue;
92 }
93 if !matches!(
94 f.action(),
95 crate::action::Action::Refract | crate::action::Action::Reflect { .. }
96 ) {
97 invalid!("Seidel coefficients need refracting or reflecting surfaces (surface {j})");
98 }
99 if f.is_mirror() {
100 invalid!(
101 "Seidel coefficients of systems with mirrors are not supported yet (surface {j})"
102 );
103 }
104 let sh = f.shape();
105 let c = sh.paraxial_curv();
106 let Some(d4) = quartic_excess(sh, c) else {
107 invalid!("Seidel coefficients need standard or even asphere surfaces (surface {j})");
108 };
109 let (n1, n2) = (s.index_before(j, w), s.n(j)[w]);
110 let a = n1 * (um[j - 1] + ym[j] * c);
111 let ab = n1 * (uc[j - 1] + yc[j] * c);
112 let y = ym[j];
113 let du = um[j] / n2 - um[j - 1] / n1;
114 let mut v = [
115 -a * a * y * du,
116 -a * ab * y * du,
117 -ab * ab * y * du,
118 -h * h * c * (1.0 / n2 - 1.0 / n1),
119 0.0,
120 ];
121 v[4] = ab
124 * (-ab * ab * y * (1.0 / (n2 * n2) - 1.0 / (n1 * n1))
125 + yc[j] * c * (1.0 / n2 - 1.0 / n1) * (ab * y + h));
126 if d4 != 0.0 {
128 let ds = 8.0 * d4 * (n2 - n1) * y.powi(4);
129 let r = if y != 0.0 { yc[j] / y } else { 0.0 };
130 v[0] += ds;
131 v[1] += ds * r;
132 v[2] += ds * r * r;
133 v[4] += ds * r * r * r;
134 }
135 if v.iter().any(|x| !x.is_finite()) {
136 invalid!("Seidel coefficients of surface {j} are not finite");
137 }
138 out[j] = v;
139 }
140 Ok(Seidel {
141 surf: out,
142 wavelength: s.wave(w).mm(),
143 })
144}
145
146pub fn chromatic(s: &System, w: usize, short: usize, long: usize) -> Result<Vec<[f64; 2]>> {
151 if !s.symmetric() {
152 invalid!("Seidel coefficients need a rotationally symmetric system");
153 }
154 let sf = &s.surfaces;
155 let img = s.image();
156 let p = s.paraxial();
157 let k = chief_scale(s);
158 let (ym, um) = s.ptrace(p.marginal.0[1], p.marginal.1[0], w, None);
159 let (yc, uc) = s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None);
160 let mut out = vec![[0.0; 2]; sf.len()];
161 for j in 1..img {
162 let f = &sf[j];
163 if f.ignore || f.is_coord_break() {
164 continue;
165 }
166 if f.is_mirror() {
167 invalid!(
168 "Seidel coefficients of systems with mirrors are not supported yet (surface {j})"
169 );
170 }
171 let c = f.shape().paraxial_curv();
172 let (n1, n2) = (s.index_before(j, w), s.n(j)[w]);
173 let dn1 = s.index_before(j, long) - s.index_before(j, short);
174 let dn2 = s.n(j)[long] - s.n(j)[short];
175 let a = n1 * (um[j - 1] + ym[j] * c);
176 let ab = n1 * (uc[j - 1] + yc[j] * c);
177 let d = dn2 / n2 - dn1 / n1;
178 let v = [a * ym[j] * d, ab * ym[j] * d];
179 if v.iter().any(|x| !x.is_finite()) {
180 invalid!("Seidel coefficients of surface {j} are not finite");
181 }
182 out[j] = v;
183 }
184 Ok(out)
185}
186
187pub fn longitudinal(s: &System, w: usize, zone: f64) -> Result<f64> {
190 let img = s.image();
191 let v = if zone == 0.0 {
192 let p = s.paraxial();
193 let (ym, um) = s.ptrace(p.marginal.0[1], p.marginal.1[0], w, None);
194 -ym[img] / um[img - 1]
195 } else {
196 let t = s.try_trace(
197 FieldSel::Norm(0.0, 0.0),
198 &[0.0],
199 &[zone],
200 Some(w),
201 None,
202 false,
203 )?;
204 let r = &t.rays[0];
205 if let Some(j) = r.status.surf() {
206 invalid!("the ray of zone {zone} stopped (surface {j})");
207 }
208 r.xyz[2] - r.xyz[1] * r.lmn[2] / r.lmn[1]
210 };
211 if !v.is_finite() {
212 invalid!("the longitudinal aberration of zone {zone} is not finite");
213 }
214 Ok(v)
215}
216
217pub fn chief_height(s: &System, w: usize) -> f64 {
220 let p = s.paraxial();
221 let k = chief_scale(s);
222 s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None).0[s.image()]
223}
224
225fn field_t(s: &System, hx: f64, hy: f64) -> Result<[f64; 2]> {
227 let (nx, ny) = s.field_norm_values();
228 if s.field_type == FieldType::Angle {
229 let (ax, ay) = ((hx * nx).to_radians(), (hy * ny).to_radians());
230 if ax.abs() >= std::f64::consts::FRAC_PI_2 || ay.abs() >= std::f64::consts::FRAC_PI_2 {
231 invalid!("the distortion of field ({hx}, {hy}) needs field angles below 90 degrees");
232 }
233 return Ok([ax.tan(), ay.tan()]);
234 }
235 Ok([hx * nx, hy * ny])
236}
237
238fn field_of_t(s: &System, t: [f64; 2]) -> (f64, f64) {
240 let (nx, ny) = s.field_norm_values();
241 if s.field_type == FieldType::Angle {
242 return (t[0].atan().to_degrees() / nx, t[1].atan().to_degrees() / ny);
243 }
244 (t[0] / nx, t[1] / ny)
245}
246
247fn chief_xy(s: &System, h: (f64, f64), w: usize) -> Result<[f64; 2]> {
250 let t = s.try_trace(
251 FieldSel::Norm(h.0, h.1),
252 &[0.0],
253 &[0.0],
254 Some(w),
255 None,
256 false,
257 )?;
258 let r = &t.rays[0];
259 if let Some(j) = r.status.surf() {
260 invalid!(
261 "the chief ray of field ({}, {}) stopped (surface {j})",
262 h.0,
263 h.1
264 );
265 }
266 if s.afocal {
267 return Ok([r.lmn[0] / r.lmn[2], r.lmn[1] / r.lmn[2]]);
268 }
269 Ok([r.xyz[0], r.xyz[1]])
270}
271
272#[derive(Debug, Clone, Copy, PartialEq)]
275pub struct DistRef {
276 pub p: [f64; 2],
277 pub t: [f64; 2],
278 pub j: [[f64; 2]; 2],
279}
280
281#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
283pub enum DistComp {
284 #[default]
286 Radial,
287 X,
288 Y,
289}
290
291pub fn distortion_point(s: &System, w: usize, reference: Option<(f64, f64)>) -> Result<DistRef> {
293 let (p, t) = match reference {
294 None => ([0.0, 0.0], [0.0, 0.0]),
295 Some(r) => (chief_xy(s, r, w)?, field_t(s, r.0, r.1)?),
296 };
297 Ok(DistRef {
298 p,
299 t,
300 j: [[1.0, 0.0], [0.0, 1.0]],
301 })
302}
303
304pub fn distortion_ref(s: &System, w: usize, reference: Option<(f64, f64)>) -> Result<DistRef> {
307 let mut r = distortion_point(s, w, reference)?;
308 r.j = match reference {
309 None => {
310 if !s.symmetric() {
311 invalid!("the distortion against the axis needs a rotationally symmetric system");
312 }
313 let img = s.image();
315 let p = s.paraxial();
316 let k = chief_scale(s);
317 let (yc, uc) = s.ptrace(p.chief.0[1] * k, p.chief.1[0] * k, w, None);
318 let tm = if s.field_type == FieldType::Angle {
320 k
321 } else {
322 s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max)
323 };
324 let m = if s.afocal { uc[img - 1] } else { yc[img] } / tm;
326 [[m, 0.0], [0.0, m]]
327 }
328 Some(_) => {
329 let tm = field_t(s, 1.0, 0.0)?[0]
330 .abs()
331 .max(field_t(s, 0.0, 1.0)?[1].abs());
332 if tm == 0.0 {
333 invalid!("the distortion needs a field other than the axis");
334 }
335 let d = 1e-5 * tm;
336 let mut j = [[0.0; 2]; 2];
337 for k in 0..2 {
338 let (mut a, mut b) = (r.t, r.t);
339 a[k] -= d;
340 b[k] += d;
341 let (pa, pb) = (
342 chief_xy(s, field_of_t(s, a), w)?,
343 chief_xy(s, field_of_t(s, b), w)?,
344 );
345 for i in 0..2 {
346 j[i][k] = (pb[i] - pa[i]) / (2.0 * d);
347 }
348 }
349 j
350 }
351 };
352 if r.j.iter().flatten().any(|v| !v.is_finite()) {
353 invalid!("the distortion is not finite");
354 }
355 Ok(r)
356}
357
358pub fn grid_field(s: &System, u: f64, v: f64) -> Result<(f64, f64)> {
361 let r = s.fields.iter().map(|f| f.x.hypot(f.y)).fold(0.0, f64::max);
362 if r == 0.0 {
363 invalid!("the grid distortion needs a field off the axis");
364 }
365 let a = if s.field_type == FieldType::Angle {
366 if r >= 90.0 {
367 invalid!("the grid distortion needs field angles below 90 degrees");
368 }
369 r.to_radians().tan()
370 } else {
371 r
372 } / std::f64::consts::SQRT_2;
373 Ok(field_of_t(s, [a * u, a * v]))
374}
375
376pub fn distortion_against(
381 s: &System,
382 w: usize,
383 h: (f64, f64),
384 r: &DistRef,
385 comp: DistComp,
386) -> Result<(f64, f64)> {
387 let t = field_t(s, h.0, h.1)?;
388 let p = chief_xy(s, h, w)?;
389 let (j, dt) = (r.j, [t[0] - r.t[0], t[1] - r.t[1]]);
390 let del = [
391 j[0][0] * dt[0] + j[0][1] * dt[1],
392 j[1][0] * dt[0] + j[1][1] * dt[1],
393 ];
394 let e = [p[0] - r.p[0], p[1] - r.p[1]];
395 let d = [e[0] - del[0], e[1] - del[1]];
396 let (v, n) = match comp {
398 DistComp::Radial => (
399 d[0].hypot(d[1])
400 .copysign(e[0].hypot(e[1]) - del[0].hypot(del[1])),
401 del[0].hypot(del[1]),
402 ),
403 DistComp::X => (d[0].abs().copysign(e[0].abs() - del[0].abs()), del[0].abs()),
404 DistComp::Y => (d[1].abs().copysign(e[1].abs() - del[1].abs()), del[1].abs()),
405 };
406 let pct = if n != 0.0 { 100.0 * v / n } else { 0.0 };
407 if !v.is_finite() || !pct.is_finite() {
408 invalid!("the distortion is not finite");
409 }
410 Ok((v, pct))
411}
412
413pub fn distortion_points(
415 s: &System,
416 w: usize,
417 h: (f64, f64),
418 r: &DistRef,
419) -> Result<([f64; 2], [f64; 2])> {
420 let t = field_t(s, h.0, h.1)?;
421 let p = chief_xy(s, h, w)?;
422 let (j, dt) = (r.j, [t[0] - r.t[0], t[1] - r.t[1]]);
423 let q = [
424 r.p[0] + j[0][0] * dt[0] + j[0][1] * dt[1],
425 r.p[1] + j[1][0] * dt[0] + j[1][1] * dt[1],
426 ];
427 Ok((p, q))
428}
429
430pub fn distortion_at(
433 s: &System,
434 w: usize,
435 h: (f64, f64),
436 reference: Option<(f64, f64)>,
437) -> Result<(f64, f64)> {
438 let r = distortion_ref(s, w, reference)?;
439 distortion_against(s, w, h, &r, DistComp::Radial)
440}
441
442pub fn distortion_max(s: &System, w: usize, h: (f64, f64), absolute: bool) -> Result<f64> {
445 let r = distortion_ref(s, w, None)?;
446 let mut m: f64 = 0.0;
447 for k in 1..=100 {
448 let f = k as f64 / 100.0;
449 let (v, pct) = distortion_against(s, w, (h.0 * f, h.1 * f), &r, DistComp::Radial)?;
450 m = m.max(if absolute { v.abs() } else { pct.abs() });
451 }
452 Ok(m)
453}
454
455pub fn ftheta_distortion(s: &System, w: usize) -> Result<(f64, f64)> {
459 if s.field_type != FieldType::Angle {
460 invalid!("the f-theta distortion needs angle fields");
461 }
462 let (_, ny) = s.field_norm_values();
463 let mut pts = Vec::with_capacity(101);
464 for k in 0..=100 {
465 let h = k as f64 / 100.0;
466 pts.push(((h * ny).to_radians(), chief_xy(s, (0.0, h), w)?[1]));
467 }
468 let c =
469 pts.iter().map(|(a, y)| a * y).sum::<f64>() / pts.iter().map(|(a, _)| a * a).sum::<f64>();
470 let (mut da, mut dp): (f64, f64) = (0.0, 0.0);
471 for &(a, y) in &pts {
472 let d = (y - c * a).abs();
473 da = da.max(d);
474 if a != 0.0 {
475 dp = dp.max(100.0 * d / (c * a).abs());
476 }
477 }
478 if !da.is_finite() || !dp.is_finite() {
479 invalid!("the f-theta distortion is not finite");
480 }
481 Ok((da, dp))
482}