Skip to main content

lib_jsl_optimization/
qap.rs

1//! The quadratic assignment problem (SciPy's `quadratic_assignment`): find the permutation `p`
2//! minimising `Σᵢⱼ A[i][j] B[p(i)][p(j)]`, by Vogelstein et al.'s Fast Approximate QAP or by 2-opt
3//! local search.
4//!
5//! See the book entry [Global and combinatorial optimisation](https://jwkunz.github.io/lib_jsl/book/optimization/shgo-qap.html).
6
7use crate::assignment::linear_sum_assignment;
8use lib_jsl_core::ErrorsJSL;
9use ndarray::Array2;
10
11/// The method of [`quadratic_assignment`].
12#[derive(Clone, Debug, PartialEq)]
13#[non_exhaustive]
14pub enum QapMethod {
15    /// Fast Approximate QAP: Frank-Wolfe on the doubly stochastic relaxation from the
16    /// barycentre, then projected to the nearest permutation (SciPy's default `faq`, with
17    /// `maxiter` and `tol`).
18    Faq { maxiter: usize, tol: f64 },
19    /// 2-opt from the given starting permutation (identity if empty): repeatedly apply the first
20    /// improving swap in the order `(0,0), (0,1), …, (n−1,n−1)` (SciPy's `2opt`).
21    TwoOpt { initial: Vec<usize> },
22    /// FAQ with the options of [`FaqOptions`]: iteration limits and seeds (`partial_match`). It
23    /// is deterministic: `shuffle_input` and a randomised start need a random source, which only
24    /// [`quadratic_assignment_seeded`] takes.
25    FaqWith(FaqOptions),
26}
27
28impl Default for QapMethod {
29    fn default() -> Self {
30        QapMethod::Faq { maxiter: 30, tol: 0.03 }
31    }
32}
33
34/// The result of [`quadratic_assignment`].
35#[derive(Clone, Debug)]
36#[non_exhaustive]
37pub struct QapResult {
38    /// `col_ind`: node `i` of `A` is matched to node `perm[i]` of `B`.
39    pub perm: Vec<usize>,
40    /// `Σᵢⱼ A[i][j] B[perm[i]][perm[j]]`.
41    pub fun: f64,
42    pub nit: usize,
43}
44
45/// `Σᵢⱼ A[i][j] B[p(i)][p(j)]`.
46pub fn qap_score(a: &Array2<f64>, b: &Array2<f64>, perm: &[usize]) -> f64 {
47    let n = perm.len();
48    (0..n).map(|i| (0..n).map(|j| a[(i, j)] * b[(perm[i], perm[j])]).sum::<f64>()).sum()
49}
50
51// ANCHOR: qap
52/// Solves (approximately: the problem is NP-hard) `min_p Σᵢⱼ A[i][j] B[p(i)][p(j)]` over
53/// permutations, or the maximum with `maximize` (SciPy's `quadratic_assignment`). Both methods
54/// are deterministic ports of SciPy's and give its permutations.
55pub fn quadratic_assignment(a: &Array2<f64>, b: &Array2<f64>, method: QapMethod, maximize: bool) -> Result<QapResult, ErrorsJSL> {
56    let n = a.nrows();
57    if a.dim() != (n, n) || b.dim() != (n, n) {
58        return Err(ErrorsJSL::InvalidInputRange("A and B must be square and of the same size"));
59    }
60    if n == 0 {
61        return Ok(QapResult { perm: Vec::new(), fun: 0.0, nit: 0 });
62    }
63    let sign = if maximize { -1.0 } else { 1.0 };
64    match method {
65        QapMethod::FaqWith(options) => quadratic_assignment_seeded(a, b, &options, maximize, None),
66        QapMethod::Faq { maxiter, tol } => {
67            let mut p = Array2::from_elem((n, n), 1.0 / n as f64);
68            let mut nit = 0;
69            for _ in 0..maxiter {
70                nit += 1;
71                let grad = a.dot(&p).dot(&b.t()) + a.t().dot(&p).dot(b);
72                let (_, cols) = linear_sum_assignment(&grad, maximize)?;
73                let q = Array2::from_shape_fn((n, n), |(i, j)| if cols[i] == j { 1.0 } else { 0.0 });
74                let r = &p - &q;
75                // f(P + t R) is quadratic in t: a t² + b t + const.
76                let ar = a.t().dot(&r);
77                let br = b.dot(&r.t());
78                let b22a: f64 = (0..n).map(|i| (0..n).map(|j| ar[(i, j)] * b[(j, cols[i])]).sum::<f64>()).sum();
79                let b22b: f64 = (0..n).map(|i| (0..n).map(|j| a[(i, j)] * br[(cols[i], j)]).sum::<f64>()).sum();
80                let qa: f64 = (0..n).map(|i| (0..n).map(|j| ar[(j, i)] * br[(i, j)]).sum::<f64>()).sum();
81                let qb = b22a + b22b;
82                let alpha = if qa * sign > 0.0 && (0.0..=1.0).contains(&(-qb / (2.0 * qa))) {
83                    -qb / (2.0 * qa)
84                } else if 0.0 <= (qb + qa) * sign {
85                    0.0
86                } else {
87                    1.0
88                };
89                let next = &p * alpha + &q * (1.0 - alpha);
90                let change = (&p - &next).iter().map(|v| v * v).sum::<f64>().sqrt() / (n as f64).sqrt();
91                p = next;
92                if change < tol {
93                    break;
94                }
95            }
96            let (_, perm) = linear_sum_assignment(&p, true)?;
97            Ok(QapResult { fun: qap_score(a, b, &perm), perm, nit })
98        }
99        QapMethod::TwoOpt { initial } => {
100            let mut perm: Vec<usize> = if initial.is_empty() { (0..n).collect() } else { initial };
101            let mut seen = perm.clone();
102            seen.sort_unstable();
103            if seen != (0..n).collect::<Vec<_>>() {
104                return Err(ErrorsJSL::InvalidInputRange("the initial guess must be a permutation of 0..n"));
105            }
106            let mut best = qap_score(a, b, &perm);
107            let mut nit = 0;
108            'outer: loop {
109                for i in 0..n {
110                    for j in i..n {
111                        nit += 1;
112                        perm.swap(i, j);
113                        let s = qap_score(a, b, &perm);
114                        if s * sign < best * sign {
115                            best = s;
116                            continue 'outer;
117                        }
118                        perm.swap(i, j);
119                    }
120                }
121                break;
122            }
123            Ok(QapResult { perm, fun: best, nit })
124        }
125    }
126}
127// ANCHOR_END: qap
128
129/// Options of [`quadratic_assignment_seeded`].
130#[derive(Clone, Debug, PartialEq)]
131#[non_exhaustive]
132pub struct FaqOptions {
133    /// The largest number of Frank-Wolfe iterations (SciPy's `maxiter`).
134    pub maxiter: usize,
135    /// The convergence tolerance on the change of the doubly stochastic matrix.
136    pub tol: f64,
137    /// Seeds: node `a` of `A` is matched to node `b` of `B` for each `(a, b)` (SciPy's
138    /// `partial_match`). The other nodes are matched by the algorithm.
139    pub partial_match: Vec<(usize, usize)>,
140    /// Shuffle the order of the unmatched nodes of `B` before solving, to break ties between equally
141    /// good assignments at random instead of by index (SciPy's `shuffle_input`). It has no effect
142    /// when the gradients are not degenerate. It needs the uniform source passed as
143    /// `randomized_start`.
144    pub shuffle_input: bool,
145}
146
147impl Default for FaqOptions {
148    fn default() -> Self {
149        FaqOptions { maxiter: 30, tol: 0.03, partial_match: Vec::new(), shuffle_input: false }
150    }
151}
152
153impl FaqOptions {
154    /// The defaults with the given seeds `(node of A, node of B)`.
155    pub fn with_partial_match(partial_match: Vec<(usize, usize)>) -> Self {
156        FaqOptions { partial_match, ..Default::default() }
157    }
158
159    /// Turns on `shuffle_input`.
160    pub fn with_shuffle_input(mut self) -> Self {
161        self.shuffle_input = true;
162        self
163    }
164
165    /// Sets the iteration limit and the tolerance.
166    pub fn with_limits(mut self, maxiter: usize, tol: f64) -> Self {
167        self.maxiter = maxiter;
168        self.tol = tol;
169        self
170    }
171}
172
173/// Sinkhorn-Knopp scaling to a doubly stochastic matrix (SciPy's `_doubly_stochastic`).
174fn doubly_stochastic(p: &Array2<f64>, tol: f64) -> Array2<f64> {
175    let n = p.nrows();
176    let mut c: Vec<f64> = (0..n).map(|j| 1.0 / p.column(j).sum()).collect();
177    let mut r: Vec<f64> = (0..n).map(|i| 1.0 / (0..n).map(|j| p[(i, j)] * c[j]).sum::<f64>()).collect();
178    let mut scaled = p.clone();
179    for _ in 0..1000 {
180        let rows_ok = (0..n).all(|i| (scaled.row(i).sum() - 1.0).abs() < tol);
181        let cols_ok = (0..n).all(|j| (scaled.column(j).sum() - 1.0).abs() < tol);
182        if rows_ok && cols_ok {
183            break;
184        }
185        c = (0..n).map(|j| 1.0 / (0..n).map(|i| r[i] * p[(i, j)]).sum::<f64>()).collect();
186        r = (0..n).map(|i| 1.0 / (0..n).map(|j| p[(i, j)] * c[j]).sum::<f64>()).collect();
187        scaled = Array2::from_shape_fn((n, n), |(i, j)| r[i] * p[(i, j)] * c[j]);
188    }
189    scaled
190}
191
192// ANCHOR: qap_seeded
193/// Fast Approximate QAP with seeds (SciPy's `quadratic_assignment` with `partial_match`, after
194/// Fishkind et al.'s seeded graph matching): the matched nodes are moved to the front of both
195/// matrices, which are split into seed and non-seed blocks, and Frank-Wolfe runs on the
196/// non-seed block with the seeds contributing a constant term to the gradient and linear terms to
197/// the step size. `randomized_start` replaces the barycentre by the mean of the barycentre and a
198/// random doubly stochastic matrix, drawn from `uniform` (values in `[0, 1)`), so that restarts
199/// from different random streams explore different local optima.
200pub fn quadratic_assignment_seeded(a: &Array2<f64>, b: &Array2<f64>, options: &FaqOptions, maximize: bool, mut randomized_start: Option<&mut dyn FnMut() -> f64>) -> Result<QapResult, ErrorsJSL> {
201    let n = a.nrows();
202    if a.dim() != (n, n) || b.dim() != (n, n) {
203        return Err(ErrorsJSL::InvalidInputRange("A and B must be square and of the same size"));
204    }
205    let seeds = &options.partial_match;
206    let (mut used_a, mut used_b) = (vec![false; n], vec![false; n]);
207    for &(i, j) in seeds {
208        if i >= n || j >= n || used_a[i] || used_b[j] {
209            return Err(ErrorsJSL::InvalidInputRange("partial_match entries must be distinct node indices below n"));
210        }
211        used_a[i] = true;
212        used_b[j] = true;
213    }
214    let (ns, nu) = (seeds.len(), n - seeds.len());
215    if n == 0 || nu == 0 {
216        let mut perm = vec![0; n];
217        for &(i, j) in seeds {
218            perm[i] = j;
219        }
220        return Ok(QapResult { fun: qap_score(a, b, &perm), perm, nit: 0 });
221    }
222    let sign = if maximize { -1.0 } else { 1.0 };
223    let perm_a: Vec<usize> = seeds.iter().map(|s| s.0).chain((0..n).filter(|&i| !used_a[i])).collect();
224    let mut perm_b: Vec<usize> = seeds.iter().map(|s| s.1).chain((0..n).filter(|&j| !used_b[j])).collect();
225    if options.shuffle_input {
226        let u = randomized_start.as_deref_mut().ok_or(ErrorsJSL::InvalidInputRange("shuffle_input needs a uniform source (pass randomized_start)"))?;
227        // Fisher-Yates on the unmatched nodes of B.
228        for i in (ns + 1..n).rev() {
229            let j = ns + (u() * (i - ns + 1) as f64) as usize;
230            perm_b.swap(i, j.min(i));
231        }
232    }
233    let pa = a.select(ndarray::Axis(0), &perm_a).select(ndarray::Axis(1), &perm_a);
234    let pb = b.select(ndarray::Axis(0), &perm_b).select(ndarray::Axis(1), &perm_b);
235    let block = |m: &Array2<f64>, rows: std::ops::Range<usize>, cols: std::ops::Range<usize>| m.slice(ndarray::s![rows, cols]).to_owned();
236    let (a12, a21, a22) = (block(&pa, 0..ns, ns..n), block(&pa, ns..n, 0..ns), block(&pa, ns..n, ns..n));
237    let (b12, b21, b22) = (block(&pb, 0..ns, ns..n), block(&pb, ns..n, 0..ns), block(&pb, ns..n, ns..n));
238    let const_sum = a21.dot(&b21.t()) + a12.t().dot(&b12);
239    let mut p = Array2::from_elem((nu, nu), 1.0 / nu as f64);
240    if let Some(u) = randomized_start {
241        let k = doubly_stochastic(&Array2::from_shape_fn((nu, nu), |_| u()), 1e-3);
242        p = (&p + &k) * 0.5;
243    }
244    let mut nit = 0;
245    for _ in 0..options.maxiter {
246        nit += 1;
247        let grad = &const_sum + &a22.dot(&p).dot(&b22.t()) + &a22.t().dot(&p).dot(&b22);
248        let (_, cols) = linear_sum_assignment(&grad, maximize)?;
249        let q = Array2::from_shape_fn((nu, nu), |(i, j)| if cols[i] == j { 1.0 } else { 0.0 });
250        let r = &p - &q;
251        let b21t = (r.t().dot(&a21) * &b21).sum();
252        let b12t = (r.t().dot(&a12.t()) * b12.t()).sum();
253        let ar22 = a22.t().dot(&r);
254        let br22 = b22.dot(&r.t());
255        let b22a: f64 = (0..nu).map(|i| (0..nu).map(|j| ar22[(i, j)] * b22[(j, cols[i])]).sum::<f64>()).sum();
256        let b22b: f64 = (0..nu).map(|i| (0..nu).map(|j| a22[(i, j)] * br22[(cols[i], j)]).sum::<f64>()).sum();
257        let qa: f64 = (0..nu).map(|i| (0..nu).map(|j| ar22[(j, i)] * br22[(i, j)]).sum::<f64>()).sum();
258        let qb = b21t + b12t + b22a + b22b;
259        let alpha = if qa * sign > 0.0 && (0.0..=1.0).contains(&(-qb / (2.0 * qa))) {
260            -qb / (2.0 * qa)
261        } else if 0.0 <= (qb + qa) * sign {
262            0.0
263        } else {
264            1.0
265        };
266        let next = &p * alpha + &q * (1.0 - alpha);
267        let change = (&p - &next).iter().map(|v| v * v).sum::<f64>().sqrt() / (nu as f64).sqrt();
268        p = next;
269        if change < options.tol {
270            break;
271        }
272    }
273    let (_, col) = linear_sum_assignment(&p, true)?;
274    let mut perm = vec![0; n];
275    for (k, &i) in perm_a.iter().enumerate() {
276        perm[i] = if k < ns { perm_b[k] } else { perm_b[ns + col[k - ns]] };
277    }
278    Ok(QapResult { fun: qap_score(a, b, &perm), perm, nit })
279}
280// ANCHOR_END: qap_seeded
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn recovers_a_hidden_permutation() {
288        // B is A relabelled by a permutation: the optimum of the maximisation is that
289        // permutation, and 2-opt and FAQ both find it on this small, well-separated instance.
290        let n = 8;
291        let a = Array2::from_shape_fn((n, n), |(i, j)| if i == j { 0.0 } else { ((i * 7 + j * 3) % 11) as f64 + (i as f64 - j as f64).abs() });
292        let hidden = [3usize, 0, 6, 1, 7, 2, 5, 4];
293        let mut b = Array2::zeros((n, n));
294        for i in 0..n {
295            for j in 0..n {
296                b[(hidden[i], hidden[j])] = a[(i, j)];
297            }
298        }
299        let best = qap_score(&a, &b, &hidden);
300        // SciPy: FAQ finds the hidden permutation in 2 iterations; 2-opt from the identity
301        // (SciPy's partial_guess) finds it after trying 144 swaps.
302        let f = quadratic_assignment(&a, &b, QapMethod::default(), true).unwrap();
303        assert_eq!((f.perm.as_slice(), f.fun, f.nit), (&hidden[..], best, 2));
304        let r = quadratic_assignment(&a, &b, QapMethod::TwoOpt { initial: Vec::new() }, true).unwrap();
305        assert_eq!((r.perm, r.fun, r.nit), (hidden.to_vec(), best, 144));
306        assert_eq!(qap_score(&a, &b, &f.perm), f.fun);
307    }
308
309    #[test]
310    fn the_plain_function_takes_seeds_through_faq_with() {
311        let n = 10;
312        let a = Array2::from_shape_fn((n, n), |(i, j)| ((i * 5 + j * 11 + i * j) % 13) as f64);
313        let b = Array2::from_shape_fn((n, n), |(i, j)| ((i * 3 + j * 7 + 2 * i * j) % 17) as f64);
314        let opts = FaqOptions::with_partial_match(vec![(0, 5), (3, 1)]);
315        let via_method = quadratic_assignment(&a, &b, QapMethod::FaqWith(opts.clone()), true).unwrap();
316        let direct = quadratic_assignment_seeded(&a, &b, &opts, true, None).unwrap();
317        assert_eq!((via_method.perm.clone(), via_method.nit), (direct.perm, direct.nit));
318        assert!(via_method.perm[0] == 5 && via_method.perm[3] == 1);
319        // Without seeds it is the default method.
320        let plain = quadratic_assignment(&a, &b, QapMethod::default(), false).unwrap();
321        assert_eq!(quadratic_assignment(&a, &b, QapMethod::FaqWith(FaqOptions::default()), false).unwrap().perm, plain.perm);
322        // Shuffling needs the random source.
323        assert!(quadratic_assignment(&a, &b, QapMethod::FaqWith(FaqOptions::default().with_shuffle_input()), false).is_err());
324    }
325
326    #[test]
327    fn seeded_faq_keeps_the_seeds_and_reduces_to_the_unseeded_one() {
328        let n = 10;
329        let a = Array2::from_shape_fn((n, n), |(i, j)| ((i * 5 + j * 11 + i * j) % 13) as f64);
330        let b = Array2::from_shape_fn((n, n), |(i, j)| ((i * 3 + j * 7 + 2 * i * j) % 17) as f64);
331        // No seeds: the same as the plain method.
332        let plain = quadratic_assignment(&a, &b, QapMethod::default(), false).unwrap();
333        let none = quadratic_assignment_seeded(&a, &b, &FaqOptions::default(), false, None).unwrap();
334        assert_eq!((none.perm.clone(), none.nit), (plain.perm.clone(), plain.nit));
335        // Seeds are kept, the result is a permutation, and the full seed set returns the seeds.
336        let opts = FaqOptions { partial_match: vec![(0, 5), (3, 1), (7, 7)], ..Default::default() };
337        let r = quadratic_assignment_seeded(&a, &b, &opts, true, None).unwrap();
338        assert!(r.perm[0] == 5 && r.perm[3] == 1 && r.perm[7] == 7);
339        let mut sorted = r.perm.clone();
340        sorted.sort_unstable();
341        assert_eq!(sorted, (0..n).collect::<Vec<_>>());
342        let full = FaqOptions { partial_match: (0..n).map(|i| (i, (i + 1) % n)).collect(), ..Default::default() };
343        assert_eq!(quadratic_assignment_seeded(&a, &b, &full, false, None).unwrap().perm, (0..n).map(|i| (i + 1) % n).collect::<Vec<_>>());
344        // A randomised start gives a valid permutation, and invalid seeds are refused.
345        let mut state = 9u64;
346        let mut u = || {
347            state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
348            (state >> 11) as f64 / (1u64 << 53) as f64
349        };
350        let rr = quadratic_assignment_seeded(&a, &b, &FaqOptions::default(), false, Some(&mut u)).unwrap();
351        assert_eq!(rr.perm.len(), n);
352        assert!(quadratic_assignment_seeded(&a, &b, &FaqOptions { partial_match: vec![(0, 1), (0, 2)], ..Default::default() }, false, None).is_err());
353        // shuffle_input needs the uniform source, keeps the seeds, and returns a permutation.
354        assert!(quadratic_assignment_seeded(&a, &b, &FaqOptions::default().with_shuffle_input(), false, None).is_err());
355        let opts = FaqOptions { partial_match: vec![(0, 5), (3, 1)], shuffle_input: true, ..Default::default() };
356        let rs = quadratic_assignment_seeded(&a, &b, &opts, true, Some(&mut u)).unwrap();
357        assert!(rs.perm[0] == 5 && rs.perm[3] == 1);
358        let mut sorted = rs.perm.clone();
359        sorted.sort_unstable();
360        assert_eq!(sorted, (0..n).collect::<Vec<_>>());
361    }
362}