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

Bound-constrained optimisation

ProblemMinimise or a sum of squares subject to simple bounds ; solve linear least squares with bounds or non-negativity
Devised byCharles Lawson and Richard Hanson (1974), non-negative least squares; Philip Stark and Robert Parker (1995), BVLS; Thomas Coleman and Yuying Li (1996), affine scaling for bounds; Mary Ann Branch, Coleman and Li (1999), trust-region reflective; Richard Byrd, Peihuang Lu, Jorge Nocedal and Ciyou Zhu (1995), L-BFGS-B
Accuracyleast_squares_bounded, lsq_linear and nnls agree with SciPy to ; L-BFGS-B reaches SciPy’s solutions to within its convergence tolerance
CostL-BFGS-B: per iteration with correction pairs. Trust-region reflective: one SVD of an matrix per iteration. BVLS and NNLS: one least-squares solve per change of the active set
Read firstNewton and quasi-Newton methods, Nonlinear least squares, Constrained optimisation
APIminimize_lbfgsb, least_squares_bounded, Loss, lsq_linear, nnls

Overview

Bounds are the most common constraints: rates and concentrations are positive, probabilities lie in , and a physical parameter has a known range. General constrained methods such as SQP can handle them, but bounds are simple enough for methods built around them. Such methods can project onto the feasible box, identify which variables sit on a bound, and use the remaining freedom as in an unconstrained method. This entry covers four, following scipy.optimize:

  • L-BFGS-B for smooth minimisation with gradients: the limited-memory BFGS model, restricted to the box.
  • Trust-region reflective (least_squares) for nonlinear least squares with bounds, and with robust losses that limit the influence of outliers.
  • BVLS (lsq_linear) for linear least squares with bounds.
  • NNLS for the most common special case, .

Where it is used

Physical parameters usually have limits, and the optimiser should respect them.

  • Parameter estimation. Fitting a model whose parameters must be positive, such as rate constants, masses, resistances and concentrations.
  • Engineering design. Dimensions and settings limited by manufacturing or by physics.
  • Robust fitting. Loss functions that limit the influence of outliers in calibration and tracking.
  • Machine learning. L-BFGS-B trains many models with bounds on their parameters.

History

Charles Lawson and Richard Hanson’s book Solving Least Squares Problems (1974) gave the active-set NNLS algorithm still used by SciPy and MATLAB. Philip Stark and Robert Parker (1995) generalised it to two-sided bounds as BVLS. Richard Byrd, Peihuang Lu, Jorge Nocedal and Ciyou Zhu (1995) combined the gradient projection method with limited-memory BFGS to give L-BFGS-B, whose Fortran code (version 3.0 of 2011 by José Luis Morales and Nocedal) underlies SciPy’s default bounded minimiser. Thomas Coleman and Yuying Li (1996) showed how to rescale a Newton step so that it slows down near the bound it approaches. With Mary Ann Branch (1999) they built the trust-region reflective method, whose least-squares form, by Nikolay Mayorov (2015), became SciPy’s least_squares.

The idea

Optimality with bounds

At a minimiser on the box, each component of the gradient must be zero if the variable is free, non-negative if it sits on its lower bound, and non-positive if on its upper bound: the function can only decrease by leaving the box. These are the KKT conditions for bounds. A convenient single measure is the projected gradient , where clips each component to its bounds. It vanishes exactly at a KKT point, and L-BFGS-B stops when its largest component is below gtol.

L-BFGS-B

Each iteration of L-BFGS-B works with the quadratic model , where is the compact form of the limited-memory BFGS matrix built from the last steps and gradient changes. It takes three stages:

  1. Generalised Cauchy point. Follow the projected steepest-descent path , a piecewise-linear path that bends at each breakpoint where a variable reaches its bound. On each piece the model is a one-dimensional quadratic, so the first local minimiser along the path is found by visiting the breakpoints in order. Thanks to the compact form, each costs only to update. The variables at a bound there form the active set of this iteration.
  2. Subspace minimisation. Minimise the model over the free variables, keeping the active ones fixed, using the Sherman-Morrison-Woodbury formula for the reduced matrix. Then truncate the step where it would leave the box.
  3. Line search along the resulting direction, satisfying the Wolfe conditions, with the step capped so that the iterate stays feasible.

The active set can change by many variables in one iteration, which is what makes gradient projection efficient compared with active-set methods that change one constraint at a time.

Trust-region reflective least squares

For a sum of squares , the Gauss-Newton model is minimised within a trust region. Coleman and Li’s idea is to scale the variables by the distance to the bound that the gradient points at:

In the scaled variables the trust region is an ellipsoid that flattens against an approaching bound, so steps slow down instead of crossing it. A diagonal term (where is the entrywise product, and is the derivative of with respect to , equal to , or in the three cases above) keeps the model consistent with the scaling. The scaled problem is solved exactly through an SVD of the augmented Jacobian, by Moré’s Levenberg-Marquardt iteration. If the step still leaves the box, three candidates are compared by their model value: the step truncated at the bound, its reflection off the bound (which keeps moving in the free directions), and a scaled gradient step. The method converges when the scaled gradient is small. That measure is zero at a KKT point, because each active variable has .

Robust loss functions

Least squares gives a residual of size an influence proportional to , so one wild point can dominate a fit. A robust loss replaces by , where the scale (f_scale) marks the size of a typical good residual. Small residuals then count as in least squares, and large ones much less. With soft-, , large residuals count linearly. With the Cauchy loss, , they count only logarithmically. Following Triggs and colleagues, the residuals and Jacobian are rescaled by and , so the same trust-region machinery applies unchanged.

Figure 5.7. Robust fits.

The three outliers pull the least-squares curve up at small and bias the offset . The robust fits ignore them and recover the true parameters , to within the noise.

Linear least squares with bounds

When the residual is linear, , the problem is convex and its solution is determined by which variables sit on which bound. Lawson and Hanson’s NNLS and Stark and Parker’s BVLS search for that set:

  1. Start with all variables on a bound (NNLS), or from the unconstrained solution clipped to the box (BVLS).
  2. Free the variable whose gradient most strongly wants to move it into the box.
  3. Solve the unconstrained least-squares problem on the free variables. If some free variable would leave the box, move only part of the way, stopping where the first one reaches its bound, fix it there, and solve again.
  4. Repeat until the KKT conditions hold.

Each stage strictly decreases the residual, so the set never repeats and the method ends after finitely many solves.

Algorithm

minimize_lbfgsb: from projected onto the box, repeat until the projected gradient is below gtol or the relative decrease is below ftol: generalised Cauchy point, subspace minimisation, line search with the step capped at the box, update the correction pairs if .

least_squares_bounded (one iteration):

  1. Compute the Coleman-Li scaling and its derivative, and stop if gtol.
  2. Form the scaled augmented matrix and its SVD.
  3. Solve the trust-region subproblem, select among the truncated, reflected and gradient steps, and evaluate the residuals at the new point (kept strictly inside the box).
  4. Accept if the cost decreased, update the trust radius from the ratio of actual to predicted reduction, and test ftol and xtol.

Implementation

/// The generalised Cauchy point: the first local minimiser of the quadratic model along the
/// projected steepest-descent path `P(x − t g)`, found by visiting the breakpoints where variables
/// reach their bounds in order (Byrd, Lu, Nocedal and Zhu, algorithm CP). Returns the point and
/// `c = Wᵀ(x_cp − x)`.
fn cauchy_point(x: &[f64], g: &[f64], lb: &[f64], ub: &[f64], b: &Compact) -> (Vec<f64>, Vec<f64>) {
    let n = x.len();
    let two_k = b.two_k();
    let mut t = vec![f64::INFINITY; n];
    let mut d = vec![0.0; n];
    for i in 0..n {
        if g[i] < 0.0 {
            t[i] = (x[i] - ub[i]) / g[i];
        } else if g[i] > 0.0 {
            t[i] = (x[i] - lb[i]) / g[i];
        }
        if t[i] > 0.0 {
            d[i] = -g[i];
        }
    }
    let mut order: Vec<usize> = (0..n).filter(|&i| t[i] > 0.0 && t[i].is_finite()).collect();
    order.sort_by(|&a, &c| t[a].total_cmp(&t[c]));
    let mut xcp = x.to_vec();
    for i in 0..n {
        if t[i] == 0.0 {
            xcp[i] = x[i];
        }
    }
    // p = Wᵀ d, c = 0.
    let mut p: Vec<f64> = (0..two_k).map(|j| (0..n).map(|i| b.w[i][j] * d[i]).sum()).collect();
    let mut c = vec![0.0; two_k];
    let mut fp = -dot(&d, &d);
    let mut fpp = -b.theta * fp - dot(&p, &b.m_times(&p));
    let mut dt_min = if fpp > 0.0 { -fp / fpp } else { f64::INFINITY };
    let mut t_old = 0.0;
    for &bi in &order {
        let dt = t[bi] - t_old;
        if dt_min < dt {
            break;
        }
        // Variable bi reaches its bound.
        xcp[bi] = if d[bi] > 0.0 { ub[bi] } else { lb[bi] };
        let zb = xcp[bi] - x[bi];
        for j in 0..two_k {
            c[j] += dt * p[j];
        }
        let gb = g[bi];
        let wb = &b.w[bi];
        let mc = b.m_times(&c);
        let mp = b.m_times(&p);
        let mw = b.m_times(wb);
        fp += dt * fpp + gb * gb + b.theta * gb * zb - gb * dot(wb, &mc);
        fpp += -b.theta * gb * gb - 2.0 * gb * dot(wb, &mp) - gb * gb * dot(wb, &mw);
        for j in 0..two_k {
            p[j] += gb * wb[j];
        }
        d[bi] = 0.0;
        dt_min = if fpp > 0.0 { -fp / fpp } else { f64::INFINITY };
        t_old = t[bi];
    }
    let dt_min = if dt_min.is_finite() { dt_min.max(0.0) } else { 0.0 };
    let t_final = t_old + dt_min;
    for i in 0..n {
        if d[i] != 0.0 {
            xcp[i] = (x[i] + t_final * d[i]).clamp(lb[i], ub[i]);
        }
    }
    for j in 0..two_k {
        c[j] += dt_min * p[j];
    }
    (xcp, c)
}
/// Non-negative least squares `min ‖A x − b‖` with `x ≥ 0` (SciPy's `nnls`), by Lawson and Hanson's
/// active-set method: repeatedly free the variable whose gradient most wants to grow, solve the
/// unconstrained problem on the free set, and step back to the boundary when a free variable
/// would turn negative.
pub fn nnls(a: &Array2<f64>, b: &[f64]) -> Result<LinearLsqResult, ErrorsJSL> {
    let (m, n) = a.dim();
    if b.len() != m {
        return Err(ErrorsJSL::IncompatibleArraySizes((b.len(), m)));
    }
    let b = Array1::from(b.to_vec());
    let mut x = Array1::<f64>::zeros(n);
    let mut passive = vec![false; n];
    let tol = 10.0 * f64::EPSILON * a.iter().fold(0.0f64, |s, v| s.max(v.abs())) * m.max(n) as f64;
    let mut iterations = 0;
    loop {
        let w = a.t().dot(&(&b - &a.dot(&x)));
        let candidate = (0..n).filter(|&j| !passive[j]).max_by(|&i, &j| w[i].total_cmp(&w[j]));
        let Some(jmax) = candidate else { break };
        if w[jmax] <= tol || iterations >= 3 * n {
            break;
        }
        passive[jmax] = true;
        loop {
            iterations += 1;
            let p: Vec<usize> = (0..n).filter(|&j| passive[j]).collect();
            let sp = lstsq(&columns(a, &p), &b)?;
            if sp.iter().all(|&v| v > 0.0) {
                x.fill(0.0);
                for (k, &j) in p.iter().enumerate() {
                    x[j] = sp[k];
                }
                break;
            }
            // Step from x towards s until the first passive variable reaches zero.
            let mut alpha = f64::INFINITY;
            for (k, &j) in p.iter().enumerate() {
                if sp[k] <= 0.0 {
                    alpha = alpha.min(x[j] / (x[j] - sp[k]));
                }
            }
            for (k, &j) in p.iter().enumerate() {
                x[j] += alpha * (sp[k] - x[j]);
            }
            for &j in &p {
                if x[j] <= tol {
                    x[j] = 0.0;
                    passive[j] = false;
                }
            }
            if iterations > 30 * n.max(1) {
                break;
            }
        }
    }
    let r = &a.dot(&x) - &b;
    let rn = r.dot(&r).sqrt();
    let active = (0..n).map(|j| if x[j] == 0.0 { -1 } else { 0 }).collect();
    Ok(LinearLsqResult { x: x.to_vec(), cost: 0.5 * rn * rn, residual_norm: rn, active, iterations })
}
  • least_squares_bounded is a port of SciPy’s trf with tr_solver='exact' and x_scale=1, so with the same Jacobian it takes the same steps. Its Loss covers SciPy’s five built-in losses.
  • minimize_lbfgsb follows the paper rather than the Fortran code. It uses its own Wolfe line search and does not include the Morales-Nocedal refinement of the subspace step, so its iterates differ from SciPy’s.
  • lsq_linear is BVLS, SciPy’s method='bvls'. nnls is Lawson and Hanson’s algorithm.

In practice

All four are compared with SciPy 1.17.1 (references from book/generator/data/make_bounded_refs.py):

Table 5.6. Bound-constrained solvers against SciPy.

problem (SciPy reference)largest difference in xdifference in the objectiveiterations (library / SciPy)evaluations (library / SciPy)
minimize_lbfgsb: Rosenbrock, n = 10, three upper bounds active3e-73e-1132 / 2756 / 31
minimize_lbfgsb: convex quadratic, n = 30, −0.5 ≤ xᵢ ≤ 0.51e-72e-1525 / 2326 / 24
least_squares_bounded: exponential with outliers, linear loss4e-16010 / 10
least_squares_bounded: exponential with outliers, soft_l1 loss04e-1610 / 10
least_squares_bounded: exponential with outliers, huber loss1e-15010 / 10
least_squares_bounded: exponential with outliers, cauchy loss1e-156e-1712 / 12
least_squares_bounded: exponential with outliers, arctan loss1e-15014 / 14
least_squares_bounded: the same, decay rate ≤ 0.4 (active)009 / 9
lsq_linear (BVLS): 40 × 12, −0.15 ≤ xᵢ ≤ 0.154e-169e-16
nnls: 40 × 123e-160

The least-squares solvers agree with SciPy to rounding, with the same evaluation counts. L-BFGS-B reaches the same minimisers to within its stopping tolerance. On Rosenbrock it needs more function evaluations than the Fortran code, whose Moré-Thuente line search usually accepts the first trial step.

Strengths

  • Bounds are handled exactly: every iterate is feasible, and the functions are never evaluated outside the box.
  • L-BFGS-B scales to many variables, with memory and work per iteration.
  • Robust losses make least-squares fits resistant to outliers with one extra parameter, f_scale.
  • NNLS and BVLS terminate with the exact solution after finitely many least-squares solves.

Weaknesses

  • Only bounds: general linear or nonlinear constraints need SQP or the augmented Lagrangian method.
  • The trust-region reflective solver uses a dense SVD per iteration, so it is suited to tens or hundreds of parameters, not thousands.
  • The library’s L-BFGS-B is less economical in function evaluations than the reference Fortran implementation.

Exercises

  1. Show that satisfies the KKT conditions for bounds exactly when .
  2. Minimise on by hand along the projected gradient path from , and find the generalised Cauchy point.
  3. Show that the Coleman-Li scaled gradient vanishes at a KKT point even though does not.
  4. For one residual , compare the influence for the linear, soft- and Cauchy losses as .
  5. Solve with by NNLS by hand.
Hints and answers
  1. Component by component: if is interior, leaves unchanged only when . If , clipping back to needs , and symmetrically at .
  2. at ; the path meets the bound at , and the quadratic is still decreasing there, so the Cauchy point is .
  3. Where is on the bound the gradient points at, ; where it is free, .
  4. Linear: (unbounded). Soft-: (bounded). Cauchy: (redescending).
  5. The unconstrained solution is , already feasible. NNLS frees first (its gradient is the most negative), solves for , and stops.

Further reading

  • C. L. Lawson and R. J. Hanson, Solving Least Squares Problems, Prentice-Hall, 1974 (SIAM reprint 1995), chapter 23.
  • P. B. Stark and R. L. Parker, “Bounded-variable least-squares: an algorithm and applications”, Computational Statistics 10 (1995) 129–141.
  • R. H. Byrd, P. Lu, J. Nocedal and C. Zhu, “A limited memory algorithm for bound constrained optimization”, SIAM Journal on Scientific Computing 16 (1995) 1190–1208.
  • M. A. Branch, T. F. Coleman and Y. Li, “A subspace, interior, and conjugate gradient method for large-scale bound-constrained minimization problems”, SIAM Journal on Scientific Computing 21 (1999) 1–23.
  • B. Triggs, P. McLauchlan, R. Hartley and A. Fitzgibbon, “Bundle adjustment — a modern synthesis”, in Vision Algorithms: Theory and Practice, Springer, 2000 (robust losses).