1use crate::error::Result;
29use crate::material::Material;
30use crate::pickup::pick_kind;
31use crate::pupil::Apodization;
32use crate::solves::solve_kind_info;
33use crate::surface::{After, Aperture, Tilt};
34use crate::system::{Aiming, ApertureKind, Keep, System};
35use crate::units::UnitKind;
36
37mod keep;
38mod kind_preds;
39mod solve;
40mod table;
41use crate::{invalid, notimpl};
42pub(crate) use keep::keep_for;
43pub use solve::{set_solve_value, solve_value};
44pub use table::set_surface_table_value;
45use table::{aperture_decenter, aperture_os_code};
46
47#[derive(
49 Debug,
50 Clone,
51 Copy,
52 PartialEq,
53 Eq,
54 Hash,
55 serde::Serialize,
56 serde::Deserialize,
57 schemars::JsonSchema,
58)]
59pub enum Kind {
60 Curv,
62 Radius,
64 Conic,
66 Asph(u8),
68 Zern(u16),
70 Thick,
72 Dx,
73 Dy,
74 Tx,
76 Ty,
77 Tz,
78 Dn,
80 Disp,
82 ObjX,
84 ObjY,
85 Wave(u8),
88 WaveW(u8),
90 Primary,
92 Aper,
94 ApertureType,
97 Stop,
99 FieldType,
102 Temp,
104 Pres,
105 Afocal,
107 ApodType,
110 Apod,
111 Aiming,
113 Ropd,
115 AimPupil(u8),
118 InputPol(u8),
121 FieldX(u8),
124 FieldY(u8),
125 FieldW(u8),
126 FieldVig(u8, u8),
129 Unit(UnitKind),
131 Semi,
134 Ignore,
136 ApMax,
138 ApMin,
140 ApDx,
142 ApDy,
143 ApType,
146 BeforeOrder,
148 AfterOrder,
149 ModelNd,
152 ModelVd,
153 ModelDpgf,
154 Tce,
156 MechSemi,
159 ChipZone,
160 CoordRet,
163 CoordRetSurf,
164 CurvSolve(u8),
168 ThickSolve(u8),
169 ParmSolve(u8, u8),
170 Material,
173 Parm(u8),
176 Before(u8),
179 After(u8),
181 Coating,
184 User(crate::usershape::UserKey),
186}
187
188impl Kind {
189 pub fn parse(s: &str) -> Result<Kind> {
190 if let Some(n) = s
191 .trim()
192 .strip_prefix("u_")
193 .filter(|n| !n.is_empty() && !n.contains('.'))
194 {
195 return match crate::usershape::UserKey::get(n) {
196 Some(k) => Ok(Kind::User(k)),
197 None => invalid!("no user-defined shape has the number setting {n}"),
198 };
199 }
200 let l = s.trim().to_ascii_lowercase();
201 Ok(match l.as_str() {
202 "c" | "curv" => Kind::Curv,
203 "r" | "radius" => Kind::Radius,
204 "k" | "conic" => Kind::Conic,
205 "t" | "thick" | "thickness" => Kind::Thick,
206 "dx" => Kind::Dx,
207 "dy" => Kind::Dy,
208 "tx" => Kind::Tx,
209 "ty" => Kind::Ty,
210 "tz" => Kind::Tz,
211 "dn" => Kind::Dn,
212 "disp" => Kind::Disp,
213 "objx" => Kind::ObjX,
214 "objy" => Kind::ObjY,
215 "semi" => Kind::Semi,
216 "ignore" => Kind::Ignore,
217 "apmax" => Kind::ApMax,
218 "material" => Kind::Material,
219 "apmin" => Kind::ApMin,
220 "apdx" => Kind::ApDx,
221 "apdy" => Kind::ApDy,
222 "aptype" => Kind::ApType,
223 "beforeorder" => Kind::BeforeOrder,
224 "afterorder" => Kind::AfterOrder,
225 "nd" => Kind::ModelNd,
226 "vd" => Kind::ModelVd,
227 "dpgf" => Kind::ModelDpgf,
228 "tce" => Kind::Tce,
229 "mech" => Kind::MechSemi,
230 "chip" => Kind::ChipZone,
231 "cror" => Kind::CoordRet,
232 "crsr" => Kind::CoordRetSurf,
233 "primary" => Kind::Primary,
234 "aper" => Kind::Aper,
235 "atype" => Kind::ApertureType,
236 "stop" => Kind::Stop,
237 "ftype" => Kind::FieldType,
238 "temp" => Kind::Temp,
239 "pres" => Kind::Pres,
240 "afocal" => Kind::Afocal,
241 "apodtype" => Kind::ApodType,
242 "apod" => Kind::Apod,
243 "aiming" => Kind::Aiming,
244 "ropd" => Kind::Ropd,
245 "pshx" => Kind::AimPupil(0),
246 "pshy" => Kind::AimPupil(1),
247 "pshz" => Kind::AimPupil(2),
248 "pscx" => Kind::AimPupil(3),
249 "pscy" => Kind::AimPupil(4),
250 "polun" => Kind::InputPol(0),
251 "poljx" => Kind::InputPol(1),
252 "poljy" => Kind::InputPol(2),
253 "polpx" => Kind::InputPol(3),
254 "polpy" => Kind::InputPol(4),
255 "coating" | "coat" => Kind::Coating,
256 _ => {
257 let num = |p: &str| l.strip_prefix(p).and_then(|n| n.parse::<u8>().ok());
258 if let Some(i) = num("before").filter(|&i| i < 5) {
259 return Ok(Kind::Before(i));
260 }
261 if let Some(i) = num("after").filter(|&i| i < 5) {
262 return Ok(Kind::After(i));
263 }
264 if let Some(i) = num("parm").or_else(|| num("p")) {
265 return Ok(Kind::Parm(i));
266 }
267 if let Some(i) = num("csp").filter(|&i| (1..=2).contains(&i)) {
268 return Ok(Kind::CurvSolve(i - 1));
269 }
270 if let Some(i) = num("tsp").filter(|&i| (1..=3).contains(&i)) {
271 return Ok(Kind::ThickSolve(i - 1));
272 }
273 if let Some((i, n)) = l
274 .strip_prefix("psp")
275 .and_then(|r| r.split_once('_'))
276 .and_then(|(i, n)| Some((i.parse::<u8>().ok()?, n.parse::<u8>().ok()?)))
277 .filter(|&(i, n)| (1..=3).contains(&i) && n >= 1)
278 {
279 return Ok(Kind::ParmSolve(n, i - 1));
280 }
281 for (j, pre) in VIG.iter().enumerate() {
282 if let Some(n) = l.strip_prefix(pre).and_then(|v| v.parse::<u16>().ok()) {
283 if (1..=256).contains(&n) {
284 return Ok(Kind::FieldVig((n - 1) as u8, j as u8));
285 }
286 }
287 }
288 for (pre, f) in [
289 ("wwt", Kind::WaveW as fn(u8) -> Kind),
290 ("fx", Kind::FieldX),
291 ("fy", Kind::FieldY),
292 ("fwt", Kind::FieldW),
293 ] {
294 if let Some(n) = l.strip_prefix(pre).and_then(|v| v.parse::<u16>().ok()) {
295 if (1..=256).contains(&n) {
296 return Ok(f((n - 1) as u8));
297 }
298 }
299 }
300 if let Some(n) = l.strip_prefix("wave").and_then(|v| v.parse::<u16>().ok()) {
301 if (1..=256).contains(&n) {
302 return Ok(Kind::Wave((n - 1) as u8));
303 }
304 }
305 if let Some(n) = l.strip_prefix('z').and_then(|v| v.parse::<u16>().ok()) {
306 if (1..=231).contains(&n) {
307 return Ok(Kind::Zern(n));
308 }
309 }
310 if let Some(n) = l.strip_prefix('a').and_then(|v| v.parse::<u8>().ok()) {
311 if (2..=16).contains(&n) && n % 2 == 0 {
312 return Ok(Kind::Asph(n / 2 - 1));
313 }
314 }
315 invalid!("parameter type {s} (c r k a2..a16 z1..z231 t dx dy tx ty tz dn disp objx objy wave1.. wwt1.. primary aper fx1.. fy1.. fwt1.. u_<setting>, for pickups also semi p1.. before0..4 after0..4 coating)")
316 }
317 })
318 }
319
320 pub fn name(&self) -> String {
321 match self {
322 Kind::Curv => "c".into(),
323 Kind::Radius => "r".into(),
324 Kind::Conic => "k".into(),
325 Kind::Asph(i) => format!("a{}", 2 * (*i as usize + 1)),
326 Kind::Zern(j) => format!("z{j}"),
327 Kind::Thick => "t".into(),
328 Kind::Dx => "dx".into(),
329 Kind::Dy => "dy".into(),
330 Kind::Tx => "tx".into(),
331 Kind::Ty => "ty".into(),
332 Kind::Tz => "tz".into(),
333 Kind::Dn => "dn".into(),
334 Kind::Disp => "disp".into(),
335 Kind::ObjX => "objx".into(),
336 Kind::ObjY => "objy".into(),
337 Kind::Wave(i) => format!("wave{}", *i as usize + 1),
338 Kind::WaveW(i) => format!("wwt{}", *i as usize + 1),
339 Kind::Primary => "primary".into(),
340 Kind::Aper => "aper".into(),
341 Kind::ApertureType => "atype".into(),
342 Kind::Stop => "stop".into(),
343 Kind::FieldType => "ftype".into(),
344 Kind::Temp => "temp".into(),
345 Kind::Pres => "pres".into(),
346 Kind::Afocal => "afocal".into(),
347 Kind::ApodType => "apodtype".into(),
348 Kind::Apod => "apod".into(),
349 Kind::Aiming => "aiming".into(),
350 Kind::Ropd => "ropd".into(),
351 Kind::InputPol(i) => {
352 ["polun", "poljx", "poljy", "polpx", "polpy"][(*i as usize).min(4)].into()
353 }
354 Kind::AimPupil(i) => {
355 ["pshx", "pshy", "pshz", "pscx", "pscy"][(*i as usize).min(4)].into()
356 }
357 Kind::FieldX(i) => format!("fx{}", *i as usize + 1),
358 Kind::FieldY(i) => format!("fy{}", *i as usize + 1),
359 Kind::FieldW(i) => format!("fwt{}", *i as usize + 1),
360 Kind::FieldVig(i, j) => format!("{}{}", VIG[*j as usize], *i as usize + 1),
361 Kind::Unit(u) => u.name().into(),
362 Kind::Semi => "semi".into(),
363 Kind::Ignore => "ignore".into(),
364 Kind::ApMax => "apmax".into(),
365 Kind::Material => "material".into(),
366 Kind::ApMin => "apmin".into(),
367 Kind::ApDx => "apdx".into(),
368 Kind::ApDy => "apdy".into(),
369 Kind::ApType => "aptype".into(),
370 Kind::BeforeOrder => "beforeorder".into(),
371 Kind::AfterOrder => "afterorder".into(),
372 Kind::ModelNd => "nd".into(),
373 Kind::ModelVd => "vd".into(),
374 Kind::ModelDpgf => "dpgf".into(),
375 Kind::Tce => "tce".into(),
376 Kind::MechSemi => "mech".into(),
377 Kind::ChipZone => "chip".into(),
378 Kind::CoordRet => "cror".into(),
379 Kind::CoordRetSurf => "crsr".into(),
380 Kind::CurvSolve(i) => format!("csp{}", i + 1),
381 Kind::ThickSolve(i) => format!("tsp{}", i + 1),
382 Kind::ParmSolve(n, i) => format!("psp{}_{n}", i + 1),
383 Kind::Parm(i) => format!("p{i}"),
384 Kind::Before(i) => format!("before{i}"),
385 Kind::After(i) => format!("after{i}"),
386 Kind::Coating => "coating".into(),
387 Kind::User(k) => format!("u_{}", k.name()),
388 }
389 }
390}
391
392#[derive(
394 Debug,
395 Clone,
396 Copy,
397 PartialEq,
398 Eq,
399 Hash,
400 serde::Serialize,
401 serde::Deserialize,
402 schemars::JsonSchema,
403)]
404#[serde(rename_all = "snake_case")]
405pub enum Target {
406 Surf(usize),
408 Unit(usize),
410 System,
412}
413
414#[derive(
417 Debug,
418 Clone,
419 Copy,
420 PartialEq,
421 Eq,
422 Hash,
423 serde::Serialize,
424 serde::Deserialize,
425 schemars::JsonSchema,
426)]
427pub struct Param {
428 pub target: Target,
429 pub kind: Kind,
430}
431
432impl Param {
433 pub fn new(surf: usize, kind: Kind) -> Param {
435 let target = if kind.is_global() {
436 Target::System
437 } else if kind.is_unit() {
438 Target::Unit(surf)
439 } else {
440 Target::Surf(surf)
441 };
442 Param { target, kind }
443 }
444 pub fn system(kind: Kind) -> Param {
446 debug_assert!(kind.is_global());
447 Param {
448 target: Target::System,
449 kind,
450 }
451 }
452 pub fn obj_x() -> Param {
453 Param::system(Kind::ObjX)
454 }
455 pub fn obj_y() -> Param {
456 Param::system(Kind::ObjY)
457 }
458 pub fn unit(u: usize, kind: UnitKind) -> Param {
460 Param {
461 target: Target::Unit(u),
462 kind: Kind::Unit(kind),
463 }
464 }
465 pub fn surface(&self) -> Option<usize> {
467 match self.target {
468 Target::Surf(j) => Some(j),
469 _ => None,
470 }
471 }
472 pub fn unit_index(&self) -> Option<usize> {
474 match self.target {
475 Target::Unit(u) => Some(u),
476 _ => None,
477 }
478 }
479 pub fn index(&self) -> usize {
481 match self.target {
482 Target::Surf(j) | Target::Unit(j) => j,
483 Target::System => 0,
484 }
485 }
486 pub fn name(&self) -> String {
487 match self.target {
488 Target::System => self.kind.name(),
489 Target::Unit(u) => format!("unit{u}.{}", self.kind.name()),
490 Target::Surf(j) => format!("{j}.{}", self.kind.name()),
491 }
492 }
493}
494
495impl System {
496 pub fn param(&self, spec: &str) -> Result<Param> {
499 let s = spec.trim();
500 if let Ok(k) = Kind::parse(s) {
501 if k.is_global() {
502 let p = Param::new(0, k);
503 self.check_param(p)?;
504 return Ok(p);
505 }
506 }
507 let Some((t, k)) = s.rsplit_once('.') else {
508 invalid!("parameter {s} (write surface.type, e.g. 3.t)");
509 };
510 let (t, force) = if let Some(x) = t.strip_prefix("unit:") {
511 (x, Some(true))
512 } else if let Some(x) = t.strip_prefix("surf:") {
513 (x, Some(false))
514 } else {
515 (t, None)
516 };
517 let unit = if force == Some(false) || t.trim().parse::<usize>().is_ok() {
518 None
519 } else {
520 self.find_unit(t)
521 };
522 if force == Some(true) && unit.is_none() {
523 invalid!("no lens or group named {}", t.trim());
524 }
525 if let Some(u) = unit {
526 if force.is_none() && self.find_surface(t).is_ok() {
527 let t = t.trim();
528 invalid!("{t} is the name of a surface and of a lens or group (write unit:{t}.{k} or surf:{t}.{k})");
529 }
530 let p = Param::unit(u, UnitKind::parse(k)?);
531 self.check_param(p)?;
532 return Ok(p);
533 }
534 let kind = Kind::parse(k)?;
535 let surf = self.find_surface(t)?;
536 let p = Param::new(surf, kind);
537 self.check_param(p)?;
538 Ok(p)
539 }
540
541 pub fn param_name(&self, p: Param) -> String {
543 match p.kind {
544 Kind::Unit(k) => match self.units.get(p.index()) {
545 Some(u) => format!("{}.{}", u.name, k.name()),
546 None => p.name(),
547 },
548 _ => p.name(),
549 }
550 }
551
552 pub fn check_param(&self, p: Param) -> Result<()> {
554 if Param::new(p.index(), p.kind) != p {
556 invalid!("parameter {}: the target doesn't match the kind", p.name());
557 }
558 if p.kind.is_pick_only() && !p.kind.is_table_only() {
559 invalid!("{} is a pickup quantity, not a parameter", p.kind.name());
560 }
561 if p.kind.is_object() {
562 return Ok(());
563 }
564 if let Kind::Wave(i) | Kind::WaveW(i) = p.kind {
565 if i as usize >= self.wavelengths.len() {
566 let (kind, nw) = (p.kind.name(), self.wavelengths.len());
567 invalid!("{kind} (there are {nw} wavelengths)");
568 }
569 return Ok(());
570 }
571 if let Kind::FieldX(i) | Kind::FieldY(i) | Kind::FieldW(i) | Kind::FieldVig(i, _) = p.kind {
572 if i as usize >= self.fields.len() {
573 let (kind, nf) = (p.kind.name(), self.fields.len());
574 invalid!("{kind} (there are {nf} field points)");
575 }
576 return Ok(());
577 }
578 if p.kind.is_system_value() {
579 return Ok(());
580 }
581 if let Kind::Unit(k) = p.kind {
582 let Some(u) = self.units.get(p.index()) else {
583 invalid!("lens or group {} ({} of them)", p.index(), self.units.len());
584 };
585 if matches!(k, UnitKind::Dn | UnitKind::Disp) && self.unit_media(p.index()).is_empty() {
586 let (unit, medium) = (&u.name, k.name());
587 invalid!("lens or group {unit} has no medium (glass) inside ({medium})");
588 }
589 return Ok(());
590 }
591 let Target::Surf(j) = p.target else {
592 invalid!("parameter {} is not on a surface", p.name());
593 };
594 if j >= self.surfaces.len() {
595 let last = self.surfaces.len() - 1;
596 invalid!("surface {j} (surfaces are 0 to {last})");
597 }
598 let d = &self.surfaces[j];
599 let curved = d.shape_params();
600 match p.kind {
601 Kind::Curv | Kind::Radius | Kind::Conic if j == 0 || !curved => {
602 invalid!("surface {j} ({:?}) {}", d.typ(), p.kind.name());
603 }
604 Kind::Asph(_) if !crate::pickup::takes_asph(d) => {
605 invalid!("surface {j} is not an even asphere ({})", p.kind.name());
606 }
607 Kind::Asph(i) if i >= 8 => invalid!("asphere coefficient {}", p.kind.name()),
608 Kind::Zern(n) => match &d.zern() {
609 Some(z) if (n as usize) <= crate::freeform::ZernSag::max_terms(z.fringe) => {}
610 Some(_) => invalid!("surface {j} Zernike term {n} is over the limit"),
611 None => invalid!(
612 "surface {j} is not a Zernike Sag surface ({})",
613 p.kind.name()
614 ),
615 },
616 _ => {}
617 }
618 if let Kind::User(k) = p.kind {
621 if d.user_shape().and_then(|u| u.value(k.name())).is_none() {
622 let kind = p.kind.name();
623 invalid!("surface {j} is not a user-defined shape with the number setting {kind}");
624 }
625 }
626 if matches!(
627 p.kind,
628 Kind::Curv | Kind::Radius | Kind::Conic | Kind::Asph(_) | Kind::Zern(_) | Kind::User(_)
629 ) && !d.takes_shape_param(p.kind)
630 {
631 let (typ, kind) = (d.typ(), p.kind.name());
632 invalid!("surface {j} ({typ:?}): {kind} doesn't change the shape of this surface type");
633 }
634 match p.kind {
635 Kind::Dx | Kind::Dy | Kind::Tx | Kind::Ty | Kind::Tz if j == 0 => {
636 notimpl!("tilt or decenter of the object surface");
637 }
638 Kind::Dn | Kind::Disp if d.is_mirror() || d.is_coord_break() => {
639 let kind = p.kind.name();
640 invalid!("surface {j} is a mirror or a coordinate break (the medium is surface {kind} before it)");
641 }
642 Kind::Thick if j == self.image() => invalid!("thickness of the image surface"),
643 _ => {}
644 }
645 Ok(())
646 }
647
648 pub fn get_param(&self, p: Param) -> Result<f64> {
650 self.check_param(p)?;
651 if p.kind.is_object() {
652 let kind = p.kind.name();
653 invalid!("field point {kind} is not system data (it is a trace input)");
654 }
655 match p.kind {
656 Kind::Wave(i) => return Ok(self.wavelengths[i as usize]),
657 Kind::WaveW(i) => return Ok(self.weights[i as usize]),
658 Kind::Primary => return Ok(self.primary as f64 + 1.0),
659 Kind::Aper => return Ok(self.aperture.1),
660 Kind::ApertureType => return Ok(self.aperture.0.os_code() as f64),
661 Kind::Stop => return Ok(self.stop() as f64),
662 Kind::FieldType => match self.field_type.os_code() {
663 Some(n) => return Ok(n as f64),
664 None => invalid!("a solved field type has no field type number"),
665 },
666 Kind::Temp => return Ok(self.temperature),
667 Kind::Pres => return Ok(self.pressure),
668 Kind::Afocal => return Ok(self.afocal as u8 as f64),
669 Kind::ApodType => return Ok(self.apodization.os_code() as f64),
670 Kind::Apod => return Ok(self.apodization.factor()),
671 Kind::Aiming => return Ok(self.aiming.os_code() as f64),
672 Kind::Ropd => return Ok(self.ropd as f64),
673 Kind::AimPupil(i) => return Ok(self.aim_pupil.value(i)),
674 Kind::InputPol(i) => return Ok(self.input_pol.value(i)),
675 Kind::FieldX(i) => return Ok(self.fields[i as usize].x),
676 Kind::FieldY(i) => return Ok(self.fields[i as usize].y),
677 Kind::FieldW(i) => return Ok(self.fields[i as usize].w),
678 Kind::FieldVig(i, j) => return Ok(*vig_mut(&mut self.fields[i as usize].clone(), j)),
679 _ => {}
680 }
681 if let Kind::Unit(k) = p.kind {
682 let u = &self.units[p.index()];
683 if let Some(i) = k.motion_index() {
684 return Ok(u.motion[i]);
685 }
686 return Ok(match k {
687 UnitKind::Shift => u.shift,
688 _ => {
689 let v: Vec<f64> = self
690 .unit_media(p.index())
691 .iter()
692 .map(|&j| {
693 let d = &self.surfaces[j];
694 if k == UnitKind::Dn {
695 d.dn
696 } else {
697 d.disp
698 }
699 })
700 .collect();
701 if v.iter().any(|&x| x != v[0]) {
702 let (unit, medium) = (&u.name, k.name());
703 invalid!("lens or group {unit}: medium {medium} differs between surfaces ({v:?})");
704 }
705 v[0]
706 }
707 });
708 }
709 if p.kind.is_solve_value() {
710 return solve::get(self, p);
711 }
712 let d = &self.surfaces[p.index()];
713 Ok(match p.kind {
714 Kind::Curv => d.c,
715 Kind::Radius => {
716 if d.c == 0.0 {
717 0.0
718 } else {
719 1.0 / d.c
720 }
721 }
722 Kind::Conic => d.k,
723 Kind::Asph(i) => d.asph().get(i as usize).copied().unwrap_or(0.0),
724 Kind::Zern(n) => d
725 .zern()
726 .as_ref()
727 .and_then(|z| z.coef.get(n as usize - 1).copied())
728 .unwrap_or(0.0),
729 Kind::User(k) => d
730 .user_shape()
731 .and_then(|u| u.value(k.name()))
732 .unwrap_or(0.0),
733 Kind::Thick => d.t,
734 Kind::Semi => d.semi,
735 Kind::Ignore => f64::from(u8::from(d.ignore)),
736 Kind::Material => invalid!("{}: a material is a name, not a number", p.name()),
737 Kind::Coating => invalid!("{}: a coating is a name, not a number", p.name()),
738 Kind::ModelNd | Kind::ModelVd | Kind::ModelDpgf => match d.mat {
739 Material::Model { nd, vd, dpgf } => match p.kind {
740 Kind::ModelNd => nd,
741 Kind::ModelVd => vd,
742 _ => dpgf,
743 },
744 _ => invalid!("{}: surface material is not a model glass", p.name()),
745 },
746 Kind::Tce => d.tce,
747 Kind::MechSemi => self.lens_radius(p.index()),
748 Kind::ChipZone => d.chip_zone,
749 Kind::CoordRet => d.coord_return.map_or(0.0, |c| c.mode.os_code() as f64),
750 Kind::CoordRetSurf => d.coord_return.map_or(0.0, |c| c.surf as f64),
751 Kind::ApMax => match d.ap {
752 Aperture::Circular { max, .. } | Aperture::Obsc { max, .. } => max,
753 _ => invalid!(
754 "{}: surface has no circular aperture or obscuration",
755 p.name()
756 ),
757 },
758 Kind::ApMin => match d.ap {
759 Aperture::Circular { min, .. } | Aperture::Obsc { min, .. } => min,
760 _ => invalid!(
761 "{}: surface has no circular aperture or obscuration",
762 p.name()
763 ),
764 },
765 Kind::ApDx | Kind::ApDy => match aperture_decenter(&d.ap) {
766 Some((dx, dy)) => {
767 if p.kind == Kind::ApDx {
768 dx
769 } else {
770 dy
771 }
772 }
773 None => invalid!("{}: surface has no aperture", p.name()),
774 },
775 Kind::ApType => aperture_os_code(&d.ap) as f64,
776 Kind::Before(i) => d.before.map_or(0.0, |t| t.d[i as usize]),
777 Kind::BeforeOrder => d.before.map_or(0.0, |t| f64::from(t.order)),
778 Kind::After(i) => match d.after {
779 After::Tilt(t) => t.d[i as usize],
780 After::None => 0.0,
781 After::Reverse => invalid!(
782 "{}: the tilt and decenter after the surface reverses the one before",
783 p.name()
784 ),
785 },
786 Kind::AfterOrder => match d.after {
787 After::Tilt(t) => f64::from(t.order),
788 After::None => 0.0,
789 After::Reverse => invalid!(
790 "{}: the tilt and decenter after the surface reverses the one before",
791 p.name()
792 ),
793 },
794 Kind::Dn => d.dn,
795 Kind::Disp => d.disp,
796 k => {
797 let i = k.tilt_index().expect("tilt kind");
798 if d.is_coord_break() {
799 d.cb()[i]
800 } else {
801 d.before.map(|b| b.d[i]).unwrap_or(0.0)
802 }
803 }
804 })
805 }
806
807 pub fn set_param(&mut self, p: Param, v: f64) -> Result<()> {
809 self.set_params(&[(p, v)])
810 }
811
812 pub fn set_params(&mut self, changes: &[(Param, f64)]) -> Result<()> {
814 *self = self.with_params(changes)?;
815 Ok(())
816 }
817
818 pub fn with_params(&self, changes: &[(Param, f64)]) -> Result<System> {
821 let mut s = self.with_params_solve(changes, true)?;
822 s.update_semi();
823 Ok(s)
824 }
825
826 pub fn with_params_fast(&self, changes: &[(Param, f64)]) -> Result<System> {
829 let mut s = self.with_params_solve(changes, true)?;
830 if s.semi_affects_trace() {
831 s.update_semi();
832 }
833 Ok(s)
834 }
835
836 pub(crate) fn with_params_solve(
838 &self,
839 changes: &[(Param, f64)],
840 solve: bool,
841 ) -> Result<System> {
842 let (flat, motions, picked) = self.unit_changes(changes)?;
843 let mut keep = keep_for(&flat);
844 if !motions.is_empty() {
845 keep.frames = false;
846 }
847 let mut s = self.clone_keep(keep);
848 s.apply(&flat)?;
849 for &(u, k, v) in &motions {
850 let x = &mut s.rx_mut().units[u];
851 match k.motion_index() {
852 Some(i) => x.motion[i] = v,
853 None => x.shift = v,
854 }
855 }
856 for &(p, v) in &picked {
858 let now = s.get_param(p)?;
859 if (now - v).abs() > 1e-12 * (1.0 + v.abs()) {
860 let name = p.name();
861 invalid!("{name} becomes {now} by a pickup and doesn't match {v} of the lens or group change");
862 }
863 }
864 let any = !s.solves.is_empty() || !s.macro_parms.is_empty();
867 if solve && any && !(keep.paraxial && s.macro_parms.is_empty() && s.solves_still_hold()) {
868 s.solve_thickness()?;
869 }
870 if flat.iter().any(|(p, _)| p.index() == 0) {
871 s.check()?;
872 }
873 Ok(s)
874 }
875
876 #[allow(clippy::type_complexity)]
879 fn unit_changes(
880 &self,
881 changes: &[(Param, f64)],
882 ) -> Result<(
883 Vec<(Param, f64)>,
884 Vec<(usize, UnitKind, f64)>,
885 Vec<(Param, f64)>,
886 )> {
887 if !changes.iter().any(|(p, _)| p.kind.is_unit()) {
888 return Ok((changes.to_vec(), Vec::new(), Vec::new()));
889 }
890 let mut flat: Vec<(Param, f64, bool)> = Vec::new();
892 let mut motions = Vec::new();
893 let mut shifted: Vec<(usize, f64)> = Vec::new();
895 let mut shift_at: Option<usize> = None;
896 for &(p, v) in changes {
897 let Kind::Unit(k) = p.kind else {
898 flat.push((p, v, false));
899 continue;
900 };
901 self.check_param(p)?;
902 if !v.is_finite() {
903 invalid!("{} = {v}", self.param_name(p));
904 }
905 match k {
906 UnitKind::Shift => {
907 let d = v - self.units[p.index()].shift;
908 for (q, f) in self.unit_terms(p, false)? {
909 match shifted.iter_mut().find(|x| x.0 == q.index()) {
910 Some(x) => x.1 += f * d,
911 None => shifted.push((q.index(), f * d)),
912 }
913 }
914 shift_at.get_or_insert(flat.len());
915 motions.push((p.index(), k, v));
916 }
917 UnitKind::Dn | UnitKind::Disp => {
918 for (q, _) in self.unit_terms(p, false)? {
919 flat.push((q, v, true));
920 }
921 }
922 _ => motions.push((p.index(), k, v)),
923 }
924 }
925 if let Some(at) = shift_at {
926 let th: Vec<(Param, f64, bool)> = shifted
927 .iter()
928 .filter(|x| x.1 != 0.0)
929 .map(|&(j, d)| (Param::new(j, Kind::Thick), self.surfaces[j].t + d, true))
930 .collect();
931 flat.splice(at..at, th);
932 }
933 let mut picked = Vec::new();
935 let srcs: Vec<Param> = flat.iter().map(|x| x.0).collect();
936 flat.retain(|&(p, v, gen)| match self.pickup_of(p) {
937 Some(pk)
938 if gen
939 && srcs.iter().any(|q| {
940 q.index() == pk.src
941 && pick_kind(&self.surfaces[q.index()], q.kind) == Some(pk.what)
942 }) =>
943 {
944 picked.push((p, v));
945 false
946 }
947 _ => true,
948 });
949 Ok((
950 flat.into_iter().map(|(p, v, _)| (p, v)).collect(),
951 motions,
952 picked,
953 ))
954 }
955
956 pub(crate) fn unit_linear(&self, p: Param) -> Result<Vec<(Param, f64)>> {
960 self.unit_terms(p, true)
961 }
962
963 fn unit_terms(&self, p: Param, drop_picked: bool) -> Result<Vec<(Param, f64)>> {
965 let Kind::Unit(k) = p.kind else {
966 return Ok(vec![(p, 1.0)]);
967 };
968 let u = &self.units[p.index()];
969 let mut out: Vec<(Param, f64)> = Vec::new();
970 match k {
971 UnitKind::Shift => {
972 let mut add = |j: usize, f: f64| match out.iter_mut().find(|x| x.0.index() == j) {
973 Some(x) => x.1 += f,
974 None => out.push((Param::new(j, Kind::Thick), f)),
975 };
976 for s in &u.spans {
977 add(s[0] - 1, 1.0);
978 add(s[1], -1.0);
979 }
980 out.retain(|(q, f)| {
981 *f != 0.0
982 && self.surfaces[q.index()].t.is_finite()
983 && !self.solves.iter().any(|x| x.surf == q.index())
984 });
985 if drop_picked {
986 let all: Vec<usize> = out.iter().map(|x| x.0.index()).collect();
987 out.retain(|(q, _)| match self.pickup_of(*q) {
988 Some(pk) => !all.contains(&pk.src),
989 None => true,
990 });
991 }
992 }
993 UnitKind::Dn | UnitKind::Disp => {
994 let kind = if k == UnitKind::Dn {
995 Kind::Dn
996 } else {
997 Kind::Disp
998 };
999 for j in self.unit_media(p.index()) {
1000 out.push((Param::new(j, kind), 1.0));
1001 }
1002 }
1003 _ => out.push((p, 1.0)),
1004 }
1005 Ok(out)
1006 }
1007
1008 fn apply(&mut self, changes: &[(Param, f64)]) -> Result<Keep> {
1010 for &(p, v) in changes {
1012 self.check_param(p)?;
1013 if p.kind.is_object() {
1014 let kind = p.kind.name();
1015 invalid!("field point {kind} is not system data (it is a trace input)");
1016 }
1017 if !v.is_finite() && !(p.kind == Kind::Thick && p.index() == 0) {
1018 invalid!("{} = {v}", p.name());
1019 }
1020 if p.kind.is_wave() {
1021 if !(v > 0.0) {
1022 invalid!("{} = {v} µm", p.name());
1023 }
1024 continue;
1025 }
1026 if p.kind.is_solve_value() {
1027 solve::check(self, p, v)?;
1028 }
1029 match p.kind {
1030 Kind::Primary
1031 if v.fract() != 0.0 || v < 1.0 || v > self.wavelengths.len() as f64 =>
1032 {
1033 invalid!("primary wavelength {v} (1 to {})", self.wavelengths.len());
1034 }
1035 Kind::WaveW(_) | Kind::FieldW(_) if v < 0.0 => invalid!("{} = {v}", p.name()),
1036 Kind::Aper if !(v > 0.0) => invalid!("aperture value {v}"),
1037 Kind::ApertureType
1038 if v.fract() != 0.0 || ApertureKind::from_os_code(v as i64).is_none() =>
1039 {
1040 invalid!("aperture type {v} (0 to 5)");
1041 }
1042 Kind::Semi if v < 0.0 => invalid!("{} = {v}", p.name()),
1043 Kind::Ignore if v != 0.0 && v != 1.0 => invalid!("{} = {v} (0 or 1)", p.name()),
1044 Kind::ApMax if v < 0.0 => invalid!("{} = {v}", p.name()),
1045 Kind::Material => invalid!("{}: a material is a name, not a number", p.name()),
1046 Kind::Coating => invalid!("{}: a coating is a name, not a number", p.name()),
1047 Kind::ModelNd | Kind::ModelVd | Kind::ModelDpgf
1048 if !matches!(self.surfaces[p.index()].mat, Material::Model { .. }) =>
1049 {
1050 invalid!("{}: surface material is not a model glass", p.name())
1051 }
1052 Kind::ModelNd if !(v > 0.0) => invalid!("{} = {v}", p.name()),
1053 Kind::ApMin | Kind::MechSemi | Kind::ChipZone if !(v >= 0.0) => {
1054 invalid!("{} = {v}", p.name())
1055 }
1056 Kind::CoordRet | Kind::CoordRetSurf => crate::coord_return::check(self, p, v)?,
1057 Kind::BeforeOrder | Kind::AfterOrder if v != 0.0 && v != 1.0 => {
1058 invalid!("{} = {v} (0 or 1)", p.name())
1059 }
1060 Kind::ApType if v.fract() != 0.0 || !(0.0..=2.0).contains(&v) => {
1061 invalid!("{}: aperture type {v} (0 to 2 can be set)", p.name())
1062 }
1063 Kind::ApType
1064 if v != 0.0
1065 && !matches!(
1066 self.surfaces[p.index()].ap,
1067 Aperture::Circular { .. } | Aperture::Obsc { .. }
1068 ) =>
1069 {
1070 invalid!(
1071 "{}: surface has no circular aperture or obscuration (its radii are kept)",
1072 p.name()
1073 )
1074 }
1075 Kind::ApMin
1076 if !matches!(
1077 self.surfaces[p.index()].ap,
1078 Aperture::Circular { .. } | Aperture::Obsc { .. }
1079 ) =>
1080 {
1081 invalid!(
1082 "{}: surface has no circular aperture or obscuration",
1083 p.name()
1084 )
1085 }
1086 Kind::ApDx | Kind::ApDy
1087 if aperture_decenter(&self.surfaces[p.index()].ap).is_none() =>
1088 {
1089 invalid!("{}: surface has no aperture", p.name())
1090 }
1091 Kind::Before(_) | Kind::BeforeOrder | Kind::After(_) | Kind::AfterOrder
1092 if self.surfaces[p.index()].is_coord_break() =>
1093 {
1094 invalid!(
1095 "{}: a coordinate break has no surface tilt or decenter",
1096 p.name()
1097 )
1098 }
1099 Kind::After(_) | Kind::AfterOrder
1100 if self.surfaces[p.index()].after == After::Reverse =>
1101 {
1102 invalid!(
1103 "{}: the tilt and decenter after the surface reverses the one before",
1104 p.name()
1105 )
1106 }
1107 Kind::ApMax
1108 if !matches!(
1109 self.surfaces[p.index()].ap,
1110 Aperture::Circular { .. } | Aperture::Obsc { .. }
1111 ) =>
1112 {
1113 invalid!(
1114 "{}: surface has no circular aperture or obscuration",
1115 p.name()
1116 )
1117 }
1118 Kind::Ignore if p.index() == 0 || p.index() + 1 >= self.surfaces.len() => {
1119 invalid!(
1120 "{}: the object and image surfaces can't be ignored",
1121 p.name()
1122 );
1123 }
1124 Kind::FieldType
1125 if v.fract() != 0.0
1126 || crate::system::FieldType::from_os_code(v as i64).is_none() =>
1127 {
1128 invalid!("field type {v} (0 to 3)");
1129 }
1130 Kind::Pres if v < 0.0 => invalid!("pressure {v} atm"),
1131 Kind::Temp if v < -273.15 => invalid!("temperature {v} °C"),
1132 Kind::Afocal if v != 0.0 && v != 1.0 => invalid!("{} = {v} (0 or 1)", p.name()),
1133 Kind::ApodType if v.fract() != 0.0 || !(0.0..=2.0).contains(&v) => {
1134 invalid!("apodization type {v} (0 to 2)");
1135 }
1136 Kind::Apod if v < 0.0 => invalid!("apodization factor {v}"),
1137 Kind::Aiming if v.fract() != 0.0 || !(0.0..=2.0).contains(&v) => {
1138 invalid!("ray aiming {v} (0 to 2)");
1139 }
1140 Kind::Ropd if v.fract() != 0.0 || !(0.0..=3.0).contains(&v) => {
1141 invalid!("OPD reference {v} (0 to 3)");
1142 }
1143 Kind::Stop
1144 if v.fract() != 0.0 || v < 1.0 || v > self.surfaces.len() as f64 - 2.0 =>
1145 {
1146 let last = self.surfaces.len() - 2;
1147 invalid!("stop surface {v} (1 to {last})");
1148 }
1149 _ => {}
1150 }
1151 if p.kind.is_system_value() {
1152 continue;
1153 }
1154 let solved = |k: Kind| {
1155 self.solves
1156 .iter()
1157 .find(|q| q.surf == p.index() && q.kind.param_kind() == k)
1158 };
1159 let q = match p.kind {
1160 Kind::Thick => solved(Kind::Thick),
1161 Kind::Curv | Kind::Radius => solved(Kind::Curv),
1162 _ => None,
1163 };
1164 if let Some(q) = q {
1165 invalid!(
1166 "{} is set by a solve ({})",
1167 p.name(),
1168 solve_kind_info(q.kind).0
1169 );
1170 }
1171 if let Some(pk) = self.pickup_of(p) {
1172 let (name, src, scale, offset) = (p.name(), pk.src, pk.scale, pk.offset);
1173 invalid!("{name} is a pickup from surface {src} (scale {scale}, offset {offset}); change the source surface");
1174 }
1175 }
1176 let mut index = false;
1177 let waves: Vec<(usize, f64)> = changes
1179 .iter()
1180 .filter_map(|&(p, v)| match p.kind {
1181 Kind::Wave(i) => Some((i as usize, v)),
1182 _ => None,
1183 })
1184 .collect();
1185 if !waves.is_empty() {
1186 self.set_wavelengths(&waves)?;
1187 index = true;
1188 }
1189 for &(p, v) in changes {
1190 let rx = self.rx_mut();
1191 match p.kind {
1192 Kind::Wave(_) => continue,
1193 Kind::WaveW(i) => rx.weights[i as usize] = v,
1194 Kind::Primary => rx.primary = v as usize - 1,
1195 Kind::Aper => rx.aperture.1 = v,
1196 Kind::ApertureType => {
1197 if let Some(k) = ApertureKind::from_os_code(v as i64) {
1199 rx.aperture.0 = k;
1200 }
1201 }
1202 Kind::FieldType => {
1203 if let Some(t) = crate::system::FieldType::from_os_code(v as i64) {
1205 rx.field_type = t;
1206 }
1207 }
1208 Kind::Stop => {
1209 for (j, d) in rx.surfaces.iter_mut().enumerate() {
1210 d.stop = j == v as usize;
1211 }
1212 }
1213 Kind::Temp => {
1214 rx.temperature = v;
1215 index = true;
1216 }
1217 Kind::Pres => {
1218 rx.pressure = v;
1219 index = true;
1220 }
1221 Kind::Afocal => rx.afocal = v != 0.0,
1222 Kind::ApodType => {
1224 let g = changes
1225 .iter()
1226 .find(|(q, _)| q.kind == Kind::Apod)
1227 .map_or(rx.apodization.factor(), |c| c.1);
1228 rx.apodization = Apodization::from_os_code(v as i64, g);
1229 }
1230 Kind::Apod => {
1231 if let Apodization::Gaussian(g) = &mut rx.apodization {
1232 *g = v;
1233 }
1234 }
1235 Kind::Aiming => rx.aiming = Aiming::from_os_code(v as i64),
1236 Kind::Ropd => rx.ropd = v as i64,
1237 Kind::AimPupil(i) => rx.aim_pupil.set(i, v),
1238 Kind::InputPol(i) => rx.input_pol.set(i, v),
1239 Kind::FieldX(i) => rx.fields[i as usize].x = v,
1240 Kind::FieldY(i) => rx.fields[i as usize].y = v,
1241 Kind::FieldW(i) => rx.fields[i as usize].w = v,
1242 Kind::FieldVig(i, j) => *vig_mut(&mut rx.fields[i as usize], j) = v,
1243 _ => {}
1244 }
1245 if p.kind.is_system_value() {
1246 continue;
1247 }
1248 if p.kind.is_solve_value() {
1249 solve::set_solve_value(self.rx_mut(), p, v);
1250 continue;
1251 }
1252 let d = &mut self.rx_mut().surfaces[p.index()];
1253 match p.kind {
1254 Kind::Curv => d.c = v,
1255 Kind::Radius => d.c = if v == 0.0 { 0.0 } else { 1.0 / v },
1256 Kind::Conic => d.k = v,
1257 Kind::Asph(i) => {
1258 let i = i as usize;
1259 if let Some(a) = d.asph_mut().filter(|a| a.len() <= i) {
1260 a.resize(8, 0.0);
1261 }
1262 d.set_asph_at(i, v);
1263 }
1264 Kind::Zern(n) => {
1265 let z = std::sync::Arc::make_mut(
1266 d.zern_mut().and_then(|z| z.as_mut()).expect("Zernike data"),
1267 );
1268 let i = n as usize - 1;
1269 if z.coef.len() <= i {
1270 z.coef.resize(i + 1, 0.0);
1271 }
1272 z.coef[i] = v;
1273 z.rebuild();
1274 }
1275 Kind::User(k) => {
1276 let slot = d.user_shape_mut().expect("user-defined shape");
1277 let u = slot
1278 .as_ref()
1279 .expect("user-defined shape")
1280 .with_value(k.name(), v)?;
1281 *slot = Some(u);
1282 }
1283 Kind::Thick => d.t = v,
1284 Kind::Semi => {
1285 d.semi = v;
1286 d.semi_auto = false;
1287 if let Aperture::Floating { semi } = &mut d.ap {
1289 *semi = v;
1290 }
1291 }
1292 Kind::Ignore => d.ignore = v != 0.0,
1293 Kind::Material | Kind::Coating => {}
1295 Kind::ModelNd | Kind::ModelVd | Kind::ModelDpgf => {
1296 set_surface_table_value(d, p.kind, v);
1297 index = true;
1298 }
1299 Kind::ApMax => {
1300 if let Aperture::Circular { max, .. } | Aperture::Obsc { max, .. } = &mut d.ap {
1301 *max = v;
1302 }
1303 }
1304 Kind::ApMin
1305 | Kind::ApDx
1306 | Kind::ApDy
1307 | Kind::ApType
1308 | Kind::Before(_)
1309 | Kind::BeforeOrder
1310 | Kind::After(_)
1311 | Kind::AfterOrder
1312 | Kind::Tce
1313 | Kind::MechSemi
1314 | Kind::ChipZone
1315 | Kind::CoordRet
1316 | Kind::CoordRetSurf => {
1317 set_surface_table_value(d, p.kind, v);
1318 }
1319 Kind::Dn => {
1320 d.dn = v;
1321 index = true;
1322 }
1323 Kind::Disp => {
1324 d.disp = v;
1325 index = true;
1326 }
1327 k => {
1328 let i = k.tilt_index().expect("tilt kind");
1329 if let Some((cb, _)) = d.cb_mut() {
1330 cb[i] = v;
1331 } else {
1332 if d.before.is_none() {
1335 d.before = Some(Tilt {
1336 d: [0.0; 5],
1337 order: 0,
1338 });
1339 if d.after == After::None {
1340 d.after = After::Reverse;
1341 }
1342 }
1343 d.before.as_mut().expect("coordinate break created above").d[i] = v;
1344 }
1345 }
1346 }
1347 }
1348 if !self.pickups.is_empty() {
1349 self.resolve_pickups()?;
1350 }
1351 if index {
1352 self.resolve_media()?;
1353 }
1354 let cr = changes.iter().any(|(p, _)| p.kind.is_coord_return());
1356 if crate::coord_return::resolve_changed(self.rx_mut())? || cr {
1357 return Ok(Keep {
1358 frames: false,
1359 paraxial: false,
1360 });
1361 }
1362 Ok(keep_for(changes))
1363 }
1364}
1365
1366const VIG: [&str; 5] = ["vdx", "vdy", "vcx", "vcy", "van"];
1368
1369fn vig_mut(f: &mut crate::system::Field, j: u8) -> &mut f64 {
1371 match j {
1372 0 => &mut f.vdx,
1373 1 => &mut f.vdy,
1374 2 => &mut f.vcx,
1375 3 => &mut f.vcy,
1376 _ => &mut f.van,
1377 }
1378}