1use lensbench_formats::zmx::merit::{MeritFunction, MeritRow};
14use serde_json::{json, Map, Value};
15use std::collections::BTreeMap;
16
17mod calc;
18mod shape;
19mod wizard;
20mod write;
21
22pub use write::rows_from_terms;
23
24#[derive(Debug, Clone, Default, PartialEq)]
26pub struct ZmxMerit {
27 pub terms: Vec<Value>,
29 pub sources: Vec<usize>,
31 pub notes: Vec<String>,
33 pub configs: usize,
35}
36
37#[derive(Debug, Clone, PartialEq)]
39pub struct ZmxSys {
40 pub glass: Vec<bool>,
42 pub symmetric: bool,
44 pub primary_varies: bool,
47 pub waves: usize,
49 pub angle_field: bool,
51 pub mce: Vec<(String, i64, i64)>,
53 pub configs: usize,
55 pub off_axis: Vec<bool>,
57}
58
59impl Default for ZmxSys {
60 fn default() -> Self {
61 ZmxSys {
62 glass: Vec::new(),
63 symmetric: true,
64 primary_varies: false,
65 waves: 0,
66 angle_field: true,
67 mce: Vec::new(),
68 configs: 1,
69 off_axis: Vec::new(),
70 }
71 }
72}
73
74impl ZmxSys {
75 pub fn of(s: &lensbench_core::System) -> ZmxSys {
76 ZmxSys {
77 glass: s
78 .surfaces
79 .iter()
80 .map(|f| f.mat.is_medium() && !f.mat.is_air())
81 .collect(),
82 symmetric: s.symmetric(),
83 primary_varies: s.configs().is_some_and(|c| {
84 c.rows
85 .iter()
86 .any(|r| r.param.kind == lensbench_core::param::Kind::Primary)
87 }),
88 waves: s.wavelengths.len(),
89 angle_field: matches!(s.field_type, lensbench_core::system::FieldType::Angle),
90 mce: Vec::new(),
91 configs: s.configs().map_or(1, |c| c.n),
92 off_axis: s.fields.iter().map(|f| f.x != 0.0 || f.y != 0.0).collect(),
93 }
94 }
95}
96
97const INT1: usize = 0;
100const INT2: usize = 1;
101const TARGET: usize = 6;
102const WEIGHT: usize = 7;
103
104fn data(k: usize) -> usize {
106 if k <= 4 {
107 k + 1
108 } else {
109 k + 3
110 }
111}
112
113const PARAXIAL: &[(&str, &str, bool)] = &[
115 ("EFFL", "efl", true),
116 ("ENPP", "enpp", true),
117 ("EPDI", "epd", true),
118 ("EXPD", "expd", true),
119 ("EXPP", "expp", true),
120 ("ISFN", "isfn", false),
121 ("ISNA", "isna", false),
122 ("PIMH", "pimh", true),
123 ("PMAG", "pmag", false),
124 ("WFNO", "wfno", false),
125 ("OBSN", "obsn", false),
126 ("TOTR", "totr", true),
127 ("AMAG", "amag", false),
128 ("LINV", "linv", true),
129 ("PETZ", "petz", true),
130 ("PETC", "petc", false),
131 ("WLEN", "wlen", false),
132];
133
134const RAY: &[(&str, &str, bool)] = &[
136 ("REAX", "x", true),
137 ("REAY", "y", true),
138 ("REAZ", "z", true),
139 ("REAA", "l", false),
140 ("REAB", "m", false),
141 ("REAC", "n", false),
142 ("TRAX", "trax", true),
143 ("TRAY", "tray", true),
144 ("TRAR", "trar", true),
145 ("TRAI", "trar", true),
147 ("OPTH", "opth", true),
148 ("RAGX", "gx", true),
149 ("RAGY", "gy", true),
150 ("RAGZ", "gz", true),
151 ("RAGA", "gl", false),
152 ("RAGB", "gm", false),
153 ("RAGC", "gn", false),
154 ("REAR", "r", true),
155 ("RANG", "ang", false),
156 ("RETX", "tanx", false),
157 ("RETY", "tany", false),
158 ("RENA", "nl", false),
159 ("RENB", "nm", false),
160 ("RENC", "nn", false),
161 ("RAID", "aoi", false),
162 ("RAED", "aoe", false),
163 ("RAIN", "cosi", false),
164 ("RAEN", "cose", false),
165 ("ANAX", "anax", false),
166 ("ANAY", "anay", false),
167 ("ANAR", "anar", false),
168 ("DXDX", "dxdx", true),
169 ("DXDY", "dxdy", true),
170 ("DYDX", "dydx", true),
171 ("DYDY", "dydy", true),
172 ("FCGS", "fcgs", true),
173 ("FCGT", "fcgt", true),
174];
175
176fn image_only(op: &str) -> bool {
178 op != "TRAI"
179 && ["TRA", "ANA", "DXD", "DYD", "FCG"]
180 .iter()
181 .any(|p| op.starts_with(p))
182}
183
184const PAR: &[(&str, &str, bool)] = &[
186 ("PARX", "x", true),
187 ("PARY", "y", true),
188 ("PARZ", "z", true),
189 ("PARA", "l", false),
190 ("PARB", "m", false),
191 ("PARC", "n", false),
192 ("PARR", "r", true),
193 ("PANA", "nl", false),
194 ("PANB", "nm", false),
195 ("PANC", "nn", false),
196 ("PATX", "tanx", false),
197 ("PATY", "tany", false),
198];
199
200fn sampling(s: i64) -> Result<usize, String> {
202 if !(1..=6).contains(&s) {
203 return Err(format!("sampling {s} (1 to 6)"));
204 }
205 Ok(32 << (s - 1))
206}
207
208fn field_no(f: i64) -> Result<usize, String> {
210 if f < 1 {
211 return Err(format!("field {f}"));
212 }
213 Ok(f as usize)
214}
215
216fn read_differs(r: &MeritRow, sys: &ZmxSys) -> Option<&'static str> {
218 let num = |i: usize| r.num(i).unwrap_or(0.0);
219 match r.op.as_str() {
220 "DENC" | "DENF" if off_axis(sys, num(data(1))) => Some(
221 "OpticStudio measures the encircled energy of an off-axis field on the plane normal to the chief ray, lensbench on the image plane (about 1% apart in the check); the term may differ",
222 ),
223 "RSRH" if num(data(1)) != 0.0 && num(data(2)) != 0.0 => Some(
224 "the value of OpticStudio for a field with both Hx and Hy not 0 could not be reproduced; the term may differ",
225 ),
226 "ANAX" | "ANAY" if num(INT2) == 0.0 => {
227 Some("Wave 0 is read as the primary wavelength (OpticStudio returns 0)")
228 }
229 "FCGT" if num(data(2)) != 0.0 => Some(FCG_DIFF),
230 "FCGS" if num(data(1)) != 0.0 => Some(FCG_DIFF),
231 "GENC" | "GENF" if num(data(4)) == 2.0 => Some(
232 "the value of OpticStudio about the vertex could not be reproduced (about 0.6% larger in the check); the term may differ",
233 ),
234 _ => None,
235 }
236}
237
238fn off_axis(sys: &ZmxSys, f: f64) -> bool {
240 let i = f as usize;
241 match sys.off_axis.get(i.wrapping_sub(1)) {
242 Some(&o) => o,
243 None => i > 1,
244 }
245}
246
247const FCG_DIFF: &str =
248 "lensbench uses a central difference; OpticStudio's one-sided difference differs by about 1e-4";
249
250struct Ctx<'a> {
252 unit: f64,
253 primary: usize,
254 image: usize,
255 sys: &'a ZmxSys,
256 rows: &'a [MeritRow],
257 notes: Vec<String>,
258}
259
260impl Ctx<'_> {
261 fn skip(&mut self, r: &MeritRow, why: &str) {
262 self.notes.push(format!(
263 ".zmx merit function row {} ({}, line {}): {why}; skipped",
264 r.row, r.op, r.line
265 ));
266 }
267}
268
269fn kind_of(
271 r: &MeritRow,
272 unit: f64,
273 primary: usize,
274 image: usize,
275 sys: &ZmxSys,
276) -> Result<Map<String, Value>, String> {
277 let num = |i: usize| r.num(i).map_err(|e| e.to_string());
278 let int = |i: usize| r.int(i).map_err(|e| e.to_string());
279 let mut m = Map::new();
280 let target = num(TARGET)?;
281 let wave = |w: i64| -> Result<Value, String> {
282 match w {
283 0 => Ok(Value::Null),
284 w if w > 0 => Ok(json!(w)),
285 w => Err(format!("wavelength {w}")),
286 }
287 };
288 let norm_field = || -> Result<Value, String> { Ok(json!([num(data(1))?, num(data(2))?])) };
289 let op = r.op.as_str();
290 if let Some((_, q, len)) = PARAXIAL.iter().find(|(o, _, _)| *o == op) {
291 let w = int(INT2)?;
294 m.insert("type".into(), json!("paraxial"));
295 m.insert("q".into(), json!(q));
296 let reads = matches!(*q, "efl" | "pimh" | "amag" | "linv" | "petz" | "petc");
297 if *q == "wlen" {
298 m.insert("wave".into(), json!(w.max(1)));
300 } else if w != 0 && w as usize != primary {
301 if !reads || w < 0 {
302 return Err(format!(
303 "wavelength {w} (lensbench reads the wavelength only for EFFL, PIMH, AMAG, LINV, PETZ and PETC)"
304 ));
305 }
306 m.insert("wave".into(), json!(w));
307 } else if w != 0 && reads && sys.primary_varies {
308 m.insert("wave".into(), json!(w));
309 }
310 m.insert(
311 "target".into(),
312 json!(if *len { target * unit } else { target }),
313 );
314 return Ok(m);
315 }
316 let par = PAR.iter().find(|(o, _, _)| *o == op);
317 if let Some((_, q, len)) = RAY.iter().find(|(o, _, _)| *o == op).or(par) {
318 m.insert("type".into(), json!("ray"));
319 if par.is_some() {
320 m.insert("paraxial".into(), json!(true));
321 }
322 if !image_only(op) {
324 let j = int(INT1)?;
325 if op == "TRAI" && j < 1 {
326 return Err(format!(
327 "surface {j} (TRAI of surface 0 is not the image surface)"
328 ));
329 }
330 m.insert("surf".into(), json!(j));
331 }
332 m.insert("wave".into(), wave(int(INT2)?)?);
333 m.insert("field".into(), norm_field()?);
334 m.insert("px".into(), json!(num(data(3))?));
335 m.insert("py".into(), json!(num(data(4))?));
336 m.insert("q".into(), json!(q));
337 m.insert(
338 "target".into(),
339 json!(if *len { target * unit } else { target }),
340 );
341 return Ok(m);
342 }
343 match op {
344 "EFLX" | "EFLY" | "CARD" | "EFLA" => {
347 let (s1, s2) = if op == "EFLA" {
348 let j = int(INT1)?;
349 (j, j + 1)
350 } else {
351 (int(INT1)?, int(INT2)?)
352 };
353 if s1 < 1 || s2 < s1 || s2 as usize >= image {
354 return Err(format!("surfaces {s1} to {s2}"));
355 }
356 let x = match op {
357 "EFLX" => true,
358 "CARD" => match int(data(2))? {
359 0 => false,
360 1 => true,
361 o => return Err(format!("orientation {o}")),
362 },
363 _ => false,
364 };
365 if x && !sys.symmetric {
366 return Err(
367 "the X orientation of a system that is not rotationally symmetric (lensbench's paraxial trace is in the Y-Z plane)"
368 .into(),
369 );
370 }
371 if op == "EFLA" && !sys.glass.is_empty() {
372 let g = |j: i64| sys.glass.get(j as usize).copied().unwrap_or(false);
373 if !(!g(s1 - 1) && g(s1) && !g(s2)) {
374 return Err(format!(
375 "surfaces {s1} and {s2} are not a single lens in air (OpticStudio gives 1e8)"
376 ));
377 }
378 }
379 let (q, w) = match op {
380 "CARD" => {
381 let d = int(data(3))?;
382 let q = usize::try_from(d)
383 .ok()
384 .and_then(lensbench_optim::CardQ::from_card_data)
385 .ok_or(format!("data {d} (0 to 11)"))?;
386 (q.name(), int(data(1))?)
387 }
388 "EFLA" => ("efl", int(INT2)?),
389 _ => ("efl", 0),
390 };
391 m.insert("type".into(), json!("cardinal"));
392 m.insert("q".into(), json!(q));
393 m.insert("from".into(), json!(s1));
394 m.insert("to".into(), json!(s2));
395 m.insert("wave".into(), wave(w)?);
396 m.insert("target".into(), json!(target * unit));
397 }
398 "PLEN" | "MXRE" | "MNRE" | "MXRI" | "MNRI" => {
400 let (s1, s2) = (int(INT1)?, int(INT2)?);
401 if s1 < i64::from(op != "PLEN") || s2 < s1 || s2 as usize > image {
402 return Err(format!("surfaces {s1} to {s2}"));
403 }
404 m.insert("type".into(), json!("ray"));
405 m.insert("surf".into(), json!(s1));
406 m.insert("to".into(), json!(s2));
407 if op != "PLEN" {
408 m.insert("wave".into(), wave(int(data(5))?)?);
409 }
410 m.insert("field".into(), norm_field()?);
411 m.insert("px".into(), json!(num(data(3))?));
412 m.insert("py".into(), json!(num(data(4))?));
413 let (q, key, t) = match op {
414 "PLEN" => ("opth", "target", target * unit),
415 _ => (
416 if op.ends_with('E') { "aoe" } else { "aoi" },
417 if op.starts_with("MX") { "max" } else { "min" },
418 target,
419 ),
420 };
421 m.insert("q".into(), json!(q));
422 m.insert(key.into(), json!(t));
423 }
424 "CTGT" | "CTLT" | "CTVA" | "TTHI" => {
426 let s1 = int(INT1)?;
427 let s2 = if op == "TTHI" { int(INT2)? } else { s1 };
428 if s1 < 1 || s2 < s1 || s2 as usize >= image {
429 return Err(format!("surfaces {s1} to {s2}"));
430 }
431 m.insert("type".into(), json!("thickness"));
432 m.insert("surf".into(), json!(s1));
433 if s2 != s1 {
434 m.insert("to".into(), json!(s2));
435 }
436 let key = match op {
437 "CTGT" => "min",
438 "CTLT" => "max",
439 _ => "target",
440 };
441 m.insert(key.into(), json!(target * unit));
442 }
443 "ETGT" | "ETLT" | "ETVA" => {
446 let j = int(INT1)?;
447 if j < 1 || j as usize >= image {
448 return Err(format!("surface {j}"));
449 }
450 m.insert("type".into(), json!("thickness"));
451 m.insert("surf".into(), json!(j));
452 m.insert("edge".into(), json!(true));
453 match int(INT2)? {
454 0 => {}
455 1 => {
456 m.insert("axis".into(), json!("+x"));
457 }
458 2 => {
459 m.insert("axis".into(), json!("-y"));
460 }
461 3 => {
462 m.insert("axis".into(), json!("-x"));
463 }
464 c => return Err(format!("code {c} (0 to 3)")),
465 }
466 match int(data(2))? {
467 0 => {}
468 1 => {
469 m.insert("clear".into(), json!(true));
470 }
471 k => return Err(format!("mode {k} (0 or 1)")),
472 }
473 let key = match op {
474 "ETGT" => "min",
475 "ETLT" => "max",
476 _ => "target",
477 };
478 m.insert(key.into(), json!(target * unit));
479 }
480 "MNCT" | "MXCT" | "MNCA" | "MXCA" | "MNCG" | "MXCG" | "MNET" | "MXET" | "MNEA" | "MXEA"
483 | "MNEG" | "MXEG" => {
484 let s1 = int(INT1)?;
485 let s2 = int(INT2)?.min(image as i64 - 1);
486 if s1 < 1 || s2 < s1 {
487 return Err(format!("surfaces {s1} to {s2}"));
488 }
489 m.insert("type".into(), json!("thickness"));
490 m.insert("surf".into(), json!(s1));
491 m.insert("to".into(), json!(s2));
492 if &op[2..3] == "E" {
493 m.insert("edge".into(), json!(true));
494 let z = num(data(1))?;
495 if z != 0.0 {
496 m.insert("zone".into(), json!(z));
497 }
498 }
499 let each = match &op[3..] {
500 "A" => "air",
501 "G" => "glass",
502 _ => "all",
503 };
504 m.insert("each".into(), json!(each));
505 let key = if op.starts_with("MN") { "min" } else { "max" };
506 m.insert(key.into(), json!(target * unit));
507 }
508 "TTGT" | "TTLT" | "TTVA" | "PMGT" | "PMLT" | "PMVA" | "VOLU" | "TMAS" | "CVOL" | "TSAG"
509 | "BFSD" => return shape::kind(r, unit, image),
510 "CVGT" | "CVLT" | "CVVA" | "COGT" | "COLT" | "COVA" | "DMGT" | "DMLT" | "DMVA" | "SAGX"
512 | "SAGY" | "SSAG" | "STHI" | "GLCX" | "GLCY" | "GLCZ" | "GLCA" | "GLCB" | "GLCC"
513 | "GCOS" | "GTCE" | "TCVA" | "TCGT" | "TCLT" => {
514 let j = int(INT1)?;
515 let last = if op == "STHI" { image - 1 } else { image };
516 if j < 0 || j as usize > last {
517 return Err(format!("surface {j}"));
518 }
519 let (q, xy) = match op {
520 "CVGT" | "CVLT" | "CVVA" => ("curv", None),
521 "COGT" | "COLT" | "COVA" => ("conic", None),
522 "DMGT" | "DMLT" | "DMVA" if int(data(2))? == 0 => ("mech_diam", None),
523 "DMGT" | "DMLT" | "DMVA" => ("diam", None),
524 "SAGX" => ("sagx", None),
525 "SAGY" => ("sagy", None),
526 "SSAG" => {
528 if (3..=5).any(|k| num(data(k)).unwrap_or(0.0) != 0.0) {
529 return Err("SSAG with Off-Axis, Remove or BFS".into());
530 }
531 ("sag", Some((num(data(1))?, num(data(2))?)))
532 }
533 "STHI" => ("thick", Some((num(data(1))?, num(data(2))?))),
535 "GLCX" => ("gx", None),
536 "GLCY" => ("gy", None),
537 "GLCZ" => ("gz", None),
538 "GLCA" => ("ga", None),
539 "GLCB" => ("gb", None),
540 "GLCC" => ("gc", None),
541 "GCOS" => ("cost", None),
543 "GTCE" => ("tce", None),
544 _ => ("surf_tce", None),
546 };
547 m.insert("type".into(), json!("surface"));
548 m.insert("surf".into(), json!(j));
549 m.insert("q".into(), json!(q));
550 if let Some((x, y)) = xy {
551 m.insert("x".into(), json!(x * unit));
552 m.insert("y".into(), json!(y * unit));
553 }
554 let key = match &op[2..] {
555 "GT" => "min",
556 "LT" => "max",
557 _ => "target",
558 };
559 let len = !matches!(
560 q,
561 "curv" | "conic" | "ga" | "gb" | "gc" | "cost" | "tce" | "surf_tce"
562 );
563 let t = match q {
565 "curv" => target / unit,
566 _ if len => target * unit,
567 _ => target,
568 };
569 m.insert(key.into(), json!(t));
570 }
571 "POWR" | "YNIP" | "INDX" => {
573 let j = int(INT1)?;
574 if j < i64::from(op == "YNIP") || j as usize > image {
575 return Err(format!("surface {j}"));
576 }
577 let w = match int(INT2)? {
578 0 if op == "INDX" => 1,
579 w => w,
580 };
581 m.insert("type".into(), json!("surface"));
582 m.insert("surf".into(), json!(j));
583 m.insert(
584 "q".into(),
585 json!(match op {
586 "POWR" => "power",
587 "YNIP" => "ynip",
588 _ => "index",
589 }),
590 );
591 m.insert("wave".into(), wave(w)?);
592 let t = match op {
593 "POWR" => target / unit,
594 "YNIP" => target * unit,
595 _ => target,
596 };
597 m.insert("target".into(), json!(t));
598 }
599 "RSCE" | "RSCH" | "RWCE" | "RWCH" => {
600 if target != 0.0 {
601 return Err(format!(
602 "a target other than 0 ({target}) can't be written as a spot or wavefront term"
603 ));
604 }
605 let spot = op.starts_with("RS");
606 m.insert(
607 "type".into(),
608 json!(if spot { "spot" } else { "wavefront" }),
609 );
610 m.insert("rings".into(), json!(int(INT1)?.max(1)));
611 m.insert("wave".into(), wave(int(INT2)?)?);
612 m.insert("field".into(), norm_field()?);
613 m.insert(
614 "reference".into(),
615 json!(if op.ends_with('E') {
616 "centroid"
617 } else {
618 "chief"
619 }),
620 );
621 m.insert("quadrature".into(), json!("opticstudio"));
622 }
623 "RSRE" | "RSRH" | "RWRE" | "RWRH" => {
625 if target != 0.0 {
626 return Err(format!(
627 "a target other than 0 ({target}) can't be written as a spot or wavefront term"
628 ));
629 }
630 let n = int(INT1)?;
631 if n < 1 {
632 return Err(format!("sampling {n} (1 or more)"));
633 }
634 m.insert(
635 "type".into(),
636 json!(if op.starts_with("RS") {
637 "spot"
638 } else {
639 "wavefront"
640 }),
641 );
642 m.insert("wave".into(), wave(int(INT2)?)?);
643 m.insert("field".into(), norm_field()?);
644 m.insert(
645 "reference".into(),
646 json!(if op.ends_with('E') {
647 "centroid"
648 } else {
649 "chief"
650 }),
651 );
652 m.insert("quadrature".into(), json!("grid"));
653 m.insert("n".into(), json!(2 * n));
654 }
655 "SPCH" => {
658 let z = num(data(1))?;
659 if !(0.0..=1.0).contains(&z) {
660 return Err(format!("zone {z} (0 to 1)"));
661 }
662 let w1 = match int(INT1)? {
663 0 => 1,
664 w => w,
665 };
666 let w2 = match int(INT2)? {
667 0 if sys.waves == 0 => return Err("Maxw 0 needs the number of wavelengths".into()),
668 0 => sys.waves as i64,
669 w => w,
670 };
671 let lona = |zone: f64| -> Result<Value, String> {
672 Ok(
673 json!({"type": "longitudinal", "wave": wave(w1)?, "wave2": wave(w2)?, "zone": zone, "target": 0.0}),
674 )
675 };
676 m.insert("type".into(), json!("calc"));
677 m.insert("op".into(), json!("diff"));
678 m.insert("args".into(), json!([lona(z)?, lona(0.0)?]));
679 m.insert("target".into(), json!(target * unit));
680 }
681 "OPDC" => {
682 m.insert("type".into(), json!("opd"));
683 m.insert("wave".into(), wave(int(INT2)?)?);
684 m.insert("field".into(), norm_field()?);
685 m.insert("px".into(), json!(num(data(3))?));
686 m.insert("py".into(), json!(num(data(4))?));
687 m.insert("target".into(), json!(target));
688 }
689 "MTFT" | "MTFS" | "MTFA" | "MSWT" | "MSWS" | "MSWA" | "GMTT" | "GMTS" | "GMTA" | "MTHT"
695 | "MTHS" | "MTHA" => {
696 let kind = match &op[..3] {
697 "MTF" => {
698 if !matches!(int(data(3))?, 0 | 1) || int(data(4))? != 0 {
699 return Err(
700 "only the MTF modulation (Grid 0 or 1, Data Type 0) is supported"
701 .into(),
702 );
703 }
704 "diffraction"
705 }
706 "MSW" => "square",
707 "GMT" => {
708 if !matches!(int(data(4))?, 0 | 1) {
709 return Err(format!("Grid {}", int(data(4))?));
710 }
711 m.insert("diff_limit".into(), json!(int(data(3))? == 0));
712 "geometric"
713 }
714 _ => {
715 if int(data(3))? != 0 || int(data(4))? != 0 || num(data(5))? != 0.0 {
716 return Err("only the Huygens MTF without polarization, of the current configuration, with the default image delta is supported".into());
717 }
718 "huygens"
719 }
720 };
721 m.insert("type".into(), json!("mtf"));
722 if kind != "diffraction" {
723 m.insert("kind".into(), json!(kind));
724 }
725 sampling(int(INT1)?)?;
726 m.insert("wave".into(), wave(int(INT2)?)?);
727 let f = int(data(1))?;
728 if f == 0 {
729 return Err("field 0 (the diffraction limit) is not supported".into());
730 }
731 m.insert("field".into(), json!(field_no(f)?));
732 if unit != 1.0 {
733 return Err("MTF frequencies in lens units other than mm are not checked".into());
734 }
735 m.insert("freq".into(), json!(num(data(2))?));
736 let dir = match op.as_bytes()[3] {
737 b'T' => "tan",
738 b'S' => "sag",
739 _ => "avg",
740 };
741 m.insert("dir".into(), json!(dir));
742 m.insert("target".into(), json!(target));
743 }
744 "GENC" | "GENF" | "DENC" | "DENF" => {
750 let shape = match int(data(3))? {
751 1 => "circle",
752 2 => "x",
753 3 => "y",
754 4 => "square",
755 k => return Err(format!("Type {k} (1 to 4)")),
756 };
757 let refp = int(data(4))?;
758 let (method, center) = match (&op[..3], refp) {
759 ("GEN", 0..=3) => ("geometric", refp),
760 ("DEN", 0..=2) => ("fft", refp),
761 ("DEN", 3..=5) => ("huygens", refp - 3),
762 _ => return Err(format!("Refp {refp}")),
763 };
764 m.insert("type".into(), json!("energy"));
765 m.insert("method".into(), json!(method));
766 if method == "geometric" && shape == "circle" && int(data(5))? == 0 {
767 m.insert("airy".into(), json!(true));
768 }
769 m.insert("shape".into(), json!(shape));
770 m.insert(
771 "center".into(),
772 json!(["chief", "centroid", "vertex", "middle"][center as usize]),
773 );
774 m.insert("wave".into(), wave(int(INT2)?)?);
775 m.insert("field".into(), json!(field_no(int(data(1))?)?));
776 let v = num(data(2))?;
777 if op.ends_with('C') {
778 m.insert("size_at".into(), json!(v));
779 m.insert("target".into(), json!(target * 1e-3));
780 } else {
781 m.insert("fraction_at".into(), json!(v * 1e-3));
782 m.insert("target".into(), json!(target));
783 }
784 }
785 "STRH" => {
788 if int(data(3))? != 0 || int(data(4))? != 0 {
789 return Err("only the Strehl ratio without polarization, of the current configuration, is supported".into());
790 }
791 m.insert("type".into(), json!("strehl"));
792 m.insert("wave".into(), wave(int(INT2)?)?);
793 m.insert("field".into(), json!(field_no(int(data(1))?)?));
794 m.insert("target".into(), json!(target));
795 }
796 "MCOV" | "MCOG" | "MCOL" => {
801 let k = int(INT1)?;
802 let c = int(INT2)?;
803 let Some((mop, j, parm)) = (k >= 1).then(|| sys.mce.get(k as usize - 1)).flatten()
804 else {
805 return Err(format!("multi-configuration row {k}"));
806 };
807 if c < 1 {
808 return Err(format!("configuration {c}"));
809 }
810 let (name, scale) = match mop.as_str() {
811 "THIC" => (format!("{j}.t"), unit),
812 "SDIA" => (format!("{j}.semi"), unit),
813 "CRVT" => (format!("{j}.c"), 1.0 / unit),
814 "CONN" => (format!("{j}.k"), 1.0),
815 "PRAM" => (format!("{j}.p{parm}"), 1.0),
816 "WAVE" => (format!("wave{j}"), 1.0),
817 "WLWT" => (format!("wwt{j}"), 1.0),
818 "PRWV" => ("primary".to_string(), 1.0),
819 "APER" => ("aper".to_string(), 1.0),
820 "XFIE" => (format!("fx{j}"), 1.0),
821 "YFIE" => (format!("fy{j}"), 1.0),
822 "FLWT" => (format!("fwt{j}"), 1.0),
823 "FVDX" => (format!("vdx{j}"), 1.0),
824 "FVDY" => (format!("vdy{j}"), 1.0),
825 "FVCX" => (format!("vcx{j}"), 1.0),
826 "FVCY" => (format!("vcy{j}"), 1.0),
827 "FVAN" | "FTAN" => (format!("van{j}"), 1.0),
828 "SATP" => ("atype".to_string(), 1.0),
829 "STPS" => ("stop".to_string(), 1.0),
830 "IGNR" => (format!("{j}.ignore"), 1.0),
831 "APMX" => (format!("{j}.apmax"), unit),
832 "APMN" => (format!("{j}.apmin"), unit),
833 "APDX" => (format!("{j}.apdx"), unit),
834 "APDY" => (format!("{j}.apdy"), unit),
835 "APTP" => (format!("{j}.aptype"), 1.0),
836 "CBOR" => (format!("{j}.beforeorder"), 1.0),
837 "CAOR" => (format!("{j}.afterorder"), 1.0),
838 "MIND" => (format!("{j}.nd"), 1.0),
839 "MABB" => (format!("{j}.vd"), 1.0),
840 "MDPG" => (format!("{j}.dpgf"), 1.0),
841 "TCEX" => (format!("{j}.tce"), 1.0),
842 "MCSD" => (format!("{j}.mech"), unit),
843 "CHZN" => (format!("{j}.chip"), unit),
844 "CROR" => (format!("{j}.cror"), 1.0),
845 "CRSR" => (format!("{j}.crsr"), 1.0),
846 "CSP1" | "CSP2" | "TSP1" | "TSP2" | "TSP3" => {
847 (format!("{j}.{}", mop.to_ascii_lowercase()), 1.0)
848 }
849 "PSP1" | "PSP2" | "PSP3" => {
850 (format!("{j}.{}_{parm}", mop.to_ascii_lowercase()), 1.0)
851 }
852 "CBDX" | "CBDY" | "CADX" | "CADY" => (
853 format!(
854 "{j}.{}{}",
855 if mop.starts_with("CB") {
856 "before"
857 } else {
858 "after"
859 },
860 u8::from(mop.ends_with('Y'))
861 ),
862 unit,
863 ),
864 "CBTX" | "CBTY" | "CBTZ" | "CATX" | "CATY" | "CATZ" => (
865 format!(
866 "{j}.{}{}",
867 if mop.starts_with("CB") {
868 "before"
869 } else {
870 "after"
871 },
872 2 + "XYZ".find(&mop[3..]).unwrap_or(0)
873 ),
874 1.0,
875 ),
876 "TEMP" => ("temp".to_string(), 1.0),
877 "PRES" => ("pres".to_string(), 1.0),
878 "AFOC" => ("afocal".to_string(), 1.0),
879 "APDT" => ("apodtype".to_string(), 1.0),
880 "APDF" => ("apod".to_string(), 1.0),
881 "RAAM" => ("aiming".to_string(), 1.0),
882 "OPDR" => ("ropd".to_string(), 1.0),
883 "PSHX" | "PSHY" | "PSHZ" => (mop.to_ascii_lowercase(), unit),
884 "PSCX" | "PSCY" => (mop.to_ascii_lowercase(), 1.0),
885 "GPIU" => ("polun".to_string(), 1.0),
886 "GPJX" => ("poljx".to_string(), 1.0),
887 "GPJY" => ("poljy".to_string(), 1.0),
888 "GPPX" => ("polpx".to_string(), 1.0),
889 "GPPY" => ("polpy".to_string(), 1.0),
890 o => return Err(format!("the multi-configuration operand {o} of row {k}")),
891 };
892 m.insert("type".into(), json!("param"));
893 m.insert("name".into(), json!(name));
894 m.insert("config".into(), json!(c));
895 let key = match op {
896 "MCOG" => "min",
897 "MCOL" => "max",
898 _ => "target",
899 };
900 m.insert(key.into(), json!(target * scale));
901 }
902 "ZTHI" => {
905 let s1 = int(INT1)?;
906 let s2 = int(INT2)?.min(image as i64 - 1);
907 if s1 < 1 || s2 < s1 {
908 return Err(format!("surfaces {s1} to {s2}"));
909 }
910 let mut t = json!({"type": "thickness", "surf": s1});
911 if s2 != s1 {
912 t["to"] = json!(s2);
913 }
914 m.insert("type".into(), json!("spread"));
915 m.insert("term".into(), t);
916 m.insert("max".into(), json!(target * unit));
917 }
918 "RELI" | "EFNO" => {
919 if int(data(2))? != 0 {
920 return Err("the illumination with polarization is not supported".into());
921 }
922 m.insert("type".into(), json!("illum"));
923 m.insert(
924 "q".into(),
925 json!(if op == "RELI" { "relative" } else { "fno" }),
926 );
927 m.insert("wave".into(), wave(int(INT2)?.max(1))?);
928 m.insert("field".into(), json!(field_no(int(data(1))?)?));
929 m.insert("target".into(), json!(target));
930 }
931 "ZERN" => {
934 let kind = match int(data(3))? {
935 0 => "fringe",
936 1 => "standard",
937 k => return Err(format!("Zernike type {k} (only Fringe 0 and Standard 1)")),
938 };
939 if num(data(4))? != 0.0 || int(data(5))? != 0 {
940 return Err("annular Zernike (Epsilon) and Vertex are not supported".into());
941 }
942 let term = int(INT1)?;
943 if term < 1 {
944 return Err(format!("Zernike term {term}"));
945 }
946 m.insert("type".into(), json!("zernike"));
947 m.insert("term".into(), json!(term));
948 m.insert("wave".into(), wave(int(INT2)?)?);
949 m.insert("n".into(), json!(sampling(int(data(1))?)?));
950 m.insert("field".into(), json!(field_no(int(data(2))?)?));
951 m.insert("kind".into(), json!(kind));
952 if kind == "fringe" {
954 m.insert("fit".into(), json!(37));
955 }
956 m.insert("target".into(), json!(target));
957 }
958 "SPHA" | "COMA" | "ASTI" | "FCUR" | "DIST" => {
963 let j = int(INT1)?;
964 if j < 0 || j as usize > image {
965 return Err(format!("surface {j}"));
966 }
967 let abs = if op == "DIST" {
968 num(data(1))? != 0.0
969 } else {
970 false
971 };
972 if op == "DIST" && (j == 0 || abs) {
973 m.insert("type".into(), json!("distortion"));
974 m.insert("wave".into(), wave(int(INT2)?)?);
975 m.insert("absolute".into(), json!(abs));
976 m.insert(
977 "target".into(),
978 json!(if abs { target * unit } else { target }),
979 );
980 } else {
981 m.insert("type".into(), json!("seidel"));
982 m.insert("q".into(), json!(op.to_ascii_lowercase()));
983 m.insert("surf".into(), json!(j));
984 m.insert("wave".into(), wave(int(INT2)?)?);
985 m.insert("target".into(), json!(target));
986 }
987 }
988 "DIMX" | "DISC" | "DISG" => {
992 m.insert("type".into(), json!("distortion"));
993 let w = int(INT2)?;
994 let abs = if op == "DISG" {
995 w < 0
996 } else {
997 num(data(1))? != 0.0
998 };
999 m.insert("wave".into(), wave(w.abs())?);
1000 m.insert("absolute".into(), json!(abs));
1001 match op {
1002 "DIMX" => {
1003 let f = int(INT1)?;
1004 if f != 0 {
1005 m.insert("field".into(), json!(field_no(f)?));
1006 }
1007 m.insert("peak".into(), json!(true));
1008 }
1009 "DISC" => {
1010 m.insert("ftheta".into(), json!(true));
1011 }
1012 _ => {
1013 m.insert("field".into(), norm_field()?);
1014 let f = int(INT1)?;
1015 if f != 0 {
1016 m.insert("reference".into(), json!(field_no(f)?));
1017 }
1018 }
1019 }
1020 m.insert(
1021 "target".into(),
1022 json!(if abs { target * unit } else { target }),
1023 );
1024 }
1025 "ABCD" | "DISA" => {
1028 m.insert("type".into(), json!("distortion"));
1029 m.insert("wave".into(), wave(int(INT2)?)?);
1030 let f = int(INT1)?;
1031 if f != 0 {
1032 m.insert("reference".into(), json!(field_no(f)?));
1033 }
1034 let k = int(data(1))?;
1035 if op == "ABCD" {
1036 let c = ["a", "b", "c", "d"]
1037 .get(k as usize)
1038 .filter(|_| k >= 0)
1039 .ok_or(format!("data {k} (0 to 3)"))?;
1040 m.insert("coef".into(), json!(c));
1041 let u = if sys.angle_field { unit } else { 1.0 };
1042 m.insert("target".into(), json!(target * u));
1043 } else {
1044 let c = ["radial", "x", "y"]
1045 .get(k as usize)
1046 .filter(|_| k >= 0)
1047 .ok_or(format!("data {k} (0 to 2)"))?;
1048 m.insert("field".into(), json!(field_no(int(data(2))?)?));
1049 let abcd = [num(data(3))?, num(data(4))?, num(data(5))?, num(data(6))?];
1050 let u = if sys.angle_field { unit } else { 1.0 };
1051 m.insert("abcd".into(), json!(abcd.map(|v| v * u)));
1052 m.insert("component".into(), json!(c));
1053 m.insert("target".into(), json!(target));
1054 }
1055 }
1056 "BSER" => {
1058 m.insert("type".into(), json!("calc"));
1059 m.insert("op".into(), json!("div"));
1060 let r = json!({"type": "ray", "wave": wave(int(INT2)?)?, "field": [0.0, 0.0], "px": 0.0, "py": 0.0, "q": "r", "target": 0.0});
1061 m.insert(
1062 "args".into(),
1063 json!([r, {"type": "paraxial", "q": "efl", "target": 0.0}]),
1064 );
1065 m.insert("target".into(), json!(target));
1066 }
1067 "LONA" | "AXCL" => {
1070 let z = num(data(1))?;
1071 if !(0.0..=1.0).contains(&z) {
1072 return Err(format!("zone {z} (0 to 1)"));
1073 }
1074 m.insert("type".into(), json!("longitudinal"));
1075 m.insert("wave".into(), wave(int(INT1)?)?);
1076 if op == "AXCL" {
1077 let w2 = match int(INT2)? {
1079 0 => primary as i64,
1080 w => w,
1081 };
1082 m.insert("wave2".into(), wave(w2)?);
1083 }
1084 m.insert("zone".into(), json!(z));
1085 m.insert("target".into(), json!(target * unit));
1086 }
1087 "LACL" => {
1088 let w2 = match int(INT2)? {
1089 0 => primary as i64,
1090 w => w,
1091 };
1092 m.insert("type".into(), json!("lateral_color"));
1093 m.insert("wave".into(), wave(int(INT1)?)?);
1094 m.insert("wave2".into(), json!(w2));
1095 m.insert("target".into(), json!(target * unit));
1096 }
1097 "MNSD" | "MXSD" | "MNIN" | "MXIN" | "MNAB" | "MXAB" | "MNPD" | "MXPD" => {
1100 let s1 = int(INT1)?;
1101 let s2 = int(INT2)?.min(image as i64 - 1);
1102 if s1 < 1 || s2 < s1 {
1103 return Err(format!("surfaces {s1} to {s2}"));
1104 }
1105 let side = if op.starts_with("MN") { "min" } else { "max" };
1106 if op.ends_with("SD") {
1107 m.insert("type".into(), json!("semi"));
1108 m.insert(side.into(), json!(target * unit));
1109 } else {
1110 m.insert("type".into(), json!("surface"));
1111 let q = match &op[2..] {
1112 "IN" => "nd",
1113 "AB" => "vd",
1114 _ => "dpgf",
1115 };
1116 m.insert("q".into(), json!(q));
1117 m.insert(side.into(), json!(target));
1118 }
1119 m.insert("surf".into(), json!(s1));
1120 m.insert("to".into(), json!(s2));
1121 }
1122 "SFNO" | "TFNO" => {
1124 m.insert("type".into(), json!("fnum"));
1125 m.insert("field".into(), json!(field_no(int(INT1)?)?));
1126 m.insert("wave".into(), wave(int(INT2)?)?);
1127 m.insert(
1128 "dir".into(),
1129 json!(if op == "SFNO" { "sag" } else { "tan" }),
1130 );
1131 m.insert("target".into(), json!(target));
1132 }
1133 "CENX" | "CENY" => {
1134 if int(INT1)? as usize != image {
1135 return Err("only the centroid on the image surface is supported".into());
1136 }
1137 if int(data(2))? != 0 {
1138 return Err("polarization is not supported".into());
1139 }
1140 m.insert("type".into(), json!("centroid"));
1141 m.insert("wave".into(), wave(int(INT2)?)?);
1142 m.insert("field".into(), json!(field_no(int(data(1))?)?));
1143 m.insert("q".into(), json!(if op == "CENX" { "x" } else { "y" }));
1144 m.insert("target".into(), json!(target * unit));
1145 }
1146 "ZPLM" => {
1148 let n = int(INT1)?;
1149 if !(0..=99).contains(&n) {
1150 return Err(format!("macro number {n} (0 to 99)"));
1151 }
1152 m.insert("type".into(), json!("zplm"));
1153 m.insert("macro".into(), json!(n));
1154 m.insert("data".into(), json!(int(INT2)?));
1155 for (k, i) in ["hx", "hy", "px", "py"].iter().zip(1..) {
1156 m.insert((*k).into(), json!(num(data(i))?));
1157 }
1158 m.insert("target".into(), json!(target));
1159 }
1160 _ => return Err("this operand is not supported".into()),
1161 }
1162 Ok(m)
1163}
1164
1165pub fn terms_from_zmx(mf: &MeritFunction, primary: usize, image: usize, sys: &ZmxSys) -> ZmxMerit {
1167 let sys = &ZmxSys {
1168 mce: mf.mce.clone(),
1169 ..sys.clone()
1170 };
1171 let mut cx = Ctx {
1172 unit: mf.lens_unit_mm,
1173 primary,
1174 image,
1175 sys,
1176 rows: &mf.rows,
1177 notes: Vec::new(),
1178 };
1179 let mut config = 1i64;
1181 let mut configs = 1usize;
1182 let mut row_config = Vec::with_capacity(mf.rows.len());
1183 for r in &mf.rows {
1184 if r.op == "CONF" {
1185 match r.int(INT1) {
1186 Ok(c) if c >= 1 => {
1187 config = c;
1188 configs = configs.max(c as usize);
1189 }
1190 Ok(c) => cx.skip(r, &format!("configuration {c}")),
1191 Err(e) => cx.skip(r, &e.to_string()),
1192 }
1193 }
1194 row_config.push(config);
1195 }
1196 let flow = flow(&mf.rows, &mut cx);
1197 let mut wiz = wizard::group(&mf.rows, &row_config, cx.unit, cx.sys.symmetric);
1199 cx.notes.append(&mut wiz.notes);
1200 let mut terms = Vec::new();
1201 let mut sources = Vec::new();
1202 for (i, r) in mf.rows.iter().enumerate() {
1203 let Some(fields) = &flow[i] else {
1204 continue;
1205 };
1206 if wiz.used[i] {
1207 for m in wiz.terms.remove(&i).unwrap_or_default() {
1208 terms.push(Value::Object(m));
1209 sources.push(r.row);
1210 }
1211 continue;
1212 }
1213 if r.op == "BLNK" || r.op == "CONF" {
1214 continue;
1215 }
1216 if !r.readable() {
1217 cx.skip(r, "can't read the merit function line");
1218 continue;
1219 }
1220 let weight = match r.num(WEIGHT) {
1221 Ok(w) => w,
1222 Err(e) => {
1223 cx.skip(r, &e.to_string());
1224 continue;
1225 }
1226 };
1227 if weight == 0.0 {
1228 continue;
1229 }
1230 if weight < 0.0 {
1231 cx.skip(
1232 r,
1233 "a negative weight (a Lagrange constraint in OpticStudio) is not supported",
1234 );
1235 continue;
1236 }
1237 let (src, side, config) = match r.op.as_str() {
1239 "OPGT" | "OPLT" => {
1240 let n = match r.int(INT1) {
1241 Ok(n) => n,
1242 Err(e) => {
1243 cx.skip(r, &e.to_string());
1244 continue;
1245 }
1246 };
1247 let k = (n >= 1)
1248 .then(|| n as usize - 1)
1249 .filter(|&k| k < cx.rows.len() && k != i);
1250 let Some(k) = k else {
1251 cx.skip(r, &format!("no row {n} in the merit function"));
1252 continue;
1253 };
1254 let side = if r.op == "OPGT" { "min" } else { "max" };
1255 (k, Some(side), row_config[k])
1256 }
1257 _ => (i, None, row_config[i]),
1258 };
1259 let at = calc::Rows {
1260 rows: cx.rows,
1261 row_config: &row_config,
1262 unit: cx.unit,
1263 primary: cx.primary,
1264 image: cx.image,
1265 sys: cx.sys,
1266 nodes: Default::default(),
1267 };
1268 let (src_i, src) = (src, &cx.rows[src]);
1269 let mut m = match at.kind(src_i) {
1270 Ok(m) => m,
1271 Err(e) => {
1272 let why = if side.is_some() {
1273 format!("the referenced row {} ({}) is {e}", src.row, src.op)
1274 } else {
1275 e
1276 };
1277 cx.skip(r, &why);
1278 continue;
1279 }
1280 };
1281 if let Some(why) = read_differs(src, cx.sys) {
1282 cx.notes.push(format!(
1283 ".zmx merit function row {} ({}, line {}): {why}",
1284 src.row, src.op, src.line
1285 ));
1286 }
1287 let len = is_length(&src.op)
1290 || m.get("absolute") == Some(&json!(true))
1291 || (src.op == "ABCD" && cx.sys.angle_field);
1292 let um = ["GENC", "DENC"].contains(&src.op.as_str());
1294 if let Some(side) = side {
1295 let single = m.get("type").and_then(Value::as_str) != Some("zplm");
1296 let Some(_) = m.remove("target").filter(|_| single) else {
1297 cx.skip(
1298 r,
1299 &format!(
1300 "the referenced row {} ({}) has no single value",
1301 src.row, src.op
1302 ),
1303 );
1304 continue;
1305 };
1306 let t = r.num(TARGET).unwrap_or(0.0);
1307 let t = if um {
1308 t * 1e-3
1309 } else if src.op == "CVOL" {
1310 t * cx.unit.powi(3) * 1e-3
1311 } else if len {
1312 t * cx.unit
1313 } else {
1314 t
1315 };
1316 m.insert(side.into(), json!(t));
1317 }
1318 let weight = if um {
1321 weight * 1e6
1322 } else if src.op == "CVOL" {
1323 weight / (cx.unit.powi(3) * 1e-3).powi(2)
1325 } else if src.op == "BFSD" {
1326 weight / shape::bfsd_scale(src.int(INT2).unwrap_or(1), cx.unit).powi(2)
1327 } else if len {
1328 weight / (cx.unit * cx.unit)
1329 } else if ["CVGT", "CVLT", "CVVA", "POWR"].contains(&src.op.as_str()) {
1330 weight * cx.unit * cx.unit
1331 } else {
1332 weight
1333 };
1334 m.insert("weight".into(), json!(weight));
1335 if m.get("type").and_then(Value::as_str) == Some("spread") {
1337 configs = configs.max(cx.sys.configs);
1338 } else if let Some(c) = m.get("config").and_then(Value::as_u64) {
1339 configs = configs.max(c as usize);
1340 } else if config != 1 {
1341 m.insert("config".into(), json!(config));
1342 }
1343 let mut v = Value::Object(m);
1344 if !fields.is_empty() {
1345 modified_fields(&mut v, fields);
1346 }
1347 terms.push(v);
1348 sources.push(r.row);
1349 }
1350 ZmxMerit {
1351 terms,
1352 sources,
1353 notes: cx.notes,
1354 configs,
1355 }
1356}
1357
1358fn flow(rows: &[MeritRow], cx: &mut Ctx) -> Vec<Option<BTreeMap<i64, (f64, f64)>>> {
1362 let mut out = Vec::with_capacity(rows.len());
1363 let mut fields = BTreeMap::new();
1364 let mut skip_to = 0usize;
1365 let mut end = false;
1366 for (i, r) in rows.iter().enumerate() {
1367 if end || i + 1 < skip_to {
1368 out.push(None);
1369 continue;
1370 }
1371 let int = |k: usize| r.int(k).map_err(|e| e.to_string());
1372 let num = |k: usize| r.num(k).map_err(|e| e.to_string());
1373 match r.op.as_str() {
1374 "ENDX" => end = true,
1375 "GOTO" => match int(INT1) {
1376 Ok(n) if n as usize > i + 1 => skip_to = n as usize,
1377 Ok(_) => {}
1378 Err(e) => cx.skip(r, &e),
1379 },
1380 "FDMO" => {
1381 let f = (|| -> Result<(i64, f64, f64, bool), String> {
1382 let vig = (3..=6).any(|k| num(data(k)).unwrap_or(0.0) != 0.0);
1383 Ok((int(INT1)?, num(data(1))?, num(data(2))?, vig))
1384 })();
1385 match f {
1386 Ok((f, hx, hy, vig)) => {
1387 if vig {
1388 cx.notes.push(format!(
1389 ".zmx merit function row {} (FDMO, line {}): the vignetting factors are not used",
1390 r.row, r.line
1391 ));
1392 }
1393 fields.insert(f, (hx, hy));
1394 }
1395 Err(e) => cx.skip(r, &e),
1396 }
1397 }
1398 "FDRE" => match int(INT1) {
1399 Ok(f) => {
1400 fields.remove(&f);
1401 }
1402 Err(e) => cx.skip(r, &e),
1403 },
1404 _ => {}
1405 }
1406 if matches!(r.op.as_str(), "ENDX" | "GOTO" | "FDMO" | "FDRE") {
1407 out.push(None);
1408 } else {
1409 out.push(Some(fields.clone()));
1410 }
1411 }
1412 out
1413}
1414
1415fn modified_fields(v: &mut Value, fields: &BTreeMap<i64, (f64, f64)>) {
1417 match v {
1418 Value::Object(m) => {
1419 for (k, x) in m.iter_mut() {
1420 let hit = x.as_i64().and_then(|n| fields.get(&n));
1421 match hit {
1422 Some(&(hx, hy)) if k == "field" || k == "reference" => *x = json!([hx, hy]),
1423 _ => modified_fields(x, fields),
1424 }
1425 }
1426 }
1427 Value::Array(a) => a.iter_mut().for_each(|x| modified_fields(x, fields)),
1428 _ => {}
1429 }
1430}
1431
1432fn is_length(op: &str) -> bool {
1434 PARAXIAL
1435 .iter()
1436 .chain(RAY)
1437 .chain(PAR)
1438 .any(|(o, _, l)| *o == op && *l)
1439 || [
1440 "CENX", "CENY", "RSCE", "RSCH", "CTGT", "CTLT", "CTVA", "TTHI", "TRAC", "TRAD", "TRAE",
1441 "TRCX", "TRCY", "ETGT", "ETLT", "ETVA", "MNCT", "MXCT", "MNCA", "MXCA", "MNCG", "MXCG",
1442 "MNET", "MXET", "MNEA", "MXEA", "MNEG", "MXEG", "DMGT", "DMLT", "DMVA", "SAGX", "SAGY",
1443 "SSAG", "STHI", "GLCX", "GLCY", "GLCZ", "PLEN", "YNIP", "EFLX", "EFLY", "EFLA", "CARD",
1444 "LONA", "AXCL", "LACL", "MNSD", "MXSD", "TTGT", "TTLT", "TTVA", "ZTHI", "TSAG",
1445 ]
1446 .contains(&op)
1447}
1448
1449fn zern_standard_fit(rows: &[MeritRow], k: usize) -> usize {
1452 let same = |r: &MeritRow| {
1453 r.op == "ZERN"
1454 && (1..10)
1455 .filter(|&j| j != TARGET && j != WEIGHT)
1456 .all(|j| r.num(j).ok() == rows[k].num(j).ok())
1457 };
1458 let lo = (0..k)
1459 .rev()
1460 .take_while(|&j| same(&rows[j]))
1461 .last()
1462 .unwrap_or(k);
1463 let hi = (k + 1..rows.len())
1464 .take_while(|&j| same(&rows[j]))
1465 .last()
1466 .unwrap_or(k);
1467 rows[lo..=hi]
1468 .iter()
1469 .filter_map(|r| r.int(INT1).ok())
1470 .map(|t| t.max(0) as usize)
1471 .max()
1472 .unwrap_or(0)
1473 .max(11)
1474}
1475
1476#[cfg(test)]
1477mod tests;