1use super::*;
4
5pub fn rows_from_terms(
11 terms: &[Value],
12 systems: &[lensbench_core::System],
13 before: &[MeritRow],
14) -> (Vec<MeritRow>, Vec<String>) {
15 let mut rows: Vec<MeritRow> = Vec::new();
16 let mut notes = Vec::new();
17 let mut config = before
18 .iter()
19 .rev()
20 .find(|r| r.op == "CONF")
21 .and_then(|r| r.int(INT1).ok())
22 .map_or(1, |c| c.max(1) as u64);
23 for (i, t) in terms.iter().enumerate() {
24 if crate::merit::is_comment(t) {
25 let text = t.get("text").and_then(Value::as_str).unwrap_or_default();
26 rows.push(MeritRow::blank(text));
27 continue;
28 }
29 let c = t.get("config").and_then(Value::as_u64).unwrap_or(1);
30 let Some(s) = (c >= 1).then(|| systems.get(c as usize - 1)).flatten() else {
31 notes.push(format!(
32 "term {}: no configuration {c}; not written to the .zmx",
33 i + 1
34 ));
35 continue;
36 };
37 let out = match row_of(t, s) {
38 Ok(r) => r,
39 Err(e) => {
40 notes.push(format!("term {}: {e}; not written to the .zmx", i + 1));
41 continue;
42 }
43 };
44 if let Some(e) = os_value_differs(t) {
45 notes.push(format!("term {}: {e}", i + 1));
46 }
47 if c != config {
48 rows.push(MeritRow::new(
49 "CONF",
50 [c as f64, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
51 0.0,
52 0.0,
53 ));
54 config = c;
55 }
56 let weight = t.get("weight").and_then(Value::as_f64).unwrap_or(1.0);
57 let weight = if ["GENC", "DENC", "CVOL"].contains(&out.0) {
59 weight * 1e-6
60 } else {
61 weight
62 };
63 match out {
64 (op, p, Bound::Target(target)) => rows.push(MeritRow::new(op, p, target, weight)),
65 (op, p, Bound::Side(side, b)) => {
66 rows.push(MeritRow::new(op, p, b, 0.0));
67 let n = (before.len() + rows.len()) as f64;
68 let z = [n, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
69 rows.push(MeritRow::new(side, z, b, weight));
70 }
71 (op, p, Bound::Both(target)) => {
72 for o in op.split(',') {
73 rows.push(MeritRow::new(o, p, target, weight));
74 }
75 }
76 }
77 }
78 (rows, notes)
79}
80
81fn os_value_differs(t: &Value) -> Option<String> {
84 let str_of = |k: &str| t.get(k).and_then(Value::as_str);
85 match str_of("type")? {
86 "zernike" => {
87 let term = t.get("term").and_then(Value::as_u64)?;
88 let fit = t
89 .get("fit")
90 .and_then(Value::as_u64)
91 .unwrap_or(term.max(37));
92 let os = if str_of("kind") == Some("standard") {
93 term.max(11)
94 } else {
95 37
96 };
97 (fit != os).then(|| {
98 format!("OpticStudio's ZERN fits {os} terms, so its value differs from the term's")
99 })
100 }
101 "spot" | "wavefront" if grid_samp(t).is_some() => None,
103 "spot" | "wavefront" => (str_of("quadrature") != Some("opticstudio")).then(|| {
104 "OpticStudio's pupil quadrature (2·Ring arms) differs from the term's, so its value differs"
105 .to_string()
106 }),
107 _ => None,
108 }
109}
110
111fn grid_samp(t: &Value) -> Option<u64> {
114 if t.get("quadrature").and_then(Value::as_str) != Some("grid") {
115 return None;
116 }
117 let n = t.get("n").and_then(Value::as_u64)?;
118 (n >= 2 && n % 2 == 0).then_some(n / 2)
119}
120
121enum Bound {
123 Target(f64),
124 Side(&'static str, f64),
126 Both(f64),
128}
129
130fn row_of(
132 t: &Value,
133 s: &lensbench_core::System,
134) -> Result<(&'static str, [f64; 8], Bound), String> {
135 let ty = t
136 .get("type")
137 .and_then(Value::as_str)
138 .unwrap_or("")
139 .to_ascii_lowercase();
140 let num = |k: &str| t.get(k).and_then(Value::as_f64);
141 let bound = |default: f64| -> Bound {
142 if let Some(b) = num("min") {
143 Bound::Side("OPGT", b)
144 } else if let Some(b) = num("max") {
145 Bound::Side("OPLT", b)
146 } else {
147 Bound::Target(num("target").unwrap_or(default))
148 }
149 };
150 let wave = || -> f64 { t.get("wave").and_then(Value::as_u64).unwrap_or(0) as f64 };
152 let primary = (s.primary + 1) as f64;
153 let field = || -> Result<(f64, f64), String> {
154 match t.get("field") {
155 Some(Value::Array(a)) if a.len() == 2 => {
156 Ok((a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0)))
157 }
158 Some(v) => match v.as_u64() {
159 Some(i) if i >= 1 && (i as usize) <= s.fields.len() => Ok(s.hxhy(i as usize - 1)),
160 _ => Err(format!("field {v}")),
161 },
162 None => Err("no field".into()),
163 }
164 };
165 let field_no = || -> Result<f64, String> {
166 match t.get("field").and_then(Value::as_u64) {
167 Some(i) if i >= 1 => Ok(i as f64),
168 _ => Err("OpticStudio needs a field number here (not a normalized field)".into()),
169 }
170 };
171 let samp = |n: Option<f64>| -> f64 {
172 let n = n.unwrap_or(64.0).max(32.0);
174 ((n / 32.0).log2().floor() + 1.0).min(6.0)
175 };
176 Ok(match ty.as_str() {
177 "paraxial" => {
178 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
179 let q = lensbench_optim::ParaxQ::parse(q)
180 .map_err(|e| e.to_string())?
181 .name();
182 let Some((op, _, _)) = PARAXIAL.iter().find(|(_, n, _)| *n == q) else {
183 return Err(format!("paraxial {q} has no OpticStudio operand"));
184 };
185 let w = match t.get("wave").and_then(Value::as_u64) {
187 Some(w) => w as f64,
188 None => primary,
189 };
190 let p = [0.0, w, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
191 (op, p, bound(0.0))
192 }
193 "spot" | "wavefront" => {
194 let chief = t.get("reference").and_then(Value::as_str) == Some("chief");
195 let samp = grid_samp(t);
196 let op = match (ty.as_str(), chief, samp.is_some()) {
197 ("spot", false, false) => "RSCE",
198 ("spot", true, false) => "RSCH",
199 (_, false, false) => "RWCE",
200 (_, true, false) => "RWCH",
201 ("spot", false, true) => "RSRE",
202 ("spot", true, true) => "RSRH",
203 (_, false, true) => "RWRE",
204 (_, true, true) => "RWRH",
205 };
206 let (hx, hy) = field()?;
207 let rings = samp.map_or(num("rings").unwrap_or(3.0), |n| n as f64);
208 (
209 op,
210 [rings, wave(), hx, hy, 0.0, 0.0, 0.0, 0.0],
211 Bound::Target(0.0),
212 )
213 }
214 "opd" => {
215 let (hx, hy) = field()?;
216 let w = if wave() == 0.0 { primary } else { wave() };
217 let p = [
218 0.0,
219 w,
220 hx,
221 hy,
222 num("px").unwrap_or(0.0),
223 num("py").unwrap_or(0.0),
224 0.0,
225 0.0,
226 ];
227 ("OPDC", p, bound(0.0))
228 }
229 "ray" if t.get("to").is_some() => {
231 let (hx, hy) = field()?;
232 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
233 let w = if wave() == 0.0 { primary } else { wave() };
234 let mut p = [
235 num("surf").unwrap_or(0.0),
236 num("to").unwrap_or(0.0),
237 hx,
238 hy,
239 num("px").unwrap_or(0.0),
240 num("py").unwrap_or(0.0),
241 0.0,
242 0.0,
243 ];
244 match (q, bound(0.0)) {
245 ("opth", b) if w == primary => ("PLEN", p, b),
246 ("opth", _) => {
247 return Err("PLEN of OpticStudio is for the primary wavelength".into())
248 }
249 ("aoi" | "aoe", Bound::Side(side, b)) => {
250 p[6] = w;
251 let op = match (side == "OPGT", q == "aoe") {
252 (true, true) => "MNRE",
253 (true, false) => "MNRI",
254 (false, true) => "MXRE",
255 (false, false) => "MXRI",
256 };
257 (op, p, Bound::Target(b))
258 }
259 _ => {
260 return Err(format!(
261 "a ray term with to and {q} has no OpticStudio operand"
262 ))
263 }
264 }
265 }
266 "ray" => {
267 let q = t
268 .get("q")
269 .and_then(Value::as_str)
270 .unwrap_or("")
271 .to_ascii_lowercase();
272 let table = if t.get("paraxial") == Some(&Value::Bool(true)) {
273 PAR
274 } else {
275 RAY
276 };
277 let Some((op, _, _)) = table
278 .iter()
279 .find(|(o, n, _)| *n == q || o.eq_ignore_ascii_case(&q))
280 else {
281 return Err(format!("ray quantity {q}"));
282 };
283 let (hx, hy) = field()?;
284 let mut surf = num("surf").unwrap_or(s.image() as f64);
285 let mut op = *op;
286 if image_only(op) {
287 if surf != s.image() as f64 {
288 if op != "TRAR" || surf < 1.0 {
290 return Err(format!("{op} of OpticStudio is on the image surface only"));
291 }
292 op = "TRAI";
293 } else {
294 surf = 0.0;
295 }
296 }
297 let w = if wave() == 0.0 { primary } else { wave() };
298 let p = [
299 surf,
300 w,
301 hx,
302 hy,
303 num("px").unwrap_or(0.0),
304 num("py").unwrap_or(0.0),
305 0.0,
306 0.0,
307 ];
308 (op, p, bound(0.0))
309 }
310 "zernike" => {
311 let kind = match t.get("kind").and_then(Value::as_str).unwrap_or("fringe") {
312 "standard" => 1.0,
313 _ => 0.0,
314 };
315 let w = if wave() == 0.0 { primary } else { wave() };
316 let p = [
317 num("term").unwrap_or(1.0),
318 w,
319 samp(num("n")),
320 field_no()?,
321 kind,
322 0.0,
323 0.0,
324 0.0,
325 ];
326 ("ZERN", p, bound(0.0))
327 }
328 "mtf" => {
330 let kind = t
331 .get("kind")
332 .and_then(Value::as_str)
333 .unwrap_or("diffraction");
334 let geo = kind == "geometric";
335 let pre = match kind {
336 "square" => "MSW",
337 "geometric" => "GMT",
338 "huygens" => "MTH",
339 _ => "MTF",
340 };
341 let no_scale = geo && t.get("diff_limit").and_then(Value::as_bool) == Some(false);
343 let p = [
344 samp(num("n")),
345 wave(),
346 field_no()?,
347 num("freq").unwrap_or(0.0),
348 if no_scale { 1.0 } else { 0.0 },
349 0.0,
350 0.0,
351 0.0,
352 ];
353 let ops: [&'static str; 4] = match pre {
355 "MSW" => ["MSWT", "MSWS", "MSWA", "MSWT,MSWS"],
356 "GMT" => ["GMTT", "GMTS", "GMTA", "GMTT,GMTS"],
357 "MTH" => ["MTHT", "MTHS", "MTHA", "MTHT,MTHS"],
358 _ => ["MTFT", "MTFS", "MTFA", "MTFT,MTFS"],
359 };
360 match t.get("dir").and_then(Value::as_str).unwrap_or("both") {
361 "tan" => (ops[0], p, bound(1.0)),
362 "sag" => (ops[1], p, bound(1.0)),
363 "avg" => (ops[2], p, bound(1.0)),
364 _ => (ops[3], p, Bound::Both(num("target").unwrap_or(1.0))),
365 }
366 }
367 "energy" => {
369 let str_of = |k: &str| t.get(k).and_then(Value::as_str);
370 let method = str_of("method").unwrap_or("geometric");
371 let shape = match str_of("shape").unwrap_or("circle") {
372 "x" => 2.0,
373 "y" => 3.0,
374 "square" => 4.0,
375 _ => 1.0,
376 };
377 let center = match str_of("center").unwrap_or("chief") {
378 "centroid" => 1.0,
379 "vertex" => 2.0,
380 "middle" if method == "geometric" => 3.0,
381 "middle" => {
382 return Err("OpticStudio's DENC and DENF have no middle of the spot".into())
383 }
384 _ => 0.0,
385 };
386 let airy = t.get("airy").and_then(Value::as_bool) == Some(true);
387 let (size, v) = match (num("size_at"), num("fraction_at")) {
388 (Some(f), None) => (true, f),
389 (None, Some(r)) => (false, r * 1e3),
390 _ => return Err("an energy term needs one of size_at and fraction_at".into()),
391 };
392 let (op, refp, d5) = match (method, size) {
393 ("geometric", true) => ("GENC", center, if airy { 0.0 } else { 1.0 }),
394 ("geometric", false) => ("GENF", center, if airy { 0.0 } else { 1.0 }),
395 ("huygens", true) => ("DENC", center + 3.0, 0.0),
396 ("huygens", false) => ("DENF", center + 3.0, 0.0),
397 (_, true) => ("DENC", center, 0.0),
398 (_, false) => ("DENF", center, 0.0),
399 };
400 let p = [samp(num("n")), wave(), field_no()?, v, shape, refp, d5, 0.0];
401 let b = match bound(0.0) {
402 Bound::Target(x) if size => Bound::Target(x * 1e3),
403 Bound::Side(sd, x) if size => Bound::Side(sd, x * 1e3),
404 b => b,
405 };
406 (op, p, b)
407 }
408 "strehl" => (
410 "STRH",
411 [5.0, wave(), field_no()?, 0.0, 0.0, 0.0, 0.0, 0.0],
412 bound(1.0),
413 ),
414 "illum" => {
416 let op = match t.get("q").and_then(Value::as_str) {
417 Some("relative") => "RELI",
418 Some("fno") => "EFNO",
419 q => return Err(format!("illum q {q:?}")),
420 };
421 let w = if wave() == 0.0 { primary } else { wave() };
422 (
423 op,
424 [100.0, w, field_no()?, 0.0, 0.0, 0.0, 0.0, 0.0],
425 bound(0.0),
426 )
427 }
428 "seidel" => {
429 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
430 let q = lensbench_optim::SeidelQ::parse(q).map_err(|e| e.to_string())?;
431 let j = num("surf").unwrap_or(0.0);
432 if q == lensbench_optim::SeidelQ::Dist && j == 0.0 {
433 return Err("the sum of the Seidel distortion has no OpticStudio operand (DIST of surface 0 is the real distortion)".into());
434 }
435 let w = if wave() == 0.0 { primary } else { wave() };
436 let op = match q.name() {
437 "spha" => "SPHA",
438 "coma" => "COMA",
439 "asti" => "ASTI",
440 "fcur" => "FCUR",
441 _ => "DIST",
442 };
443 (op, [j, w, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0))
444 }
445 "distortion" => {
448 let w = if wave() == 0.0 { primary } else { wave() };
449 let abs = t.get("absolute").and_then(Value::as_bool) == Some(true);
450 let a = if abs { 1.0 } else { 0.0 };
451 let flag = |k: &str| t.get(k).and_then(Value::as_bool) == Some(true);
452 let reference = match t.get("reference") {
453 None => 0.0,
454 Some(v) => match v.as_u64() {
455 Some(i) if i >= 1 && (i as usize) <= s.fields.len() => i as f64,
456 _ => return Err("OpticStudio needs a field number for the reference".into()),
457 },
458 };
459 if let Some(c) = t.get("coef").and_then(Value::as_str) {
460 let k = ["a", "b", "c", "d"]
461 .iter()
462 .position(|x| *x == c)
463 .ok_or(format!("coefficient {c}"))?;
464 (
465 "ABCD",
466 [reference, w, k as f64, 0.0, 0.0, 0.0, 0.0, 0.0],
467 bound(0.0),
468 )
469 } else if let Some(v) = t.get("abcd").and_then(Value::as_array) {
470 let x = |i: usize| v.get(i).and_then(Value::as_f64).unwrap_or(0.0);
471 let comp = match t
472 .get("component")
473 .and_then(Value::as_str)
474 .unwrap_or("radial")
475 {
476 "x" => 1.0,
477 "y" => 2.0,
478 _ => 0.0,
479 };
480 if abs {
481 return Err("DISA of OpticStudio gives only percent (not absolute)".into());
482 }
483 let p = [reference, w, comp, field_no()?, x(0), x(1), x(2), x(3)];
484 ("DISA", p, bound(0.0))
485 } else if t
486 .get("component")
487 .and_then(Value::as_str)
488 .is_some_and(|c| c != "radial")
489 {
490 return Err("only the radial distortion without abcd can be written".into());
491 } else if flag("ftheta") {
492 ("DISC", [0.0, w, a, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0))
493 } else if flag("peak") {
494 let f = if t.get("field").is_some() {
495 field_no()?
496 } else {
497 0.0
498 };
499 ("DIMX", [f, w, a, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0))
500 } else if t.get("field").is_some() || reference != 0.0 {
501 let (hx, hy) = if t.get("field").is_some() {
502 field()?
503 } else {
504 (0.0, 1.0)
505 };
506 let w = if abs { -w } else { w };
507 (
508 "DISG",
509 [reference, w, hx, hy, 0.0, 0.0, 0.0, 0.0],
510 bound(0.0),
511 )
512 } else {
513 ("DIST", [0.0, w, a, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0))
514 }
515 }
516 "longitudinal" => {
517 let w = if wave() == 0.0 { primary } else { wave() };
518 let z = num("zone").unwrap_or(0.0);
519 match t.get("wave2").and_then(Value::as_f64) {
520 Some(w2) => ("AXCL", [w, w2, z, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0)),
521 None => ("LONA", [w, 0.0, z, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0)),
522 }
523 }
524 "lateral_color" => {
525 let w = if wave() == 0.0 { primary } else { wave() };
526 let w2 = num("wave2").unwrap_or(primary);
527 ("LACL", [w, w2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0))
528 }
529 "semi" => {
530 let s1 = num("surf").unwrap_or(1.0);
531 let s2 = num("to").unwrap_or(s1);
532 let p = [s1, s2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
533 match bound(0.0) {
534 Bound::Side("OPGT", b) => ("MNSD", p, Bound::Target(b)),
535 Bound::Side(_, b) => ("MXSD", p, Bound::Target(b)),
536 _ => return Err("a semi term needs min or max".into()),
537 }
538 }
539 "fnum" => {
540 let op = match t.get("dir").and_then(Value::as_str) {
541 Some("sag") => "SFNO",
542 _ => "TFNO",
543 };
544 let w = if wave() == 0.0 { primary } else { wave() };
545 (
546 op,
547 [field_no()?, w, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
548 bound(0.0),
549 )
550 }
551 "centroid" => {
552 let op = if t.get("q").and_then(Value::as_str) == Some("y") {
553 "CENY"
554 } else {
555 "CENX"
556 };
557 let p = [
558 s.image() as f64,
559 wave(),
560 field_no()?,
561 0.0,
562 5.0,
563 0.0,
564 0.0,
565 0.0,
566 ];
567 (op, p, bound(0.0))
568 }
569 "thickness" => {
570 let s1 = num("surf").unwrap_or(0.0);
571 let s2 = num("to").unwrap_or(s1);
572 let mut p = [s1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
573 let edge = t.get("edge") == Some(&Value::Bool(true));
574 let zone = num("zone").unwrap_or(1.0);
575 let clear = t.get("clear") == Some(&Value::Bool(true));
576 let code = match t.get("axis").and_then(Value::as_str) {
578 None | Some("+y") => 0.0,
579 Some("+x") => 1.0,
580 Some("-y") => 2.0,
581 Some("-x") => 3.0,
582 Some(a) => return Err(format!("axis {a}")),
583 };
584 if let Some(e) = t.get("each").and_then(Value::as_str) {
585 if code != 0.0 {
586 return Err("edge thicknesses of each surface along other than +y can't be written (MNET, MXET and the like)".into());
587 }
588 if clear {
589 return Err("edge thicknesses of each surface at the clear semi-diameter can't be written (MNET, MXET and the like)".into());
590 }
591 p[1] = s2;
593 if edge {
594 p[2] = if zone == 1.0 { 0.0 } else { zone };
595 }
596 let lower = match bound(0.0) {
597 Bound::Side(s, b) => (s == "OPGT", b),
598 _ => return Err("a thickness term with each needs min or max".into()),
599 };
600 let op = match (lower.0, edge, e) {
601 (true, false, "air") => "MNCA",
602 (true, false, "glass") => "MNCG",
603 (true, false, _) => "MNCT",
604 (false, false, "air") => "MXCA",
605 (false, false, "glass") => "MXCG",
606 (false, false, _) => "MXCT",
607 (true, true, "air") => "MNEA",
608 (true, true, "glass") => "MNEG",
609 (true, true, _) => "MNET",
610 (false, true, "air") => "MXEA",
611 (false, true, "glass") => "MXEG",
612 (false, true, _) => "MXET",
613 };
614 (op, p, Bound::Target(lower.1))
615 } else if edge {
616 if s2 != s1 || zone != 1.0 {
617 return Err("only the edge thickness of one surface at its semi-diameter can be written (ETGT, ETLT, ETVA)".into());
618 }
619 p[1] = code;
621 p[3] = f64::from(clear);
622 match bound(0.0) {
623 Bound::Side("OPGT", b) => ("ETGT", p, Bound::Target(b)),
624 Bound::Side(_, b) => ("ETLT", p, Bound::Target(b)),
625 b => ("ETVA", p, b),
626 }
627 } else if s2 != s1 {
628 p[1] = s2;
629 ("TTHI", p, bound(0.0))
630 } else {
631 match bound(0.0) {
633 Bound::Side("OPGT", b) => ("CTGT", p, Bound::Target(b)),
634 Bound::Side(_, b) => ("CTLT", p, Bound::Target(b)),
635 b => ("CTVA", p, b),
636 }
637 }
638 }
639 "spread" => {
641 let inner = t.get("term").ok_or("no term")?;
642 let thick = inner.get("type").and_then(Value::as_str) == Some("thickness")
643 && inner.get("edge").and_then(Value::as_bool) != Some(true)
644 && inner.get("each").is_none();
645 match (thick, bound(0.0)) {
646 (true, Bound::Side("OPLT", b)) => {
647 let s1 = inner.get("surf").and_then(Value::as_f64).unwrap_or(1.0);
648 let s2 = inner.get("to").and_then(Value::as_f64).unwrap_or(s1);
649 (
650 "ZTHI",
651 [s1, s2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
652 Bound::Target(b),
653 )
654 }
655 _ => {
656 return Err(
657 "only the max of the spread of a thickness term can be written (ZTHI)"
658 .into(),
659 )
660 }
661 }
662 }
663 "surface" if t.get("to").is_some() => {
664 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
665 let s1 = num("surf").unwrap_or(1.0);
666 let s2 = num("to").unwrap_or(s1);
667 let p = [s1, s2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
668 let (mn, mx) = match q {
669 "semi" => ("MNSD", "MXSD"),
670 "nd" => ("MNIN", "MXIN"),
671 "vd" => ("MNAB", "MXAB"),
672 "dpgf" => ("MNPD", "MXPD"),
673 _ => return Err(format!("surface quantity {q} with to")),
674 };
675 match bound(0.0) {
676 Bound::Side("OPGT", b) => (mn, p, Bound::Target(b)),
677 Bound::Side(_, b) => (mx, p, Bound::Target(b)),
678 _ => return Err("a surface term with to needs min or max".into()),
679 }
680 }
681 "surface" => {
682 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
683 let mut p = [
684 num("surf").unwrap_or(0.0),
685 0.0,
686 0.0,
687 0.0,
688 0.0,
689 0.0,
690 0.0,
691 0.0,
692 ];
693 let (x, y) = (num("x").unwrap_or(0.0), num("y").unwrap_or(0.0));
694 let (va, gt, lt) = match q {
696 "curv" => ("CVVA", "CVGT", "CVLT"),
697 "conic" => ("COVA", "COGT", "COLT"),
698 "diam" | "mech_diam" => {
699 p[3] = if q == "diam" { 1.0 } else { 0.0 };
700 ("DMVA", "DMGT", "DMLT")
701 }
702 "sagx" => ("SAGX", "", ""),
703 "sagy" => ("SAGY", "", ""),
704 "sag" => {
705 (p[1], p[2], p[3]) = (0.0, x, y);
706 ("SSAG", "", "")
707 }
708 "thick" => {
709 (p[2], p[3]) = (x, y);
710 ("STHI", "", "")
711 }
712 "total" | "total_clear" => {
713 p[3] = f64::from(q == "total_clear");
715 p[1] = match (x, y) {
716 (0.0, y) if y >= 0.0 => 0.0,
717 (x, 0.0) if x > 0.0 => 1.0,
718 (0.0, _) => 2.0,
719 (_, 0.0) => 3.0,
720 _ => return Err(
721 "only the total thickness along +y, +x, −y or −x can be written (TTVA)"
722 .into(),
723 ),
724 };
725 ("TTVA", "TTGT", "TTLT")
726 }
727 "param" => {
728 p[1] = num("param").unwrap_or(0.0);
729 ("PMVA", "PMGT", "PMLT")
730 }
731 "gx" => ("GLCX", "", ""),
732 "gy" => ("GLCY", "", ""),
733 "gz" => ("GLCZ", "", ""),
734 "ga" => ("GLCA", "", ""),
735 "gb" => ("GLCB", "", ""),
736 "gc" => ("GLCC", "", ""),
737 "cost" => ("GCOS", "", ""),
738 "tce" => ("GTCE", "", ""),
739 "surf_tce" => ("TCVA", "TCGT", "TCLT"),
740 "power" | "ynip" | "index" => {
741 p[1] = if wave() == 0.0 { primary } else { wave() };
742 let op = match q {
743 "power" => "POWR",
744 "ynip" => "YNIP",
745 _ => "INDX",
746 };
747 (op, "", "")
748 }
749 _ => return Err(format!("surface quantity {q}")),
750 };
751 match bound(0.0) {
752 Bound::Side("OPGT", b) if !gt.is_empty() => (gt, p, Bound::Target(b)),
753 Bound::Side(_, b) if !lt.is_empty() => (lt, p, Bound::Target(b)),
754 b => (va, p, b),
755 }
756 }
757 "tsag" => {
758 let v3 = |k: &str| -> [f64; 3] {
759 let a = t.get(k).and_then(Value::as_array);
760 let x = |i: usize| {
761 a.and_then(|a| a.get(i))
762 .and_then(Value::as_f64)
763 .unwrap_or(0.0)
764 };
765 [x(0), x(1), x(2)]
766 };
767 let (pt, tl) = (v3("point"), v3("tilt"));
768 let flat = t.get("flat") == Some(&Value::Bool(true));
769 let p = [
770 num("surf").unwrap_or(1.0),
771 f64::from(!flat),
772 pt[0],
773 pt[1],
774 pt[2],
775 tl[0],
776 tl[1],
777 tl[2],
778 ];
779 ("TSAG", p, bound(0.0))
780 }
781 "bfs" => {
782 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
783 let Some(d) = super::shape::BFSD.iter().position(|x| *x == q) else {
784 return Err(format!("bfs q {q}"));
785 };
786 let p = [
787 num("surf").unwrap_or(1.0),
788 d as f64,
789 num("rmin").unwrap_or(0.0),
790 num("rmax").unwrap_or(0.0),
791 0.0,
792 0.0,
793 0.0,
794 0.0,
795 ];
796 ("BFSD", p, bound(0.0))
797 }
798 "volume" => {
799 let s1 = num("surf").unwrap_or(1.0);
800 let s2 = num("to").unwrap_or(s1);
801 let clear = t.get("clear") == Some(&Value::Bool(true));
802 if t.get("cylinder") == Some(&Value::Bool(true)) {
803 let p = [s1, s2 + 1.0, 0.0, f64::from(clear), 0.0, 0.0, 0.0, 0.0];
805 let b = match bound(0.0) {
806 Bound::Target(x) => Bound::Target(x * 1e3),
807 Bound::Side(o, x) => Bound::Side(o, x * 1e3),
808 b => b,
809 };
810 return Ok(("CVOL", p, b));
811 }
812 let op = if t.get("mass") == Some(&Value::Bool(true)) {
813 "TMAS"
814 } else {
815 "VOLU"
816 };
817 let p = [s1, s2, 0.0, f64::from(clear), 0.0, 0.0, 0.0, 0.0];
818 (op, p, bound(0.0))
819 }
820 "cardinal" => {
821 let q = t.get("q").and_then(Value::as_str).unwrap_or("");
822 let q = lensbench_optim::CardQ::parse(q).map_err(|e| e.to_string())?;
823 let last = (1..s.image())
824 .rev()
825 .find(|&j| !s.surfaces[j].ignore)
826 .unwrap_or(1);
827 let from = num("from").unwrap_or(1.0);
828 let to = num("to").unwrap_or(last as f64);
829 let w = if wave() == 0.0 { primary } else { wave() };
830 match q.card_data() {
831 None if w == primary => {
833 ("EFLY", [from, to, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], bound(0.0))
834 }
835 None => {
836 return Err(
837 "efl at a wavelength other than the primary has no OpticStudio operand"
838 .into(),
839 )
840 }
841 Some(d) => (
842 "CARD",
843 [from, to, w, 0.0, d as f64, 0.0, 0.0, 0.0],
844 bound(0.0),
845 ),
846 }
847 }
848 "zplm" => match t.get("macro").and_then(Value::as_u64) {
849 Some(m) if m <= 99 && t.get("file").is_none() => {
850 let p = [
851 m as f64,
852 num("data").unwrap_or(0.0),
853 num("hx").unwrap_or(0.0),
854 num("hy").unwrap_or(0.0),
855 num("px").unwrap_or(0.0),
856 num("py").unwrap_or(0.0),
857 0.0,
858 0.0,
859 ];
860 ("ZPLM", p, bound(0.0))
861 }
862 _ => return Err("only a ZPL macro given by number can be written as ZPLM".into()),
863 },
864 t => return Err(format!("{t} terms have no OpticStudio operand")),
865 })
866}