1use crate::{DefaultMerit, DlsOpts, ParaxQ, Problem, Stop, Term, TermKind, Var};
26use lensbench_analysis::sweep::RmsRef;
27use lensbench_core::error::{Error, Result};
28use lensbench_core::invalid;
29use lensbench_core::param::Param;
30use lensbench_core::system::System;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34pub enum TargetMethod {
35 Penalty,
37 #[default]
39 Lagrange,
40}
41
42impl TargetMethod {
43 pub fn parse(s: &str) -> Option<TargetMethod> {
45 match s {
46 "penalty" => Some(TargetMethod::Penalty),
47 "lagrange" => Some(TargetMethod::Lagrange),
48 _ => None,
49 }
50 }
51
52 pub fn name(self) -> &'static str {
54 match self {
55 TargetMethod::Penalty => "penalty",
56 TargetMethod::Lagrange => "lagrange",
57 }
58 }
59}
60
61#[derive(Debug, Clone)]
63pub struct ZoomSpec {
64 pub moving: Vec<Param>,
66 pub bounds: Vec<(f64, f64)>,
68 pub q: ParaxQ,
70 pub targets: Vec<Option<f64>>,
72 pub target_weight: f64,
75 pub target_tol: f64,
77 pub method: TargetMethod,
79 pub merit: DefaultMerit,
81 pub rings: usize,
82 pub reference: RmsRef,
83 pub steps: usize,
85 pub opts: DlsOpts,
86 pub stopped_as_vignetted: bool,
88}
89
90impl ZoomSpec {
91 pub fn new(moving: Vec<Param>, targets: Vec<Option<f64>>) -> ZoomSpec {
92 ZoomSpec {
93 moving,
94 bounds: Vec::new(),
95 q: ParaxQ::Efl,
96 targets,
97 target_weight: 10.0,
98 target_tol: 1e-8,
99 method: TargetMethod::Lagrange,
100 merit: DefaultMerit::Spot,
101 rings: 3,
102 reference: RmsRef::Centroid,
103 steps: 0,
104 opts: DlsOpts::default(),
105 stopped_as_vignetted: false,
106 }
107 }
108}
109
110#[derive(Debug, Clone, PartialEq)]
112pub enum PointStop {
113 Solved(Stop),
115 Failed(String),
117}
118
119impl PointStop {
120 pub fn as_str(&self) -> &'static str {
122 match self {
123 PointStop::Solved(s) => s.as_str(),
124 PointStop::Failed(_) => "failed",
125 }
126 }
127 pub fn error(&self) -> Option<&str> {
129 match self {
130 PointStop::Solved(_) => None,
131 PointStop::Failed(e) => Some(e),
132 }
133 }
134}
135
136#[derive(Debug, Clone)]
138pub struct ZoomPoint {
139 pub state: Option<usize>,
141 pub pos: f64,
143 pub target: Option<f64>,
145 pub value: f64,
147 pub x: Vec<f64>,
149 pub merit: f64,
151 pub stop: PointStop,
152 pub iterations: usize,
153}
154
155#[derive(Debug, Clone)]
157pub struct ZoomResult {
158 pub states: Vec<ZoomPoint>,
160 pub path: Vec<ZoomPoint>,
162 pub systems: Vec<System>,
164 pub warnings: Vec<String>,
165}
166
167fn problem(
168 s: &System,
169 spec: &ZoomSpec,
170 target: Option<f64>,
171 weight: f64,
172) -> Result<(Problem, Problem)> {
173 let mut img = Problem::single(s.clone());
174 img.stopped_as_vignetted = spec.stopped_as_vignetted;
175 for (i, &p) in spec.moving.iter().enumerate() {
176 let mut v = Var::new(p);
177 if let Some(&(lo, hi)) = spec.bounds.get(i) {
178 v = v.bounds(lo, hi);
179 }
180 img.vars.push(v);
181 }
182 img.add_default(spec.merit, spec.rings, spec.reference);
183 let mut full = img.clone();
184 if let Some(t) = target {
185 let w: f64 = img.terms.iter().map(|t| t.weight).sum();
186 full.terms.push(Term {
187 side: Default::default(),
188 config: 0,
189 weight: weight * w,
190 kind: TermKind::Paraxial {
191 q: spec.q,
192 wave: None,
193 target: t,
194 },
195 });
196 }
197 Ok((full, img))
198}
199
200fn solve_point(
204 s: &System,
205 spec: &ZoomSpec,
206 target: Option<f64>,
207 state: Option<usize>,
208 pos: f64,
209) -> Result<(ZoomPoint, System)> {
210 match try_point(s, spec, target, state, pos)? {
211 Ok(v) => Ok(v),
212 Err(e) => {
213 let x = spec
214 .moving
215 .iter()
216 .map(|&p| s.get_param(p))
217 .collect::<Result<Vec<f64>>>()?;
218 Ok((
219 ZoomPoint {
220 state,
221 pos,
222 target,
223 value: f64::NAN,
224 x,
225 merit: f64::NAN,
226 stop: PointStop::Failed(e.to_string()),
227 iterations: 0,
228 },
229 s.clone(),
230 ))
231 }
232 }
233}
234
235fn unsolved<T>(r: Result<T>) -> Result<std::result::Result<T, Error>> {
237 match r {
238 Ok(v) => Ok(Ok(v)),
239 Err(Error::Cancelled) => Err(Error::Cancelled),
240 Err(_) if lensbench_core::par::cancelled() => Err(Error::Cancelled),
241 Err(e) => Ok(Err(e)),
242 }
243}
244
245type PointResult = std::result::Result<(ZoomPoint, System), Error>;
246
247fn try_point(
248 s: &System,
249 spec: &ZoomSpec,
250 target: Option<f64>,
251 state: Option<usize>,
252 pos: f64,
253) -> Result<PointResult> {
254 let lagrange = spec.method == TargetMethod::Lagrange;
255 let mut w = spec.target_weight;
258 let mut shifted = target;
259 let mut cur = s.clone();
260 let mut iterations = 0;
261 let mut tries = 0;
262 let max_tries = if lagrange { 9 } else { 4 };
263 let (r, img) = loop {
264 let (full, img) = problem(&cur, spec, shifted, w)?;
265 full.check()?;
266 let r = match unsolved(crate::dls_inner(&full, &spec.opts))? {
267 Ok(r) => r,
268 Err(e) => return Ok(Err(e)),
269 };
270 iterations += r.iterations;
271 tries += 1;
272 let sys = &r.systems[0];
273 let miss = target.map(|t| spec.q.value(sys) - t);
274 let ok = target.is_none_or(|t| {
275 miss.expect("miss is set whenever there is a target").abs()
276 <= spec.target_tol * t.abs().max(f64::MIN_POSITIVE)
277 });
278 if ok || tries >= max_tries {
279 break (r, img);
280 }
281 cur = sys.clone();
282 if lagrange {
283 shifted = shifted.zip(miss).map(|(a, m)| a - m);
284 } else {
285 w *= 100.0;
286 }
287 };
288 let sys = r
289 .systems
290 .into_iter()
291 .next()
292 .expect("the optimizer returns one system per configuration");
293 let merit = match unsolved(img.merit(&r.x))? {
294 Ok(m) => m,
295 Err(e) => return Ok(Err(e)),
296 };
297 Ok(Ok((
298 ZoomPoint {
299 state,
300 pos,
301 target,
302 value: spec.q.value(&sys),
303 x: r.x,
304 merit,
305 stop: PointStop::Solved(r.stop),
306 iterations,
307 },
308 sys,
309 )))
310}
311
312fn interp(a: f64, b: f64, f: f64) -> f64 {
314 if a * b > 0.0 {
315 a * (b / a).powf(f)
316 } else {
317 a + (b - a) * f
318 }
319}
320
321pub fn solve(configs: &[System], spec: &ZoomSpec) -> Result<ZoomResult> {
323 let n = configs.len();
324 if n == 0 {
325 invalid!("no states");
326 }
327 if spec.moving.is_empty() {
328 invalid!("no parameters to move");
329 }
330 if spec.targets.len() != n {
331 invalid!("{} targets for {n} states", spec.targets.len());
332 }
333 if !spec.bounds.is_empty() && spec.bounds.len() != spec.moving.len() {
334 invalid!(
335 "{} ranges for {} parameters",
336 spec.bounds.len(),
337 spec.moving.len()
338 );
339 }
340 if !(spec.target_weight > 0.0) {
341 invalid!("weight of the paraxial term {}", spec.target_weight);
342 }
343 spec.opts.check()?;
344 let mut states = Vec::with_capacity(n);
345 let mut systems = Vec::with_capacity(n);
346 let total = n + n.saturating_sub(1) * spec.steps;
348 let t0 = web_time::Instant::now();
349 let mut done = 0;
350 let mut tick = || {
351 done += 1;
352 if lensbench_core::par::reporting() {
353 let el = t0.elapsed().as_secs_f64();
354 lensbench_core::par::report(&lensbench_core::par::Event::Count(
355 lensbench_core::par::Count {
356 stage: "",
357 done,
358 total,
359 ran: done,
360 elapsed: el,
361 eta: Some(el / done as f64 * total.saturating_sub(done) as f64),
362 },
363 ));
364 }
365 };
366 for (k, s) in configs.iter().enumerate() {
367 lensbench_core::par::check_cancel()?;
368 let (p, sys) = solve_point(s, spec, spec.targets[k], Some(k), k as f64)?;
369 tick();
370 states.push(p);
371 systems.push(sys);
372 }
373 let mut warnings = Vec::new();
374 for p in &states {
375 let k = p
376 .state
377 .expect("every configuration has a state after the solve");
378 if let Some(e) = p.stop.error() {
379 warnings.push(format!("state {}: not solved ({e})", k + 1));
380 continue;
381 }
382 if let Some(t) = p.target {
383 let rel = (p.value - t).abs() / t.abs().max(1e-300);
384 if rel > spec.target_tol {
385 warnings.push(format!(
386 "state {}: {} does not reach the target ({} / target {t})",
387 k + 1,
388 spec.q.name(),
389 p.value
390 ));
391 }
392 }
393 }
394 let mut path = Vec::new();
395 for k in 0..n {
396 path.push(states[k].clone());
397 if k + 1 == n || spec.steps == 0 {
398 continue;
399 }
400 let ch: Vec<(Param, f64)> = spec
402 .moving
403 .iter()
404 .copied()
405 .zip(states[k + 1].x.iter().copied())
406 .collect();
407 let probe = systems[k].with_params(&ch)?;
408 let (va, vb) = (spec.q.value(&probe), states[k + 1].value);
409 let solved = states[k].stop.error().is_none() && states[k + 1].stop.error().is_none();
410 if solved && (va - vb).abs() > 1e-9 * vb.abs().max(1.0) {
411 warnings.push(format!(
412 "states {} and {} differ in more than the moved parameters (points between them were found with the system of state {})",
413 k + 1,
414 k + 2,
415 k + 1
416 ));
417 }
418 let (ta, tb) = (
419 states[k].target.unwrap_or(states[k].value),
420 states[k + 1].target.unwrap_or(states[k + 1].value),
421 );
422 if !(ta.is_finite() && tb.is_finite()) {
423 for _ in 0..spec.steps {
425 tick();
426 }
427 warnings.push(format!(
428 "points between states {} and {} were skipped (a state without a target was not solved)",
429 k + 1,
430 k + 2
431 ));
432 continue;
433 }
434 let nx = spec.moving.len();
435 let dx: Vec<f64> = (0..nx)
436 .map(|q| (states[k + 1].x[q] - states[k].x[q]) / (spec.steps + 1) as f64)
437 .collect();
438 let mut x = states[k].x.clone();
439 for j in 1..=spec.steps {
440 let f = j as f64 / (spec.steps + 1) as f64;
441 let start: Vec<(Param, f64)> = (0..nx)
442 .map(|q| {
443 let mut v = x[q] + dx[q];
444 if let Some(&(lo, hi)) = spec.bounds.get(q) {
445 v = v.clamp(lo, hi);
446 }
447 (spec.moving[q], v)
448 })
449 .collect();
450 lensbench_core::par::check_cancel()?;
451 let s0 = systems[k].with_params(&start)?;
452 let pos = k as f64 + f;
453 let (p, _) = solve_point(&s0, spec, Some(interp(ta, tb, f)), None, pos)?;
454 tick();
455 if let Some(e) = p.stop.error() {
456 warnings.push(format!(
457 "between states {} and {} at {f:.3}: not solved ({e})",
458 k + 1,
459 k + 2
460 ));
461 }
462 x = p.x.clone();
463 path.push(p);
464 }
465 }
466 Ok(ZoomResult {
467 states,
468 path,
469 systems,
470 warnings,
471 })
472}