1use super::*;
3
4#[derive(Debug, Clone, Copy)]
8pub struct DlsOpts {
9 pub max_iter: usize,
11 pub ftol: f64,
13 pub xtol: f64,
15 pub damping: f64,
17 pub gtol: f64,
20 pub qr: bool,
24 pub active_set: bool,
27}
28
29impl Default for DlsOpts {
30 fn default() -> Self {
31 DlsOpts {
32 max_iter: 50,
33 ftol: 1e-10,
34 xtol: 1e-12,
35 damping: 1e-3,
36 gtol: 0.0,
37 qr: false,
38 active_set: false,
39 }
40 }
41}
42
43impl DlsOpts {
44 pub fn check(&self) -> Result<()> {
46 for (k, v) in [
47 ("ftol", self.ftol),
48 ("xtol", self.xtol),
49 ("gtol", self.gtol),
50 ] {
51 if !(v >= 0.0) {
52 lensbench_core::invalid!("{k} must be 0 or more ({v})");
53 }
54 }
55 if !(self.damping > 0.0 && self.damping.is_finite()) {
56 lensbench_core::invalid!("damping must be a positive number ({})", self.damping);
57 }
58 Ok(())
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum Stop {
65 Converged,
67 SmallStep,
69 SmallGradient,
71 NoProgress,
73 MaxIter,
75 Cancelled,
77 NoVars,
79 JacobianFailed,
82}
83
84impl Stop {
85 pub fn as_str(self) -> &'static str {
87 match self {
88 Stop::Converged => "converged",
89 Stop::SmallStep => "small_step",
90 Stop::SmallGradient => "small_gradient",
91 Stop::NoProgress => "no_progress",
92 Stop::MaxIter => "max_iter",
93 Stop::Cancelled => "cancelled",
94 Stop::NoVars => "no_vars",
95 Stop::JacobianFailed => "jacobian_failed",
96 }
97 }
98}
99
100pub use lensbench_core::par::Iter as Progress;
102
103#[derive(Debug, Clone)]
105pub struct DlsResult {
106 pub x0: Vec<f64>,
107 pub x: Vec<f64>,
108 pub merit0: f64,
109 pub merit: f64,
110 pub history: Vec<f64>,
112 pub iterations: usize,
113 pub evals: usize,
114 pub stop: Stop,
115 pub note: Option<String>,
117 pub inactive: Vec<usize>,
119 pub systems: Vec<System>,
121}
122
123const EFFECT_TOL: f64 = 1e-9;
126
127const SUSPECT_TOL: f64 = 1e-3;
132
133fn fd_noise(p: &Problem, x: &[f64], r: &[f64], j: &[f64], q: usize, scale: f64) -> bool {
137 let nv = x.len();
138 let h = 1e3 * p.fd_rel * scale;
139 let v = &p.vars[q];
140 let at = |d: f64| -> Option<Vec<f64>> {
141 let xv = x[q] + d;
142 if xv < v.lo || xv > v.hi {
143 return None;
144 }
145 let mut xs = x.to_vec();
146 xs[q] = xv;
147 p.residuals(&xs).ok().filter(|rr| rr.len() == r.len())
148 };
149 let big: Vec<f64> = match (at(h), at(-h)) {
150 (Some(rp), Some(rm)) => rp
151 .iter()
152 .zip(&rm)
153 .map(|(a, b)| (a - b) / (2.0 * h))
154 .collect(),
155 (Some(rp), None) => rp.iter().zip(r).map(|(a, b)| (a - b) / h).collect(),
156 (None, Some(rm)) => r.iter().zip(&rm).map(|(a, b)| (a - b) / h).collect(),
157 (None, None) => return false,
159 };
160 let n_small: f64 = (0..r.len())
161 .map(|i| j[i * nv + q].powi(2))
162 .sum::<f64>()
163 .sqrt();
164 let n_big: f64 = big.iter().map(|v| v * v).sum::<f64>().sqrt();
165 n_big < 0.1 * n_small
166}
167
168pub fn dls(p: &Problem, o: &DlsOpts) -> Result<DlsResult> {
172 dls_report(p, o)
173}
174
175pub fn dls_inner(p: &Problem, o: &DlsOpts) -> Result<DlsResult> {
178 par::with_progress(None, || dls_report(p, o))
179}
180
181fn dls_report(p: &Problem, o: &DlsOpts) -> Result<DlsResult> {
182 p.check()?;
183 o.check()?;
184 let nv = p.vars.len();
185 let x0 = p.x0()?;
186 let mut x: Vec<f64> = x0
187 .iter()
188 .zip(&p.vars)
189 .map(|(&v, var)| v.clamp(var.lo, var.hi))
190 .collect();
191 let mut evals = 0;
192 if nv == 0 {
193 let r = p.residuals(&x)?;
194 let m = p.merit_of(&r);
195 return Ok(DlsResult {
196 x0: x0.clone(),
197 x: x0,
198 merit0: m,
199 merit: m,
200 history: vec![m],
201 iterations: 0,
202 evals: 1,
203 stop: Stop::NoVars,
204 note: None,
205 inactive: Vec::new(),
206 systems: p.final_systems(&x)?,
207 });
208 }
209 let (mut r, mut j) = p.jacobian_checked(&x)?;
210 let mut f = dot_n(&r, &r);
211 let merit0 = p.merit_of(&r);
212 let mut history = vec![merit0];
213 let mut mu = o.damping;
214 let mut nu = 2.0;
215 let mut stop = Stop::MaxIter;
216 let mut note = None;
217 let mut inactive = Vec::new();
218 let mut iterations = 0;
219 let scale: Vec<f64> = p
220 .vars
221 .iter()
222 .zip(&x0)
223 .map(|(v, &xv)| xv.abs().max(typical(v.param.kind)))
224 .collect();
225 for it in 0..o.max_iter {
226 iterations = it + 1;
227 let m = r.len();
228 let mut a = vec![0.0; nv * nv];
230 let mut g = vec![0.0; nv];
231 for i in 0..m {
232 let row = &j[i * nv..(i + 1) * nv];
233 for q in 0..nv {
234 g[q] += row[q] * r[i];
235 for s in 0..=q {
236 a[q * nv + s] += row[q] * row[s];
237 }
238 }
239 }
240 for q in 0..nv {
241 for s in 0..q {
242 a[s * nv + q] = a[q * nv + s];
243 }
244 }
245 let rn2 = f.sqrt();
248 inactive = (0..nv)
249 .filter(|&q| {
250 let ratio = a[q * nv + q].sqrt() * scale[q] / rn2.max(f64::MIN_POSITIVE);
251 !(ratio > EFFECT_TOL)
252 || (ratio < SUSPECT_TOL && fd_noise(p, &x, &r, &j, q, scale[q]))
253 })
254 .collect();
255 evals += 2
256 * (0..nv)
257 .filter(|&q| {
258 let ratio = a[q * nv + q].sqrt() * scale[q] / rn2.max(f64::MIN_POSITIVE);
259 ratio > EFFECT_TOL && ratio < SUSPECT_TOL
260 })
261 .count();
262 let effective = |q: usize| !inactive.contains(&q);
263 let free: Vec<usize> = (0..nv)
264 .filter(|&q| {
265 let v = &p.vars[q];
266 !((x[q] <= v.lo && g[q] > 0.0) || (x[q] >= v.hi && g[q] < 0.0)) && effective(q)
267 })
268 .collect();
269 if free.is_empty() {
270 stop = Stop::NoProgress;
271 break;
272 }
273 if o.gtol > 0.0 {
274 let gmax = free
276 .iter()
277 .map(|&q| g[q].abs() / (a[q * nv + q].sqrt() * rn2).max(f64::MIN_POSITIVE))
278 .fold(0.0, f64::max);
279 if gmax < o.gtol {
280 stop = Stop::SmallGradient;
281 break;
282 }
283 }
284 let mut accepted = None;
285 let mut raised = false;
287 for _ in 0..30 {
288 let Some(xn) = lm_point(p, o, &x, &r, &j, &a, &g, &free, mu) else {
289 mu *= nu;
290 nu *= 2.0;
291 raised = true;
292 continue;
293 };
294 let step: Vec<f64> = (0..nv).map(|q| xn[q] - x[q]).collect();
295 if step.iter().zip(&scale).all(|(s, c)| s.abs() <= o.xtol * c) {
296 stop = if raised {
297 Stop::NoProgress
298 } else {
299 Stop::SmallStep
300 };
301 break;
302 }
303 evals += 1;
304 let rn = match p.residuals(&xn) {
305 Ok(rn) => rn,
306 Err(Error::Cancelled) => {
308 stop = Stop::Cancelled;
309 break;
310 }
311 Err(_) if par::cancelled() => {
312 stop = Stop::Cancelled;
313 break;
314 }
315 Err(_) => {
316 mu *= nu;
317 nu *= 2.0;
318 raised = true;
319 continue;
320 }
321 };
322 let fn_ = dot_n(&rn, &rn);
323 let mut pred = 0.0;
325 for q in 0..nv {
326 let mut ad = 0.0;
327 for s in 0..nv {
328 ad += a[q * nv + s] * step[s];
329 }
330 pred -= 2.0 * g[q] * step[q] + step[q] * ad;
331 }
332 if fn_.is_finite() && fn_ < f {
333 let rho = if pred > 0.0 { (f - fn_) / pred } else { 1.0 };
334 mu *= (1.0 - (2.0 * rho - 1.0).powi(3)).max(1.0 / 3.0);
335 nu = 2.0;
336 accepted = Some((xn, rn, fn_));
337 break;
338 }
339 mu *= nu;
340 nu *= 2.0;
341 raised = true;
342 }
343 let Some((xn, rn, fn_)) = accepted else {
344 if !matches!(stop, Stop::SmallStep | Stop::Cancelled) {
345 stop = Stop::NoProgress;
346 }
347 break;
348 };
349 let rel = (f - fn_) / f.max(f64::MIN_POSITIVE);
350 x = xn;
351 f = fn_;
352 r = rn;
353 history.push(p.merit_of(&r));
354 if par::reporting() {
355 par::report(&par::Event::Iter(Progress {
356 iter: iterations,
357 merit: history.last().copied().unwrap_or(f64::NAN),
358 x: x.clone(),
359 damping: mu,
360 evals,
361 }));
362 }
363 if par::cancelled() {
364 stop = Stop::Cancelled;
365 break;
366 }
367 if rel < o.ftol {
368 stop = Stop::Converged;
369 break;
370 }
371 if it + 1 < o.max_iter {
372 match p.jacobian_checked(&x) {
374 Ok(v) => (r, j) = v,
375 Err(Error::Cancelled) => {
376 stop = Stop::Cancelled;
377 break;
378 }
379 Err(e) => {
380 stop = Stop::JacobianFailed;
381 note = Some(e.to_string());
382 break;
383 }
384 }
385 }
386 }
387 Ok(DlsResult {
388 x0,
389 merit0,
390 merit: p.merit_of(&r),
391 history,
392 iterations,
393 evals,
394 stop,
395 note,
396 inactive,
397 systems: p.final_systems(&x)?,
398 x,
399 })
400}
401
402fn dot_n(a: &[f64], b: &[f64]) -> f64 {
403 a.iter().zip(b).map(|(x, y)| x * y).sum()
404}
405
406#[allow(clippy::too_many_arguments)]
411fn lm_point(
412 p: &Problem,
413 o: &DlsOpts,
414 x: &[f64],
415 r: &[f64],
416 j: &[f64],
417 a: &[f64],
418 g: &[f64],
419 free: &[usize],
420 mu: f64,
421) -> Option<Vec<f64>> {
422 let nv = x.len();
423 let m = r.len();
424 let mut xn = x.to_vec();
425 let mut cols: Vec<usize> = free.to_vec();
426 let mut rr = r.to_vec();
428 loop {
429 let nc = cols.len();
430 if nc == 0 {
431 return Some(xn);
432 }
433 let d = if o.qr {
434 qr_step(j, &rr, nv, a, &cols, mu)?
435 } else {
436 let gg: Vec<f64> = if cols.len() == free.len() {
438 g.to_vec()
439 } else {
440 (0..nv)
441 .map(|q| (0..m).map(|i| j[i * nv + q] * rr[i]).sum())
442 .collect()
443 };
444 normal_step(a, &gg, nv, &cols, mu)?
445 };
446 let mut out = Vec::new();
447 for (k, &q) in cols.iter().enumerate() {
448 let v = x[q] + d[k];
449 let (lo, hi) = (p.vars[q].lo, p.vars[q].hi);
450 if o.active_set && (v < lo || v > hi) {
451 out.push((q, v.clamp(lo, hi)));
452 }
453 xn[q] = v.clamp(lo, hi);
454 }
455 if out.is_empty() {
456 return Some(xn);
457 }
458 for &(q, bnd) in &out {
460 xn[q] = bnd;
461 let d = bnd - x[q];
462 for i in 0..m {
463 rr[i] += j[i * nv + q] * d;
464 }
465 }
466 cols.retain(|q| !out.iter().any(|e| e.0 == *q));
467 for &q in &cols {
468 xn[q] = x[q];
469 }
470 }
471}
472
473fn normal_step(a: &[f64], g: &[f64], nv: usize, cols: &[usize], mu: f64) -> Option<Vec<f64>> {
475 let nf = cols.len();
476 let mut af = vec![0.0; nf * nf];
477 let mut bf = vec![0.0; nf];
478 for (u, &q) in cols.iter().enumerate() {
479 bf[u] = -g[q];
480 for (w, &s) in cols.iter().enumerate() {
481 af[u * nf + w] = a[q * nv + s];
482 }
483 af[u * nf + u] += mu * a[q * nv + q];
484 }
485 lensbench_core::linalg::Cholesky::new(&af, nf).map(|c| c.solve(&bf))
486}
487
488fn qr_step(
490 j: &[f64],
491 r: &[f64],
492 nv: usize,
493 a: &[f64],
494 cols: &[usize],
495 mu: f64,
496) -> Option<Vec<f64>> {
497 let (m, nc) = (r.len(), cols.len());
498 let dn: Vec<f64> = cols.iter().map(|&q| a[q * nv + q].sqrt()).collect();
499 let rows = m + nc;
500 let mut mat = vec![0.0; rows * nc];
501 let mut b = vec![0.0; rows];
502 for i in 0..m {
503 for (k, &q) in cols.iter().enumerate() {
504 mat[i * nc + k] = j[i * nv + q] / dn[k];
505 }
506 b[i] = -r[i];
507 }
508 let sm = mu.sqrt();
509 for k in 0..nc {
510 mat[(m + k) * nc + k] = sm;
511 }
512 let y = qr_lstsq(mat, rows, nc, b)?;
513 Some(y.iter().zip(&dn).map(|(y, d)| y / d).collect())
514}
515
516fn qr_lstsq(m: Vec<f64>, rows: usize, n: usize, b: Vec<f64>) -> Option<Vec<f64>> {
518 let qr = lensbench_core::linalg::Qr::from_rows(&m, rows, n);
519 if !qr.rdiag().iter().all(|d| d.abs() > 0.0) {
520 return None;
521 }
522 let y = qr.solve(&b);
523 y.iter().all(|v| v.is_finite()).then_some(y)
524}