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

Global and combinatorial optimisation: shgo and quadratic assignment

ProblemFind the global minimum of a function in a box, with constraints, together with its other local minima; and find the permutation that best aligns two weighted graphs (the quadratic assignment problem)
Devised byStefan Endres, Carl Sandrock and Walter Focke (2018), simplicial homology global optimisation; Tjalling Koopmans and Martin Beckmann (1957), the quadratic assignment problem; Joshua Vogelstein et al. (2015), Fast Approximate QAP; Marguerite Frank and Philip Wolfe (1956), the conditional gradient method
Accuracyshgo: the same global minima as SciPy to the local solver’s tolerance. quadratic_assignment: identical permutations and iteration counts to SciPy’s
Costshgo: one Delaunay triangulation of the samples plus one local solve per minimiser. FAQ: one O(n³) linear assignment per iteration; 2-opt: O(n²) swaps of O(n²) scores per pass
Read firstStochastic global optimisation, Geometry in any dimension, Constrained optimisation
APIshgo, ShgoOptions, ShgoResult; quadratic_assignment, QapMethod, qap_score

Overview

These are the last two of SciPy’s global optimisers.

shgo samples the search box and triangulates the samples. A sample lower than all its neighbours in the triangulation lies in the basin of a local minimum. A local solve from each such minimiser finds every minimum the sampling has resolved, so the method returns the whole list of local minima as well as the global one. Unlike stochastic methods, it is deterministic, and it handles nonlinear constraints directly.

quadratic_assignment solves the quadratic assignment problem over permutations . Examples are placing facilities with flows at sites with distances , or matching the nodes of two graphs. The problem is NP-hard, so both methods are heuristics.

Where it is used

Global optimisation and combinatorial matching, two problems that local methods cannot solve.

  • Global minimum with several basins. Finding all local minima of an engineering objective and choosing the best, as in structural design and parameter estimation with several plausible solutions.
  • Quadratic assignment. Placing facilities, departments or circuit blocks so as to minimise the total of flow times distance; matching graphs, as in comparing the connectomes of two brains.

History

Koopmans and Beckmann (1957) posed the quadratic assignment problem for locating plants. It remains one of the hardest combinatorial problems in practice: exact solutions are rare beyond 30 or so facilities. Vogelstein and colleagues (2015) relaxed permutations to doubly stochastic matrices and applied Frank and Wolfe’s conditional gradient method. The resulting Fast Approximate QAP matches brains’ connectomes quickly and well. Endres, Sandrock and Focke (2018) built shgo on ideas from algebraic topology: the minimisers of a sampled function on a simplicial complex estimate the number of its basins of attraction.

The idea

Minimisers on a triangulation

Triangulate the feasible samples (Delaunay, in any dimension). Within each basin of attraction, the lowest sample on the triangulation has no lower neighbour: it is a minimiser. As the sampling grows finer, there is one minimiser per basin that the sampling resolves. Starting a local solver from each minimiser therefore finds each resolved local minimum once, instead of the many repeated starts a multistart method needs.

Constraints are handled twice: infeasible samples are dropped before triangulating, and the local solves (SQP) enforce the constraints exactly.

Fast Approximate QAP

Relax permutation matrices to doubly stochastic matrices and minimise . Each iteration:

  1. computes the gradient ;
  2. finds the permutation matrix minimising , a linear assignment problem;
  3. moves to the best point on the segment between and , where is a quadratic in the step.

At the end, is projected to the nearest permutation, by another linear assignment. Starting from the barycentre makes the method deterministic.

Seeds. If some nodes are known to correspond (partial_match), the matrices are permuted to put them first and split into blocks, and likewise , with the seeds in the first block. Only the non-seed block is optimised. The seeds contribute a constant to the gradient, , and linear terms to the step-size quadratic. A randomised start replaces the barycentre by the mean of the barycentre and a random doubly stochastic matrix, found by Sinkhorn-Knopp scaling of uniform noise; running several of them and keeping the best is the usual way to escape a poor local optimum.

2-opt

Starting from a permutation, try the swaps in order, take the first that improves the score, and begin again. The search stops at a permutation that no single swap improves: a local optimum.

Implementation

/// Finds the global minimum of `problem` in the box `[lower, upper]` (with its inequality and
/// equality constraints) by simplicial homology global optimisation.
///
/// The box is sampled either by a simplicial complex (the corners and centre of the box, refined `iters − 1`
/// times by the midpoints of all edges; vertices violating an inequality get the value +∞) or by the first
/// `n · iters` points of the (unscrambled) Sobol sequence (infeasible ones dropped); the vertices are
/// Delaunay-triangulated. A
/// sample whose value is lower than at all its neighbours in the triangulation is a
/// *minimiser*: it approximates a local minimum, and the number of them estimates the number of
/// basins (the rank of the complex's homology, in the language of the paper). A local SLSQP solve
/// is started from each minimiser in order of value, and the distinct results are returned with
/// the best of them.
pub fn shgo<P: ConstrainedProblem>(problem: &P, lower: &[f64], upper: &[f64], options: ShgoOptions) -> Result<ShgoResult, ErrorsJSL> {
    let d = lower.len();
    if d == 0 || upper.len() != d || lower.iter().zip(upper).any(|(l, u)| l.is_nan() || u.is_nan() || l >= u) {
        return Err(ErrorsJSL::InvalidInputRange("need finite bounds with lower < upper"));
    }
    let feasible = |x: &[f64]| !problem.inequalities(x).iter().any(|g| *g > 0.0);
    let mut pts: Vec<Vec<f64>> = Vec::new();
    let mut vals: Vec<f64> = Vec::new();
    let mut nfev = 0;
    let mut nbrs: Vec<Vec<usize>>;
    match options.sampling {
        ShgoSampling::Sobol => {
            let mut sobol = SobolSequence::new(d)?;
            let total = options.n * options.iters.max(1);
            for _ in 0..total {
                let u = sobol.next_point();
                let x: Vec<f64> = u.iter().zip(lower.iter().zip(upper)).map(|(t, (l, h))| l + t * (h - l)).collect();
                if !feasible(&x) {
                    continue;
                }
                nfev += 1;
                vals.push(problem.objective(&x));
                pts.push(x);
            }
            if pts.len() < d + 2 {
                return Err(ErrorsJSL::InvalidInputRange("too few feasible sampling points; increase n"));
            }
            nbrs = vec![Vec::new(); pts.len()];
            fill_neighbours(&mut nbrs, &pts)?;
        }
        ShgoSampling::Simplicial => {
            if d > 8 {
                return Err(ErrorsJSL::InvalidInputRange("simplicial sampling is limited to 8 variables; use Sobol sampling"));
            }
            // The corners and the centre; infeasible vertices stay in the complex (with value +∞) so that
            // the triangulation covers the whole box, and are never minimisers.
            let mut all: Vec<Vec<f64>> = (0..1usize << d).map(|c| (0..d).map(|k| if c >> k & 1 == 1 { upper[k] } else { lower[k] }).collect()).collect();
            all.push(lower.iter().zip(upper).map(|(l, h)| 0.5 * (l + h)).collect());
            let scale = lower.iter().zip(upper).map(|(l, h)| h - l).fold(0.0f64, f64::max);
            let mut done = 0;
            let mut level = 1;
            loop {
                vals.extend((done..all.len()).map(|i| {
                    if feasible(&all[i]) {
                        nfev += 1;
                        problem.objective(&all[i])
                    } else {
                        f64::INFINITY
                    }
                }));
                done = all.len();
                nbrs = vec![Vec::new(); all.len()];
                fill_neighbours(&mut nbrs, &all)?;
                if level >= options.iters.max(1) {
                    break;
                }
                level += 1;
                // Refinement: the midpoint of every edge.
                let mut added: Vec<Vec<f64>> = Vec::new();
                for i in 0..all.len() {
                    for &j in nbrs[i].iter().filter(|&&j| j > i) {
                        let m: Vec<f64> = all[i].iter().zip(&all[j]).map(|(a, b)| 0.5 * (a + b)).collect();
                        if !all.iter().chain(&added).any(|q| q.iter().zip(&m).all(|(a, b)| (a - b).abs() <= 1e-9 * scale)) {
                            added.push(m);
                        }
                    }
                }
                if added.is_empty() {
                    break;
                }
                all.extend(added);
            }
            let finite: Vec<usize> = (0..all.len()).filter(|&i| vals[i].is_finite()).collect();
            if finite.is_empty() {
                return Err(ErrorsJSL::InvalidInputRange("no feasible vertex in the box"));
            }
            pts = all;
        }
    }
    let mut minimizers: Vec<usize> = (0..pts.len()).filter(|&i| vals[i].is_finite() && !nbrs[i].is_empty() && nbrs[i].iter().all(|&j| vals[i] < vals[j])).collect();
    minimizers.sort_by(|&a, &b| vals[a].total_cmp(&vals[b]));
    let local = SlsqpOptions::new(options.local.tolerance, options.local.max_iterations);
    let mut xl: Vec<Vec<f64>> = Vec::new();
    let mut funl: Vec<f64> = Vec::new();
    let mut nlfev = 0;
    for &m in &minimizers {
        nlfev += 1;
        let r = slsqp(problem, pts[m].clone(), Some(lower), Some(upper), local)?;
        if r.maxcv > 1e-6 || !r.fun.is_finite() {
            continue;
        }
        let scale = lower.iter().zip(upper).map(|(l, h)| h - l).fold(0.0f64, f64::max);
        let dup = xl.iter().any(|x| x.iter().zip(&r.x).map(|(a, b)| (a - b).abs()).fold(0.0f64, f64::max) <= 1e-6 * scale);
        if !dup {
            xl.push(r.x);
            funl.push(r.fun);
        }
    }
    let mut order: Vec<usize> = (0..xl.len()).collect();
    // Minima that tie to 1e-8 keep the order in which their minimisers were found (as SciPy's list does), so that
    // the "best" of equal minima does not depend on rounding noise.
    order.sort_by(|&a, &b| (funl[a] * 1e8).round().total_cmp(&(funl[b] * 1e8).round()));
    let xl: Vec<Vec<f64>> = order.iter().map(|&i| xl[i].clone()).collect();
    let funl: Vec<f64> = order.iter().map(|&i| funl[i]).collect();
    let (x, fun) = match xl.first() {
        Some(x) => (x.clone(), funl[0]),
        None => {
            let b = (0..pts.len()).filter(|&i| vals[i].is_finite()).min_by(|&a, &b| vals[a].total_cmp(&vals[b])).unwrap();
            (pts[b].clone(), vals[b])
        }
    };
    Ok(ShgoResult { x, fun, xl, funl, nfev, nlfev, minimizers: minimizers.iter().map(|&m| pts[m].clone()).collect() })
}
/// Solves (approximately: the problem is NP-hard) `min_p Σᵢⱼ A[i][j] B[p(i)][p(j)]` over
/// permutations, or the maximum with `maximize` (SciPy's `quadratic_assignment`). Both methods
/// are deterministic ports of SciPy's and give its permutations.
pub fn quadratic_assignment(a: &Array2<f64>, b: &Array2<f64>, method: QapMethod, maximize: bool) -> Result<QapResult, ErrorsJSL> {
    let n = a.nrows();
    if a.dim() != (n, n) || b.dim() != (n, n) {
        return Err(ErrorsJSL::InvalidInputRange("A and B must be square and of the same size"));
    }
    if n == 0 {
        return Ok(QapResult { perm: Vec::new(), fun: 0.0, nit: 0 });
    }
    let sign = if maximize { -1.0 } else { 1.0 };
    match method {
        QapMethod::FaqWith(options) => quadratic_assignment_seeded(a, b, &options, maximize, None),
        QapMethod::Faq { maxiter, tol } => {
            let mut p = Array2::from_elem((n, n), 1.0 / n as f64);
            let mut nit = 0;
            for _ in 0..maxiter {
                nit += 1;
                let grad = a.dot(&p).dot(&b.t()) + a.t().dot(&p).dot(b);
                let (_, cols) = linear_sum_assignment(&grad, maximize)?;
                let q = Array2::from_shape_fn((n, n), |(i, j)| if cols[i] == j { 1.0 } else { 0.0 });
                let r = &p - &q;
                // f(P + t R) is quadratic in t: a t² + b t + const.
                let ar = a.t().dot(&r);
                let br = b.dot(&r.t());
                let b22a: f64 = (0..n).map(|i| (0..n).map(|j| ar[(i, j)] * b[(j, cols[i])]).sum::<f64>()).sum();
                let b22b: f64 = (0..n).map(|i| (0..n).map(|j| a[(i, j)] * br[(cols[i], j)]).sum::<f64>()).sum();
                let qa: f64 = (0..n).map(|i| (0..n).map(|j| ar[(j, i)] * br[(i, j)]).sum::<f64>()).sum();
                let qb = b22a + b22b;
                let alpha = if qa * sign > 0.0 && (0.0..=1.0).contains(&(-qb / (2.0 * qa))) {
                    -qb / (2.0 * qa)
                } else if 0.0 <= (qb + qa) * sign {
                    0.0
                } else {
                    1.0
                };
                let next = &p * alpha + &q * (1.0 - alpha);
                let change = (&p - &next).iter().map(|v| v * v).sum::<f64>().sqrt() / (n as f64).sqrt();
                p = next;
                if change < tol {
                    break;
                }
            }
            let (_, perm) = linear_sum_assignment(&p, true)?;
            Ok(QapResult { fun: qap_score(a, b, &perm), perm, nit })
        }
        QapMethod::TwoOpt { initial } => {
            let mut perm: Vec<usize> = if initial.is_empty() { (0..n).collect() } else { initial };
            let mut seen = perm.clone();
            seen.sort_unstable();
            if seen != (0..n).collect::<Vec<_>>() {
                return Err(ErrorsJSL::InvalidInputRange("the initial guess must be a permutation of 0..n"));
            }
            let mut best = qap_score(a, b, &perm);
            let mut nit = 0;
            'outer: loop {
                for i in 0..n {
                    for j in i..n {
                        nit += 1;
                        perm.swap(i, j);
                        let s = qap_score(a, b, &perm);
                        if s * sign < best * sign {
                            best = s;
                            continue 'outer;
                        }
                        perm.swap(i, j);
                    }
                }
                break;
            }
            Ok(QapResult { perm, fun: best, nit })
        }
    }
}
  • shgo implements SciPy’s sampling_method='sobol' (ShgoOptions::with_samples): the first points of the unscrambled Sobol sequence, scaled to the box. These are the same samples SciPy uses, so the minimisers are the same.
  • The default is the simplicial sampling (ShgoOptions::simplicial(iters)): the corners and the centre of the box, triangulated, and at each further iteration refined by the midpoints of all edges of the triangulation, with vertices that violate a constraint kept in the complex at the value . SciPy builds its own simplicial complex and refines it by a different rule, so the vertices, the numbers of evaluations and the iteration at which a basin is resolved differ (on Himmelblau, SciPy finds one minimum after the first iteration and the library too, and all four by the fourth iteration, against SciPy’s six local minima listing duplicates). The complex is a Delaunay triangulation of the vertices, which limits it to eight variables; use Sobol sampling beyond six or so.
  • The local solver is the library’s slsqp (SciPy’s SLSQP, as shgo uses), with the box as its bounds. Local minima closer than of the box size are merged.
  • quadratic_assignment has the barycentre start, and with QapMethod::FaqWith(FaqOptions) the seeds (partial_match) and iteration limits too; quadratic_assignment_seeded takes partial_match seeds and optionally a randomised start (from any uniform source: a closure returning values in , so a seeded generator makes restarts repeatable). FaqOptions::shuffle_input (with the uniform source passed as randomized_start) shuffles the unmatched nodes of before solving, so that ties between equally good assignments are broken at random, as SciPy’s shuffle_input does. 2-opt starts from a given permutation, the identity by default. SciPy starts from a random one, or from partial_guess.

In practice

The references are from SciPy 1.17.1, written by book/generator/data/make_glob218_refs.py:

Table 5.20. shgo against SciPy's with Sobol sampling.

ProblemLibrary minimumSciPy minimumMinimiser differenceDistinct local minima, library / SciPyLocal solves / SciPy’s local evaluations
Himmelblau, [−5, 5]², n = 1280.0000000.0000001e-74 / 44 / 111
Eggholder, [−512, 512]², n = 256, 3 iterations-959.640663-959.6406639e-748 / 4753 / 1930
Ackley, [−5, 5]², n = 1280.0000000.0000009e-112 / 24 / 178
Rosenbrock 4-D, [−2, 2]⁴, n = 1280.0000000.0000001e-52 / 22 / 685
SciPy’s constrained example (a disc and a half-plane), n = 1281.0227741.0227741e-91 / 11 / 112

Both libraries find the global minimum of every problem, including the Eggholder function’s corner minimum at . The lists of local minima nearly agree. The differences come from local solves that converge to the same minimum to slightly different accuracy, which SciPy’s list can contain twice and the library merges. The last column compares different things: the library counts local solves, while SciPy counts function evaluations inside its local searches.

Table 5.21. quadratic_assignment against SciPy on random integer instances.

Random integer instanceFAQ: libraryFAQ: SciPy2-opt from the identity: library2-opt: SciPy
n = 10, minimise1587 (30 it.); permutation identical15871595; permutation identical1595
n = 10, maximise2082 (4 it.); permutation identical20822128; permutation identical2128
n = 20, minimise6150 (28 it.); permutation identical61506384; permutation identical6384
n = 20, maximise8409 (5 it.); permutation identical84098321; permutation identical8321
n = 40, minimise27317 (30 it.); permutation identical2731727780; permutation identical27780
n = 40, maximise34812 (9 it.); permutation identical3481234731; permutation identical34731

Every permutation and iteration count is SciPy’s. FAQ beats 2-opt on five of the six instances, at a fraction of the cost.

Figure 5.16. shgo on Himmelblau's function. Of 128 Sobol samples, four are lower than all their Delaunay neighbours, one in each basin, and the four local solves started from them find the four global minima.

Strengths

  • shgo is deterministic, returns every local minimum it resolves, and handles nonlinear constraints.
  • Few local solves: one per basin, not one per random start.
  • FAQ gives good permutations of large graphs in a handful of linear assignments.

Seeded FAQ against SciPy’s partial_match, on random integer matrices:

Table 5.22. Seeded Fast Approximate QAP against SciPy.

InstanceLibrary: objectiveSciPy: objectivePermutationIdentity permutation, for scale
n = 12, 3 seeds, minimise2644 (18 it.)2644 (18 it.)identical3027
n = 12, 3 seeds, maximise3331 (14 it.)3331 (14 it.)identical3027
n = 20, 5 seeds, minimise6831 (9 it.)6831 (9 it.)identical7842
n = 20, 5 seeds, maximise8845 (8 it.)8845 (8 it.)identical7842

The permutations and iteration counts are identical: the seeded algorithm is a deterministic port.

Weaknesses

  • shgo’s triangulation grows quickly with dimension; beyond about six variables it becomes expensive, and narrow basins between samples are missed.
  • QAP heuristics come with no guarantee of optimality; for small instances, branch and bound finds the true optimum.
  • 2-opt depends on its starting permutation and stops at the first local optimum.

Exercises

  1. Why does a sample with no lower neighbour on a triangulation of a fine enough sampling lie in the basin of a local minimum?
  2. Show that with , and find .
  3. Why is the linear assignment step of FAQ exact on the doubly stochastic matrices (the Birkhoff polytope)?
  4. How many swaps does one pass of 2-opt try for facilities?
Hints and answers
  1. Follow the steepest descent from the sample: on a fine sampling it cannot cross to a lower sample without passing through a lower neighbour.
  2. .
  3. A linear function on a polytope is minimised at a vertex, and the vertices of the Birkhoff polytope are the permutation matrices (Birkhoff-von Neumann).
  4. , counting the trivial swaps , as SciPy does.

Further reading

  • S. C. Endres, C. Sandrock and W. W. Focke, “A simplicial homology algorithm for Lipschitz optimisation”, Journal of Global Optimization 72 (2018) 181–217.
  • J. T. Vogelstein et al., “Fast approximate quadratic programming for graph matching”, PLoS ONE 10 (2015) e0121002.
  • T. C. Koopmans and M. Beckmann, “Assignment problems and the location of economic activities”, Econometrica 25 (1957) 53–76.
  • R. E. Burkard, E. Çela, S. E. Karisch and F. Rendl, “QAPLIB — a quadratic assignment problem library”, Journal of Global Optimization 10 (1997) 391–403.