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

Multiple Hungarian methods

These methods build cliques by solving pairwise LAPs and merging parts. Use Am–Fm to reproduce the original paper’s methods, or use Am, Dm, or Shift for bounded construction work.

Signature

The Python declarations show public defaults. The Rust declaration shows the entry point; its types are imported from kap.

def multiple_hungarian(cost_matrices, method="Cm", *, max_iter=100, n_trials=1,
                       maximize=False, return_free=False, backend="kap", random_state=None,
                       threshold=None):
    ...
#![allow(unused)]
fn main() {
pub fn k_assignment<T: Cost>(
    mats: &[MatrixView<'_, T>],
    algo: Algo,
    opts: &Options,
) -> Result<KSolution<T::Acc>, KapError>
where
    T::Acc: Cost<Acc = T::Acc>;
}

Parameters

PythonRustDefaultMeaning
cost_matricesmatsRequiredPairwise matrices in combinations order.
methodalgo"Cm" / explicit AlgoAm, Bm, Cm, Dm, Em, Fm, or Shift; Python names are case-insensitive.
max_iteropts.max_iter100Cm/Em/Fm move limit; positive for Em/Fm. Ignored by Am/Bm/Dm/Shift.
n_trialsopts.n_trials1Positive independent Em trial count; ignored by other methods.
maximizeopts.senseFalse / Sense::MinimizeMaximize the objective when true / Sense::Maximize; with a threshold, use the shifted objective.
thresholdopts.thresholdNoneFinite real pair-cost threshold; native core only. Optimizes sums of (cost − threshold), allowing singletons; costs remain in original units. See optional matching.
return_free-FalseInclude singleton vertices in Python free; Rust always returns them.
backend-"kap"LAP backend: kap, scipy, lap, lapjv, or munkres. Rust uses its native LAP solver.
random_stateopts.seedNone / 0Python accepts a nonnegative integer, RandomState, or Generator; Rust uses u64.

Returns

Python returns AssignmentResult(cliques, costs, free). Each clique contains (part, vertex) pairs, and its cost is the sum of its pairwise edges. result.cost gives the total cost. free is None unless requested; it then lists singleton vertices.

Rust returns Result<KSolution<T::Acc>, KapError>. cliques and costs correspond to the Python fields. cost is their sum, and free always lists singletons. Singleton vertices are excluded from both languages’ clique lists.

Errors

PythonRustCondition
ValueErrorKapError::BadCountThe matrix count does not describe 2 through 64 parts in the native core.
ValueErrorKapError::ShapeMismatchMatrix dimensions disagree about a part’s size.
TypeErrorRejected by the Cost trait at compilationA matrix has an unsupported element type.
OverflowError-Python uses int64 arithmetic and a uint64 value exceeds int64.
ValueErrorKapError::TooManyVerticesA native part exceeds u32 vertex capacity.
ValueErrorKapError::LapA constituent LAP encounters an invalid numeric entry or an infeasible assignment.

Python raises ValueError for a negative integer seed and TypeError for an unsupported seed object.

Python raises ValueError for an invalid method or backend, nonpositive Em/Fm move limits, or nonpositive Em trials. Shift raises ValueError without the native core and backend="kap". Missing optional backends raise ModuleNotFoundError. Rust returns KapError::BadOption("max_iter") for zero Em/Fm moves and KapError::BadOption("n_trials") for zero Em trials.

Example

import numpy as np
import kap

C01 = np.array([[4, 12, 15], [18, 20, 15], [2, 21, 28]], dtype=np.int64)
C02 = np.array([[19, 25, 26], [18, 18, 4], [16, 23, 23]], dtype=np.int64)
C12 = np.array([[24, 7, 24], [4, 11, 3], [11, 14, 2]], dtype=np.int64)
costs = [C01, C02, C12]

result = kap.multiple_hungarian(costs, method="Bm", return_free=True)
print("cliques =", result.cliques)
print("costs =", result.costs)
print("free =", result.free)
use kap::{Algo, MatrixView, Options, k_assignment};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let c01 = [4, 12, 15, 18, 20, 15, 2, 21, 28i64];
    let c02 = [19, 25, 26, 18, 18, 4, 16, 23, 23i64];
    let c12 = [24, 7, 24, 4, 11, 3, 11, 14, 2i64];
    let costs = [
        MatrixView::from_row_major(&c01, 3, 3)?,
        MatrixView::from_row_major(&c02, 3, 3)?,
        MatrixView::from_row_major(&c12, 3, 3)?,
    ];
    let result = k_assignment(&costs, Algo::Bm, &Options::default())?;
    println!("cliques = {:?}", result.cliques);
    println!("costs = {:?}", result.costs);
    println!("free = {:?}", result.free);
    Ok(())
}

Python output:

cliques = [[(0, 0), (1, 1), (2, 0)], [(0, 1), (1, 2), (2, 2)], [(0, 2), (1, 0), (2, 1)]]
costs = [35, 21, 32]
free = []

The Rust example prints the same cliques and costs, with the same free vertices.

Notes and limits

  • threshold=None preserves unchanged behaviour. All-integer Python matrices require an integral threshold and keep exact int64 arithmetic. For a fractional threshold, explicitly convert the matrices to float64; otherwise the call raises ValueError. See optional matching for the shifted objective, forbidden pairs, and validation.

  • Am uses k−1 LAPs, and Shift uses k(k−1). Dm chooses the cheapest immediate merge. Bm explores merge trees and memoizes commuting merges.

  • Native Bm uses 6, 39, 310, and 3,000 LAPs for k=3, 4, 5, and 6. Cm, Em, and Fm invoke Bm for neighbors, so their cost grows further.

  • Cm follows steepest descent. Em runs randomized first-improvement trials. Fm permits sideways or worse moves and returns its best solution.

  • Without the native core, Am–Fm use the Python implementation. Other LAP backends also select it; its Cm and Fm behavior differs from the native implementation.

  • Integer seeds reproduce Em/Fm iteration-limited runs. The random sequences differ from kap 0.2.

  • Part sizes may differ. Prefer Am or Dm over Bm-based methods when k exceeds about 6.

See also

Algorithm strategies and LAP counts · Backend measurements · ILS