Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

18. Least-Squares and QP Reference

The two solvers in this chapter take model data directly: a residual vector and Jacobian, or a quadratic objective with linear constraints. The theory is in chapters 7 and 10.

18.1 Residual model

Least squares solves

$$ \min_x f(x)=\tfrac12\lVert r(x)\rVert^2,\qquad r:\mathbb{R}^n\to\mathbb{R}^m, $$

with Jacobian \(J(x)=\partial r/\partial x\) of size \(m\times n\).

Interface:

pub trait LeastSquares {
    fn residuals(&self, x: &Vector) -> Vector;
    fn jacobian(&self, x: &Vector) -> Matrix;
    fn try_residuals(&self, x: &Vector) -> Result<Vector, EvaluationError> { ... }
    fn try_jacobian(&self, x: &Vector) -> Result<Matrix, EvaluationError> { ... }
}

API page (docs.rs): LeastSquares.

A (residuals, jacobian) closure tuple implements the trait automatically. The residual count \(m\) stays fixed and positive during a solve, and all outputs are finite.

18.2 The two LM entries

EntryStep computationDampingUse
levenberg_marquardtNormal equations \((J^\top J+\mu I)d=-J^\top r\), \(\mu=\max(\lVert r\rVert,10^{-12})\), Armijo backtrackingFixed ruleWell-conditioned problems with small residuals
levenberg_marquardt_with_optionsColumn-scaled augmented QR, adaptive \(\mu\)Nielsen updateIll-conditioned, rank-deficient and rectangular problems

Signatures:

pub fn levenberg_marquardt<P: LeastSquares + ?Sized>(
    problem: &P, x0: &Vector, options: &Options,
) -> Result<Solution, Error>

pub fn levenberg_marquardt_with_options<P: LeastSquares + ?Sized>(
    problem: &P, x0: &Vector, options: &LmOptions,
) -> Result<Solution, Error>

API pages (docs.rs): levenberg_marquardt, levenberg_marquardt_with_options, LmOptions.

LmOptions defaults:

FieldDefaultNotes
stoppingStopOptions::default()Gradient tolerance applies to the column-scaled stationarity quantity
initial_damping1e-3At or above the damping lower bound
minimum_damping1e-15Damping lower bound
acceptance_ratio1e-4Actual/predicted decrease ratio threshold, in \([0,1)\)
max_damping_trials40Damping trials per accepted iterate

Convergence quantity of the adaptive variant:

$$ \lVert D^{-1}J^\top r\rVert,\qquad D=\operatorname{diag}(\lVert J_{:,j}\rVert), $$

with a unit value for zero column norms. This quantity fills Solution::gradient_norm.

Example (linear residuals with exact solution \(x=1\)):

#![allow(unused)]
fn main() {
use nlopt4r::{Matrix, Vector, least_squares::{LmOptions, levenberg_marquardt_with_options}};

let problem = (
    |x: &Vector| Vector::from_vec(vec![x[0] - 1.0, 2.0 * x[0] - 2.0]),
    |_: &Vector| Matrix::from_column_slice(2, 1, &[1.0, 2.0]),
);
let result = levenberg_marquardt_with_options(
    &problem, &Vector::zeros(1), &LmOptions::default(),
)?;
assert!(result.converged());
assert!((result.x[0] - 1.0).abs() < 1e-6);
Ok::<(), nlopt4r::Error>(())
}

Counting convention: each residual call (rejected trials and failed callbacks included) counts in evaluations.objective and evaluations.residuals; Jacobian calls additionally count in evaluations.gradient and evaluations.jacobian.

18.3 Quadratic program model

pub struct QuadraticProgram {
    pub hessian: Matrix,          // H, symmetric positive semidefinite, n x n
    pub linear: Vector,           // c, length n
    pub equalities: Matrix,       // Ae, rows = equality_rhs.len()
    pub equality_rhs: Vector,     // be
    pub inequalities: Matrix,     // Ai, rows = inequality_rhs.len()
    pub inequality_rhs: Vector,   // bi
}

API page (docs.rs): QuadraticProgram.

Objective and constraints:

$$ \min_x \tfrac12 x^\top H x + c^\top x \quad\text{s.t.}\quad A_e x=b_e,\quad A_i x\ge b_i. $$
  • the inequality direction is \(A_i x\ge b_i\);
  • with zero constraint rows the matrices have shape \(0\times n\); QuadraticProgram::unconstrained builds empty constraints from linear.len();
  • convexity check threshold: \(\lambda_{\min}(H)\ge-10^{-10}(1+\lVert H\rVert)\).

Solve entries:

pub fn minimize(
    qp: &QuadraticProgram, x0: &Vector, options: &StopOptions,
) -> Result<QuadraticSolution, Error>

pub fn equality_constrained(
    hessian: &Matrix, linear: &Vector, a: &Matrix, b: &Vector,
) -> Result<QuadraticSolution, Error>

API pages (docs.rs): minimize, equality_constrained.

  • minimize: active-set iteration; a feasible initial point enters the main loop directly, and an infeasible one first runs phase I,
$$ \min t\quad\text{s.t.}\quad A_e x=b_e,\ A_i x+t\mathbf 1\ge b_i,\ t\ge0, $$
from \\(t=\text{violation}(x_0)+1\\); - each phase receives the `max_iterations` allowance and both share the strict `max_evaluations`; - `equality_constrained` solves the KKT system directly, including consistent rank-deficient cases; an LU failure switches to the SVD minimum-norm solution.

API page (docs.rs): QuadraticSolution.

QuadraticSolution fields:

FieldMeaning
solutionIteration/objective/stationarity report; check solution.converged() first
equality_multipliersEquality multipliers \(\mu\) satisfying \(Hx+c-A_e^\top\mu-A_i^\top\lambda=0\)
inequality_multipliersActive inequality multipliers, nonnegative; zero outside the active set
constraint_violationMaximum of equality residuals and the negative part of inequality residuals

Example:

#![allow(unused)]
fn main() {
use nlopt4r::{Matrix, StopOptions, Vector, quadratic::{QuadraticProgram, minimize}};

let mut qp = QuadraticProgram::unconstrained(
    Matrix::identity(2, 2),
    Vector::from_vec(vec![-2.0, -4.0]),
);
qp.equalities = Matrix::from_row_slice(1, 2, &[1.0, 1.0]);
qp.equality_rhs = Vector::from_vec(vec![3.0]);
let result = minimize(&qp, &Vector::zeros(2), &StopOptions::default())?;
assert!(result.solution.converged());
assert!((result.solution.x.sum() - 3.0).abs() < 1e-6);
Ok::<(), nlopt4r::Error>(())
}

18.4 QP stopping criteria

The gradient tolerance of StopOptions serves both the stationarity norm and the constraint violation:

  • an initial point already meeting \(\lVert\nabla f\rVert\le\tau\) and constraint_violation \(\le\tau\) converges with KktTolerance;
  • each main-loop step solves the active-set equality subproblem, checks multiplier signs and releases the constraint of the most negative multiplier;
  • budget exhaustion returns a non-converged checkpoint of the same dimension as the original problem;
  • an unsolvable phase I or KKT subproblem returns an explicit error (Infeasible, SingularSystem and related variants).

Counting convention: QP evaluations describe model states, with objective/gradient/constraints each counted once per step; external callbacks are absent.

18.5 Model suite and validation

The repository ships NIST nonlinear least-squares data for adaptive LM validation:

cargo test -p nlopt4r --test nist

The tests check certified parameters and residuals and cover ill-conditioned and rank-deficient models. QP tests cover phase I, redundant constraints, active-set transitions and KKT multiplier signs.

Theory background

  • Gauss–Newton and LM derivations, Nielsen damping: see chapter 7.
  • Active sets, phase I and KKT multipliers: see chapter 10.
  • Stopping criteria and counts: see chapter 12.